blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
911c5bc19d5b1080ef90fb9c28dcbeb394ab35d2
13bfcfd7492f3f4ee184aeafd0153a098e0e2fa5
/Kattis/quickestimate.cpp
31d2c1ccf9a44f3fa4bc716eece97538b6a4481b
[]
no_license
jqk6/CodeArchive
fc59eb3bdf60f6c7861b82d012d298f2854d7f8e
aca7db126e6e6f24d0bbe667ae9ea2c926ac4a5f
refs/heads/master
2023-05-05T09:09:54.032436
2021-05-20T07:10:02
2021-05-20T07:10:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
#include<iostream> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; string a; cin>>n; while(n--){ cin>>a; cout<<a.size()<<'\n'; } return 0; }
[ "froghackervirus@gmail.com" ]
froghackervirus@gmail.com
953737bde45651fbba0aaa535f6c92cf4f670496
3bbe06642f31145e5172c94b92f204261ea510ba
/TornadoEngine/Source/Developer/ShareDev/Adapters/AdapterSoundEngine.cpp
a3db27911df42fbddb1394574cb8a585bc5eb25f
[]
no_license
xJayLee/MMO-Framework
82061fce005a613fd8e685c8056882bc63db41cf
bf024d1265712e784d247883965c5bbbf43c3599
refs/heads/master
2021-05-29T18:12:13.845027
2015-01-16T20:59:30
2015-01-16T20:59:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information License.h. */ #include "AdapterSoundEngine.h" AdapterSoundEngine::AdapterSoundEngine() { } //---------------------------------------------------------------------- AdapterSoundEngine::~AdapterSoundEngine() { } //---------------------------------------------------------------------- bool AdapterSoundEngine::Work() { return true; } //----------------------------------------------------------------------
[ "ramil2085@mail.ru" ]
ramil2085@mail.ru
cdf81bf63d2da602e6de8925a3439d07eb248eb9
93294d148df93b4378f59ac815476919273d425f
/src/Lib/steam/isteamugc.h
4a7d2964b66dd427ab4869f7ed9678240a8f854f
[ "MIT" ]
permissive
FreeAllegiance/Allegiance
f1addb3b26efb6b8518705a0b0300974820333c3
3856ebcd8c35a6d63dbf398a4bc7f0264d6c823c
refs/heads/master
2023-07-06T17:53:24.363387
2023-06-29T00:24:26
2023-06-29T00:24:26
98,829,929
86
34
MIT
2023-06-28T03:57:34
2017-07-30T23:09:14
C++
UTF-8
C++
false
false
28,116
h
//====== Copyright 1996-2013, Valve Corporation, All rights reserved. ======= // // Purpose: interface to steam ugc // //============================================================================= #ifndef ISTEAMUGC_H #define ISTEAMUGC_H #ifdef _WIN32 #pragma once #endif #include "isteamclient.h" // callbacks #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error isteamclient.h must be included #endif typedef uint64 UGCQueryHandle_t; typedef uint64 UGCUpdateHandle_t; const UGCQueryHandle_t k_UGCQueryHandleInvalid = 0xffffffffffffffffull; const UGCUpdateHandle_t k_UGCUpdateHandleInvalid = 0xffffffffffffffffull; // Matching UGC types for queries enum EUGCMatchingUGCType { k_EUGCMatchingUGCType_Items = 0, // both mtx items and ready-to-use items k_EUGCMatchingUGCType_Items_Mtx = 1, k_EUGCMatchingUGCType_Items_ReadyToUse = 2, k_EUGCMatchingUGCType_Collections = 3, k_EUGCMatchingUGCType_Artwork = 4, k_EUGCMatchingUGCType_Videos = 5, k_EUGCMatchingUGCType_Screenshots = 6, k_EUGCMatchingUGCType_AllGuides = 7, // both web guides and integrated guides k_EUGCMatchingUGCType_WebGuides = 8, k_EUGCMatchingUGCType_IntegratedGuides = 9, k_EUGCMatchingUGCType_UsableInGame = 10, // ready-to-use items and integrated guides k_EUGCMatchingUGCType_ControllerBindings = 11, k_EUGCMatchingUGCType_GameManagedItems = 12, // game managed items (not managed by users) k_EUGCMatchingUGCType_All = ~0, // return everything }; // Different lists of published UGC for a user. // If the current logged in user is different than the specified user, then some options may not be allowed. enum EUserUGCList { k_EUserUGCList_Published, k_EUserUGCList_VotedOn, k_EUserUGCList_VotedUp, k_EUserUGCList_VotedDown, k_EUserUGCList_WillVoteLater, k_EUserUGCList_Favorited, k_EUserUGCList_Subscribed, k_EUserUGCList_UsedOrPlayed, k_EUserUGCList_Followed, }; // Sort order for user published UGC lists (defaults to creation order descending) enum EUserUGCListSortOrder { k_EUserUGCListSortOrder_CreationOrderDesc, k_EUserUGCListSortOrder_CreationOrderAsc, k_EUserUGCListSortOrder_TitleAsc, k_EUserUGCListSortOrder_LastUpdatedDesc, k_EUserUGCListSortOrder_SubscriptionDateDesc, k_EUserUGCListSortOrder_VoteScoreDesc, k_EUserUGCListSortOrder_ForModeration, }; // Combination of sorting and filtering for queries across all UGC enum EUGCQuery { k_EUGCQuery_RankedByVote = 0, k_EUGCQuery_RankedByPublicationDate = 1, k_EUGCQuery_AcceptedForGameRankedByAcceptanceDate = 2, k_EUGCQuery_RankedByTrend = 3, k_EUGCQuery_FavoritedByFriendsRankedByPublicationDate = 4, k_EUGCQuery_CreatedByFriendsRankedByPublicationDate = 5, k_EUGCQuery_RankedByNumTimesReported = 6, k_EUGCQuery_CreatedByFollowedUsersRankedByPublicationDate = 7, k_EUGCQuery_NotYetRated = 8, k_EUGCQuery_RankedByTotalVotesAsc = 9, k_EUGCQuery_RankedByVotesUp = 10, k_EUGCQuery_RankedByTextSearch = 11, k_EUGCQuery_RankedByTotalUniqueSubscriptions = 12, k_EUGCQuery_RankedByPlaytimeTrend = 13, k_EUGCQuery_RankedByTotalPlaytime = 14, k_EUGCQuery_RankedByAveragePlaytimeTrend = 15, k_EUGCQuery_RankedByLifetimeAveragePlaytime = 16, k_EUGCQuery_RankedByPlaytimeSessionsTrend = 17, k_EUGCQuery_RankedByLifetimePlaytimeSessions = 18, }; enum EItemUpdateStatus { k_EItemUpdateStatusInvalid = 0, // The item update handle was invalid, job might be finished, listen too SubmitItemUpdateResult_t k_EItemUpdateStatusPreparingConfig = 1, // The item update is processing configuration data k_EItemUpdateStatusPreparingContent = 2, // The item update is reading and processing content files k_EItemUpdateStatusUploadingContent = 3, // The item update is uploading content changes to Steam k_EItemUpdateStatusUploadingPreviewFile = 4, // The item update is uploading new preview file image k_EItemUpdateStatusCommittingChanges = 5 // The item update is committing all changes }; enum EItemState { k_EItemStateNone = 0, // item not tracked on client k_EItemStateSubscribed = 1, // current user is subscribed to this item. Not just cached. k_EItemStateLegacyItem = 2, // item was created with ISteamRemoteStorage k_EItemStateInstalled = 4, // item is installed and usable (but maybe out of date) k_EItemStateNeedsUpdate = 8, // items needs an update. Either because it's not installed yet or creator updated content k_EItemStateDownloading = 16, // item update is currently downloading k_EItemStateDownloadPending = 32, // DownloadItem() was called for this item, content isn't available until DownloadItemResult_t is fired }; enum EItemStatistic { k_EItemStatistic_NumSubscriptions = 0, k_EItemStatistic_NumFavorites = 1, k_EItemStatistic_NumFollowers = 2, k_EItemStatistic_NumUniqueSubscriptions = 3, k_EItemStatistic_NumUniqueFavorites = 4, k_EItemStatistic_NumUniqueFollowers = 5, k_EItemStatistic_NumUniqueWebsiteViews = 6, k_EItemStatistic_ReportScore = 7, k_EItemStatistic_NumSecondsPlayed = 8, k_EItemStatistic_NumPlaytimeSessions = 9, k_EItemStatistic_NumComments = 10, k_EItemStatistic_NumSecondsPlayedDuringTimePeriod = 11, k_EItemStatistic_NumPlaytimeSessionsDuringTimePeriod = 12, }; enum EItemPreviewType { k_EItemPreviewType_Image = 0, // standard image file expected (e.g. jpg, png, gif, etc.) k_EItemPreviewType_YouTubeVideo = 1, // video id is stored k_EItemPreviewType_Sketchfab = 2, // model id is stored k_EItemPreviewType_EnvironmentMap_HorizontalCross = 3, // standard image file expected - cube map in the layout // +---+---+-------+ // | |Up | | // +---+---+---+---+ // | L | F | R | B | // +---+---+---+---+ // | |Dn | | // +---+---+---+---+ k_EItemPreviewType_EnvironmentMap_LatLong = 4, // standard image file expected k_EItemPreviewType_ReservedMax = 255, // you can specify your own types above this value }; const uint32 kNumUGCResultsPerPage = 50; const uint32 k_cchDeveloperMetadataMax = 5000; // Details for a single published file/UGC struct SteamUGCDetails_t { PublishedFileId_t m_nPublishedFileId; EResult m_eResult; // The result of the operation. EWorkshopFileType m_eFileType; // Type of the file AppId_t m_nCreatorAppID; // ID of the app that created this file. AppId_t m_nConsumerAppID; // ID of the app that will consume this file. char m_rgchTitle[k_cchPublishedDocumentTitleMax]; // title of document char m_rgchDescription[k_cchPublishedDocumentDescriptionMax]; // description of document uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. uint32 m_rtimeCreated; // time when the published file was created uint32 m_rtimeUpdated; // time when the published file was last updated uint32 m_rtimeAddedToUserList; // time when the user added the published file to their list (not always applicable) ERemoteStoragePublishedFileVisibility m_eVisibility; // visibility bool m_bBanned; // whether the file was banned bool m_bAcceptedForUse; // developer has specifically flagged this item as accepted in the Workshop bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file // file/url information UGCHandle_t m_hFile; // The handle of the primary file UGCHandle_t m_hPreviewFile; // The handle of the preview file char m_pchFileName[k_cchFilenameMax]; // The cloud filename of the primary file int32 m_nFileSize; // Size of the primary file int32 m_nPreviewFileSize; // Size of the preview file char m_rgchURL[k_cchPublishedFileURLMax]; // URL (for a video or a website) // voting information uint32 m_unVotesUp; // number of votes up uint32 m_unVotesDown; // number of votes down float m_flScore; // calculated score // collection details uint32 m_unNumChildren; }; //----------------------------------------------------------------------------- // Purpose: Steam UGC support API //----------------------------------------------------------------------------- class ISteamUGC { public: // Query UGC associated with a user. Creator app id or consumer app id must be valid and be set to the current running app. unPage should start at 1. virtual UGCQueryHandle_t CreateQueryUserUGCRequest( AccountID_t unAccountID, EUserUGCList eListType, EUGCMatchingUGCType eMatchingUGCType, EUserUGCListSortOrder eSortOrder, AppId_t nCreatorAppID, AppId_t nConsumerAppID, uint32 unPage ) = 0; // Query for all matching UGC. Creator app id or consumer app id must be valid and be set to the current running app. unPage should start at 1. virtual UGCQueryHandle_t CreateQueryAllUGCRequest( EUGCQuery eQueryType, EUGCMatchingUGCType eMatchingeMatchingUGCTypeFileType, AppId_t nCreatorAppID, AppId_t nConsumerAppID, uint32 unPage ) = 0; // Query for the details of the given published file ids (the RequestUGCDetails call is deprecated and replaced with this) virtual UGCQueryHandle_t CreateQueryUGCDetailsRequest( PublishedFileId_t *pvecPublishedFileID, uint32 unNumPublishedFileIDs ) = 0; // Send the query to Steam CALL_RESULT( SteamUGCQueryCompleted_t ) virtual SteamAPICall_t SendQueryUGCRequest( UGCQueryHandle_t handle ) = 0; // Retrieve an individual result after receiving the callback for querying UGC virtual bool GetQueryUGCResult( UGCQueryHandle_t handle, uint32 index, SteamUGCDetails_t *pDetails ) = 0; virtual bool GetQueryUGCPreviewURL( UGCQueryHandle_t handle, uint32 index, OUT_STRING_COUNT(cchURLSize) char *pchURL, uint32 cchURLSize ) = 0; virtual bool GetQueryUGCMetadata( UGCQueryHandle_t handle, uint32 index, OUT_STRING_COUNT(cchMetadatasize) char *pchMetadata, uint32 cchMetadatasize ) = 0; virtual bool GetQueryUGCChildren( UGCQueryHandle_t handle, uint32 index, PublishedFileId_t* pvecPublishedFileID, uint32 cMaxEntries ) = 0; virtual bool GetQueryUGCStatistic( UGCQueryHandle_t handle, uint32 index, EItemStatistic eStatType, uint64 *pStatValue ) = 0; virtual uint32 GetQueryUGCNumAdditionalPreviews( UGCQueryHandle_t handle, uint32 index ) = 0; virtual bool GetQueryUGCAdditionalPreview( UGCQueryHandle_t handle, uint32 index, uint32 previewIndex, OUT_STRING_COUNT(cchURLSize) char *pchURLOrVideoID, uint32 cchURLSize, OUT_STRING_COUNT(cchURLSize) char *pchOriginalFileName, uint32 cchOriginalFileNameSize, EItemPreviewType *pPreviewType ) = 0; virtual uint32 GetQueryUGCNumKeyValueTags( UGCQueryHandle_t handle, uint32 index ) = 0; virtual bool GetQueryUGCKeyValueTag( UGCQueryHandle_t handle, uint32 index, uint32 keyValueTagIndex, OUT_STRING_COUNT(cchKeySize) char *pchKey, uint32 cchKeySize, OUT_STRING_COUNT(cchValueSize) char *pchValue, uint32 cchValueSize ) = 0; // Release the request to free up memory, after retrieving results virtual bool ReleaseQueryUGCRequest( UGCQueryHandle_t handle ) = 0; // Options to set for querying UGC virtual bool AddRequiredTag( UGCQueryHandle_t handle, const char *pTagName ) = 0; virtual bool AddExcludedTag( UGCQueryHandle_t handle, const char *pTagName ) = 0; virtual bool SetReturnOnlyIDs( UGCQueryHandle_t handle, bool bReturnOnlyIDs ) = 0; virtual bool SetReturnKeyValueTags( UGCQueryHandle_t handle, bool bReturnKeyValueTags ) = 0; virtual bool SetReturnLongDescription( UGCQueryHandle_t handle, bool bReturnLongDescription ) = 0; virtual bool SetReturnMetadata( UGCQueryHandle_t handle, bool bReturnMetadata ) = 0; virtual bool SetReturnChildren( UGCQueryHandle_t handle, bool bReturnChildren ) = 0; virtual bool SetReturnAdditionalPreviews( UGCQueryHandle_t handle, bool bReturnAdditionalPreviews ) = 0; virtual bool SetReturnTotalOnly( UGCQueryHandle_t handle, bool bReturnTotalOnly ) = 0; virtual bool SetReturnPlaytimeStats( UGCQueryHandle_t handle, uint32 unDays ) = 0; virtual bool SetLanguage( UGCQueryHandle_t handle, const char *pchLanguage ) = 0; virtual bool SetAllowCachedResponse( UGCQueryHandle_t handle, uint32 unMaxAgeSeconds ) = 0; // Options only for querying user UGC virtual bool SetCloudFileNameFilter( UGCQueryHandle_t handle, const char *pMatchCloudFileName ) = 0; // Options only for querying all UGC virtual bool SetMatchAnyTag( UGCQueryHandle_t handle, bool bMatchAnyTag ) = 0; virtual bool SetSearchText( UGCQueryHandle_t handle, const char *pSearchText ) = 0; virtual bool SetRankedByTrendDays( UGCQueryHandle_t handle, uint32 unDays ) = 0; virtual bool AddRequiredKeyValueTag( UGCQueryHandle_t handle, const char *pKey, const char *pValue ) = 0; // DEPRECATED - Use CreateQueryUGCDetailsRequest call above instead! virtual SteamAPICall_t RequestUGCDetails( PublishedFileId_t nPublishedFileID, uint32 unMaxAgeSeconds ) = 0; // Steam Workshop Creator API CALL_RESULT( CreateItemResult_t ) virtual SteamAPICall_t CreateItem( AppId_t nConsumerAppId, EWorkshopFileType eFileType ) = 0; // create new item for this app with no content attached yet virtual UGCUpdateHandle_t StartItemUpdate( AppId_t nConsumerAppId, PublishedFileId_t nPublishedFileID ) = 0; // start an UGC item update. Set changed properties before commiting update with CommitItemUpdate() virtual bool SetItemTitle( UGCUpdateHandle_t handle, const char *pchTitle ) = 0; // change the title of an UGC item virtual bool SetItemDescription( UGCUpdateHandle_t handle, const char *pchDescription ) = 0; // change the description of an UGC item virtual bool SetItemUpdateLanguage( UGCUpdateHandle_t handle, const char *pchLanguage ) = 0; // specify the language of the title or description that will be set virtual bool SetItemMetadata( UGCUpdateHandle_t handle, const char *pchMetaData ) = 0; // change the metadata of an UGC item (max = k_cchDeveloperMetadataMax) virtual bool SetItemVisibility( UGCUpdateHandle_t handle, ERemoteStoragePublishedFileVisibility eVisibility ) = 0; // change the visibility of an UGC item virtual bool SetItemTags( UGCUpdateHandle_t updateHandle, const SteamParamStringArray_t *pTags ) = 0; // change the tags of an UGC item virtual bool SetItemContent( UGCUpdateHandle_t handle, const char *pszContentFolder ) = 0; // update item content from this local folder virtual bool SetItemPreview( UGCUpdateHandle_t handle, const char *pszPreviewFile ) = 0; // change preview image file for this item. pszPreviewFile points to local image file, which must be under 1MB in size virtual bool RemoveItemKeyValueTags( UGCUpdateHandle_t handle, const char *pchKey ) = 0; // remove any existing key-value tags with the specified key virtual bool AddItemKeyValueTag( UGCUpdateHandle_t handle, const char *pchKey, const char *pchValue ) = 0; // add new key-value tags for the item. Note that there can be multiple values for a tag. virtual bool AddItemPreviewFile( UGCUpdateHandle_t handle, const char *pszPreviewFile, EItemPreviewType type ) = 0; // add preview file for this item. pszPreviewFile points to local file, which must be under 1MB in size virtual bool AddItemPreviewVideo( UGCUpdateHandle_t handle, const char *pszVideoID ) = 0; // add preview video for this item virtual bool UpdateItemPreviewFile( UGCUpdateHandle_t handle, uint32 index, const char *pszPreviewFile ) = 0; // updates an existing preview file for this item. pszPreviewFile points to local file, which must be under 1MB in size virtual bool UpdateItemPreviewVideo( UGCUpdateHandle_t handle, uint32 index, const char *pszVideoID ) = 0; // updates an existing preview video for this item virtual bool RemoveItemPreview( UGCUpdateHandle_t handle, uint32 index ) = 0; // remove a preview by index starting at 0 (previews are sorted) CALL_RESULT( SubmitItemUpdateResult_t ) virtual SteamAPICall_t SubmitItemUpdate( UGCUpdateHandle_t handle, const char *pchChangeNote ) = 0; // commit update process started with StartItemUpdate() virtual EItemUpdateStatus GetItemUpdateProgress( UGCUpdateHandle_t handle, uint64 *punBytesProcessed, uint64* punBytesTotal ) = 0; // Steam Workshop Consumer API CALL_RESULT( SetUserItemVoteResult_t ) virtual SteamAPICall_t SetUserItemVote( PublishedFileId_t nPublishedFileID, bool bVoteUp ) = 0; CALL_RESULT( GetUserItemVoteResult_t ) virtual SteamAPICall_t GetUserItemVote( PublishedFileId_t nPublishedFileID ) = 0; CALL_RESULT( UserFavoriteItemsListChanged_t ) virtual SteamAPICall_t AddItemToFavorites( AppId_t nAppId, PublishedFileId_t nPublishedFileID ) = 0; CALL_RESULT( UserFavoriteItemsListChanged_t ) virtual SteamAPICall_t RemoveItemFromFavorites( AppId_t nAppId, PublishedFileId_t nPublishedFileID ) = 0; CALL_RESULT( RemoteStorageSubscribePublishedFileResult_t ) virtual SteamAPICall_t SubscribeItem( PublishedFileId_t nPublishedFileID ) = 0; // subscribe to this item, will be installed ASAP CALL_RESULT( RemoteStorageUnsubscribePublishedFileResult_t ) virtual SteamAPICall_t UnsubscribeItem( PublishedFileId_t nPublishedFileID ) = 0; // unsubscribe from this item, will be uninstalled after game quits virtual uint32 GetNumSubscribedItems() = 0; // number of subscribed items virtual uint32 GetSubscribedItems( PublishedFileId_t* pvecPublishedFileID, uint32 cMaxEntries ) = 0; // all subscribed item PublishFileIDs // get EItemState flags about item on this client virtual uint32 GetItemState( PublishedFileId_t nPublishedFileID ) = 0; // get info about currently installed content on disc for items that have k_EItemStateInstalled set // if k_EItemStateLegacyItem is set, pchFolder contains the path to the legacy file itself (not a folder) virtual bool GetItemInstallInfo( PublishedFileId_t nPublishedFileID, uint64 *punSizeOnDisk, OUT_STRING_COUNT( cchFolderSize ) char *pchFolder, uint32 cchFolderSize, uint32 *punTimeStamp ) = 0; // get info about pending update for items that have k_EItemStateNeedsUpdate set. punBytesTotal will be valid after download started once virtual bool GetItemDownloadInfo( PublishedFileId_t nPublishedFileID, uint64 *punBytesDownloaded, uint64 *punBytesTotal ) = 0; // download new or update already installed item. If function returns true, wait for DownloadItemResult_t. If the item is already installed, // then files on disk should not be used until callback received. If item is not subscribed to, it will be cached for some time. // If bHighPriority is set, any other item download will be suspended and this item downloaded ASAP. virtual bool DownloadItem( PublishedFileId_t nPublishedFileID, bool bHighPriority ) = 0; // game servers can set a specific workshop folder before issuing any UGC commands. // This is helpful if you want to support multiple game servers running out of the same install folder virtual bool BInitWorkshopForGameServer( DepotId_t unWorkshopDepotID, const char *pszFolder ) = 0; // SuspendDownloads( true ) will suspend all workshop downloads until SuspendDownloads( false ) is called or the game ends virtual void SuspendDownloads( bool bSuspend ) = 0; // usage tracking CALL_RESULT( StartPlaytimeTrackingResult_t ) virtual SteamAPICall_t StartPlaytimeTracking( PublishedFileId_t *pvecPublishedFileID, uint32 unNumPublishedFileIDs ) = 0; CALL_RESULT( StopPlaytimeTrackingResult_t ) virtual SteamAPICall_t StopPlaytimeTracking( PublishedFileId_t *pvecPublishedFileID, uint32 unNumPublishedFileIDs ) = 0; CALL_RESULT( StopPlaytimeTrackingResult_t ) virtual SteamAPICall_t StopPlaytimeTrackingForAllItems() = 0; // parent-child relationship or dependency management CALL_RESULT( AddUGCDependencyResult_t ) virtual SteamAPICall_t AddDependency( PublishedFileId_t nParentPublishedFileID, PublishedFileId_t nChildPublishedFileID ) = 0; CALL_RESULT( RemoveUGCDependencyResult_t ) virtual SteamAPICall_t RemoveDependency( PublishedFileId_t nParentPublishedFileID, PublishedFileId_t nChildPublishedFileID ) = 0; // add/remove app dependence/requirements (usually DLC) CALL_RESULT( AddAppDependencyResult_t ) virtual SteamAPICall_t AddAppDependency( PublishedFileId_t nPublishedFileID, AppId_t nAppID ) = 0; CALL_RESULT( RemoveAppDependencyResult_t ) virtual SteamAPICall_t RemoveAppDependency( PublishedFileId_t nPublishedFileID, AppId_t nAppID ) = 0; // request app dependencies. note that whatever callback you register for GetAppDependenciesResult_t may be called multiple times // until all app dependencies have been returned CALL_RESULT( GetAppDependenciesResult_t ) virtual SteamAPICall_t GetAppDependencies( PublishedFileId_t nPublishedFileID ) = 0; // delete the item without prompting the user CALL_RESULT( DeleteItemResult_t ) virtual SteamAPICall_t DeleteItem( PublishedFileId_t nPublishedFileID ) = 0; }; #define STEAMUGC_INTERFACE_VERSION "STEAMUGC_INTERFACE_VERSION010" //----------------------------------------------------------------------------- // Purpose: Callback for querying UGC //----------------------------------------------------------------------------- struct SteamUGCQueryCompleted_t { enum { k_iCallback = k_iClientUGCCallbacks + 1 }; UGCQueryHandle_t m_handle; EResult m_eResult; uint32 m_unNumResultsReturned; uint32 m_unTotalMatchingResults; bool m_bCachedData; // indicates whether this data was retrieved from the local on-disk cache }; //----------------------------------------------------------------------------- // Purpose: Callback for requesting details on one piece of UGC //----------------------------------------------------------------------------- struct SteamUGCRequestUGCDetailsResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 2 }; SteamUGCDetails_t m_details; bool m_bCachedData; // indicates whether this data was retrieved from the local on-disk cache }; //----------------------------------------------------------------------------- // Purpose: result for ISteamUGC::CreateItem() //----------------------------------------------------------------------------- struct CreateItemResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 3 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; // new item got this UGC PublishFileID bool m_bUserNeedsToAcceptWorkshopLegalAgreement; }; //----------------------------------------------------------------------------- // Purpose: result for ISteamUGC::SubmitItemUpdate() //----------------------------------------------------------------------------- struct SubmitItemUpdateResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 4 }; EResult m_eResult; bool m_bUserNeedsToAcceptWorkshopLegalAgreement; PublishedFileId_t m_nPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: a Workshop item has been installed or updated //----------------------------------------------------------------------------- struct ItemInstalled_t { enum { k_iCallback = k_iClientUGCCallbacks + 5 }; AppId_t m_unAppID; PublishedFileId_t m_nPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: result of DownloadItem(), existing item files can be accessed again //----------------------------------------------------------------------------- struct DownloadItemResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 6 }; AppId_t m_unAppID; PublishedFileId_t m_nPublishedFileId; EResult m_eResult; }; //----------------------------------------------------------------------------- // Purpose: result of AddItemToFavorites() or RemoveItemFromFavorites() //----------------------------------------------------------------------------- struct UserFavoriteItemsListChanged_t { enum { k_iCallback = k_iClientUGCCallbacks + 7 }; PublishedFileId_t m_nPublishedFileId; EResult m_eResult; bool m_bWasAddRequest; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to SetUserItemVote() //----------------------------------------------------------------------------- struct SetUserItemVoteResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 8 }; PublishedFileId_t m_nPublishedFileId; EResult m_eResult; bool m_bVoteUp; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to GetUserItemVote() //----------------------------------------------------------------------------- struct GetUserItemVoteResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 9 }; PublishedFileId_t m_nPublishedFileId; EResult m_eResult; bool m_bVotedUp; bool m_bVotedDown; bool m_bVoteSkipped; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to StartPlaytimeTracking() //----------------------------------------------------------------------------- struct StartPlaytimeTrackingResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 10 }; EResult m_eResult; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to StopPlaytimeTracking() //----------------------------------------------------------------------------- struct StopPlaytimeTrackingResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 11 }; EResult m_eResult; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to AddDependency //----------------------------------------------------------------------------- struct AddUGCDependencyResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 12 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; PublishedFileId_t m_nChildPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to RemoveDependency //----------------------------------------------------------------------------- struct RemoveUGCDependencyResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 13 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; PublishedFileId_t m_nChildPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to AddAppDependency //----------------------------------------------------------------------------- struct AddAppDependencyResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 14 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; AppId_t m_nAppID; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to RemoveAppDependency //----------------------------------------------------------------------------- struct RemoveAppDependencyResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 15 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; AppId_t m_nAppID; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to GetAppDependencies. Callback may be called // multiple times until all app dependencies have been returned. //----------------------------------------------------------------------------- struct GetAppDependenciesResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 16 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; AppId_t m_rgAppIDs[32]; uint32 m_nNumAppDependencies; // number returned in this struct uint32 m_nTotalNumAppDependencies; // total found }; //----------------------------------------------------------------------------- // Purpose: The result of a call to DeleteItem //----------------------------------------------------------------------------- struct DeleteItemResult_t { enum { k_iCallback = k_iClientUGCCallbacks + 17 }; EResult m_eResult; PublishedFileId_t m_nPublishedFileId; }; #pragma pack( pop ) #endif // ISTEAMUGC_H
[ "nick@zaphop.com" ]
nick@zaphop.com
f507e5bb6456db79a6576bd6e0f0b279958179ec
b24c8b02807377cdc70ba226f275cf738aba2220
/Module04/ex03/IMateriaSource.hpp
cb489072f45c4dfecc9140805459b380fe998a12
[]
no_license
Saadelfadil/Cplusplus
a619708999a5cab0c50d33b5be3318e6c6409b39
99121d3cff2a914c418d7b5ca66ed8f6d7a65f4f
refs/heads/main
2023-08-25T02:46:40.542522
2021-10-05T19:50:08
2021-10-05T19:50:08
352,775,594
0
0
null
null
null
null
UTF-8
C++
false
false
1,277
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* IMateriaSource.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sel-fadi <sel-fadi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/11 13:13:46 by sel-fadi #+# #+# */ /* Updated: 2021/07/15 19:18:36 by sel-fadi ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef IMATERIASOURCE_HPP # define IMATERIASOURCE_HPP # include <iostream> # include <string> # include "AMateria.hpp" class IMateriaSource { public: virtual ~IMateriaSource() {} virtual void learnMateria(AMateria*) = 0; virtual AMateria* createMateria(std::string const & type) = 0; }; #endif /* ******************************************************** IMATERIASOURCE_H */
[ "saadelfadil18@gmail.com" ]
saadelfadil18@gmail.com
18263d045d8d89d8876f872b98a7fae8c22bf887
401852dcbbabb0c1efd168d24dfdc5e265dc3148
/stack/deleteMiddle.cpp
05ebd4af42770c7fdb11243710f7fae6e161f373
[]
no_license
radhikaarajput/Competitive_Programming
85090db5d26cb6c5fa4e9cbd3e6482c818127894
f974efa92972b4f992cb5c6f778c669016b00ca8
refs/heads/master
2023-06-10T08:23:59.419847
2021-06-22T13:28:53
2021-06-22T13:28:53
370,107,313
0
0
null
null
null
null
UTF-8
C++
false
false
863
cpp
#include <iostream> #include<cmath> #include <stack> using namespace std; /* Approach use a recusive fn pop all elememts in stack and store them in a variable call recusive f till all elemenst pop cout push all ements in stack again (x) except the middle eleemnts i.e. (n+1)/2 */ void del_mid(stack<int>s,int n,int cur); int main() { stack<int>s; int n,x,i,cur=0; cin>>n; for(i=0;i<n;i++) { cin>>x; s.push(x); } del_mid(s,n,cur); return 0; } void del_mid(stack<int>s,int n, int cur=0) { stack<int>s2; while(!s.empty()) { int z=s.top(); s.pop(); if(cur != floor(n/2)+1) { s2.push(z); cur++; } } while(!s2.empty()) { cout<<s2.top()<<" "; s2.pop(); } }
[ "rajputradhika20177@gmail.com" ]
rajputradhika20177@gmail.com
3071ab018fc7cab0d27b196e368b128e501da2fd
19eb97436a3be9642517ea9c4095fe337fd58a00
/private/inet/mshtml/btools/pdlparse/pdlparse.hxx
ad969645a6260ebfb535250e0357a6088dacb4a9
[]
no_license
oturan-boga/Windows2000
7d258fd0f42a225c2be72f2b762d799bd488de58
8b449d6659840b6ba19465100d21ca07a0e07236
refs/heads/main
2023-04-09T23:13:21.992398
2021-04-22T11:46:21
2021-04-22T11:46:21
360,495,781
2
0
null
null
null
null
UTF-8
C++
false
false
22,823
hxx
#define COLLECT_STATISTICS 0 // Set to 1 to enable statics gathering extern const char *rgszCcssString[]; #define CCSSF_NONE 0 // no flags #define CCSSF_CLEARCACHES 1 // clear the caches when changing #define CCSSF_REMEASURECONTENTS 2 // need to resize site after changing this #define CCSSF_SIZECHANGED 4 // notify the parent of a size change. #define CCSSF_REMEASUREINPARENT 8 // remeasure in parent layout's context #define CCSSF_CLEARFF 16 // clear the caches when changing #define CCSSF_REMEASUREALLCONTENTS 32 // resize self & all nested layout elements struct CCachedAttrArrayInfo { char *szDispId; DWORD dwFlags; }; enum StorageType { STORAGETYPE_OTHER, STORAGETYPE_NUMBER, STORAGETYPE_STRING, }; struct AssociateDataType { char *szKey; char *szValue; char *szMethodFnPrefix; StorageType stStorageType; }; struct Associate { char *szKey; char *szValue; }; // Maximum allowed length of a parse line #define MAX_LINE_LEN 2048 // Max number of tags per token #define MAX_TAGS 63 #define MAX_SUBTOKENS 8 class CString { char szString [ MAX_LINE_LEN+1 ]; public: CString() { szString [ 0 ] = '\0'; } BOOL operator== ( LPCSTR szStr1 ) { return _stricmp ( (const char *)szString, (const char *)szStr1 ) == 0 ? TRUE : FALSE; } #ifndef UNIX static BOOL operator== ( const CString& szStr1, LPCSTR szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? TRUE : FALSE; } static BOOL operator== ( LPCSTR szStr1, const CString &szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? TRUE : FALSE; } #endif BOOL operator!= ( LPCSTR szStr1 ) { return _stricmp ( (const char *)szString, (const char *)szStr1 ) == 0 ? FALSE : TRUE; } #ifndef UNIX static BOOL operator!= ( const CString& szStr1, LPCSTR szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? FALSE : TRUE; } static BOOL operator!= ( LPCSTR szStr1, const CString &szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? FALSE : TRUE; } #endif const CString &operator= ( LPCSTR pStr ) { strcpy ( szString, pStr ); return *this; } const CString &operator+= ( LPCSTR pStr ) { strcat ( szString, pStr ); return *this; } const CString &operator+ ( CString szStr ) { strcat ( szString, (LPCSTR)szStr ); return *this; } const CString &operator+ ( LPCSTR pStr ) { strcat ( szString, pStr ); return *this; } char operator[] ( INT nIndex ) { return szString [ nIndex ]; } operator LPCSTR () const { return (const char *)szString; } CString &ToUpper () { _strupr ( szString ); return *this; } int Length ( void ) { return strlen ( szString ); } char * FindChar ( char ch ) { return strchr(szString, ch); } UINT Lookup ( Associate *pArray, LPCSTR pStr ); UINT Lookup ( AssociateDataType *pArray, LPCSTR pStr ); }; #ifdef UNIX inline BOOL operator== ( const CString& szStr1, LPCSTR szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? TRUE : FALSE; } inline BOOL operator== ( LPCSTR szStr1, const CString &szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? TRUE : FALSE; } inline BOOL operator== ( const CString& szStr1, const CString& szStr2) { return _stricmp( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? TRUE : FALSE; } inline BOOL operator!= ( const CString& szStr1, LPCSTR szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? FALSE : TRUE; } #if 0 // apogee can't tell the difference between these two. inline BOOL operator!= ( LPCSTR szStr1, const CString &szStr2 ) { return _stricmp ( (LPCSTR)szStr1, (LPCSTR)szStr2 ) == 0 ? FALSE : TRUE; } #endif #endif struct TagDescriptor { char *szTag; BOOL fIsFlag; BOOL fIsRequired; BOOL fRefersToClass; }; // This enum must match the order that the corresponding structs appear in AllDescriptors enum DESCRIPTOR_TYPE; class TagArray { char *szValues [ MAX_TAGS ]; static char *szEmptyString; public: BOOL AddTag ( int iTag, LPCSTR szStr, int nLen ); TagArray() { INT i; for ( i = 0 ; i < MAX_TAGS ; i++ ) { szValues [ i ] = NULL; } } ~TagArray() { INT i; for ( i = 0 ; i < MAX_TAGS ; i++ ) { if ( szValues [ i ] ) delete szValues [ i ]; } } BOOL CompareTag ( INT nIndex, char *szWith ); char *GetTagValue ( INT nIndex ); BOOL IsSet ( INT nIndex ) { return szValues [ nIndex ] == NULL ? FALSE : TRUE; } // Only use this method if you must - use GetTagValue normaly char *GetInternalValue ( INT nIndex ) { return szValues [ nIndex ]; } }; struct TokenDescriptor; class CTokenList; class Token { friend class CRuntimeTokenList; friend class CPDLParser; friend class CTokenList; friend class CTokenListWalker; protected: DESCRIPTOR_TYPE nType; // Calculate bitwise enum vaklidation mask UINT uEnumMask; UINT nNextEnumValue; // Token *_pNextToken; CTokenList *_pChildList; public: Token ( DESCRIPTOR_TYPE nDescriptorType ) { nType = nDescriptorType; uEnumMask = 0; nNextEnumValue = 0; _pNextToken = NULL; _pChildList = NULL; } void Clone ( Token *pFrom ); ~Token(); TagArray TagValues; // Array of values size == nTag BOOL CompareTag ( INT nIndex, char *szWith ) { return TagValues.CompareTag ( nIndex, szWith ); } char *GetTagValue ( INT nIndex ) { return TagValues.GetTagValue ( nIndex ); } BOOL AddTag ( int iTag, LPCSTR szStr, int nLen = -1 ) { if ( nLen == -1 ) nLen = strlen ( szStr ); return TagValues.AddTag ( iTag, szStr, nLen ); } BOOL IsSet ( INT nIndex ) { return TagValues.IsSet ( nIndex ); } // Sets a flag value to TRUE BOOL Set ( INT nIndex ) { return TagValues.AddTag ( nIndex, "", 1 ); } void AddParam ( CString &szArg, INT nTag, LPCSTR szText ); void AddParamStr ( CString &szArg, INT nTag, LPCSTR szText ); void GetTagValueOrDefault ( CString &szArg, INT nTag, LPCSTR szDefault ) { if ( IsSet ( nTag ) ) szArg = (LPCSTR)GetTagValue ( nTag ); else szArg = (LPCSTR)szDefault; } DESCRIPTOR_TYPE GetType ( void ) const { return nType; } void SetNextToken ( Token *pToken ) { _pNextToken = pToken; } Token *GetNextToken ( void ) const { return _pNextToken; } Token *AddChildToken ( DESCRIPTOR_TYPE nType ); void CalculateEnumMask ( Token *pParentToken ); UINT GetChildTokenCount ( void ); }; struct TokenDescriptor { char *szTokenName; BOOL fIsParentToken; TagDescriptor Tags [MAX_TAGS]; // BOOL LookupTagName ( char *szTag, int nTagLen, INT *pnIndex ) { for ( *pnIndex = 0 ; Tags [ *pnIndex ].szTag != NULL ; (*pnIndex)++ ) { if ( _strnicmp ( Tags [ *pnIndex ].szTag, szTag, nTagLen ) == 0 ) { // Descriptors never have an entry for the "name", so // the actual tag array index is always 1 more than the // corresponding descriptor index (*pnIndex)++; return TRUE; } } return FALSE; } }; class CTokenList { private: // Linked list of all tokens Token *_pFirstToken; // Pointer to last item in token list Token *_pLastToken; // Count of number of tokens in list UINT _uTokens; ULONG ulRefs; // protect out destructor so people don't delete us, use Release() instead ~CTokenList(); public: CTokenList() { _pFirstToken = NULL; _pLastToken = NULL; _uTokens = 0; ulRefs = 1; } Token *AddNewToken ( DESCRIPTOR_TYPE nTokenDescriptor ); Token *FindToken ( char *pTokenName, DESCRIPTOR_TYPE nType ) const; Token *GetFirst ( void ) const { return _pFirstToken; } UINT GetTokenCount ( void ) const { return _uTokens; } // We reference count to simplify Cloning of arg lists // for ref properties void AddRef ( void ) { ulRefs++; }; void Release ( void ) { if ( --ulRefs == 0 ) delete this; } }; class CTokenListWalker { private: CTokenList *_pList; Token *_pCurrentToken; char *_pszFileName; BOOL _fInCurrentFile; BOOL _fAtEnd; private: Token *GetNextToken ( void ) { if ( _fAtEnd || _pList == NULL ) { return NULL; } if ( _pCurrentToken == NULL ) _pCurrentToken = _pList -> GetFirst (); else { _pCurrentToken = _pCurrentToken -> GetNextToken(); if ( _pCurrentToken == NULL ) _fAtEnd = TRUE; } return _pCurrentToken; } public: Token *CurrentToken ( void ) { return _pCurrentToken; } void Reset ( void ); // Generic walker CTokenListWalker ( CTokenList *pList ) { _pList = pList; _pszFileName = NULL; Reset(); } // Walker that will just walk definitions in a given pdl file CTokenListWalker ( CTokenList *pList, char *pszFileName ) { _pList = pList; _pszFileName = pszFileName; Reset(); } // Child token list walker CTokenListWalker ( Token *pParentToken ) { if ( pParentToken ) _pList = pParentToken -> _pChildList; else _pList = NULL; _pszFileName = NULL; Reset(); } Token *GetNext ( void ); Token *GetNext ( DESCRIPTOR_TYPE Type, LPCSTR pName = NULL ); UINT GetTokenCount ( void ) { return _pList ? _pList -> GetTokenCount() : 0; } BOOL IsGenericWalker ( void ) { return _pszFileName == 0; } }; struct PropdescInfo{ LPCSTR _szClass; LPCSTR _szPropName; BOOL _fAppendA; BOOL _fProperty; // TRUE if property FALSE if method UINT _uVTblIndex; // VTable Index of method or first Property (Get or Set) LPCSTR _szAttrName; LPCSTR _szSortKey; void Set(LPCSTR szClass, LPCSTR szPropName, BOOL fAppendA, LPCSTR szAttrName, UINT uVTblIndex = 0, BOOL fProperty = TRUE) { _szClass = szClass; _szPropName = szPropName; _fAppendA = fAppendA; _szAttrName = szAttrName; // If szAttribute specified, use that to override property name for sorting. _szSortKey = strlen(szAttrName) ? szAttrName : szPropName; _uVTblIndex = uVTblIndex; _fProperty = fProperty; } void SetVTable(LPCSTR szClass, LPCSTR szPropName, BOOL fAppendA, LPCSTR szAttrName, UINT uVTblIndex = 0, BOOL fProperty = TRUE) { _szClass = szClass; _szPropName = szPropName; _fAppendA = fAppendA; _szAttrName = szAttrName; // If szPropName use that it's the exported name else the szAttrName is the usd. _szSortKey = strlen(szPropName) ? szPropName : szAttrName; _uVTblIndex = uVTblIndex; _fProperty = fProperty; } }; #define MAX_ARGS 8 // Maximum # of args (w/ default parameters PDL handles) class CPDLParser { private: char *_pszPDLFileName; char *_pszOutputFileRoot; char *_pszInputFile; char *_pszOutputPath; CTokenList *pRuntimeList; FILE *fpHDLFile; FILE *fpIDLFile; FILE *fpHeaderFile; FILE *fpLOGFile; FILE *fpHTMFile; FILE *fpHTMIndexFile; FILE *fpDISPIDFile; FILE *fpMaxLenFile; int cOnFileSignatures; int cOnFileIIDs; char **rgszSignatures; char **rgszIIDs; int cSignatures; int cIIDs; int _numPropDescs; int _numVTblEntries; void RemoveSignatures ( void ); BOOL LoadSignatures ( char *pszOutputPath ); BOOL SaveSignatures ( char *pszOutputPath ); BOOL FindAndAddSignature ( LPCSTR szType, LPCSTR szSignature, LPSTR pszInvokeMethod ); int FindAndAddIIDs ( CString szInterface ); #if COLLECT_STATISTICS==1 #define MAX_STATS 20 #define NUM_PROPTURDS 0 // Number of code turds for all properties #define NUM_EMUMTURDS 1 // Number of code turds for enum properties #define NUM_GETENUMS 2 // Number of unique enum property gets per interface #define NUM_SETENUMS 3 // Number of unique enum property gets per interface #define NUM_GETPROPERTY 4 // Number of unique property sets per interface #define NUM_SETPROPERTY 5 // Number of unique property sets per interface long rgcStats[MAX_STATS]; void LoadStatistics ( char *pszOutputPath ); void SaveStatistics ( char *pszOutputPath ); void CollectStatistic (long lStatisticIdx, long lValue) { rgcStats[lStatisticIdx] = lValue; } long GetStatistic (long lStatisticIdx) { return rgcStats[lStatisticIdx]; } #endif // Used to use this fn, leaving it for posterity UINT CountTags ( TokenDescriptor *tokdesc ); // Token * IsSuperInterface( CString szSuper, Token * pInterface ); Token * FindMatchingEntryWOPropDesc(Token *pClass, Token *pToFindToken, BOOL fNameMatchOnly = FALSE); Token * FindMethodInInterfaceWOPropDesc(Token *pInterface, Token *pToFindToken, BOOL fNameMatchOnly = FALSE); void GenerateThunkContext ( Token *pClassToken ); void GenerateThunkContextImplemenation ( Token *pClassToken ); void GenerateSingleThunkContextPrototype ( Token *pClassToken, Token * pChildToken, BOOL fNodeContext ); void GenerateSingleThunkContextImplementation ( Token *pClassToken, Token * pChildToken, BOOL fNodeContext ); void GenerateClassDISPIDs ( void ); void GenerateInterfaceDISPIDs ( void ); void GenerateExternalInterfaceDISPIDs ( void ); void GenerateEventDISPIDs ( FILE *fp, BOOL fPutDIID ); BOOL ComputePROPDESC_STRUCT ( FILE *fp, Token *pClassToken, Token *pChild, CString & szHandler, CString & szFnPrefix ); Token * FindEnum ( Token *pChild ); char * MapTypeToIDispatch ( CString & szType ); BOOL ComputeProperty ( Token *pClassToken, Token *pChild ); BOOL ComputeMethod ( Token *pClassToken, Token *pChild ); BOOL BuildMethodSignature(Token *pChild, CString &szTypesSig, CString &szArgsType, BOOL &fBSTRArg, BOOL &fVARIANTArg, int &cArgs, int &cRequiredArgs, char *pDefaultParams[MAX_ARGS] = NULL, char *pDefaultStrParams[MAX_ARGS] = NULL); BOOL GeneratePROPDESCs ( void ); BOOL GeneratePROPDESCArray ( Token *pThisClassToken, int *pNumVTblEntries ); void GenerateVTableArray ( Token *pThisClassToken, int *pNumVTblEntries ); void SortPropDescInfo ( PropdescInfo *pPI, int cPDI ); BOOL ComputeVTable ( Token *pClass, Token *pInterface, BOOL fDerived, PropdescInfo *pPI, int *piPI, UINT *pUVTblIdx, BOOL fPrimaryTearoff = FALSE ); BOOL GeneratePropMethodImplementation ( void ); void SplitTag ( char *pStr, int nLen, char **pTag, int *pnTagLen, char **pValue, int *pnValueLen ); BOOL IsStoredAsString( Token *pClassToken ); BOOL LookupToken ( LPCSTR pTokenName, int nTokenLen, TokenDescriptor **ppTokenDescriptor, DESCRIPTOR_TYPE *pnTokenDes ); BOOL GetElem ( char **pStr, char **pElem, int *pnLen, BOOL fBreakOnOpenParenthesis = FALSE, BOOL fBreakOnCloseParenthesis = FALSE, BOOL fBreakOnComma=FALSE ); LPCSTR ConvertType ( LPCSTR szType ); BOOL ParseInputFile ( BOOL fDebugging ); BOOL GenerateHDLFile ( void ); void GenerateCPPEnumDefs ( void ); BOOL GetTypeDetails ( char *szTypeName, CString& szHandler, CString &szFnPrefix, StorageType *pStorageType = NULL ); void GenerateMethodImp ( Token *pClassToken, Token *pChildToken, BOOL fIsSet, CString &szHandler, CString &szHandlerArgs, CString &szOffsetOf, CString &szAType ); BOOL FindTearoffMethod ( Token *pTearoff, LPCSTR pszTearoffMethod, LPSTR pszUseTearoff); BOOL GenerateTearoffTable ( Token *pClassToken, Token *pTearoff, LPCSTR pszInterface, BOOL fMostDerived ); BOOL GenerateTearOffMethods ( LPCSTR szClassName, Token *pTearoff, LPCSTR szInterfaceName, BOOL fMostDerived = FALSE ); BOOL GenerateIDispatchTearoff(LPCSTR szClassName, Token *pTearoff, LPCSTR pszInterfaceName, BOOL fMostDerived = FALSE ); BOOL HasMondoDispInterface ( Token *pClassToken ); BOOL PatchInterfaceRefTypes ( void ); BOOL CloneToken ( Token *pChildToken, DESCRIPTOR_TYPE Type, INT nClassName, INT nTagName ); void GeneratePropMethodDecl ( Token *pClassToken ); void GenerateGetAAXImplementations ( Token *pClassToken ); void GenerateGetAAXPrototypes ( Token *pClassToken ); BOOL PrimaryTearoff (Token *pInterface); Token* NextTearoff (LPCSTR szClassname, Token *pLastTearoff = NULL); Token* FindTearoff (LPCSTR szClassname, LPCSTR szInterface); BOOL GenerateClassIncludes ( void ); BOOL GenerateEventFireDecl ( Token *pToken ); BOOL GenerateEventDecl ( Token *pClassToken, Token *pEventToken ); BOOL GenerateIDLFile ( char *szFileName ); void GenerateIDLInterfaceDecl ( Token *pInterfaceToken, char *pszGUID, char *pszSuper, BOOL fDispInterface = FALSE, Token *pClassToken = NULL ); void ComputePropType ( Token *pPropertyToken, CString &szProp, BOOL fComment ); void GenerateMkTypelibDecl ( Token *pInterfaceToken, BOOL fDispInterface = FALSE, Token *pClass =NULL ); void GenerateMidlInterfaceDecl ( Token *pInterfaceToken, char *pszGUID, char *pszSuper ); void GenerateCoClassDecl ( Token *pClassToken ); void GenerateEnumDescIDL ( Token *pEnumToken ); void ReportError ( LPCSTR szErrorString ); void GenerateHeaderFile ( void ); void GenerateIncludeStatement ( Token *pImportToken ); void GenerateIncludeInterface ( Token *pInterfaceToken ); void GenerateIncludeEnum(Token *pEnumToken, BOOL fSpitExtern, FILE *pFile = NULL); BOOL GenerateHTMFile ( void ); void GenerateArg ( Token *pArgToken ); void GenerateInterfaceArg ( Token *pArgToken ); void GenerateMethodHTM ( Token *pClassToken ); void GenerateInterfaceMethodHTM ( Token *pClassToken ); void GenerateEventMethodHTM ( Token *pClassToken ); void GenerateEnumHTM ( Token *pClassToken, char *pEnumPrefix ); void GeneratePropertiesHTM ( Token *pClassToken, BOOL fAttributes ); void GenerateInterfacePropertiesHTM ( Token *pIntfToken ); void GenerateStruct(Token *pStructToken, FILE *pFile); Token* FindInterface (CString szInterfaceMatch); Token* FindInterfaceLocally (CString szInterfaceMatch); BOOL IsPrimaryInterface(CString szInterface); Token* FindClass (CString szClassMatch); BOOL IsUniqueCPC ( Token *pClassToken ); BOOL FindTearoffProperty ( Token *pPropertyToken, LPSTR szTearoffMethod, LPSTR szTearOffClassName, LPSTR szPropArgs, BOOL fPropGet ); BOOL GeneratePropDescsInVtblOrder(Token *pClassToken, int *pNumVtblPropDescs); BOOL IsSpecialProperty(Token *pClassToken); BOOL IsSpecialTearoff(Token *pTearoff); const CCachedAttrArrayInfo* GetCachedAttrArrayInfo( LPCSTR szDispId ); // Manage a dynamic list of types CTokenList *pDynamicTypeList; CTokenList *pDynamicEventTypeList; enum { DATATYPE_NAME, DATATYPE_HANDLER, }; enum { TYPE_DATATYPE=-1 }; BOOL LookupType ( LPCSTR szTypeName, CString &szIntoString, CString &szFnPrefix, StorageType *pStorageType = NULL ); BOOL AddType ( LPCSTR szTypeName, LPCSTR szHandler ); BOOL LookupEventType ( CString &szIntoString, LPCSTR szTypeName ); BOOL AddEventType ( LPCSTR szTypeName, LPCSTR szVTSType ); BOOL PatchPropertyTypes ( void ); BOOL PatchInterfaces (); BOOL HasClassGotProperties ( Token *pClassToken ); Token *GetSuperClassTokenPtr ( Token *pClassToken ); Token *GetPropAbstractClassTokenPtr ( Token *pClassToken ); BOOL GeneratePropdescReference ( Token *pClassToken, BOOL fDerivedClass, PropdescInfo *pPI, int *pnPI ); void GeneratePropdescExtern ( Token *pClassToken, BOOL fRecurse = TRUE ); void Init ( void ); public: CPDLParser (); ~CPDLParser () { if (fpMaxLenFile) fclose(fpMaxLenFile); if ( fpHDLFile ) fclose ( fpHDLFile ); if ( fpHeaderFile ) fclose ( fpHeaderFile ); if ( fpIDLFile ) fclose ( fpIDLFile ); if ( fpLOGFile ) fclose ( fpLOGFile ); if ( fpDISPIDFile ) fclose ( fpDISPIDFile ); if ( fpHTMFile ) fclose ( fpHTMFile ); if ( fpHTMIndexFile ) fclose ( fpHTMIndexFile ); pRuntimeList -> Release(); pDynamicTypeList -> Release(); pDynamicEventTypeList -> Release(); } int Parse ( char *szInputFile, char *szOutputFileRoot, char *szPDLFileName, char *szOutputPath, BOOL fDebugging ); }; BOOL GetStdInLine ( char *szLineBuffer, int nMaxLen ); // Every Token array has a name as the first item #define NAME_TAG 0 // Always have this as the last element in the descriptor array #define END_OF_ARG_ARRAY { NULL, FALSE, FALSE } #define ARRAY_SIZE(ar) (sizeof(ar)/sizeof (ar[0]))
[ "mehmetyilmaz3371@gmail.com" ]
mehmetyilmaz3371@gmail.com
a50d12719ee5879ff038e0ff9d007602aadb8aa8
8565325365db437120a4ae8b97f2919e362be8a6
/Baekjoon/Graph/14502/14502.cpp
a6a235f5a47356f64bfef89e88caf82423e5a875
[]
no_license
FacerAin/Algorithm-Study
31e56ea9ba01cff0fb27211b62d6665f1620dbb5
ad7474c72d8a6c83a15880b86e931ac6f03893fd
refs/heads/master
2021-07-24T00:53:10.022607
2021-07-03T14:37:48
2021-07-03T14:37:48
194,530,669
0
0
null
null
null
null
UTF-8
C++
false
false
1,727
cpp
//14502번 연구소 #include <iostream> #include <queue> #include <utility> #include <algorithm> using namespace std; int wall_cnt = 0; int dy[4] = {1,-1,0,0}; int dx[4] = {0,0,1,-1}; int map[10][10]; int temp[10][10]; int check[10][10]; int N, M; int ans; queue<pair<int,int>> init_q; queue<pair<int,int>> q; void copyMap(){ for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ temp[i][j] = map[i][j]; } } } bool isInside(int a, int b){ return (a >= 0 && a < N) && (b >=0 && b < M); } void BFS(){ int v_map[10][10]; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ v_map[i][j] = temp[i][j]; } } q = init_q; while(!q.empty()){ int cur_y = q.front().first; int cur_x = q.front().second; q.pop(); for(int i = 0; i < 4; i++){ int next_y = cur_y + dy[i]; int next_x = cur_x + dx[i]; if(isInside(next_y,next_x) && v_map[next_y][next_x] == 0){ v_map[next_y][next_x] = 2; q.push(pair<int,int>(next_y,next_x)); } } } int sum = 0; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(v_map[i][j] == 0){ sum++; } } } ans = max(ans, sum); } void make_wall(int cnt){ if(cnt == 3){ BFS(); return; } for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ if(temp[i][j] == 0){ temp[i][j] = 1; make_wall(cnt+1); temp[i][j] = 0; } } } } int main(){ //시작 바이러스의 위치는 바뀌지 않는다. //큐를 한번 저장해두고 계속 복사해서 사용하자. cin >> N >> M; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ cin >> map[i][j]; if(map[i][j] == 2){ init_q.push(pair<int,int>(i,j)); } } } copyMap(); make_wall(0); cout << ans; return 0; }
[ "ywsong.dev@kakao.com" ]
ywsong.dev@kakao.com
b2b3f58f03f145868b41873e2de73f03fd969173
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/D/E/C/E/C/ADECEC.h
2690b682817f3caaa2ed7b19733f8781ab175d6b
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
67
h
#ifndef ADECEC_H namespace ADECEC { std::string run(); } #endif
[ "nakhyun@devsisters.com" ]
nakhyun@devsisters.com
f03ccfa02b8512af10704fcb8e3c595e935c276e
56ac25837e47a1fde7a76750a5b2b6dddd48989e
/NewSuperMarioBrosPC/MarioState.cpp
d795a699da20855b6da77e7e791dcc9e516980b7
[]
no_license
TranAnhMinh/NewSuperMarioBrosPC
1c0a459a3f719c148dc8a9cda5b69be61c5e4f16
d82eb4a48831fb5be401d7f2bad95cb5feb224fa
refs/heads/master
2021-01-23T02:05:21.421693
2015-11-27T14:40:15
2015-11-27T14:41:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,692
cpp
#include "MarioState.h" #include "MarioObject.h" #include <string> using namespace std; //================STATE==================== void MarioState::onAPress(){ //do nothing } void MarioState::onBPress(){ //do nothing } void MarioState::onCollision(Object* ob){ // do nothing } string MarioState::getName(){ return "mario_state"; } //================STATE SMALL============== const string MarioStateSmall::STATE_NAME = "mario_state_small"; string MarioStateSmall::getName(){ return STATE_NAME; } MarioStateSmall::MarioStateSmall(Mario* ob){//contructor MarioStateSmall::mMario = ob; } void MarioStateSmall::onAPress(){ //jump } void MarioStateSmall::onBPress(){ //do nothing } void MarioStateSmall::onCollision(Object* ob){ //xử lý va chạm khi mario ở trạng thái Small } //==================SATE_LARGE============== const string MarioStateLarge::STATE_NAME = "mario_state_large"; string MarioStateLarge::getName(){ return STATE_NAME; } MarioStateLarge::MarioStateLarge(Mario* ob){ MarioStateLarge::mMario = ob; } void MarioStateLarge::onAPress(){ //jump; } void MarioStateLarge::onBPress(){ //do nothing; } void MarioStateLarge::onCollision(Object* ob){ //xử lý va chạm trong trường hợp mario Lớn } //==================SATE_RACON============== const string MarioStateRacon::STATE_NAME = "mario_state_racon"; string MarioStateRacon::getName(){ return STATE_NAME; } MarioStateRacon::MarioStateRacon(Mario* ob){ MarioStateRacon::mMario = ob; } void MarioStateRacon::onAPress(){ //jump; } void MarioStateRacon::onBPress(){ //do nothing; } void MarioStateRacon::onCollision(Object* ob){ //xử lý va chạm trong trường hợp mario Lớn }
[ "whitefang.tcotw@gmail.com" ]
whitefang.tcotw@gmail.com
0358e12e39d57d6d5629c4e270cac5dbf01b5628
87ccab055884dace36a74d530790e70011b764d2
/a.2.7/a.2.7/main.cpp
0e3a92a024db741a4d7d94c7f81a1b090bd9d504
[]
no_license
matricir/ADS2020
70b841caca0bfe55baab81593440ad4d5716d7eb
cc8ca1d2cf0a2307d4b3283de4ea4e553f656341
refs/heads/master
2022-04-13T14:31:48.907499
2020-02-23T22:07:15
2020-02-23T22:07:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
cpp
// // 7.cpp // Assignment2 // // Created by Luis Alberto Perez on 2/17/20. // Copyright © 2020 Luis Alberto Perez. All rights reserved. // /* //If this shows up as copied I got this from myself as I am retaking this course CH08-320143 a2 p7.cpp Luis Alberto Perez l.perezoteiza@jacobs-university.de */ #include <iostream> #include <map> #include <iterator> #include <algorithm> #include <fstream> using namespace std; int main(){ map<string,string>A; string line; ifstream data; string in; data.open("data.txt");//open text file well be checking the names from int x = 0; int r = 0; string p; while(getline(data,line)) { r = x % 2; if(r == 0){ A[line]; p = line; }else { A.at(p) = line; } x++; } while(true){ getline(cin,in); auto it = A.find(in); if (it != A.end()){ std::cout << it->first<<" =>"<< it->second << '\n'; } else { cout << "Name not found!"<< endl; } } }
[ "noreply@github.com" ]
matricir.noreply@github.com
f99cc9e3dc05b4f41841d7d2a74d34cb2abc2e67
a2c3b3126cb130b3c6f498b674919fcff81752df
/include/entradas.hpp
e35ccd102a8bf1a5229a82b0a9823d8189e9829d
[]
no_license
DinoMah/PrimalPikachusDrugStore
78f88dfe27195c3d7fabf9376bda3dad21b27f46
06b14091a96425aefa8f7aacda848cda20526271
refs/heads/master
2022-12-31T14:45:24.333088
2020-10-16T18:47:30
2020-10-16T18:47:30
300,769,277
0
0
null
null
null
null
UTF-8
C++
false
false
117
hpp
#ifndef ENTRADAS_H #define ENTRADAS_H #include "../src/objeto.cpp" void entradas( objeto & ); #endif // ENTRADAS_H
[ "leithonpeas@hotmail.com" ]
leithonpeas@hotmail.com
48db3b06d5004c4e32604543a7f63aff01784031
330030bc578ce17ab3f795ded8060c5834aba601
/lower_or_upper.cpp
66bd55e15dc2c5e97fbd2d3541c6f42376ff680e
[]
no_license
pravinkumarkg/basic_programs_part1
6efcd0baa3ad34d1fa9a83377e2c120ba9827440
cddc58b780258f90d89f7ddfa0b46d3daed156c1
refs/heads/master
2020-07-07T12:30:06.975134
2019-09-07T07:27:14
2019-09-07T07:27:14
203,347,756
0
0
null
null
null
null
UTF-8
C++
false
false
170
cpp
#include <iostream> using namespace std; int main() { char ch; cin>>ch; if(ch>=97&&ch<=122) { cout<<"lowercase"; } else { cout<<"uppercase"; } return 0; }
[ "noreply@github.com" ]
pravinkumarkg.noreply@github.com
30622cb6f82a7f1ab45cdc1fc54ebe068e48bb4a
add092c3d2998e666fb633e809903c11b6f8d7c0
/Window.cpp
1e9a02c946f5e77e24c6bbd9c477ac8c93b88802
[]
no_license
rodreri/ProyectoPC-Grafica
f7cd263a23efc67b0f20c5757547e293881a26cc
76c391c30c96adcae639bace86bd01471f04e583
refs/heads/master
2023-08-15T01:29:31.594628
2021-08-13T23:13:17
2021-08-13T23:13:17
389,838,608
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,343
cpp
#include "Window.h" Window::Window() { width = 800; height = 600; for (size_t i = 0; i < 1024; i++) { keys[i] = 0; } } Window::Window(GLint windowWidth, GLint windowHeight) { width = windowWidth; height = windowHeight; muevex = 2.0f; for (size_t i = 0; i < 1024; i++) { keys[i] = 0; } } int Window::Initialise() { //Inicialización de GLFW if (!glfwInit()) { printf("Falló inicializar GLFW"); glfwTerminate(); return 1; } //Asignando variables de GLFW y propiedades de ventana glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //para solo usar el core profile de OpenGL y no tener retrocompatibilidad glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //CREAR VENTANA mainWindow = glfwCreateWindow(width, height, "Primer ventana", NULL, NULL); if (!mainWindow) { printf("Fallo en crearse la ventana con GLFW"); glfwTerminate(); return 1; } //Obtener tamaño de Buffer glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight); //asignar el contexto glfwMakeContextCurrent(mainWindow); //MANEJAR TECLADO y MOUSE createCallbacks(); //permitir nuevas extensiones glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { printf("Falló inicialización de GLEW"); glfwDestroyWindow(mainWindow); glfwTerminate(); return 1; } glEnable(GL_DEPTH_TEST); //HABILITAR BUFFER DE PROFUNDIDAD // Asignar valores de la ventana y coordenadas //Asignar Viewport glViewport(0, 0, bufferWidth, bufferHeight); //Callback para detectar que se está usando la ventana glfwSetWindowUserPointer(mainWindow, this); } void Window::createCallbacks() { glfwSetKeyCallback(mainWindow, ManejaTeclado); glfwSetCursorPosCallback(mainWindow, ManejaMouse); } GLfloat Window::getXChange() { GLfloat theChange = xChange; xChange = 0.0f; return theChange; } GLfloat Window::getYChange() { GLfloat theChange = yChange; yChange = 0.0f; return theChange; } void Window::ManejaTeclado(GLFWwindow* window, int key, int code, int action, int mode) { Window* theWindow = static_cast<Window*>(glfwGetWindowUserPointer(window)); if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (key == GLFW_KEY_Y) { theWindow->muevex += 1.0; } if (key == GLFW_KEY_U) { theWindow->muevex -= 1.0; } if (key == GLFW_KEY_C) { if (theWindow->numcamara > 4) { theWindow->numcamara = 0; } else { theWindow->numcamara++; } } if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) { theWindow->keys[key] = true; printf("se presiono la tecla %d'\n", key); } else if (action == GLFW_RELEASE) { theWindow->keys[key] = false; printf("se solto la tecla %d'\n", key); } } } void Window::ManejaMouse(GLFWwindow* window, double xPos, double yPos) { Window* theWindow = static_cast<Window*>(glfwGetWindowUserPointer(window)); if (theWindow->mouseFirstMoved) { theWindow->lastX = xPos; theWindow->lastY = yPos; theWindow->mouseFirstMoved = false; } theWindow->xChange = xPos - theWindow->lastX; theWindow->yChange = theWindow->lastY - yPos; theWindow->lastX = xPos; theWindow->lastY = yPos; } Window::~Window() { glfwDestroyWindow(mainWindow); glfwTerminate(); }
[ "rodreri@gmail.com" ]
rodreri@gmail.com
9781f8d6ddb220a928e80527e91f09e56c48ec47
2a4aeb44cb6609a3700787b902c1a265c5023a85
/week4/rational_calculator.cpp
e1dc3190d0a3b60e724393232439d62453e2d103
[]
no_license
RealAntonVoronov/coursera_cpp_white
1c262bc4af9084c4dbf06e56df53f62d3a0a8016
943edd004f69f4126d39a2fe2442b7a7506328dd
refs/heads/master
2023-08-21T02:39:21.363281
2021-09-22T12:11:32
2021-09-22T12:11:32
400,862,835
0
0
null
null
null
null
UTF-8
C++
false
false
2,529
cpp
#include <iostream> #include "numeric" using namespace std; class Rational { public: Rational() { p = 0; q = 1; } Rational(int numerator, int denominator) { if (denominator == 0) { throw invalid_argument("Invalid argument"); } else { int gcd = std::gcd(numerator, denominator); p = numerator / gcd; q = denominator / gcd; if (denominator < 0) { p *= -1; q *= -1; } } } int Numerator() const { return p; } int Denominator() const { return q; } private: int p, q; }; Rational operator * (const Rational& lhs, const Rational& rhs){ return {lhs.Numerator() * rhs.Numerator(), lhs.Denominator() * rhs.Denominator()}; } Rational operator / (const Rational& lhs, const Rational& rhs){ if (rhs.Numerator() == 0){ throw domain_error("Division by zero"); } else return Rational(lhs.Numerator() * rhs.Denominator(), lhs.Denominator() * rhs.Numerator()); } Rational operator + (const Rational& lhs, const Rational& rhs){ return {lhs.Numerator() * rhs.Denominator() + rhs.Numerator() * lhs.Denominator(), rhs.Denominator() * lhs.Denominator()}; } Rational operator - (const Rational& lhs, const Rational& rhs){ return {lhs.Numerator() * rhs.Denominator() - rhs.Numerator() * lhs.Denominator(), rhs.Denominator() * lhs.Denominator()}; } istream& operator >> (istream& input, Rational& rational){ int p, q; if (input >> p){ char sep; input >> sep; if (sep == '/'){ if(input >> q){ rational = Rational(p, q); return input; } } } return input; } ostream& operator << (ostream& output, const Rational& rational){ output << rational.Numerator() << "/" << rational.Denominator(); return output; } int main(){ char operation; Rational a, b; try{ cin >> a >> operation >> b; } catch (invalid_argument& ex){ cout << ex.what(); return 0; } if (operation == '+'){ cout << a + b; } else if (operation == '-'){ cout << a - b; } else if (operation == '*'){ cout << a * b; } else if (operation == '/'){ try{ cout << a / b; } catch (domain_error& ex){ cout << ex.what(); } } else cout << "Unknown operation\n"; return 0; }
[ "a.voronov3797@gmail.com" ]
a.voronov3797@gmail.com
a6ddde2528d0dd1a69cb6a23689d0fe391e4b602
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/Profile/UNIX_Profile_LINUX.hxx
ca28052bce17b2e492883dfe91186bced7aea68e
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,799
hxx
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_LINUX #ifndef __UNIX_PROFILE_PRIVATE_H #define __UNIX_PROFILE_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
a4a59e07f795395c9658f02199c57c9b65eaec10
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/深度优先搜索初步/P1219.cpp
7e1d70ac0f33adc9b2fef59e0cad5b1ea294954e
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
611
cpp
#include<iostream> #define MAXN 15 using namespace std; int a[MAXN],b[MAXN<<1],c[MAXN<<1],ans[MAXN],n=0,cnt=0; void dfs(int); int main() { int i=0; cin>>n; dfs(1); cout<<cnt<<endl; return 0; } void dfs(int x) { int i=0; if(x==n+1) { cnt++; if(cnt<=3) { for(i=1;i<=n;i++) { cout<<ans[i]<<' '; } cout<<endl; } return; } for(i=1;i<=n;i++) { if(a[i] || b[x+i] || c[i+n-x]) { continue; } a[i]=b[x+i]=c[i+n-x]=ans[x]=i; dfs(x+1); a[i]=b[x+i]=c[i+n-x]=ans[x]=0; } return; }
[ "3305049949@qq.com" ]
3305049949@qq.com
93249c18893b9b170d3f4daad5de2cac3daab93b
c6551fc92088db6d2a8481fd974994f1880ec198
/evita/dom/text/text_mutation_observer.h
8fec2e3de674a47e02f1486a2cbfd7ca9c4fc71f
[]
no_license
eval1749/evita
dd2c40180b32fada64dce4aad1f597a6beeade8a
4e9dd86009af091e213a208270ef9bd429fbb698
refs/heads/master
2022-10-16T23:10:07.605527
2022-10-04T07:35:37
2022-10-04T07:35:37
23,464,799
3
3
null
2015-09-19T20:33:38
2014-08-29T13:27:24
C++
UTF-8
C++
false
false
1,547
h
// Copyright (c) 1996-2014 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef EVITA_DOM_TEXT_TEXT_MUTATION_OBSERVER_H_ #define EVITA_DOM_TEXT_TEXT_MUTATION_OBSERVER_H_ #include <memory> #include <vector> #include "evita/ginx/scoped_persistent.h" #include "evita/ginx/scriptable.h" #include "evita/text/models/offset.h" namespace dom { class ScriptHost; class TextDocument; class TextMutationObserverInit; class TextMutationRecord; namespace bindings { class TextMutationObserverClass; } ////////////////////////////////////////////////////////////////////// // // TextMutationObserver implements IDL interface |TextMutationObserver|. // class TextMutationObserver final : public ginx::Scriptable<TextMutationObserver> { DECLARE_SCRIPTABLE_OBJECT(TextMutationObserver); public: class Tracker; ~TextMutationObserver() final; private: friend class bindings::TextMutationObserverClass; TextMutationObserver(ScriptHost* script_host, v8::Local<v8::Function> callback); // Bindings void Disconnect(); void Observe(TextDocument* document, const TextMutationObserverInit& options); std::vector<TextMutationRecord*> TakeRecords(); const ginx::ScopedPersistent<v8::Function> callback_; ScriptHost* const script_host_; std::vector<std::unique_ptr<Tracker>> trackers_; DISALLOW_COPY_AND_ASSIGN(TextMutationObserver); }; } // namespace dom #endif // EVITA_DOM_TEXT_TEXT_MUTATION_OBSERVER_H_
[ "eval1749@gmail.com" ]
eval1749@gmail.com
867e98dcb4c6105e52688fb25fd9ff6a5d972852
e09287b0da2feb548d8c7dd307a0119e6ae65f4d
/menge_core/src/BFSM/Actions/ObstacleAction.cpp
d3189d35046b3bb2be2dcacea845975b282d6af5
[]
no_license
flztiii/menge_ros
ee52f37a0aa710c6128c047a4c4e3d25832bfe7b
af50499f90117a29ea8bddd1b496dead232b5ec0
refs/heads/master
2023-03-18T10:57:48.634069
2017-08-23T19:34:27
2017-08-23T19:34:27
510,190,699
1
1
null
2022-07-04T02:48:29
2022-07-04T02:48:29
null
WINDOWS-1252
C++
false
false
5,200
cpp
/* License Menge Copyright © and trademark ™ 2012-14 University of North Carolina at Chapel Hill. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and non-profit purposes, without fee, and without a written agreement is hereby granted, provided that the above copyright notice, this paragraph, and the following four paragraphs appear in all copies. This software program and documentation are copyrighted by the University of North Carolina at Chapel Hill. The software program and documentation are supplied "as is," without any accompanying services from the University of North Carolina at Chapel Hill or the authors. The University of North Carolina at Chapel Hill and the authors do not warrant that the operation of the program will be uninterrupted or error-free. The end-user understands that the program was developed for research purposes and is advised not to rely exclusively on the program for any reason. IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. Any questions or comments should be sent to the authors {menge,geom}@cs.unc.edu */ #include "Actions/ObstacleAction.h" #include "BaseAgent.h" namespace Menge { namespace BFSM { ///////////////////////////////////////////////////////////////////// // Implementation of ObstacleAction ///////////////////////////////////////////////////////////////////// ObstacleAction::ObstacleAction():Action(), _setOperand(0),_originalMap() { } ///////////////////////////////////////////////////////////////////// ObstacleAction::~ObstacleAction() { // Is this delete safe? This may require a destroy method if it is // instantiated in MengeCore and used in external dll _originalMap.clear(); } ///////////////////////////////////////////////////////////////////// void ObstacleAction::onEnter( Agents::BaseAgent * agent ) { _lock.lock(); if ( _undoOnExit ) _originalMap[ agent->_id ] = agent->_obstacleSet; agent->_obstacleSet = newValue( agent->_obstacleSet ); _lock.release(); } ///////////////////////////////////////////////////////////////////// void ObstacleAction::leaveAction( Agents::BaseAgent * agent ) { _lock.lock(); std::map< size_t, size_t >::iterator itr = _originalMap.begin(); assert( itr != _originalMap.end() && "Trying to find an original value for an agent whose value was not cached" ); agent->_obstacleSet = itr->second; _originalMap.erase( itr ); _lock.release(); } ///////////////////////////////////////////////////////////////////// // Implementation of ObstacleActFactory ///////////////////////////////////////////////////////////////////// ObstacleActFactory::ObstacleActFactory():ActionFactory() { _operandID = _attrSet.addSizeTAttribute( "operand", true /*required*/ ); } ///////////////////////////////////////////////////////////////////// bool ObstacleActFactory::setFromXML( Action * action, TiXmlElement * node, const std::string & behaveFldr ) const { ObstacleAction * oAction = dynamic_cast< ObstacleAction * >( action ); assert( oAction != 0x0 && "Trying to set obstacle set action properties on an incompatible object" ); if ( ! ActionFactory::setFromXML( action, node, behaveFldr ) ) return false; oAction->_setOperand = _attrSet.getSizeT( _operandID ); return true; } ///////////////////////////////////////////////////////////////////// // Implementation of RemoveObstacleSetAction ///////////////////////////////////////////////////////////////////// size_t RemoveObstacleSetAction::newValue( size_t value ) { return value & (~_setOperand); } ///////////////////////////////////////////////////////////////////// // Implementation of AddObstacleSetAction ///////////////////////////////////////////////////////////////////// size_t AddObstacleSetAction::newValue( size_t value ) { return value | _setOperand; } ///////////////////////////////////////////////////////////////////// // Implementation of SetObstacleSetAction ///////////////////////////////////////////////////////////////////// size_t SetObstacleSetAction::newValue( size_t value ) { return _setOperand; } } // namespace BFSM } // namespace Menge
[ "anooparoor@Minerva.cs.hunter.cuny.edu" ]
anooparoor@Minerva.cs.hunter.cuny.edu
583c9162629b16adaa3a4ed61f451939695064c4
58337d1029cfc8b830408cd2f7053237e6c40d06
/song.h
5898cf5393b58544aa9c74b001b71dab9d0aa2d2
[]
no_license
JustviCiT/QTXMLParser
14300bc38a1f7c77b68e7a1bab16c38bcbdde4b7
de50db19f483c170b1dd83132abc5a18bd082e40
refs/heads/master
2020-09-03T03:35:17.742368
2019-11-04T09:12:16
2019-11-04T09:12:16
219,376,169
0
0
null
null
null
null
UTF-8
C++
false
false
426
h
#ifndef SONG_H #define SONG_H #include <QObject> #include <QDebug> class Song { public: explicit Song(); void print(); void setArtist(QString); void setiD(int); void setAlbum(QString); void setFav(bool); void setID(int); QString gArtist(); QString gAlbum(); bool gFav(); int giD(); private: int id; QString artist; QString album; bool fav; }; #endif // SONG_H
[ "victor.serov@protonmail.com" ]
victor.serov@protonmail.com
3339fa471f6138de4c041d9f85964861d013ad89
469c34f2a031d0add6de15cfadd4d6b351b8fe99
/src/include/spin/SpinClusterIndex.h
466fa0df4ff0e9c139ae3d3d1ae069148d970878
[]
no_license
HoldenGao/oops
d0bc3e280678be2e4d78952d187c9e46130de78f
6710eebdb28b74b982475074ea67157bfbb7a9fb
refs/heads/master
2021-01-20T16:47:57.410682
2016-04-08T08:22:19
2016-04-08T08:22:19
56,654,023
1
0
null
2016-04-20T03:59:55
2016-04-20T03:59:53
null
UTF-8
C++
false
false
1,337
h
#ifndef SPINCLUSTERINDEX_H #define SPINCLUSTERINDEX_H #include <iostream> #include <vector> #include <set> #include <string> #include <armadillo> #include "include/easylogging++.h" #include "include/spin/Spin.h" typedef pair<size_t, size_t> ClusterPostion; //////////////////////////////////////////////////////////////////////////////// //{{{ cClusterIndex /// This class defines index list of a cluster. /// class cClusterIndex { public: cClusterIndex(); cClusterIndex(const uvec& idx); ~cClusterIndex(); mat get_array(size_t nspin); uvec getIndex() const {return _index;}; size_t getNum() const {return _spin_num;}; size_t getOrder() const {return _spin_num-1;}; set< ClusterPostion > getSubClstPos() const; void appendSubClstPos(int pos) const {_sub_clst_pos.push_back( pos );}; void setSubClstPos(vector<size_t> pos_lst) const {_sub_clst_pos = pos_lst;}; friend bool operator == (const cClusterIndex& idx1, const cClusterIndex& idx2); friend bool operator < (const cClusterIndex& idx1, const cClusterIndex& idx2); friend ostream& operator << (ostream& outs, const cClusterIndex& idx); private: uvec _index; size_t _spin_num; mutable vector<size_t> _sub_clst_pos; }; //}}} //////////////////////////////////////////////////////////////////////////////// #endif
[ "nzhao@csrc.ac.cn" ]
nzhao@csrc.ac.cn
4df4fc772752dbf68ea63988337d014d9d329f69
a521ad7729b50b554ec571f7be0332db0c20ffd6
/geant4reweight/src/PredictionBase/G4CascadeDetectorConstruction.hh
f2bf2be4066f65915dc113d635a73ed0cfc67437
[]
no_license
nusense/Geant4Reweight
cc47a8ee238074e7d4bdbedd5d249e28a73fbcdc
333947cf58f436b3ad37c13a4cf7b3d91927644e
refs/heads/master
2023-06-19T06:34:41.824032
2021-07-23T21:07:14
2021-07-23T21:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
531
hh
#ifndef G4CascadeDetectorConstruction_h #define G4CascadeDetectorConstruction_h 1 #include "Geant4/G4VUserDetectorConstruction.hh" class G4VPhysicalVolume; class G4LogicalVolume; class G4CascadeDetectorConstruction : public G4VUserDetectorConstruction{ public: G4CascadeDetectorConstruction(); G4CascadeDetectorConstruction(G4VPhysicalVolume * phys_vol); virtual ~G4CascadeDetectorConstruction(); virtual G4VPhysicalVolume * Construct(); protected: G4VPhysicalVolume * fPhysicalVol = 0x0; }; #endif
[ "calcuttj@msu.edu" ]
calcuttj@msu.edu
3b42d8491eba897d2322a7ffb06b80cdbd4c9810
117246cd4faafd099cb8ec981378820ca111d744
/Snake/Game.cpp
edfa45f9e72b3f071701ca46d3d348a7a712794c
[]
no_license
TruongHoangPhuLoc/Snake
eebeb23d6a0367f6f61b70255c4dc1805a323bd4
b359c5aecee6505474125ba145c1be31e6624bba
refs/heads/master
2023-07-30T19:57:26.945354
2021-09-19T05:18:25
2021-09-19T05:18:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,185
cpp
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<Windows.h> #include<conio.h> #include<time.h> #define DOT_RAN 254 #define MAX 100 #define LEN 1 #define XUONG 2 #define TRAI 3 #define PHAI 4 #define WallTop 5 #define WallBot 28 #define WallLeft 0 #define WallRight 118 void Nocursortype() { CONSOLE_CURSOR_INFO Info; Info.bVisible = FALSE; Info.dwSize = 20; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &Info); } void gotoxy(short x, short y) { HANDLE hConsoleOutput; COORD Cursor_an_Pos = { x, y }; hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hConsoleOutput, Cursor_an_Pos); } struct TOADO { int x; int y; }; struct NODE { TOADO info; NODE* pNext; NODE* pPrevious; }; TOADO randomFOOD(); bool checkPosOfFood(NODE* head, TOADO food); void DrawWall(); void InitializeSNAKE(NODE*& head); NODE* findendNODE(NODE* head); TOADO Move(NODE* head, int huong); void DisplaySNAKE(NODE* head, TOADO endNODE, int huong); void DisplaySNAKE_2(NODE* head, TOADO end); void GetFromKeyBoard(int& huong); bool GameOver(NODE* head); bool checkAte(NODE* head, NODE* food); TOADO getEndNODE(NODE* head, int huong); void InsertNODE(NODE*& head, TOADO endNODE); int countNODE(NODE* head); void DisPlayScore(int score); void DisPlayPlayer(char* name, int tuoi); void ENDGAME(char* name, int score); void DisPlayFOOD(NODE* food); void InitializeFOOD(NODE*& food); void InsertFOOD(NODE* head, int nOFfood, NODE*& food); NODE* FindFOODtobeEaten(NODE* head, NODE* food); void ChangeNODETobeEATEN(NODE* head, NODE* food, NODE* nodeFoodTobeEaten); bool CheckSNAKE(NODE* head); int main() { srand(time(NULL)); char* name = new char[100]; printf("Nhap ten: "); gets_s(name, 100); int age; do { printf("Nhap tuoi: "); scanf("%d", &age); if (age < 18) { printf("Game nay chi danh cho nguoi tren 18 thoi nha %s oii :))\nNhap lai tuoi di\n", name); } } while (age < 18); system("cls"); NODE* head; InitializeSNAKE(head); NODE* food; InitializeFOOD(food); int nOFfood = 3; InsertFOOD(head, nOFfood, food); DisPlayFOOD(food); int huong = PHAI; int score = 0; gotoxy(50, 1); printf("WELCOME TO MY GAME"); gotoxy(55, 2); printf("Coding and design by Phu Loc"); DrawWall(); DisPlayPlayer(name, age); DisPlayScore(score); int time = 100; Nocursortype(); while (true) { TOADO endNODE = getEndNODE(head, huong); DisplaySNAKE(head, endNODE, huong); Sleep(time); GetFromKeyBoard(huong); if (GameOver(head) == true) { break; } if (checkAte(head, food) == true) { NODE* eaten = FindFOODtobeEaten(head, food); ChangeNODETobeEATEN(head, food, eaten); DisPlayFOOD(food); score++; InsertNODE(head, endNODE); DisPlayScore(score); if (time == 1) { time = 1; } else { time = time - 1; } } } system("cls"); /*int after = countNODE(head); int score = after - before;*/ ENDGAME(name, score); system("pause"); } void DrawWall() { for (int i = WallLeft; i <= WallRight; i++)// ve tuong tren { gotoxy(i, WallTop); printf("%c", 220); } for (int i = WallTop + 1; i <= WallBot; i++)// tuong trai { gotoxy(WallLeft, i); printf("%c", 221); } for (int i = WallTop + 1; i <= WallBot; i++) { gotoxy(WallRight, i); printf("%c", 222); } for (int i = WallLeft; i <= WallRight; i++) { gotoxy(i, WallBot); printf("%c", 223); } } void InitializeSNAKE(NODE*& head) { head = new NODE; head->info.x = 3; head->info.y = 8; head->pPrevious = NULL; NODE* p = new NODE; p->info.x = 2; p->info.y = 8; p->pPrevious = head; head->pNext = p; NODE* q = new NODE; q->info.x = 1; q->info.y = 8; q->pNext = NULL; q->pPrevious = p; p->pNext = q; } NODE* findendNODE(NODE* head) { NODE* p = head; NODE* q = new NODE; while (p != NULL) { q = p; p = p->pNext; } return q; } TOADO Move(NODE* head, int huong) { TOADO temp = findendNODE(head)->info; NODE* p = findendNODE(head); while (p != head) { NODE* k = p->pPrevious; p->info = k->info; p = p->pPrevious; } switch (huong) { case LEN: head->info.y--; break; case XUONG: head->info.y++; break; case TRAI: head->info.x--; break; case PHAI: head->info.x++; break; } return temp; } void DisplaySNAKE(NODE* head, TOADO endNODE, int huong) { gotoxy(endNODE.x, endNODE.y); printf(" "); NODE* p = head; while (p != NULL) { gotoxy(p->info.x, p->info.y); if (p == head && huong == PHAI) { printf(">"); } if (p == head && huong == TRAI) { printf("<"); } if (p == head && huong == LEN) { printf("^"); } if (p == head && huong == XUONG) { printf("v"); } if (p != head) { printf("-"); } p = p->pNext; } } void DisplaySNAKE_2(NODE* head, TOADO end) { while (head != NULL) { gotoxy(head->info.x, head->info.y); printf("*"); head = head->pNext; } gotoxy(end.x, end.y); printf(" "); } void GetFromKeyBoard(int& huong) { if (_kbhit()) { int key = _getch(); if (key == 'w' || key == 'W' || key == 72) { if (huong == XUONG) { huong = XUONG; } else { huong = LEN; } } else if (key == 's' || key == 'S' || key == 80) { if (huong == LEN) { huong = LEN; } else { huong = XUONG; } } else if (key == 'a' || key == 'A' || key == 75) { if (huong == PHAI) { huong = PHAI; } else { huong = TRAI; } } else if (key == 'd' || key == 'D' || key == 77) { if (huong == TRAI) { huong = TRAI; } else { huong = PHAI; } } } } TOADO randomFOOD() { TOADO food; food.x = (WallLeft + 1) + rand() % ((WallRight - 1) + 1 - (WallLeft + 1)); food.y = (WallTop + 1) + rand() % ((WallBot - 1) + 1 - (WallTop + 1)); return food; } bool checkPosOfFood(NODE* head, TOADO food) { while (head != NULL) { if (head->info.x == food.x && head->info.y == food.y) { return true; } head = head->pNext; } return false; } bool GameOver(NODE* head) { NODE* p = head; if (p->info.y == WallTop) { return true; } else if (p->info.y == WallBot) { return true; } else if (p->info.x == WallLeft) { return true; } else if (p->info.x == WallRight) { return true; } else if (CheckSNAKE(head) == true) { return true; } else { return false; } } bool checkAte(NODE* head, NODE* food) { while (food != NULL) { if (head->info.x == food->info.x && head->info.y == food->info.y) { return true; } food = food->pNext; } return false; } bool CheckSNAKE(NODE* head) { NODE* p = head->pNext; while (p != NULL) { if (head->info.x == p->info.x && head->info.y == p->info.y) { return true; } p = p->pNext; } return false; } TOADO getEndNODE(NODE* head, int huong) { TOADO endNODE = Move(head, huong); return endNODE; } void InsertNODE(NODE*& head, TOADO endNODE) { NODE* end = findendNODE(head); NODE* p = new NODE; p->info = endNODE; p->pNext = NULL; p->pPrevious = end; end->pNext = p; } int countNODE(NODE* head) { NODE* p = head; int count = 0; while (p != NULL) { count++; p = p->pNext; } return count; } void DisPlayScore(int score) { gotoxy(100, 1); printf("Score is %d", score); } void DisPlayPlayer(char* name, int age) { gotoxy(5, 1); printf("Name: %s", name); gotoxy(5, 2); printf("Age: %d", age); } void ENDGAME(char* name, int score) { gotoxy(35, 1); printf("Thua roi %s oi ahahahaha do ngok", name); gotoxy(35, 2); printf("Chi dat duoc %d diem thoi nha cung\n", score); } void DisPlayFOOD(NODE* food) { while (food != NULL) { gotoxy(food->info.x, food->info.y); printf("%c", 254); food = food->pNext; } } void InsertFOOD(NODE* head, int nOFfood, NODE*& food) { TOADO info; for (int i = 0; i < nOFfood; i++) { do { info = randomFOOD(); } while (checkPosOfFood(head, info) == true); if (food == NULL) { NODE* p = new NODE; p->info = info; p->pNext = NULL; p->pPrevious = NULL; food = p; } else { while (checkPosOfFood(food, info) == true) { info = randomFOOD(); } NODE* q = new NODE; q->info = info; q->pNext = NULL; NODE* temp = food; while (temp->pNext != NULL) { temp = temp->pNext; } temp->pNext = q; q->pPrevious = temp; } } } NODE* findFOODtobeEaten(NODE* head, NODE* food) { NODE* p = NULL; while (food != NULL) { if (head->info.x == food->info.x && head->info.y == food->info.y) { p = food; } food = food->pNext; } return p; } void changeNODETobeEATEN(NODE* head, NODE* food, NODE* nodeFoodTobeEaten) { TOADO info = randomFOOD(); while (checkPosOfFood(head, info) == true || checkPosOfFood(food, info) == true) { info = randomFOOD(); } nodeFoodTobeEaten->info = info; } NODE* FindFOODtobeEaten(NODE* head, NODE* food) { NODE* p = NULL; while (food != NULL) { if (head->info.x == food->info.x && head->info.y == food->info.y) { p = food; } food = food->pNext; } return p; } void ChangeNODETobeEATEN(NODE* head, NODE* food, NODE* nodeFoodTobeEaten) { TOADO info = randomFOOD(); while (checkPosOfFood(head, info) == true || checkPosOfFood(food, info) == true) { info = randomFOOD(); } nodeFoodTobeEaten->info = info; } void InitializeFOOD(NODE*& food) { food = NULL; }
[ "truongphuloc030499@gmail.com" ]
truongphuloc030499@gmail.com
31698a12640782a4afdf2e762fee6e3ef7777828
ffa9bada806a6330cfe6d2ab3d7decfc05626d10
/51Nod/Nod2653.cpp
d6df7799bbec093dafa2f93002cf7451b6587d5b
[ "MIT" ]
permissive
James3039/OhMyCodes
064ef03d98384fd8d57c7d64ed662f51218ed08e
f25d7a5e7438afb856035cf758ab43812d5bb600
refs/heads/master
2023-07-15T15:52:45.419938
2021-08-28T03:37:27
2021-08-28T03:37:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
443
cpp
#include <cstdio> #include <iostream> #include <cmath> int ans, a, b, bi, len; int main(){ scanf("%d %d", &a, &b); bi=log(a)/log(2); if((1<<bi)<a) bi++; len=log(b-(1<<bi)+1)/log(2); if(len==1 || (1<<bi)>=b) { for(int i=a; i<=b; i++) ans = ans^i; } else{ for(int i=a; i<(1<<bi); i++){ ans = ans^i; } for(int i=(1<<bi)+(1<<len); i<=b; i++){ ans = ans^i; } } printf("%d", ans); return 0; }
[ "1816750728@qq.com" ]
1816750728@qq.com
60738dee6b30c63a8c39cf2434bc77f7ee8a8bd5
d8e7a11322f6d1b514c85b0c713bacca8f743ff5
/7.6.00.37/V76_00_37/MaxDB_ORG/sys/src/SAPDB/DBM/Srv/BackupHistory/DBMSrvBHist_FileLineEBF.cpp
74ae1634a28f09ad0399655cf87379e0a8dd680d
[]
no_license
zhaonaiy/MaxDB_GPL_Releases
a224f86c0edf76e935d8951d1dd32f5376c04153
15821507c20bd1cd251cf4e7c60610ac9cabc06d
refs/heads/master
2022-11-08T21:14:22.774394
2020-07-07T00:52:44
2020-07-07T00:52:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,018
cpp
/*! \file DBMSrvBHist_FileLineEBF.cpp \author TiloH \ingroup backup history handling by the DBMServer \brief a class determining the layout of a line of dbm.ebf \if EMIT_LICENCE ========== licence begin GPL Copyright (c) 2004-2005 SAP AG This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ========== licence end \endif */ #include "hcn36.h" #include "SAPDB/DBM/Srv/BackupHistory/DBMSrvBHist_FileLineEBF.hpp" #include "SAPDB/SAPDBCommon/SAPDB_ToString.hpp" DBMSrvBHist_FileLineEBF::DBMSrvBHist_FileLineEBF(const DBMSrvBHist_Part & part) :m_line(0) { size_t lineLength=16; //there are 16 '|' in the line as separators lineLength+=strlen(part.GiveKey()); lineLength+=strlen(part.GiveLabel()); lineLength+=strlen(part.GiveEBID()); lineLength+=strlen(part.getBackupType()); lineLength+=strlen(part.getBackupDateTime()); lineLength+=strlen(part.GiveUsedBackupTool().AsString()); lineLength+=strlen(SAPDB_ToString(part.GiveDBMReturnCode())); lineLength+=strlen(part.GiveDBMReturnText()); lineLength+=strlen(part.GiveMediumName()); lineLength+=strlen(part.getMediumType()); lineLength+=strlen(part.getMediumOverwrite()); lineLength+=strlen(part.getMediumSize()); lineLength+=strlen(part.getMediumBlockSize()); lineLength+=strlen(part.getMediumKind()); lineLength+=strlen(part.getMediumLocation()); lineLength+=strlen(SAPDB_ToString(part.GivePartNumber())); if(cn36_StrAlloc(m_line, lineLength)) { sprintf(m_line, "%s|%s|%s|%s|%s|%s|%d|%s|%s|%s|%s|%s|%s|%s|%s|%d|", part.GiveKey(), part.GiveLabel(), part.GiveEBID(), part.getBackupType(), part.getBackupDateTime(), part.GiveUsedBackupTool().AsString(), (int)part.GiveDBMReturnCode(), part.GiveDBMReturnText(), part.GiveMediumName(), part.getMediumType(), part.getMediumOverwrite(), part.getMediumSize(), part.getMediumBlockSize(), part.getMediumKind(), part.getMediumLocation(), (int)part.GivePartNumber()); } } DBMSrvBHist_FileLineEBF::~DBMSrvBHist_FileLineEBF() { cn36_StrDealloc(m_line); } const char * DBMSrvBHist_FileLineEBF::asString() { return m_line; }
[ "gunter.mueller@gmail.com" ]
gunter.mueller@gmail.com
bee55885367599bb4cc013e06e1f63600bae8d94
1a76cdf3b8776c238f0fecaca9c9491145106ec6
/SDK/FN_Athena_PlayerCameraModeSkydiveDive_classes.hpp
dae2da56422b8ed4e8928065b10a6768dbc36da8
[]
no_license
JimmyJones97/aasd
9af6e9c83eec4d1b4c76c601c2ccba814ce8a1c0
1961458db5ef577e6f013ca9ea744dcd48f2b4ad
refs/heads/master
2022-02-19T11:47:42.191429
2017-10-27T11:59:07
2017-10-27T11:59:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
668
hpp
#pragma once // Fortnite SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Athena_PlayerCameraModeSkydiveDive.Athena_PlayerCameraModeSkydiveDive_C // 0x0000 (0x0110 - 0x0110) class UAthena_PlayerCameraModeSkydiveDive_C : public UAthena_PlayerCameraModeBase_C { public: static UClass* StaticClass() { static UClass* ptr = nullptr; if (!ptr) ptr = UObject::FindClass(0x12ff1741); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "joker@slaughter-gaming.de" ]
joker@slaughter-gaming.de
6b03970353ede99d395b4e12cb2a5e14f2f02ea2
01c93dfd17bf4aa76067bcc3baf6aa8d0a400536
/PAT乙级/B1070.cpp
3c21ebad60cc8931102eff9139c4230cd1b4a78a
[]
no_license
lfwbale/PATbasic
908aa8e99afcffe3753eb380cc7bd32317f99a5b
26d51773bb8304bc8c5baff67cb5cf41f49b8e2c
refs/heads/master
2020-09-05T19:22:41.441664
2019-11-07T10:54:16
2019-11-07T10:54:16
220,191,335
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include<stdio.h> #include<algorithm> using namespace std; int main(){ int n; scanf("%d",&n); int a[n]; for(int i=0;i<n;i++){ scanf("%d",&a[i]); } sort(a,a+n); int sum=0; for(int i=0;i<n;i++){ sum=(sum+a[i])/2; } printf("%d\n",sum); return 0; }
[ "stunning@MacBook-Pro-4.local" ]
stunning@MacBook-Pro-4.local
1cdf121cacb8d1f5d799187bb64a9eff464fe58d
80ea2ec75f3505931c6643a4159f5784d24f7112
/magic_get/include/boost/pfr/detail/core14.hpp
6ea3607dbd0c596cb73604356cac1777f4bc7d27
[]
no_license
ksmurph1/VulkanConfigurator
843c6282b5eb75c9bcf5d0501ba2ff2b293fc930
986992a8b963a6b271785a77d5efd349b6e6ea4f
refs/heads/master
2023-03-30T14:11:27.417840
2021-04-03T20:57:28
2021-04-03T20:57:28
270,752,561
0
0
null
null
null
null
UTF-8
C++
false
false
455
hpp
// Copyright (c) 2016-2019 Antony Polukhin // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PFR_DETAIL_CORE14_HPP #define BOOST_PFR_DETAIL_CORE14_HPP #pragma once #include "config.hpp" #if BOOST_PFR_USE_LOOPHOLE # include "core14_loophole.hpp" #else # include "core14_classic.hpp" #endif #endif // BOOST_PFR_DETAIL_CORE14_HPP
[ "ksmurph1@gmail.com" ]
ksmurph1@gmail.com
253999d3d9f0236851131f53e43e8a5845825c84
0ca50389f4b300fa318452128ab5437ecc97da65
/example/less-than-1k/assign/rgb/rgb2YPbPr709.cpp
4d31b1bd6edc2caa2b12bf6837f6195a1c31ae1d
[ "Apache-2.0" ]
permissive
dmilos/color
5981a07d85632d5c959747dac646ac9976f1c238
84dc0512cb5fcf6536d79f0bee2530e678c01b03
refs/heads/master
2022-09-03T05:13:16.959970
2022-08-20T09:22:24
2022-08-22T06:03:32
47,105,546
160
25
Apache-2.0
2021-09-29T07:11:04
2015-11-30T08:37:43
C++
UTF-8
C++
false
false
783
cpp
#include <iostream> #include <iomanip> #include "color/color.hpp" int main( int argc, char *argv[] ) { ::color::rgb< float > c0; //!< Instead of float you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double ::color::YPbPr< std::uint8_t, ::color::constant::YPbPr::BT_709_entity > c1; //!< Instead of std::uint8_t you may put std::uint16_t, std::uint32_t, std::uint64_t, float, double, long double c0 = ::color::constant::lavender_t{}; c1 = ::color::constant::orange_t{}; // Assign c0 = c1; std::cout << c0[0] << ", " << c0[1] << ", " << c0[2] << std::endl; // .. and vice versa c1 = c0; std::cout << c1[0] << ", " << c1[1] << ", " << c1[2] << std::endl; return EXIT_SUCCESS; }
[ "dmilos@gmail.com" ]
dmilos@gmail.com
cb917761fef4adba5af9cca4e434fd2bc231f3af
3e7ae0d825853090372e5505f103d8f3f39dce6d
/AutMarine v4.2.0/AutLib/Geom/GeoMesh/GeoMesh_TriangleMesh2dInnerBoundaryList.hxx
6540bf8df89fd38e3b6f625984f622789bb1dfb7
[]
no_license
amir5200fx/AutMarine-v4.2.0
bba1fe1aa1a14605c22a389c1bd3b48d943dc228
6beedbac1a3102cd1f212381a9800deec79cb31a
refs/heads/master
2020-11-27T05:04:27.397790
2019-12-20T17:59:03
2019-12-20T17:59:03
227,961,590
0
0
null
null
null
null
UTF-8
C++
false
false
396
hxx
#pragma once #ifndef _GeoMesh_TriangleMesh2dInnerBoundaryList_Header #define _GeoMesh_TriangleMesh2dInnerBoundaryList_Header #include <GeoMesh_TriangleMesh2dInnerBoundary.hxx> #include <ADT_Ary1d.hxx> namespace AutLib { typedef ADT_Ary1d<Global_Handle(GeoMesh_TriangleMesh2dInnerBoundary)> GeoMesh_TriangleMesh2dInnerBoundaryList; } #endif // !_GeoMesh_TriangleMesh2dInnerBoundaryList_Header
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
570c3c3ae858c17a276c1075ecdd38a025dbcbe8
d12ef5f7472ad8ef90410f7232ba52620314263f
/baekjoon/DP/2758.cpp
504791fda4c52870877e6a8e9b184ad7726882ce
[]
no_license
b-chae/AlgorithmStudy
34c1af96058c29caae49c0692a21bdc190adac7f
d5d2f01bcfbff56f23c05b1238d3b060169b732f
refs/heads/master
2023-08-04T04:08:34.051246
2021-09-12T00:15:49
2021-09-12T00:15:49
257,220,705
0
1
null
null
null
null
UTF-8
C++
false
false
620
cpp
#include <iostream> using namespace std; int T, N, M; long long D[15][2001]; int main(){ ios::sync_with_stdio(0); cin.tie(0); cin >> T; for(int i=0;i<T;i++){ cin >> N >> M; for(int x=1; x<=M; x++) D[1][x] = 1; for(int x=2; x<=N; x++){ for(int y=1; y<=M; y++){ D[x][y] = 0; for(int k=1;k<=y/2;k++){ D[x][y] += D[x-1][k]; } } } long long ans = 0; for(int y=1; y<=M; y++){ ans += D[N][y]; } cout << ans << "\n"; } return 0; }
[ "noreply@github.com" ]
b-chae.noreply@github.com
52b716d7310aca87be4d977f3889aa1c2eb1689d
70cb5e043b7a469fecf810fc1c12ddd3faba452f
/c++ primer ,5th/word map/main.cpp
cd257407389cf7b89e7d762b723516d866b0e76a
[]
no_license
yulifromchina/exercise
5205d7e27f46d397a3048919e76d45ab4c3f9b32
bc2302db0fa75db85c4ab6bc7356b5f3727b2701
refs/heads/master
2021-01-19T13:42:29.552298
2018-02-23T05:17:42
2018-02-23T05:17:42
100,857,569
1
0
null
null
null
null
GB18030
C++
false
false
289
cpp
#include "Filter.h" int main() { Filter obj_filter; obj_filter.AddBlackListFromFile("KeyWords.txt");//添加C/C++中的关键字 obj_filter.AddRuleFromFile("Rule.txt");//读取规则 obj_filter.TransFile("OriginText.txt");//翻译原文本,生成result.txt return 0; }
[ "yulifromchina@gmail.com" ]
yulifromchina@gmail.com
3d908408a8c8447c48431adeb0d4c8064357f51a
b7691235885c17306a660d242afe1cf6a70e867b
/8/81265.cpp
b934aec5617af3f8d2313f8c6177f9bf1f8f702a
[]
no_license
DobrinTs/Artifical-Intelligence-FMI-course
8dc67a27f9a50d0d756b7a7405519d9d7d8b7714
d171e092c9c2f1192932f92646e26f867169ed8c
refs/heads/master
2020-04-14T11:56:52.539124
2019-01-08T09:55:56
2019-01-08T09:55:56
163,827,100
0
0
null
null
null
null
UTF-8
C++
false
false
5,358
cpp
#include<iostream> #include<fstream> #include<vector> #include<queue> #include<math.h> using namespace std; string fullClassName(string classAbbreviation) { if(classAbbreviation == "set") { return "Iris-setosa"; } else if(classAbbreviation == "ver") { return "Iris-versicolor"; } else if(classAbbreviation == "vir") { return "Iris-virginica"; } } struct Plant { double sepalLength; double sepalWidth; double petalLength; double petalWidth; string plantClass; Plant(double sepalLength, double sepalWidth, double petalLength, double petalWidth, string plantClass) : sepalLength(sepalLength), sepalWidth(sepalWidth), petalLength(petalLength), petalWidth(petalWidth), plantClass(plantClass) {} Plant(const Plant& other) : sepalLength(other.sepalLength), sepalWidth(other.sepalWidth), petalLength(other.petalLength), petalWidth(other.petalWidth), plantClass(other.plantClass) {} Plant& operator=(const Plant& other) { if(this!=&other) { sepalLength=other.sepalLength; sepalWidth=other.sepalWidth; petalLength=other.petalLength; petalWidth=other.petalWidth; plantClass=other.plantClass; } return *this; } bool operator<(const Plant& other) const //for priority queue of pair<double, Plant> { int chance = rand() % 10; return chance < 5; } string getPlantClass() const { return plantClass; } void print() const { cout<<sepalLength<<" "<<sepalWidth<<" "<<petalLength<<" "<<petalWidth<<" "<<fullClassName(plantClass)<<endl; } }; string findClassByKNeighbours(const vector<Plant> trainingDataset, Plant newEntry, int k) { priority_queue<pair<double, Plant> > nearestNeighbours; double distance; for(int i=0; i<trainingDataset.size(); i++) { distance = sqrt( (newEntry.petalLength - trainingDataset[i].petalLength)*(newEntry.petalLength - trainingDataset[i].petalLength) + (newEntry.petalWidth - trainingDataset[i].petalWidth)*(newEntry.petalWidth - trainingDataset[i].petalWidth) + (newEntry.sepalLength - trainingDataset[i].sepalLength)*(newEntry.sepalLength - trainingDataset[i].sepalLength) + (newEntry.sepalWidth - trainingDataset[i].sepalWidth)*(newEntry.sepalWidth - trainingDataset[i].sepalWidth) ); if(nearestNeighbours.size() < k) { nearestNeighbours.push(pair<double, Plant>(distance, trainingDataset[i])); } else if(nearestNeighbours.top().first > distance) { nearestNeighbours.pop(); nearestNeighbours.push(pair<double, Plant>(distance, trainingDataset[i])); } } int irisSetosa = 0, irisVersicolor = 0, irisVirginica = 0; string nearestNeighbourClass; while(!nearestNeighbours.empty()) { string topClass = nearestNeighbours.top().second.getPlantClass(); if(nearestNeighbours.size() == 1) { nearestNeighbourClass = topClass; } if( topClass == "set") { irisSetosa++; } else if(topClass == "ver") { irisVersicolor++; } else if( topClass == "vir") { irisVirginica++; } nearestNeighbours.pop(); } string maxCountClass = "set"; int maxCount = irisSetosa; if(irisVersicolor > maxCount || (irisVersicolor == maxCount && nearestNeighbourClass == "ver")) { maxCountClass = "ver"; maxCount = irisVersicolor; } if(irisVirginica > maxCount || (irisVirginica == maxCount && nearestNeighbourClass == "vir")) { maxCountClass = "vir"; maxCount = irisVirginica; } return maxCountClass; } void kNN() { ifstream file ("iris.txt", std::ifstream::in); double sL, sW, pL, pW; string pC; vector<Plant> trainingDataset; vector<Plant> testDataset; while(file>>sL) { file.ignore(1); file>>sW; file.ignore(1); file>>pL; file.ignore(1); file>>pW; file.ignore(1); getline(file, pC); pC = pC.substr(5, 3); trainingDataset.push_back(Plant(sL, sW, pL, pW, pC)); } while(testDataset.size() < 20) { int idx = rand() % trainingDataset.size(); testDataset.push_back(trainingDataset[idx]); trainingDataset.erase(trainingDataset.begin()+idx); } int k; cout<<"Enter k: "; cin>>k; int correctCount = 0; for(int i=0; i<testDataset.size(); i++) { cout<<"Test dataset individual info: "<<endl; testDataset[i].print(); cout<<"Predicted class: "; string predictionResult = findClassByKNeighbours(trainingDataset, testDataset[i], k); cout<<fullClassName(predictionResult)<<endl; cout<<"------------------"<<endl; if(testDataset[i].getPlantClass() == predictionResult) { correctCount++; } } double accuracy = (double)correctCount/testDataset.size(); cout<<"Accuracy: "<< accuracy; } int main() { srand (time(NULL)); kNN(); }
[ "dobrits97@gmail.com" ]
dobrits97@gmail.com
72cca768972d3edd6cacc0b0254665146100172b
fce8d9c72923ed0123ac9b7ee1b09731084b8faa
/D3D_Base/cRabitGirl.h
05aa8e37bd4094d8c52a44b31d87b63603e2286d
[]
no_license
asy1256/TestGit
b7a68787e79a219c7231797c88110cac4a1cecd0
9ac26242c349990dcf08e0403655489e49c27f22
refs/heads/master
2021-07-25T10:21:37.475127
2017-11-05T07:58:26
2017-11-05T07:58:26
109,367,418
0
0
null
2017-11-05T07:58:27
2017-11-03T07:49:08
C++
UTF-8
C++
false
false
247
h
#pragma once #include "cCharacter.h" class cAseLoader; class cRabitGirl : public cCharacter { private: LPD3DXMESH m_pMesh; cAseLoader* m_pAseLoader; public: cRabitGirl(); ~cRabitGirl(); void Setup(); void Update(); void Render(); };
[ "asy1256@daum.net" ]
asy1256@daum.net
957f5f51b6241890070678e1b68f747ee242b21d
9987a33adf46172cf5352b57e2e1319955dd75ab
/SongInfoEditor/TabID3v2.h
1e05ddd67e4070b79d339eac8cdc6f77f6e3e67a
[]
no_license
lilinayuy/SongInfo
ce4cb73c7d4b394abf1f063939d758cbef79743c
d02929c16f5144a542093b88be02118e9d54f20b
refs/heads/master
2016-09-10T18:24:53.640838
2015-03-24T01:53:41
2015-03-24T01:53:41
32,769,729
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
h
#pragma once #include "afxwin.h" // CTabID3v2 dialog class CTabID3v2 : public CDialog { DECLARE_DYNAMIC(CTabID3v2) public: CTabID3v2(CWnd* pParent = NULL); // standard constructor virtual ~CTabID3v2(); // Dialog Data enum { IDD = IDD_DLG_ID3V2 }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: CString m_strTitle; CString m_strTrack; CString m_strArtist; CString m_strAlbum; CString m_strYear; CString m_strGenre; CString m_strComposer; CString m_strLyricist; CString m_strOriginalArtist; CString m_strCopyright; CString m_strEncoder; CString m_strEncodedBy; CString m_strComment; CString m_strURL; CString m_strLyricText; CString m_strFileType; CString m_strMediaType; afx_msg void OnBnClickedBtnCopyartistout(); afx_msg void OnBnClickedBtnCopyalbumout(); int m_nID3Version; CComboBox m_cUnicode; BOOL m_bUnicode; afx_msg void OnBnClickedBtnShowlyric(); afx_msg void OnBnClickedBtnGotourl(); afx_msg void OnBnClickedBtnTojapanese(); afx_msg void OnBnClickedBtnTochinese(); afx_msg void OnBnClickedBtnSave(); virtual BOOL OnInitDialog(); BOOL ChangeUnicode(int Des); BOOL m_bEnable; void EnableDialog(BOOL bEnable); BOOL m_bGenreAdded; CComboBox m_cCmbGenre; CComboBox m_cCmbID3Version; CDialog* m_pDlg; CDialog* m_pLyricDlg; BOOL m_bShowLyric; CButton m_cBtnToJapanese; CButton m_cBtnToChinese; CButton m_cBtnSave; afx_msg void OnBnClickedBtnAdd(); afx_msg void OnBnClickedBtnDelete(); afx_msg void OnBnClickedBtnUpload(); };
[ "heeroyuy1982@163.com" ]
heeroyuy1982@163.com
95a8c9a3ae97d2c01f845a82f19e1c8ee8bb4ff2
335e56925e49716c7b7766f2bbca71590e0c77a8
/hdoj/Problem Achieve/2102 A计划.cpp
e4e7291d9aefb6d21544c54bd81356fc50231b1b
[]
no_license
suzumiyayuhi/AlgorithmTraining
388b9bfd5aed5d76a20c71ad03b69a5269d2e7a7
1af9584fde2ec209429e6b85c5e0381685733c16
refs/heads/master
2021-01-18T17:54:03.491535
2018-01-20T10:57:12
2018-01-20T10:57:12
86,822,395
4
0
null
null
null
null
UTF-8
C++
false
false
1,911
cpp
#include<iostream> #include<queue> #include<string.h> #include<cstdio> using namespace std; char palace[11][11][3]; bool flag[11][11][3]; int N,M,T,ex,ey,ez; struct point { int x,y,z,time; }person; int dx[4]={0,0,1,-1}; int dy[4]={1,-1,0,0}; bool check(point a) { if(a.x>=1&&a.x<=N&&a.y>=1&&a.y<=M) if(palace[a.x][a.y][a.z]!='*') if(!flag[a.x][a.y][a.z]) return true; return false; } bool bfs() { queue<point> q; q.push(person); point cur,next; while(!q.empty()) { cur=q.front(); flag[cur.x][cur.y][cur.z]=true; q.pop(); if(cur.x==ex&&cur.y==ey&&cur.z==ez&&cur.time<=T) return true; if(cur.time>T) return false; if(palace[cur.x][cur.y][cur.z]=='#') { next=cur; if(next.z==1) next.z=2; else next.z=1; if(check(next)) q.push(next); } else { for(int i=0;i!=4;i++) { next.x=cur.x+dx[i]; next.y=cur.y+dy[i]; next.z=cur.z; next.time=cur.time+1; if(check(next)) q.push(next); } } } return false; } int main() { int cc; cin>>cc; while(cc--) { cin>>N>>M>>T; memset(flag,false,sizeof(flag)); for(int z=1;z!=3;z++) { for(int x=1;x<=N;x++) { for(int y=1;y<=M;y++) { cin>>palace[x][y][z]; if(palace[x][y][z]=='S') { person.x=x; person.y=y; person.z=z; person.time=0; flag[x][y][z]=true; } else if(palace[x][y][z]=='P') { ex=x; ey=y; ez=z; } } } } for(int j=1;j<=N;j++) { for(int k=1;k<=M;k++) { if(palace[j][k][1]=='#'&&palace[j][k][2]=='#') { palace[j][k][1]='*'; palace[j][k][2]='*'; } else if(palace[j][k][1]=='#'&&palace[j][k][2]=='*') { palace[j][k][1]='*'; } else if(palace[j][k][2]=='#'&&palace[j][k][1]=='*') { palace[j][k][2]='*'; } } } if(bfs()) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
[ "923051761@qq.com" ]
923051761@qq.com
195102e22851dae46772b6ab4a64c44a9812f322
e0aa106c29732b28625e03f0dbe64a534f63da6a
/src/051-prime-digit-replacements/cpp/bin/range.cpp
374a42b1ba69eefa82cbbf7d61a4470ef130b466
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xfbs/euler
ee2002c77c67ed7c6a57ebca014ae8b764a8c380
e26768c56ff87b029cb2a02f56dc5cd32e1f7c87
refs/heads/master
2020-04-16T17:05:25.589886
2019-06-12T22:12:21
2019-06-12T22:12:21
40,597,273
1
0
null
null
null
null
UTF-8
C++
false
false
916
cpp
#include <array> #include <iostream> #include <range/v3/all.hpp> #include <vector> using std::cout; using std::endl; using namespace ranges; auto is_six = [](int i) -> bool { return i == 6; }; auto doub = [](int i) -> int { return 2 * i; }; int main() { std::vector<int> v{6, 2, 3, 4, 5, 6}; auto c = count_if(v, is_six); cout << "count-sixes: " << c << endl; auto s = accumulate(v, 0); cout << "sum-vetor: " << s << endl; auto cand = view::ints(1) | view::transform(doub); auto e = find_if(cand, is_six); cout << "find-six: " << *e << endl; auto odd_perfect_square = front(view::ints // make perfect squares | view::transform([](int a) { return a * a; }) // keep odd ones only | view::filter([](int a) { return a % 2 == 1; }) // ignore first two | view::drop_exactly(2)); cout << odd_perfect_square << endl; }
[ "pelsen@xfbs.net" ]
pelsen@xfbs.net
f668a94d5cffaefaba1530a6b563c0f6fa24e75d
6ff225ced3f8ea771a0db118933907da4445690e
/logdevice/server/locallogstore/ShardedRocksDBLocalLogStore.cpp
3f89fbb5ce249d3d8eb538f6ca7d3259b2a20350
[ "BSD-3-Clause" ]
permissive
mickvav/LogDevice
c5680d76b5ebf8f96de0eca0ba5e52357408997a
24a8b6abe4576418eceb72974083aa22d7844705
refs/heads/master
2020-04-03T22:33:29.633769
2018-11-07T12:17:25
2018-11-07T12:17:25
155,606,676
0
0
NOASSERTION
2018-10-31T18:39:23
2018-10-31T18:39:23
null
UTF-8
C++
false
false
26,794
cpp
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * 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. */ #include "ShardedRocksDBLocalLogStore.h" #include <array> #include <cerrno> #include <cstdio> #include <cstdlib> #include <future> #include <thread> #include <folly/FileUtil.h> #include <folly/Memory.h> #include <folly/ScopeGuard.h> #include <rocksdb/db.h> #include <rocksdb/statistics.h> #include <sys/stat.h> #include "logdevice/common/ConstructorFailed.h" #include "logdevice/common/RandomAccessQueue.h" #include "logdevice/common/ThreadID.h" #include "logdevice/common/settings/RebuildingSettings.h" #include "logdevice/common/types_internal.h" #include "logdevice/server/ServerProcessor.h" #include "logdevice/server/fatalsignal.h" #include "logdevice/server/locallogstore/FailingLocalLogStore.h" #include "logdevice/server/locallogstore/PartitionedRocksDBStore.h" #include "logdevice/server/locallogstore/RocksDBKeyFormat.h" #include "logdevice/server/locallogstore/RocksDBListener.h" #include "logdevice/server/locallogstore/RocksDBLogStoreFactory.h" #include "logdevice/server/locallogstore/ShardToPathMapping.h" #include "logdevice/server/storage_tasks/ShardedStorageThreadPool.h" namespace facebook { namespace logdevice { namespace fs = boost::filesystem; // Returns 1/0 if base_path looks like it contains an existing database, -1 on // error static int database_exists(const std::string& base_path); // Called when the database directory exists. Expect a NSHARDS file that // contains the number of shards this directory was created for. Verify that // this number matches `nshards_expected` which is retrieved from the // "num_shards" property of this node in the config. // // Returns 0 on success, or -1 on any error. static int check_nshards(const std::string& base_path, shard_size_t nshards_expected); // Tries to create a new sharded database at the given path, returns 0 on // success static int create_new_sharded_db(const std::string& base_path, shard_size_t nshards); using DiskShardMappingEntry = ShardedRocksDBLocalLogStore::DiskShardMappingEntry; ShardedRocksDBLocalLogStore::ShardedRocksDBLocalLogStore( const std::string& base_path, shard_size_t nshards, Settings settings, UpdateableSettings<RocksDBSettings> db_settings, UpdateableSettings<RebuildingSettings> rebuilding_settings, std::shared_ptr<UpdateableConfig> updateable_config, RocksDBCache* caches, StatsHolder* stats) : stats_(stats), db_settings_(db_settings), partitioned_(db_settings->partitioned) { if (db_settings->num_levels < 2 && db_settings->compaction_style == rocksdb::kCompactionStyleLevel) { ld_error("Level-style compaction requires at least 2 levels. %d given.", db_settings->num_levels); throw ConstructorFailed(); } int rv = database_exists(base_path); if (rv < 0) { throw ConstructorFailed(); } // This value should have been validated by the Configuration module. ld_check(nshards > 0 && nshards <= MAX_SHARDS); if (rv) { // Database exists, check that the number of shards matches. We do not // want to start up otherwise. if (check_nshards(base_path, nshards) < 0) { throw ConstructorFailed(); } } else { if (db_settings->auto_create_shards == false) { ld_error("Auto creation of shards & directories is not enabled and " "they do not exist"); throw ConstructorFailed(); } // Directory does not exist. Create a new sharded database. if (nshards < 0) { ld_error("Number of shards was not specified and database does not " "exist. Don't know how many shards to create!"); throw ConstructorFailed(); } if (create_new_sharded_db(base_path, nshards) != 0) { throw ConstructorFailed(); } } std::shared_ptr<Configuration> config = updateable_config ? updateable_config->get() : nullptr; env_ = std::make_unique<RocksDBEnv>(db_settings); { int num_bg_threads_lo = db_settings->num_bg_threads_lo; if (num_bg_threads_lo == -1) { num_bg_threads_lo = nshards * db_settings->max_background_compactions; } env_->SetBackgroundThreads(num_bg_threads_lo, rocksdb::Env::LOW); } { int num_bg_threads_hi = db_settings->num_bg_threads_hi; if (num_bg_threads_hi == -1) { num_bg_threads_hi = nshards * db_settings->max_background_flushes; } env_->SetBackgroundThreads(num_bg_threads_hi, rocksdb::Env::HIGH); } rocksdb_config_ = RocksDBLogStoreConfig( db_settings, rebuilding_settings, env_.get(), updateable_config, stats); // save the rocksdb cache information to be used by the SIGSEGV handler if (caches) { caches->block_cache = rocksdb_config_.table_options_.block_cache; caches->block_cache_compressed = rocksdb_config_.table_options_.block_cache_compressed; if (rocksdb_config_.metadata_table_options_.block_cache != rocksdb_config_.table_options_.block_cache) { caches->metadata_block_cache = rocksdb_config_.metadata_table_options_.block_cache; } } rv = ShardToPathMapping(base_path, nshards).get(&shard_paths_); if (rv != 0) { throw ConstructorFailed(); } ld_check(static_cast<int>(shard_paths_.size()) == nshards); // Create shards in multiple threads since it's a bit slow using FutureResult = std::pair<std::unique_ptr<LocalLogStore>, std::shared_ptr<RocksDBCompactionFilterFactory>>; std::vector<std::future<FutureResult>> futures; for (shard_index_t shard_idx = 0; shard_idx < nshards; ++shard_idx) { fs::path shard_path = shard_paths_[shard_idx]; ld_check(!shard_path.empty()); futures.push_back(std::async(std::launch::async, [=]() { ThreadID::set(ThreadID::UTILITY, "ld:open-rocksdb"); // Make a copy of RocksDBLogStoreConfig for this shard. RocksDBLogStoreConfig shard_config = rocksdb_config_; shard_config.createMergeOperator(shard_idx); // Create SstFileManager for this shard shard_config.addSstFileManagerForShard(); // If rocksdb statistics are enabled, create a Statistics object for // each shard. if (db_settings->statistics) { shard_config.options_.statistics = rocksdb::CreateDBStatistics(); } // Create a compaction filter factory. Later (in // setShardedStorageThreadPool()) we'll link it to the storage // thread pool so that it can see the world. auto filter_factory = std::make_shared<RocksDBCompactionFilterFactory>(db_settings); shard_config.options_.compaction_filter_factory = filter_factory; if (stats) { shard_config.options_.listeners.push_back( std::make_shared<RocksDBListener>(stats, shard_idx)); } RocksDBLogStoreFactory factory( std::move(shard_config), settings, config, stats); std::unique_ptr<LocalLogStore> shard_store; // Treat the shard as failed if we find a file named // LOGDEVICE_DISABLED. Used by tests. auto disable_marker = shard_path / fs::path("LOGDEVICE_DISABLED"); bool should_open_shard = true; try { if (fs::exists(disable_marker) && fs::is_regular_file(disable_marker)) { ld_info("Found %s, not opening shard %d", disable_marker.string().c_str(), shard_idx); should_open_shard = false; } if (fs::exists(shard_path) && !fs::is_directory(shard_path)) { ld_info("%s exists but is not a directory; not opening shard %d", shard_path.string().c_str(), shard_idx); should_open_shard = false; } } catch (const fs::filesystem_error& e) { ld_error("Error while checking for existence of %s or %s: %s. " "Not opening shard %d", disable_marker.string().c_str(), shard_path.string().c_str(), e.what(), shard_idx); should_open_shard = false; } if (should_open_shard) { shard_store = factory.create(shard_idx, shard_path.string()); } if (shard_store) { ld_info("Opened RocksDB instance at %s", shard_path.c_str()); bool enable_tracing = settings.trace_all_db_shards || shard_idx == settings.trace_db_shard; shard_store->setTracingEnabled(enable_tracing); } else { PER_SHARD_STAT_INCR(stats_, failing_log_stores, shard_idx); shard_store.reset(new FailingLocalLogStore()); ld_info("Opened FailingLocalLogStore instance for shard %d", shard_idx); } return std::make_pair(std::move(shard_store), std::move(filter_factory)); })); } for (int shard_idx = 0; shard_idx < nshards; ++shard_idx) { auto& future = futures[shard_idx]; std::unique_ptr<LocalLogStore> shard_store; std::shared_ptr<RocksDBCompactionFilterFactory> filter_factory; std::tie(shard_store, filter_factory) = future.get(); ld_check(shard_store); if (dynamic_cast<FailingLocalLogStore*>(shard_store.get()) != nullptr) { shards_.push_back(std::move(shard_store)); filters_.push_back(std::move(filter_factory)); failing_log_store_shards_.insert(shard_idx); continue; } shards_.push_back(std::move(shard_store)); filters_.push_back(std::move(filter_factory)); } // Subscribe for rocksdb config updates after initializing shards. rocksdb_settings_handle_ = db_settings.callAndSubscribeToUpdates( std::bind(&ShardedRocksDBLocalLogStore::onSettingsUpdated, this)); if (failing_log_store_shards_.size() >= nshards && nshards > 0) { ld_critical("All shards failed to open. Not starting the server."); throw ConstructorFailed(); } // Check that we can map shards to devices if (createDiskShardMapping() != nshards) { throw ConstructorFailed(); } printDiskShardMapping(); } ShardedRocksDBLocalLogStore::~ShardedRocksDBLocalLogStore() { for (shard_index_t shard_idx : failing_log_store_shards_) { PER_SHARD_STAT_DECR(stats_, failing_log_stores, shard_idx); } // Unsubscribe from settings update before destroying shards. rocksdb_settings_handle_.unsubscribe(); // destroy each RocksDBLocalLogStore instance in a separate thread std::vector<std::thread> threads; for (size_t i = 0; i < numShards(); ++i) { threads.emplace_back([this, i]() { ThreadID::set(ThreadID::Type::UTILITY, "ld:stop-rocksdb"); ld_debug("Destroying RocksDB shard %zd", i); shards_[i].reset(); ld_info("Destroyed RocksDB shard %zd", i); }); } for (auto& thread : threads) { thread.join(); } } static int database_exists(const std::string& base_path) { boost::system::error_code code; bool exists = fs::exists(base_path, code); if (code.value() != boost::system::errc::success && code.value() != boost::system::errc::no_such_file_or_directory) { ld_error("Error checking if path \"%s\" exists: %s", base_path.c_str(), code.message().c_str()); return -1; } if (!exists) { return 0; } bool isdir = fs::is_directory(base_path, code); if (code.value() != boost::system::errc::success && code.value() != boost::system::errc::not_a_directory) { ld_error("Error checking if path \"%s\" is a directory: %s", base_path.c_str(), code.message().c_str()); return -1; } if (!isdir) { ld_error("Path \"%s\" exists but is not a directory, cannot open local " "log store", base_path.c_str()); return -1; } bool isempty = fs::is_empty(base_path, code); if (code.value() != boost::system::errc::success) { ld_error("Error checking if path \"%s\" is empty: %s", base_path.c_str(), code.message().c_str()); return -1; } return !isempty; } static int check_nshards(const std::string& base_path, const shard_size_t nshards_expected) { fs::path nshards_path = fs::path(base_path) / fs::path("NSHARDS"); FILE* fp = std::fopen(nshards_path.c_str(), "r"); if (fp == nullptr) { ld_error("Database directory \"%s\" exists but there was an error opening " "the NSHARDS file, errno=%d (%s). To create a new sharded " "database, please delete the directory and try again.", base_path.c_str(), errno, strerror(errno)); return -1; } SCOPE_EXIT { std::fclose(fp); }; shard_size_t nshards_read; if (std::fscanf(fp, "%hd", &nshards_read) != 1) { ld_error("Error reading file \"%s\"", nshards_path.c_str()); return -1; } if (nshards_read != nshards_expected) { ld_error("Tried to open existing sharded database \"%s\" with a different " "number of shards (expected %d, found %d)", base_path.c_str(), nshards_expected, nshards_read); return -1; } return 0; } static int create_new_sharded_db(const std::string& base_path, shard_size_t nshards) { boost::system::error_code code; fs::create_directories(base_path, code); if (code.value() != boost::system::errc::success) { ld_error("Error creating directory \"%s\": %s", base_path.c_str(), code.message().c_str()); return -1; } fs::path nshards_path = fs::path(base_path) / fs::path("NSHARDS"); FILE* fp = std::fopen(nshards_path.c_str(), "w"); if (fp == nullptr) { ld_error("Failed to open \"%s\" for writing, errno=%d (%s)", nshards_path.c_str(), errno, strerror(errno)); return -1; } SCOPE_EXIT { std::fclose(fp); }; if (std::fprintf(fp, "%d", nshards) < 0) { ld_error("Error writing to \"%s\"", nshards_path.c_str()); return -1; } return 0; } int ShardedRocksDBLocalLogStore::trimLogsBasedOnSpaceIfNeeded( const DiskShardMappingEntry& mapping, boost::filesystem::space_info info, bool* full) { if (!partitioned_) { RATELIMIT_INFO(std::chrono::minutes(1), 1, "Space based trimming requested on non-partitioned storage"); return -1; } *full = false; if (db_settings_->free_disk_space_threshold_low == 0) { return 0; } size_t space_limit_coordinated = (1 - db_settings_->free_disk_space_threshold_low) * info.capacity; // Get & reset sequencer-initiated flag, so that if the flag was set by a // trailing probe after it was not full anymore, that value is not used in // the future if it becomes full again. ld_check(mapping.shards.size()); auto disk_info_kv = fspath_to_dsme_.find(shard_to_devt_[mapping.shards[0]]); if (disk_info_kv == fspath_to_dsme_.end()) { ld_check(false); return -1; } bool sequencer_initiated_trimming = disk_info_kv->second.sequencer_initiated_space_based_retention.exchange( false); if (space_limit_coordinated >= (info.capacity - info.free)) { // Not breaking any limits return 0; } using PartitionPtr = std::shared_ptr<PartitionedRocksDBStore::Partition>; using PartitionIterator = std::vector<PartitionPtr>::const_iterator; struct ShardTrimPoint { shard_index_t shard_idx; PartitionIterator it; // Keeping partition list so it is not freed while we use the iterator PartitionedRocksDBStore::PartitionList partition_list; size_t space_usage; size_t reclaimed; }; // Comparator to get the oldest partition timestamp first auto timestamp_cmp = [](const ShardTrimPoint& a, const ShardTrimPoint& b) { return (*a.it)->starting_timestamp > (*b.it)->starting_timestamp; }; std::priority_queue<ShardTrimPoint, std::vector<ShardTrimPoint>, decltype(timestamp_cmp)> shards_oldest_partitions_queue(timestamp_cmp); // Comparator to get lowest shard_idx first, for nicer prints auto shard_idx_cmp = [](const ShardTrimPoint& a, const ShardTrimPoint& b) { return a.shard_idx > b.shard_idx; }; std::priority_queue<ShardTrimPoint, std::vector<ShardTrimPoint>, decltype(shard_idx_cmp)> trim_points_sorted(shard_idx_cmp); // 1) Get snapshot of partitions from each shard, and put in priority queue. size_t total_space_used_by_partitions = 0; for (shard_index_t shard_idx : mapping.shards) { auto store = getByIndex(shard_idx); auto partitioned_store = dynamic_cast<PartitionedRocksDBStore*>(store); ld_check(partitioned_store != nullptr); auto partition_list = partitioned_store->getPartitionList(); // Add its size size_t partition_space_usage = partitioned_store->getApproximatePartitionSize( // Metadata partitioned_store->getMetadataCFHandle()) + partitioned_store->getApproximatePartitionSize( // Unpartitioned partitioned_store->getUnpartitionedCFHandle()); for (PartitionPtr partition_ptr : *partition_list) { // Partitions partition_space_usage += partitioned_store->getApproximatePartitionSize( partition_ptr->cf_.get()); } total_space_used_by_partitions += partition_space_usage; ShardTrimPoint stp{ shard_idx, // shard id partition_list->begin(), // iterator at beginning partition_list, // partition list (to keep in mem) partition_space_usage, // space usage 0 // reclaimed space (none yet) }; // Only add shard to priority queue if there are partitions we can drop. if (partition_list->size() > 1) { shards_oldest_partitions_queue.push(stp); } else { trim_points_sorted.push(stp); } } double ld_percentage = double(total_space_used_by_partitions) / double(info.capacity); double actual_percentage = double(info.capacity - info.free) / double(info.capacity); if (std::abs(actual_percentage - ld_percentage) > 0.3) { // TODO: add a stat and raise an alarm? RATELIMIT_WARNING( std::chrono::seconds(5), 1, "Estimated size differ %d%% from actual size! Would be unsafe " "to do space-based trimming, skipping it", static_cast<int>( round(100 * std::abs(actual_percentage - ld_percentage)))); return -1; } bool coordinated_limit_exceeded = total_space_used_by_partitions > space_limit_coordinated; *full = coordinated_limit_exceeded; ld_debug("example path:%s -> coordinated_limit_exceeded:%s, " "sequencer_initiated_trimming:%s, sbr_force:%s, " "space_limit_coordinated:%lu, coordinated_threshold:%lf" "[ld_percentage:%lf, total_space_used_by_partitions:%lu," " actual_percentage:%lf] [info.capacity:%lu, info.free:%lu]", mapping.example_path.c_str(), coordinated_limit_exceeded ? "yes" : "no", sequencer_initiated_trimming ? "yes" : "no", db_settings_->sbr_force ? "yes" : "no", space_limit_coordinated, db_settings_->free_disk_space_threshold_low, ld_percentage, total_space_used_by_partitions, actual_percentage, info.capacity, info.free); if (!coordinated_limit_exceeded) { return 0; } if (!sequencer_initiated_trimming && !db_settings_->sbr_force) { return 0; } // 2) Calculate how much to trim. size_t reclaimed_so_far = 0; size_t total_to_reclaim = total_space_used_by_partitions - space_limit_coordinated; // 3) Keep picking the oldest partition until enough space is freed. while (reclaimed_so_far <= total_to_reclaim && !shards_oldest_partitions_queue.empty()) { ShardTrimPoint current = shards_oldest_partitions_queue.top(); shards_oldest_partitions_queue.pop(); auto partitioned_store = dynamic_cast<PartitionedRocksDBStore*>(getByIndex(current.shard_idx)); size_t partition_size = partitioned_store->getApproximatePartitionSize( (*current.it)->cf_.get()); reclaimed_so_far += partition_size; current.reclaimed += partition_size; current.it++; // Don't drop latest partition if ((*current.it)->id_ == current.partition_list->nextID() - 1) { trim_points_sorted.push(current); } else { shards_oldest_partitions_queue.push(current); } } // 4) Tell the low-pri thread in each shard to drop the decided partitions. while (!shards_oldest_partitions_queue.empty()) { trim_points_sorted.push(shards_oldest_partitions_queue.top()); shards_oldest_partitions_queue.pop(); } // Apply trim points, log stats size_t num_trim_points = trim_points_sorted.size(); while (!trim_points_sorted.empty()) { ShardTrimPoint current = trim_points_sorted.top(); trim_points_sorted.pop(); auto partitioned_store = dynamic_cast<PartitionedRocksDBStore*>(getByIndex(current.shard_idx)); ld_check(partitioned_store != nullptr); partition_id_t first = current.partition_list->firstID(); partition_id_t target = (*current.it)->id_; ld_spew("Setting trim-limit target:%lu for shard:%d. " "coordinated threshold: %lf", target, current.shard_idx, db_settings_->free_disk_space_threshold_low); partitioned_store->setSpaceBasedTrimLimit(target); if (target == first) { ld_debug("Space-based trimming of shard%d: %ju used, dropping nothing", current.shard_idx, current.space_usage); } else { PER_SHARD_STAT_INCR(stats_, sbt_num_storage_trims, current.shard_idx); ld_info("Space-based trimming of shard %d: %ju used, %ju reclaimed, " "dropping partitions [%ju,%ju)", current.shard_idx, current.space_usage, current.reclaimed, first, target); } } if (num_trim_points > 1) { ld_info("Space based trimming, total on disk:%s: used:%ju, limit:%ju, " "reclaimed:%ju", mapping.example_path.c_str(), total_space_used_by_partitions, space_limit_coordinated, reclaimed_so_far); } return 0; } void ShardedRocksDBLocalLogStore::setSequencerInitiatedSpaceBasedRetention( int shard_idx) { ld_debug("shard_idx:%d, coordinated threshold:%lf", shard_idx, db_settings_->free_disk_space_threshold_low); if (db_settings_->free_disk_space_threshold_low == 0) { return; } auto disk_info_kv = fspath_to_dsme_.find(shard_to_devt_[shard_idx]); if (disk_info_kv == fspath_to_dsme_.end()) { RATELIMIT_ERROR(std::chrono::seconds(1), 5, "Couldn't find disk info for disk %s (containing shard %d)", shard_paths_[shard_idx].c_str(), shard_idx); ld_check(false); } else { ld_debug("Setting sequencer_initiated_space_based_retention for shard%d", shard_idx); disk_info_kv->second.sequencer_initiated_space_based_retention.store(true); } } void ShardedRocksDBLocalLogStore::setShardedStorageThreadPool( const ShardedStorageThreadPool* sharded_pool) { for (size_t i = 0; i < shards_.size(); ++i) { filters_[i]->setStorageThreadPool(&sharded_pool->getByIndex(i)); shards_[i]->setProcessor(checked_downcast<Processor*>( &sharded_pool->getByIndex(i).getProcessor())); } } const std::unordered_map<dev_t, DiskShardMappingEntry>& ShardedRocksDBLocalLogStore::getShardToDiskMapping() { return fspath_to_dsme_; } size_t ShardedRocksDBLocalLogStore::createDiskShardMapping() { ld_check(!shard_paths_.empty()); std::unordered_map<dev_t, size_t> dev_to_out_index; size_t success = 0, added_to_map = 0; shard_to_devt_.resize(shard_paths_.size()); for (int shard_idx = 0; shard_idx < shard_paths_.size(); ++shard_idx) { const fs::path& path = shard_paths_[shard_idx]; boost::system::error_code ec; // Resolve any links and such auto db_canonical_path = fs::canonical(path, ec); if (ec.value() != boost::system::errc::success) { RATELIMIT_ERROR(std::chrono::minutes(10), 1, "Failed to find canonical path of shard %d (path %s): %s", shard_idx, path.c_str(), ec.message().c_str()); continue; } std::string true_path = db_canonical_path.generic_string(); struct stat st; int rv = ::stat(true_path.c_str(), &st); if (rv != 0) { RATELIMIT_ERROR(std::chrono::minutes(10), 1, "stat(\"%s\") failed with errno %d (%s)", true_path.c_str(), errno, strerror(errno)); continue; } shard_to_devt_[shard_idx] = st.st_dev; auto insert_result = dev_to_out_index.emplace(st.st_dev, added_to_map); if (!insert_result.second) { // A previous shard had the same dev_t so they are on the same disk. // Just append this shard idx to the list in DiskSpaceInfo. fspath_to_dsme_[shard_to_devt_[shard_idx]].shards.push_back(shard_idx); ++success; continue; } // First time we're seeing the device. The index in the output vector // was "reserved" by the map::emplace() above. fspath_to_dsme_[shard_to_devt_[shard_idx]].example_path = db_canonical_path; fspath_to_dsme_[shard_to_devt_[shard_idx]].shards.push_back(shard_idx); ++added_to_map; ++success; } return success; } void ShardedRocksDBLocalLogStore::printDiskShardMapping() { // Format disk -> shard mapping log std::stringstream disk_mapping_ss; disk_mapping_ss << "Disk -> Shard mapping: "; bool first = true; for (const auto& kv : fspath_to_dsme_) { if (!first) { disk_mapping_ss << ", "; } first = false; disk_mapping_ss << kv.second.example_path.c_str() << " -> ["; auto& last_shard = kv.second.shards.back(); for (auto& shard_idx : kv.second.shards) { disk_mapping_ss << shard_idx << (shard_idx == last_shard ? "]" : ","); } } ld_info("%s", disk_mapping_ss.str().c_str()); } void ShardedRocksDBLocalLogStore::onSettingsUpdated() { for (auto& shard : shards_) { auto rocksdb_shard = dynamic_cast<RocksDBLogStoreBase*>(shard.get()); if (rocksdb_shard == nullptr) { continue; } rocksdb_shard->onSettingsUpdated(db_settings_.get()); } } }} // namespace facebook::logdevice
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
4709b69c8360e57dbce60265702549451a7155f8
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/wget/hunk_191.cpp
c5c6ff2cb2af6099e3920b1925375ca4b95d4f22
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
break; default: - /* Can't happen. */ - assert (1); + logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()")); + logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"), + cwd_count, cwd_start, cwd_end); + abort (); } if (!opt.server_response)
[ "993273596@qq.com" ]
993273596@qq.com
301fcb8c103dc5c5f4ecff5181c077e391710f34
ca4471cd7cbc445953244aa71b1999b8c290b5f4
/farm/farm/QuestTable.cpp
8b21b25be89db8b4e0862ed902e7edb9d63ab40c
[]
no_license
YangHun/d3d12-example-farm
e2bed7b3d64f0403504d1977b37ad7f15cbe518d
25b7b19af41fee32b7add4a10320f85d11aec675
refs/heads/master
2021-01-05T01:37:25.601418
2020-03-31T12:58:07
2020-03-31T12:58:07
240,831,755
1
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
#include "stdafx.h" #include "Objects.h" QuestTable::QuestTable() { SetTag("QuestTable"); GetRenderer()->SetMesh("Assets/table.fbx"); GetCollider()->SetBoundFromMesh(GetRenderer()->meshDesc()); } void QuestTable::Update(float dt) { } void QuestTable::Interact() { Notify(nullptr, E_Event::TABLE_INTERACT_CLICKED); }
[ "pitahano@gmail.com" ]
pitahano@gmail.com
d7cd9d3be7b38cec4f15998a16ef5862672baf1d
34fe5b48225c2509d272032c44d6fe5be08a6330
/src/test/scheduler_tests.cpp
4cacb3d84c431888bcfd7f6aa59d12982d2e1ad5
[ "MIT" ]
permissive
mcret1/socialcoin
8386f2ef1287dadd7530c65d2b8464d83adeb308
7c2a94ff33cd48708113b29ce40515a7236bf7fd
refs/heads/main
2023-06-27T13:29:24.003888
2021-08-04T12:25:04
2021-08-04T12:25:04
376,731,408
0
0
null
null
null
null
UTF-8
C++
false
false
5,017
cpp
// Copyright (c) 2012-2013 The Bitcoin Core developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2018 The socialcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "scheduler.h" #if defined(HAVE_CONFIG_H) #include "config/socialcoin-config.h" #else #define HAVE_WORKING_BOOST_SLEEP_FOR #endif #include <boost/bind.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/thread.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(scheduler_tests) static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime) { { boost::unique_lock<boost::mutex> lock(mutex); counter += delta; } boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min(); if (rescheduleTime != noTime) { CScheduler::Function f = boost::bind(&microTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime); s.schedule(f, rescheduleTime); } } static void MicroSleep(uint64_t n) { #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::microseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::microseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } BOOST_AUTO_TEST_CASE(manythreads) { seed_insecure_rand(false); // Stress test: hundreds of microsecond-scheduled tasks, // serviced by 10 threads. // // So... ten shared counters, which if all the tasks execute // properly will sum to the number of tasks done. // Each task adds or subtracts from one of the counters a // random amount, and then schedules another task 0-1000 // microseconds in the future to subtract or add from // the counter -random_amount+1, so in the end the shared // counters should sum to the number of initial tasks performed. CScheduler microTasks; boost::mutex counterMutex[10]; int counter[10] = { 0 }; boost::random::mt19937 rng(insecure_rand()); boost::random::uniform_int_distribution<> zeroToNine(0, 9); boost::random::uniform_int_distribution<> randomMsec(-11, 1000); boost::random::uniform_int_distribution<> randomDelta(-1000, 1000); boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now(); boost::chrono::system_clock::time_point now = start; boost::chrono::system_clock::time_point first, last; size_t nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 0); for (int i = 0; i < 100; i++) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } nTasks = microTasks.getQueueInfo(first, last); BOOST_CHECK(nTasks == 100); BOOST_CHECK(first < last); BOOST_CHECK(last > now); // As soon as these are created they will start running and servicing the queue boost::thread_group microThreads; for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); MicroSleep(600); now = boost::chrono::system_clock::now(); // More threads and more tasks: for (int i = 0; i < 5; i++) microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, &microTasks)); for (int i = 0; i < 100; i++) { boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng)); boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng)); int whichCounter = zeroToNine(rng); CScheduler::Function f = boost::bind(&microTask, boost::ref(microTasks), boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]), randomDelta(rng), tReschedule); microTasks.schedule(f, t); } // Drain the task queue then exit threads microTasks.stop(true); microThreads.join_all(); // ... wait until all the threads are done int counterSum = 0; for (int i = 0; i < 10; i++) { BOOST_CHECK(counter[i] != 0); counterSum += counter[i]; } BOOST_CHECK_EQUAL(counterSum, 200); } BOOST_AUTO_TEST_SUITE_END()
[ "80612177+mcret1@users.noreply.github.com" ]
80612177+mcret1@users.noreply.github.com
f9da8f7f503cc2ba8e464abac4dd56ee21c23647
3242efa02269cacff87891448dd4c532e3bef882
/InterestingXOR.cpp
a683ead0bbe190148a62d126c93b66e7b76e554b
[]
no_license
m0hit312000/CppPrograms
35419ca81450aa4afdd9ffe79c8870ae1c0530be
da1f2ca1f625833d293c8bd471ca13ef76cc6055
refs/heads/master
2023-04-03T14:48:58.733788
2021-04-13T17:59:21
2021-04-13T17:59:21
286,248,881
0
0
null
null
null
null
UTF-8
C++
false
false
1,425
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define REP(i, a, b) for (int i = a; i < b; i++) #define REV(i, a, b) for (int i = a; i >= b; i--) #define vi vector<int> #define vl vector<long long> int main() { ll t; cin >> t; while (t--) { ll c, no1 = 0, no2 = 0; vi a, b, bin; cin >> c; while (c > 0) { bin.push_back(c % 2); c = c / 2; } reverse(bin.begin(), bin.end()); REP(i, 0, bin.size()) { if (i == 0) { if (bin[0] == 1) { a.push_back(1); b.push_back(0); } else if (bin[i] == 0) { a.push_back(0); b.push_back(0); } } else if (bin[i] == 0) { a.push_back(1); b.push_back(1); } else if (bin[i] == 1) { a.push_back(0); b.push_back(1); } } reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); REV(i, a.size() - 1, 0) { no1 += pow(2, i) * a[i]; } REV(i, b.size() - 1, 0) { no2 += pow(2, i) * b[i]; } cout << no1 * no2 << "\n"; } }
[ "mm8085574989@gmail.com" ]
mm8085574989@gmail.com
00b50a7b40ed9b05301d87b413cd8fdbbf0be452
cff9a867a30cd0478a659f200e657401555ab13c
/Windows/OldEksamensOPRG/Reeksamen Jan16/e16opg4.h
3881e0e8beee353529297d2072d4d60825c19e91
[]
no_license
AndreasAHN/AHN2018
a1e6d6a33503cfbf56e8c1051c9cb1258563d77e
f41e165674f3ca50e5799433a00863da50eb08ed
refs/heads/master
2020-03-08T00:50:55.082617
2018-09-09T23:07:51
2018-09-09T23:07:51
127,815,266
0
0
null
null
null
null
UTF-8
C++
false
false
293
h
#pragma once #include "e16opg5.h" class Taxa { public: Taxa(int vognNummer, int maxAntalKunder); void setErDrift(bool iDrift); void setErLedig(bool ledig); void udskrivStatus()const; private: int vognNummer_; int maxAntalKunder_; bool erIDrift_; bool erLedig_; };
[ "andreas.hervert@gmail.com" ]
andreas.hervert@gmail.com
3b7ededaa9fd96d858a2089960001b982bed8f52
ca08b976e9772a756314648eb913c7a7da261523
/Codeforces/230A. Dragons.cpp
5ca23e23730256bd4923cbd345db28c9dbec409b
[]
no_license
NousinTabassum/ProblemSolving
11574a340d1d899b6ae5e053b74adef452b984c4
f313d7497307139d2a50e44e9b1500be0087d0ca
refs/heads/main
2023-08-04T23:27:48.503539
2021-09-24T15:33:02
2021-09-24T15:33:02
410,012,571
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
#include<iostream> using namespace std; int main() { int s,n,i,x[1000],y[1000],temp,j,c=0,temp2; cin>>s>>n; for(i=0; i<n; i++) { cin>>x[i]>>y[i]; } for(i=0; i<n; i++) { for(j=0; j<n; j++) { if(x[i]<x[j]) { temp=x[i]; temp2=y[i]; x[i]=x[j]; y[i]=y[j]; x[j]=temp; y[j]=temp2; } } } for(i=0; i<n; i++) { if(x[i]<s) { s=s+y[i]; c++; } } if(c==n) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } }
[ "noreply@github.com" ]
NousinTabassum.noreply@github.com
b366307ec1b0122b5bf770d994077e55b8f88788
f9a8e812a0f8e8ddcae5a7da6576f376d5b4c100
/test/unit_and_integrationtests/TestGlobalData.cpp
8792e243a1836bc91bd5f52b7604706b183e6e63
[ "MIT" ]
permissive
CapRat/APAL
d44bfbee74540e812ccd63901d47de401fefb672
a08f4bc6ee6299e8e370ef99750262ad23c87d58
refs/heads/master
2022-12-13T18:52:11.512432
2020-08-19T11:24:40
2020-08-19T11:24:40
290,733,218
2
0
null
null
null
null
ISO-8859-3
C++
false
false
501
cpp
//#include <interfaces/IPlugin.hpp> #include "CatchTools.hpp" #include "base/PluginBases.hpp" #include <GlobalData.hpp> using namespace APAL; class SimpleExamplePlugin : public LazyPlugin { public: // Geerbt über LazyPlugin virtual void processAudio() override {} }; REGISTER_PLUGIN(SimpleExamplePlugin); using namespace APAL; TEST_CASE("Registration of derived Plugins") { REQUIRE_MESSAGE(GlobalData().getNumberOfRegisteredPlugins() >= 1, "Static Initialisation Failed"); }
[ "benjaminheisch@yahoo.de" ]
benjaminheisch@yahoo.de
5334c9e04defb26aa4c0a74167c5981696708821
6ec6ebbd57752e179c3c74cb2b5d2d3668e91110
/rsase/SgBagUML/src/ihm/vuecanevas.h
3b31a2792b274f039f6c16dac0ef57047bddbe4b
[]
no_license
padenot/usdp
6e0562a18d2124f1970fb9f2029353c92fdc4fb4
a3ded795e323e5a2e475ade08839b0f2f41b192b
refs/heads/master
2016-09-05T15:24:53.368597
2010-11-25T16:13:47
2010-11-25T16:13:47
1,106,052
0
0
null
null
null
null
UTF-8
C++
false
false
2,030
h
#ifndef VUE_CANEVAS_H #define VUE_CANEVAS_H #include <QGraphicsItem> class FenetrePrincipale; /** * Classe abstraite, qui permet de définir des implémentation * de méthodes communes au éléments graphiques. */ class VueCanevas: public QGraphicsItem { public: /** * Classe abstraite, qui permet de définir des implémentation * de méthodes communes au éléments graphiques. * @param fenetrePrincipale Un référence sur la fenêtre principale. */ explicit VueCanevas(FenetrePrincipale& fenetrePrincipale); /** * Constructeur prenant un rectangle, qui sera la boite englobante * de l'élément graphique. * @param fenetrePrincipale Une référence sur la fenêtre principale. * @param boundingBox La boundingbox de l'élément graphique. * @return */ VueCanevas(FenetrePrincipale& fenetrePrincipale, QRectF boundingBox); /** * Un accesseur pour la bounding box, permettant d'optimiser le dessin. * @return La boite englobante de l'objet, incluant les marges. */ QRectF boundingRect() const; protected : /** * Un accesseur en écriture pour les coordonnées de l'objet graphique. * @param positionDebut La position du début de l'objet. * @param positionFin La position de fin de l'objet. * @param largeur La largeur de l'objet. * @param ajoutLongueurApresFin Une marge après la fin de l'objet. * @param ajoutLongueurAvantDebut Une marge avant le début de l'objet. */ void definirCoordonnees(QPointF positionDebut, QPointF positionFin, double largeur, double ajoutLongueurApresFin = 0, double ajoutLongueurAvantDebut = 0); /** * @var fenetrePrincipale Référence vers la fenêtre principale. */ FenetrePrincipale& _fenetrePrincipale; /** * Le rectangle englobant pour l'objet, au plus serré (sans les marges). */ QRectF _rect; }; #endif // VUE_CANEVAS_H
[ "golumbeanu.monica@gmail.com" ]
golumbeanu.monica@gmail.com
faa04cf0a9dcd98a9f4b7172e0ffb74c3ed51d1f
75d19cc8b24640f0e632176dc48458d8455dbb7b
/code_generator.cpp
39abdad742194ff92afb2c3c2b76c683db3830eb
[]
no_license
pablogadhi/DecafCompiler
8e91ce7bddf3fa3a2843b0d14e808205c565d930
af59ab996774cf23aae7c82b51c4db8474c9a4d3
refs/heads/master
2023-01-20T01:42:07.894232
2020-11-27T01:12:06
2020-11-27T01:12:06
281,763,276
0
0
null
null
null
null
UTF-8
C++
false
false
11,677
cpp
#include "code_generator.h" #include <fstream> #include <iostream> CodeGenerator::CodeGenerator(vector<Triple> code, shared_ptr<SymbolTable> &table) : inter_code(code), symbol_table(table) { init_code(); main_name = dynamic_pointer_cast<Literal>(inter_code[0].arg0())->value(); end_label = dynamic_pointer_cast<Literal>(inter_code.back().arg0())->value(); // The fist 2 instructions are useless, so we remove them inter_code.erase(inter_code.begin()); inter_code.erase(inter_code.begin()); } CodeGenerator::~CodeGenerator() {} void CodeGenerator::init_code() { gen_code += "section .text\n\n"; gen_code += "extern _alloc_mem, _dealloc_mem, _init_brks, _print_int, _input_int\n"; gen_code += "extern _last_brk, _current_brk\n\n"; gen_code += "global _start\n"; } string get_reg(string temp_name) { if (temp_name == "_tmp_0") { return "rbx"; } else if (temp_name == "_tmp_1") { return "rcx"; } return "rdx"; } string CodeGenerator::operand_to_str(shared_ptr<Address> operand, vector<Triple> &pending) { auto as_literal = dynamic_pointer_cast<Literal>(operand); if (as_literal != nullptr) { string literal_val = as_literal->value(); if (as_literal->type() == "string") { if (literal_val[0] != '_') { if (literal_val != main_name) { literal_val = "_" + literal_val; } else { literal_val = "_start"; } } else { literal_val = "." + literal_val.substr(1, literal_val.size() - 1); } } else { Type type; get_where<Type>( symbol_table->types(), [&](Type &t) { return t.name() == as_literal->type(); }, &type); literal_val = size_prefixes[type.size()] + " " + literal_val; } return literal_val; } auto as_temp = dynamic_pointer_cast<Temp>(operand); if (as_temp != nullptr) { // Add pending pops for (auto &p : pending) { auto pending_temp = dynamic_pointer_cast<Temp>(p.arg0()); if (pending_temp->name() == as_temp->name()) { for (int i = pending.size() - 1; i >= 0; i--) { auto p_temp_name = dynamic_pointer_cast<Temp>(pending[i].arg0())->name(); gen_code += " pop " + get_reg(p_temp_name) + "\n"; } pending.clear(); break; } } if (as_temp->as_offset()) { return "[" + get_reg(as_temp->name()) + "]"; } else { return get_reg(as_temp->name()); } } if (operand->value() != -1) { return "[r14+" + to_string(operand->value()) + "]"; } return ""; } string CodeGenerator::convert_reg(string reg, int size) { string base = reg; function<string(string)> word_transform; if (reg.back() == 'x') { base = reg.substr(1, 1); word_transform = [](string reg_b) { return "e" + reg_b + "x"; }; } else { word_transform = [](string reg_b) { return reg_b + "d"; }; } if (size == 1) { return base + "l"; } else if (size == 4) { return word_transform(base); } return base; } void CodeGenerator::translate_to_asm() { shared_ptr<SymbolTable> local_table; string cond_jump = ""; vector<Triple> pending; bool skip_pop = false; for (int i = 0; i < inter_code.size(); i++) { Triple &instr = inter_code[i]; switch (instr.op()) { case Operator::ASSIGN: { auto l_operand = operand_to_str(instr.arg0(), pending); auto r_operand = operand_to_str(instr.arg1(), pending); if (dynamic_pointer_cast<Temp>(instr.arg0()) != nullptr && instr.arg1()->value() != -1) { Symbol symb; get_where<Symbol>( local_table->symbols(), [&](Symbol &s) { return s.offset() == instr.arg1()->value(); }, &symb); l_operand = convert_reg(l_operand, symb.size()); } else if (dynamic_pointer_cast<Temp>(instr.arg1()) != nullptr && instr.arg0()->value() != -1) { Symbol symb; get_where<Symbol>( local_table->symbols(), [&](Symbol &s) { return s.offset() == instr.arg0()->value(); }, &symb); r_operand = convert_reg(r_operand, symb.size()); } gen_code += " mov " + l_operand + ", " + r_operand + "\n"; break; } case Operator::MUL: { auto l_operand = operand_to_str(instr.arg0(), pending); auto r_operand = operand_to_str(instr.arg1(), pending); if (dynamic_pointer_cast<Temp>(instr.arg0()) == nullptr) { int size = 8; if (instr.arg0()->value() != -1) { Symbol symb; get_where<Symbol>( local_table->symbols(), [&](Symbol &s) { return s.offset() == instr.arg0()->value(); }, &symb); size = symb.size(); } gen_code += " mov " + convert_reg("rax", size) + ", " + l_operand + "\n"; } else { gen_code += " mov rax, " + l_operand + "\n"; } if (dynamic_pointer_cast<Temp>(instr.arg1()) == nullptr) { int size = 8; if (instr.arg1()->value() != -1) { Symbol symb; get_where<Symbol>( local_table->symbols(), [&](Symbol &s) { return s.offset() == instr.arg1()->value(); }, &symb); size = symb.size(); } gen_code += " mov " + convert_reg("rbx", size) + ", " + r_operand + "\n"; } else { gen_code += " mov rbx, " + r_operand + "\n"; } gen_code += " mul rbx\n"; gen_code += " mov " + operand_to_str(inter_code[i - 1].arg0(), pending) + ", rax\n"; break; } case Operator::SUM: gen_code += " add " + operand_to_str(instr.arg0(), pending) + ", " + operand_to_str(instr.arg1(), pending) + "\n"; break; case Operator::LESS: cond_jump = "jl"; break; case Operator::LESS_EQ: cond_jump = "jle"; break; case Operator::GREATER: cond_jump = "jg"; break; case Operator::GREATER_EQ: cond_jump = "jge"; break; case Operator::EQ: cond_jump = "je"; break; case Operator::NOT_EQ: cond_jump = "jne"; break; case Operator::MINUS: if (instr.arg1() != nullptr) { gen_code += " sub " + operand_to_str(instr.arg0(), pending) + ", " + operand_to_str(instr.arg1(), pending) + "\n"; } break; case Operator::LABEL: { auto alias = dynamic_pointer_cast<Literal>(instr.arg0())->value(); auto label_str = operand_to_str(instr.arg0(), pending); gen_code += "\n" + label_str + ":\n"; if (label_str[0] == '_') { Method method; get_where<Method>( symbol_table->methods(), [=](Method &m) { return m.alias() == alias; }, &method); local_table = symbol_table->children()[method]; auto last_symb = local_table->symbols().back(); auto mem_to_alloc = last_symb.size() + last_symb.offset(); // Call _init_brks if label is the main one if (alias == main_name) { gen_code += " call _init_brks\n\n"; } // Allocate memory for all variables gen_code += " mov r13, [_last_brk]\n"; gen_code += " push r13\n"; gen_code += " push " + to_string(mem_to_alloc) + "\n"; gen_code += " call _alloc_mem\n"; gen_code += " pop r13\n"; gen_code += " pop r15\n"; gen_code += " mov r14, [_last_brk]\n"; // Store each param in memory auto &symbols = local_table->symbols(); for (int j = method.param_signature().size() - 1; j >= 0; j--) { gen_code += " pop rbx\n"; gen_code += " mov [r14+" + to_string(symbols[j].offset()) + "], " + convert_reg("rbx", symbols[j].size()) + "\n"; } // Init the rest of variables for (int j = method.param_signature().size(); j < symbols.size(); j++) { Type type; recursive_lookup<Type>( local_table, [&](shared_ptr<SymbolTable> table) { return table->types(); }, [&](Type &t) { return t.name() == symbols[j].type(); }, &type); if (type.type() == "basic") { string default_value = basic_init_vals[type.name()]; gen_code += " mov [r14+" + to_string(symbols[j].offset()) + "], " + size_prefixes[type.size()] + " " + default_value + "\n"; } } // Put back addresses on the vector gen_code += " push r15\n"; gen_code += " push r13\n\n"; } else if (alias == end_label) { gen_code += " mov rax, 60\n"; gen_code += " xor rdi, rdi\n"; gen_code += " syscall\n"; } break; } case Operator::IF: gen_code += " cmp " + operand_to_str(instr.arg0(), pending) + ", " + operand_to_str(inter_code[i - 1].arg1(), pending) + "\n"; break; case Operator::JUMP: if (cond_jump != "") { gen_code += " " + cond_jump + " " + operand_to_str(instr.arg0(), pending) + "\n"; cond_jump = ""; } else { gen_code += " jmp " + operand_to_str(instr.arg0(), pending) + "\n"; } break; case Operator::CALL: gen_code += " call " + operand_to_str(instr.arg0(), pending) + "\n"; gen_code += " mov r14, [_last_brk]\n"; if (inter_code[i + 1].op() == Operator::POP) { pending.push_back(inter_code[i + 1]); skip_pop = true; } break; case Operator::PARAM: case Operator::PUSH: { if (inter_code[i + 1].op() == Operator::RET) { string reg = "r12"; if (instr.arg0()->value() != -1) { Symbol symb; get_where<Symbol>( local_table->symbols(), [&](Symbol &s) { return s.offset() == instr.arg0()->value(); }, &symb); reg = convert_reg(reg, symb.size()); } gen_code += " mov " + reg + ", " + operand_to_str(instr.arg0(), pending) + "\n"; } else { if (instr.arg0()->value() != -1) { Symbol symb; get_where<Symbol>( local_table->symbols(), [&](Symbol &s) { return s.offset() == instr.arg0()->value(); }, &symb); gen_code += " mov " + convert_reg("rbx", symb.size()) + ", " + operand_to_str(instr.arg0(), pending) + "\n"; gen_code += " push rbx\n"; } else { gen_code += " push " + operand_to_str(instr.arg0(), pending) + "\n"; } } break; } case Operator::POP: if (!skip_pop) { gen_code += " pop " + operand_to_str(instr.arg0(), pending) + "\n"; } else { skip_pop = false; } break; case Operator::RET: if (inter_code[i + 1].op() != Operator::LABEL || dynamic_pointer_cast<Literal>(inter_code[i + 1].arg0())->value() != end_label) { gen_code += " call _dealloc_mem\n"; gen_code += " pop r15\n"; // TODO Handle void fuctions gen_code += " push r12\n"; gen_code += " push r15\n"; gen_code += " ret\n"; } break; default: break; } } } void CodeGenerator::generate(string file_name) { auto dot_pos = file_name.find("."); auto asm_filename = file_name.substr(0, dot_pos) + ".asm"; cout << asm_filename << endl; ofstream out_file; out_file.open(asm_filename); translate_to_asm(); out_file << gen_code; out_file.close(); }
[ "pablogadhi@gmail.com" ]
pablogadhi@gmail.com
63c2608b3c1d6e8ad3f665836f7e0686b555d88a
653f49d47f6f88c7c8c0b0343b02e8a5bb8ae66d
/gazebo/converter/convertURDF.cpp
3c897edd2b465423e107308ed09fd29f57bd2a05
[]
no_license
ana-GT/huboCode
53a860454c40090fc61d68ba8c3d6b205e810e42
a45fd1b78b7c3c6a9b37d6097dddfeca831994e4
refs/heads/master
2021-01-10T14:30:48.400413
2013-05-12T04:05:07
2013-05-12T04:05:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
/** * @file convertURDF.cpp */ #include <gazebo/sdf/interface/parser_urdf.hh> /** * @function main */ int main( int argc, char* argv[] ) { urdf2gazebo::URDF2Gazebo u2g; TiXmlDocument xml_sdf; xml_sdf = u2g.InitModelFile( argv[1] ); xml_sdf.SaveFile("test.sdf" ); return 0; }
[ "ahuaman3@gatech.edu" ]
ahuaman3@gatech.edu
309888b30219beb00c58b3c3b8eebb049553e412
fe4ac813edf7cece997d4a02940c1aed40efe4b7
/src/Fryer.h
36daf3ed394299d1d3c95f05a6196a1ac5110d6d
[]
no_license
piotrek-k/SO2_Projekt_2
0d312f1a8c954080f909e04168fbc898b595d128
d5272a1352ce3e59e649a6a452069cf3575b5857
refs/heads/master
2022-10-22T22:09:08.464478
2020-06-15T13:50:07
2020-06-15T13:50:07
258,800,293
0
0
null
null
null
null
UTF-8
C++
false
false
479
h
#ifndef SO2_PROJEKT_FRYER #define SO2_PROJEKT_FRYER #include <mutex> #include <functional> #include "Worker.h" enum FryerState { Inactive, WorkingAndFoodNotYetPrepared, WorkingAndFoodBurnt }; class Worker; class Fryer { private: std::mutex mtx; bool taken = false; public: Fryer(); ~Fryer(); bool TryToLockAndExecute(Worker *w, const std::function<void(Worker *)> &action); bool IsTaken() { return taken; } }; #endif //SO2_PROJEKT_FRYER
[ "kpiotrek3@gmail.com" ]
kpiotrek3@gmail.com
eeb28be50d77a8af8fb73f4feb40646e0e8c8b7b
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634697451274240_1/C++/amalykh/Source1.cpp
2165d46058f35b1d19a88b0c49d7480b1e8b6a75
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
831
cpp
#define _CRT_SECURE_NO_WARNINGS #pragma comment(linker, "/STACK:134217728") #include <algorithm> #include <iostream> #include <string> #include <cstring> #include <cstdio> #include <cstdlib> #include <set> #include <vector> #include <map> #include <sstream> #include <queue> #include <ctime> typedef long long ll; #define mp make_pair #define mt(a, b, c) mp(a, mp(b, c)) #define ZERO(x) memset((x), 0, sizeof(x)) using namespace std; int main() { #ifdef XXX freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; scanf("%d", &t); for (int w = 0; w < t; w++) { string s; cin >> s; s.push_back('+'); int ans = 0; for (int i = 1; i < s.size(); i++) if (s[i] != s[i - 1]) ans++; printf("Case #%d: %d\n", w + 1, ans); } return 0; }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
c2f95714cf0bd71d2a9c5935bd525c861c25901d
a25c33ac5f47e8a28e4cb7439d658e511e95843b
/Palindrome Assignment/Project13/Main.cpp
fa1d35e2a758eb7d81142805ce5ee5d66f81e8cd
[]
no_license
SGNitron/Palindrome-Checker
9d92f649b34307ded61951f9313ebc617db14b1b
5388ce59011bd3beaaebdfb3a5229c3ae14629e2
refs/heads/master
2020-09-29T11:26:09.431599
2019-12-10T05:23:08
2019-12-10T05:23:08
227,029,493
0
0
null
null
null
null
UTF-8
C++
false
false
2,202
cpp
#include "ArrayQueue.h" #include "ArrayStack.h" #include "PrecondViolatedExcept.h" #include "QueueInterface.h" #include "StackInterface.h" #include <fstream> #include <iostream> #include <string> using namespace std; void fixCaps(char array[], int size); int main() { string fileInput, originalInput; char chArray[75]; ArrayStack <char> palindromeStack; ArrayQueue <char> palindromeQueue; char queueFront, stackTop; bool isPalindrome; int len; ifstream inFile; inFile.open("Palindrome.txt"); if (!inFile) { //Failsafe in case the file is not found cout << "Error: File Not Found" << endl; } while (!inFile.eof()) { getline(inFile, fileInput); originalInput = fileInput; } for (unsigned int i = 0; i < fileInput.size(); i++) { //accounts for spaces and punctuation if (fileInput[i] < 65 || (90 < fileInput[i] && fileInput[i < 97]) || fileInput[i] > 122) { fileInput.erase(i, 1); i--; } } strcpy_s(chArray, fileInput.c_str()); //string to char array len = strlen(chArray); fixCaps(chArray, len); //calls function to convert to lowercase cout << "Checking: " << chArray << endl << endl; for (int i = 0; i < len; i++) { palindromeStack.push(chArray[i]); palindromeQueue.enqueue(chArray[i]); } while (!palindromeQueue.isEmpty() && !palindromeStack.isEmpty()) { stackTop = palindromeQueue.peekFront(); queueFront = palindromeStack.peek(); if (stackTop == queueFront) { palindromeQueue.dequeue(); palindromeStack.pop(); isPalindrome = true; } else { isPalindrome = false; while (!palindromeStack.isEmpty() && !palindromeQueue.isEmpty()) { palindromeQueue.dequeue(); palindromeStack.pop(); } } } if (isPalindrome == true) cout << originalInput << " is a palindrome" << endl; else if (isPalindrome == false) cout << originalInput << " is not a palindrome" << endl; system("PAUSE"); } void fixCaps(char array[], int size) { //converts uppercase to lowercase for (int i = 0; i <= size; i++) { if (array[i] >= 65 && array[i] <= 92) { array[i] = array[i] + 32; } } }
[ "noreply@github.com" ]
SGNitron.noreply@github.com
98a9d7e3f949b2f949eedd9fd9e74c947d51736d
2470b6e1cfb284400cee9e61b05c8e1ea7dfcbb9
/Source/Voxel/Private/VoxelDebug/VoxelDebugManager.cpp
d7cffa3a2cd16cb62f24c313331b3a7606cced02
[ "MIT" ]
permissive
ADMTec/VoxelPlugin
893a77e9a52249b9a3f1f02baf3d944b93cba0f0
db3c94fd8140d27671b9e80f09c47b28d02a6096
refs/heads/master
2022-04-29T20:27:16.755901
2022-03-06T14:39:33
2022-03-06T14:39:33
128,440,588
0
0
MIT
2020-03-30T13:39:07
2018-04-06T18:42:52
HLSL
UTF-8
C++
false
false
25,279
cpp
// Copyright 2021 Phyronnaz #include "VoxelDebug/VoxelDebugManager.h" #include "VoxelDebug/VoxelDebugUtilities.h" #include "VoxelData/VoxelData.h" #include "VoxelRender/IVoxelLODManager.h" #include "VoxelRender/IVoxelRenderer.h" #include "VoxelData/VoxelDataIncludes.h" #include "VoxelComponents/VoxelInvokerComponent.h" #include "VoxelTools/VoxelDataTools.h" #include "VoxelTools/VoxelSurfaceTools.h" #include "VoxelTools/VoxelBlueprintLibrary.h" #include "VoxelMessages.h" #include "VoxelWorld.h" #include "VoxelPool.h" #include "VoxelThreadPool.h" #include "VoxelUtilities/VoxelConsoleUtilities.h" #include "VoxelUtilities/VoxelThreadingUtilities.h" #include "Engine/Engine.h" #include "EngineUtils.h" #include "DrawDebugHelpers.h" #include "Kismet/GameplayStatics.h" static TAutoConsoleVariable<int32> CVarShowUpdatedChunks( TEXT("voxel.renderer.ShowUpdatedChunks"), 0, TEXT("If true, will show the chunks recently updated"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowRenderChunks( TEXT("voxel.renderer.ShowRenderChunks"), 0, TEXT("If true, will show the render chunks"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowMultiplayerSyncedChunks( TEXT("voxel.multiplayer.ShowSyncedChunks"), 0, TEXT("If true, will show the synced chunks"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowValuesState( TEXT("voxel.data.ShowValuesState"), 0, TEXT("If true, will show the values data chunks and their status (cached/created...)"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowMaterialsState( TEXT("voxel.data.ShowMaterialsState"), 0, TEXT("If true, will show the materials data chunks and their status (cached/created...)"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowDirtyValues( TEXT("voxel.data.ShowDirtyValues"), 0, TEXT("If true, will show the data chunks with dirty values"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowDirtyMaterials( TEXT("voxel.data.ShowDirtyMaterials"), 0, TEXT("If true, will show the data chunks with dirty materials"), ECVF_Default); static TAutoConsoleVariable<int32> CVarFreezeDebug( TEXT("voxel.FreezeDebug"), 0, TEXT("If true, won't clear previous frames boxes"), ECVF_Default); static TAutoConsoleVariable<int32> CVarDebugDrawTime( TEXT("voxel.debug.DrawTime"), 1, TEXT("Draw time will be multiplied by this"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowChunksEmptyStates( TEXT("voxel.renderer.ShowChunksEmptyStates"), 0, TEXT("If true, will show updated chunks empty state, only if non-empty. Use ShowAllChunksEmptyStates to show empty too."), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowAllChunksEmptyStates( TEXT("voxel.renderer.ShowAllChunksEmptyStates"), 0, TEXT("If true, will show updated chunks empty state, both empty and non-empty. Use ShowChunksEmptyStates to only show non-empty ones"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowWorldBounds( TEXT("voxel.ShowWorldBounds"), 0, TEXT("If true, will show the world bounds"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowInvokers( TEXT("voxel.ShowInvokers"), 0, TEXT("If true, will show the voxel invokers"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowDirtyVoxels( TEXT("voxel.data.ShowDirtyVoxels"), 0, TEXT("If true, will show every dirty voxel in the scene"), ECVF_Default); static TAutoConsoleVariable<int32> CVarShowPlaceableItemsChunks( TEXT("voxel.data.ShowPlaceableItemsChunks"), 0, TEXT("If true, will show every chunk that has a placeable item"), ECVF_Default); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// static FAutoConsoleCommandWithWorld ClearChunksEmptyStatesCmd( TEXT("voxel.renderer.ClearChunksEmptyStates"), TEXT("Clear the empty states debug"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { World.GetSubsystemChecked<FVoxelDebugManager>().ClearChunksEmptyStates(); })); static FAutoConsoleCommandWithWorld UpdateAllCmd( TEXT("voxel.renderer.UpdateAll"), TEXT("Update all the chunks in all the voxel world in the scene"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelBlueprintLibrary::UpdateBounds(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld RecomputeComponentPositionsCmd( TEXT("voxel.RecomputeComponentPositions"), TEXT("Recompute the positions of all the components in all the voxel world in the scene"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelBlueprintLibrary::RecomputeComponentPositions(&World); })); static FAutoConsoleCommandWithWorld ForceLODsUpdateCmd( TEXT("voxel.renderer.ForceLODUpdate"), TEXT("Update the LODs"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { World.GetSubsystemChecked<IVoxelLODManager>().ForceLODsUpdate(); })); static FAutoConsoleCommandWithWorld CacheAllValuesCmd( TEXT("voxel.data.CacheAllValues"), TEXT("Cache all values"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::CacheValues(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld CacheAllMaterialsCmd( TEXT("voxel.data.CacheAllMaterials"), TEXT("Cache all materials"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::CacheMaterials(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld ClearAllCachedValuesCmd( TEXT("voxel.data.ClearAllCachedValues"), TEXT("Clear all cached values"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::ClearCachedValues(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld ClearAllCachedMaterialsCmd( TEXT("voxel.data.ClearAllCachedMaterials"), TEXT("Clear all cached materials"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::ClearCachedMaterials(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld CheckForSingleValuesCmd( TEXT("voxel.data.CheckForSingleValues"), TEXT("Check if values in a chunk are all the same, and if so only store one"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::CheckForSingleValues(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld CheckForSingleMaterialsCmd( TEXT("voxel.data.CheckForSingleMaterials"), TEXT("Check if materials in a chunk are all the same, and if so only store one"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::CheckForSingleMaterials(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld RoundVoxelsCmd( TEXT("voxel.data.RoundVoxels"), TEXT("Round all voxels that do not impact the surface nor the normals"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::RoundVoxels(&World, FVoxelIntBox::Infinite); if (World.GetSubsystemChecked<FVoxelData>().bEnableUndoRedo) UVoxelBlueprintLibrary::SaveFrame(&World); })); static FAutoConsoleCommandWithWorld ClearUnusedMaterialsCmd( TEXT("voxel.data.ClearUnusedMaterials"), TEXT("Will clear all materials that do not affect the surface to improve compression"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::ClearUnusedMaterials(&World, FVoxelIntBox::Infinite); if (World.GetSubsystemChecked<FVoxelData>().bEnableUndoRedo) UVoxelBlueprintLibrary::SaveFrame(&World); })); static FAutoConsoleCommandWithWorld RegenerateAllSpawnersCmd( TEXT("voxel.foliage.RegenerateAll"), TEXT("Regenerate all foliage that can be regenerated"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelBlueprintLibrary::RegenerateSpawners(&World, FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld CompressIntoHeightmapCmd( TEXT("voxel.data.CompressIntoHeightmap"), TEXT("Update the heightmap to match the voxel world data"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::CompressIntoHeightmap(&World); UVoxelBlueprintLibrary::UpdateBounds(&World, FVoxelIntBox::Infinite); if (World.GetSubsystemChecked<FVoxelData>().bEnableUndoRedo) UVoxelBlueprintLibrary::SaveFrame(&World); })); static FAutoConsoleCommandWithWorld RoundToGeneratorCmd( TEXT("voxel.data.RoundToGenerator"), TEXT("Set the voxels back to the generator value if all the voxels in a radius of 2 have the same sign as the generator"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelDataTools::RoundToGenerator(&World, FVoxelIntBox::Infinite); UVoxelBlueprintLibrary::UpdateBounds(&World, FVoxelIntBox::Infinite); if (World.GetSubsystemChecked<FVoxelData>().bEnableUndoRedo) UVoxelBlueprintLibrary::SaveFrame(&World); })); static FAutoConsoleCommandWithWorld CompactTexturePoolCmd( TEXT("voxel.texturepool.compact"), TEXT("Reallocate all the entries, reducing fragmentation & saving memory"), FVoxelUtilities::CreateVoxelWorldCommand([](AVoxelWorld& World) { UVoxelBlueprintLibrary::CompactVoxelTexturePool(&World); })); static bool GShowCollisionAndNavmeshDebug = false; static FAutoConsoleCommandWithWorldAndArgs ShowCollisionAndNavmeshDebugCmd( TEXT("voxel.renderer.ShowCollisionAndNavmeshDebug"), TEXT("If true, will show chunks used for collisions/navmesh and will color all chunks according to their usage"), FVoxelUtilities::CreateVoxelWorldCommandWithArgs([](AVoxelWorld& World, const TArray<FString>& Args) { if (Args.Num() == 0) { GShowCollisionAndNavmeshDebug = !GShowCollisionAndNavmeshDebug; } else if (Args[0] == "0") { GShowCollisionAndNavmeshDebug = false; } else { GShowCollisionAndNavmeshDebug = true; } World.GetSubsystemChecked<IVoxelLODManager>().UpdateBounds(FVoxelIntBox::Infinite); })); static FAutoConsoleCommandWithWorld RebaseOntoCameraCmd( TEXT("voxel.RebaseOntoCamera"), TEXT("Call SetWorldOriginLocation so that the camera is at 0 0 0"), FConsoleCommandWithWorldDelegate::CreateLambda([](UWorld* World) { auto* CameraManager = UGameplayStatics::GetPlayerCameraManager(World, 0); if (ensure(CameraManager)) { const FVector Position = CameraManager->GetCameraLocation(); UGameplayStatics::SetWorldOriginLocation(World, UGameplayStatics::GetWorldOriginLocation(World) + FIntVector(Position)); } })); static FAutoConsoleCommand CmdLogMemoryStats( TEXT("voxel.LogMemoryStats"), TEXT(""), FConsoleCommandDelegate::CreateStatic(&UVoxelBlueprintLibrary::LogMemoryStats)); static void LogSecondsPerCycles() { LOG_VOXEL(Log, TEXT("SECONDS PER CYCLES: %e"), FPlatformTime::GetSecondsPerCycle()); } static FAutoConsoleCommand CmdLogSecondsPerCycles( TEXT("voxel.debug.LogSecondsPerCycles"), TEXT(""), FConsoleCommandDelegate::CreateStatic(&LogSecondsPerCycles)); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// bool FVoxelGlobalDebugManager::Tick(float DeltaTime) { VOXEL_FUNCTION_COUNTER(); const auto Counters = GVoxelThreadPool->GetGlobalCounters(); const int32 PoolTaskCount = Counters.GetTotalNumTasks(); const int32 MesherTaskCount = Counters.GetNumTasksForType(EVoxelTaskType::ChunksMeshing) + Counters.GetNumTasksForType(EVoxelTaskType::VisibleChunksMeshing) + Counters.GetNumTasksForType(EVoxelTaskType::CollisionsChunksMeshing) + Counters.GetNumTasksForType(EVoxelTaskType::VisibleCollisionsChunksMeshing) + Counters.GetNumTasksForType(EVoxelTaskType::MeshMerge); const int32 FoliageTaskCount = Counters.GetNumTasksForType(EVoxelTaskType::FoliageBuild) + Counters.GetNumTasksForType(EVoxelTaskType::HISMBuild); const int32 EditTaskCount = Counters.GetNumTasksForType(EVoxelTaskType::AsyncEditFunctions); const int32 LODTaskCount = Counters.GetNumTasksForType(EVoxelTaskType::RenderOctree); const int32 CollisionTaskCount = Counters.GetNumTasksForType(EVoxelTaskType::CollisionCooking); if (PoolTaskCount > 0) { const FString Message = FString::Printf(TEXT("Voxel tasks: %d (mesher: %d; foliage: %d; edits: %d; LOD: %d; Collision: %d) %d threads"), PoolTaskCount, MesherTaskCount, FoliageTaskCount, EditTaskCount, LODTaskCount, CollisionTaskCount, CVarVoxelThreadingNumThreads.GetValueOnGameThread()); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DeltaTime * 1.5f, FColor::White, Message); } return true; } FVoxelGlobalDebugManager* GVoxelDebugManager = nullptr; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// inline float GetBoundsThickness(const FVoxelIntBox& Bounds) { return Bounds.Size().GetMax(); } #define DRAW_BOUNDS(Bounds, Color, bThick) UVoxelDebugUtilities::DrawDebugIntBox(World, Bounds, DebugDT, bThick ? GetBoundsThickness(Bounds) : 0, FLinearColor(Color)); #define DRAW_BOUNDS_ARRAY(BoundsArray, Color, bThick) for (auto& Bounds : BoundsArray) { DRAW_BOUNDS(Bounds, FColorList::Color, bThick) } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// DEFINE_VOXEL_SUBSYSTEM_PROXY(UVoxelDebugSubsystemProxy); void FVoxelDebugManager::Destroy() { Super::Destroy(); StopTicking(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FVoxelDebugManager::ReportUpdatedChunks(TFunction<TArray<FVoxelIntBox>()> InUpdatedChunks) { if (CVarShowUpdatedChunks.GetValueOnGameThread()) { VOXEL_ASYNC_FUNCTION_COUNTER(); UpdatedChunks = InUpdatedChunks(); FString Log = "Updated chunks: "; for (auto& Bounds : UpdatedChunks) { Log += Bounds.ToString() + "; "; } GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), 1, FColor::Blue, Log); LOG_VOXEL(Log, TEXT("%s"), *Log); } } void FVoxelDebugManager::ReportRenderChunks(TFunction<TArray<FVoxelIntBox>()> InRenderChunks) { if (CVarShowRenderChunks.GetValueOnGameThread()) { VOXEL_ASYNC_FUNCTION_COUNTER(); RenderChunks = InRenderChunks(); } } void FVoxelDebugManager::ReportMultiplayerSyncedChunks(TFunction<TArray<FVoxelIntBox>()> InMultiplayerSyncedChunks) { if (CVarShowMultiplayerSyncedChunks.GetValueOnGameThread()) { VOXEL_ASYNC_FUNCTION_COUNTER(); MultiplayerSyncedChunks = InMultiplayerSyncedChunks(); } } void FVoxelDebugManager::ReportMeshTasksCallbacksQueueNum(int32 Num) { MeshTasksCallbacksQueueNum = Num; } void FVoxelDebugManager::ReportMeshActionQueueNum(int32 Num) { MeshActionQueueNum = Num; } void FVoxelDebugManager::ReportChunkEmptyState(const FVoxelIntBox& Bounds, bool bIsEmpty) { ChunksEmptyStates.Emplace(FChunkEmptyState{ Bounds, bIsEmpty }); } void FVoxelDebugManager::ClearChunksEmptyStates() { ChunksEmptyStates.Reset(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// bool FVoxelDebugManager::ShowCollisionAndNavmeshDebug() { return GShowCollisionAndNavmeshDebug; } FColor FVoxelDebugManager::GetCollisionAndNavmeshDebugColor(bool bEnableCollisions, bool bEnableNavmesh) { if (bEnableCollisions && bEnableNavmesh) { return FColor::Yellow; } if (bEnableCollisions) { return FColor::Blue; } if (bEnableNavmesh) { return FColor::Green; } return FColor::White; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void FVoxelDebugManager::Tick(float DeltaTime) { VOXEL_FUNCTION_COUNTER(); const AVoxelWorld* World = Settings.VoxelWorld.Get(); if (!World || Settings.bDisableDebugManager) { return; } const float DebugDT = DeltaTime * 1.5f * CVarDebugDrawTime.GetValueOnGameThread(); if (CVarShowRenderChunks.GetValueOnGameThread()) { DRAW_BOUNDS_ARRAY(RenderChunks, Grey, false); } if (CVarShowUpdatedChunks.GetValueOnGameThread()) { DRAW_BOUNDS_ARRAY(UpdatedChunks, Blue, true); } if (CVarShowMultiplayerSyncedChunks.GetValueOnGameThread()) { DRAW_BOUNDS_ARRAY(MultiplayerSyncedChunks, Blue, true); } if (CVarShowWorldBounds.GetValueOnGameThread()) { DRAW_BOUNDS(Settings.GetWorldBounds(), FColorList::Red, true); } if (!Settings.bDisableOnScreenMessages) { if (MeshTasksCallbacksQueueNum > 0) { GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, FColor::White, FString::Printf(TEXT("Mesh tasks callbacks queued: %d"), MeshTasksCallbacksQueueNum)); } if (MeshActionQueueNum > 0) { GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, FColor::White, FString::Printf(TEXT("Mesh actions queued: %d"), MeshActionQueueNum)); } } if (!CVarFreezeDebug.GetValueOnGameThread()) { UpdatedChunks.Reset(); MultiplayerSyncedChunks.Reset(); } if (CVarShowInvokers.GetValueOnGameThread()) { const FColor LocalInvokerColor = FColor::Green; const FColor RemoteInvokerColor = FColor::Silver; const FColor LODColor = FColor::Red; const FColor CollisionsColor = FColor::Blue; const FColor NavmeshColor = FColor::Green; GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, LocalInvokerColor, TEXT("Local Invokers")); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, RemoteInvokerColor, TEXT("Remote Invokers")); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, LODColor, TEXT("Invokers LOD Bounds")); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, CollisionsColor, TEXT("Invokers Collisions Bounds")); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, NavmeshColor, TEXT("Invokers Navmesh Bounds")); for (auto& Invoker : UVoxelInvokerComponentBase::GetInvokers(World)) { if (Invoker.IsValid()) { DrawDebugPoint( World->GetWorld(), World->LocalToGlobal(Invoker->GetInvokerVoxelPosition(World)), 100, Invoker->IsLocalInvoker() ? LocalInvokerColor : RemoteInvokerColor, false, DebugDT); const auto InvokerSettings = Invoker->GetInvokerSettings(World); if (InvokerSettings.bUseForLOD) { DRAW_BOUNDS(InvokerSettings.LODBounds, LODColor, true); } if (InvokerSettings.bUseForCollisions) { DRAW_BOUNDS(InvokerSettings.CollisionsBounds, CollisionsColor, true); } if (InvokerSettings.bUseForNavmesh) { DRAW_BOUNDS(InvokerSettings.NavmeshBounds, NavmeshColor, true); } } } } if (CVarShowChunksEmptyStates.GetValueOnGameThread()) { const static FColor NotEmpty = FColorList::Brown; GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, NotEmpty, TEXT("Not empty chunks (range analysis failed)")); for (auto& EmptyState : ChunksEmptyStates) { if (!EmptyState.bIsEmpty) { DRAW_BOUNDS(EmptyState.Bounds, NotEmpty, false); } } } if (CVarShowAllChunksEmptyStates.GetValueOnGameThread()) { const static FColor Empty = FColorList::Green; const static FColor NotEmpty = FColorList::Brown; GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, Empty, TEXT("Empty chunks (range analysis successful)")); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, NotEmpty, TEXT("Not empty chunks (range analysis failed)")); for (auto& EmptyState : ChunksEmptyStates) { if (EmptyState.bIsEmpty) { DRAW_BOUNDS(EmptyState.Bounds, Empty, false); } else { DRAW_BOUNDS(EmptyState.Bounds, NotEmpty, false); } } } const FColor SingleColor = FColorList::Green; const FColor SingleDirtyColor = FColorList::Blue; const FColor CachedColor = FColorList::Yellow; const FColor DirtyColor = FColorList::Red; const UVoxelDebugUtilities::FDrawDataOctreeSettings DrawDataOctreeSettings { World, DebugDT, false, false, SingleColor, SingleDirtyColor, CachedColor, DirtyColor }; FVoxelData& Data = GetSubsystemChecked<FVoxelData>(); if (CVarShowValuesState.GetValueOnGameThread()) { GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, FColor::White, "Values state:"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, DirtyColor, "Dirty"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, CachedColor, "Cached"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, SingleColor, "Single Item Stored"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, SingleDirtyColor, "Single Item Stored - Dirty"); auto LocalDrawDataOctreeSettings = DrawDataOctreeSettings; LocalDrawDataOctreeSettings.bShowSingle = true; LocalDrawDataOctreeSettings.bShowCached = true; FVoxelReadScopeLock Lock(Data, FVoxelIntBox::Infinite, FUNCTION_FNAME); UVoxelDebugUtilities::DrawDataOctreeImpl<FVoxelValue>(Data, LocalDrawDataOctreeSettings); } if (CVarShowMaterialsState.GetValueOnGameThread()) { GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, FColor::White, "Materials state:"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, DirtyColor, "Dirty"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, CachedColor, "Cached"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, SingleColor, "Single Item Stored"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, SingleDirtyColor, "Single Item Stored - Dirty"); auto LocalDrawDataOctreeSettings = DrawDataOctreeSettings; LocalDrawDataOctreeSettings.bShowSingle = true; LocalDrawDataOctreeSettings.bShowCached = true; FVoxelReadScopeLock Lock(Data, FVoxelIntBox::Infinite, FUNCTION_FNAME); UVoxelDebugUtilities::DrawDataOctreeImpl<FVoxelMaterial>(Data, LocalDrawDataOctreeSettings); } if (CVarShowDirtyValues.GetValueOnGameThread()) { auto LocalDrawDataOctreeSettings = DrawDataOctreeSettings; LocalDrawDataOctreeSettings.bShowSingle = false; LocalDrawDataOctreeSettings.bShowCached = false; FVoxelReadScopeLock Lock(Data, FVoxelIntBox::Infinite, FUNCTION_FNAME); UVoxelDebugUtilities::DrawDataOctreeImpl<FVoxelValue>(Data, LocalDrawDataOctreeSettings); } if (CVarShowDirtyMaterials.GetValueOnGameThread()) { auto LocalDrawDataOctreeSettings = DrawDataOctreeSettings; LocalDrawDataOctreeSettings.bShowSingle = false; LocalDrawDataOctreeSettings.bShowCached = false; FVoxelReadScopeLock Lock(Data, FVoxelIntBox::Infinite, FUNCTION_FNAME); UVoxelDebugUtilities::DrawDataOctreeImpl<FVoxelMaterial>(Data, LocalDrawDataOctreeSettings); } if (CVarShowPlaceableItemsChunks.GetValueOnGameThread()) { FVoxelReadScopeLock Lock(Data, FVoxelIntBox::Infinite, FUNCTION_FNAME); FVoxelOctreeUtilities::IterateEntireTree(Data.GetOctree(), [&](const FVoxelDataOctreeBase& Octree) { if (Octree.IsLeafOrHasNoChildren() && Octree.GetItemHolder().NumItems() > 0) { ensureThreadSafe(Octree.IsLockedForRead()); UVoxelDebugUtilities::DrawDebugIntBox(World, Octree.GetBounds(), DebugDT, 0, FColorList::Red); } }); } if (GShowCollisionAndNavmeshDebug) { GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, GetCollisionAndNavmeshDebugColor(true, false), "Chunks with collisions"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, GetCollisionAndNavmeshDebugColor(false, true), "Chunks with navmesh"); GEngine->AddOnScreenDebugMessage(OBJECT_LINE_ID(), DebugDT, GetCollisionAndNavmeshDebugColor(true, true), "Chunks with navmesh and collision"); } if (CVarShowDirtyVoxels.GetValueOnGameThread()) { FVoxelDataUtilities::IterateDirtyDataInBounds<FVoxelValue>( Data, FVoxelIntBox::Infinite, [&](int32 X, int32 Y, int32 Z, const FVoxelValue& Value) { DrawDebugPoint( World->GetWorld(), World->LocalToGlobal(FIntVector(X, Y, Z)), 2, Value.IsEmpty() ? FColor::Blue : FColor::Red, false, DebugDT); }); } }
[ "phyronnaz@gmail.com" ]
phyronnaz@gmail.com
8b267815331340b27c84475de651766dce21b93a
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/tests/Utils/NameValidatorTest.cpp
79cee49175e24ac8854f42826853129257770bc4
[ "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "BSL-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
64,709
cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Julia Puget //////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" #include "Utilities/NameValidator.h" #include <string_view> TEST(NameValidatorTest, test_isSystemName) { EXPECT_FALSE(arangodb::NameValidator::isSystemName("")); EXPECT_TRUE(arangodb::NameValidator::isSystemName("_")); EXPECT_TRUE(arangodb::NameValidator::isSystemName("_abc")); EXPECT_FALSE(arangodb::NameValidator::isSystemName("abc")); EXPECT_FALSE(arangodb::NameValidator::isSystemName("abc_")); } TEST(DatabaseNameValidatorTest, test_isAllowedName_traditionalNames) { // direct (non-system) std::string const borderline(64, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); { EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, false, std::string_view(tooLong)) .ok()); } // direct (system) { EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(borderline)) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(tooLong)) .ok()); } // special characters EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("<script>alert(1);")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a b c")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("/")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a/")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a/b")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\\b")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a.b.c")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("\na")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("\ta")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("\ra")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("\ba")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("\fa")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\n")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\t")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\r")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\b")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a\f")) .ok()); // spaces EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a ")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("a b")) .ok()); // unicode EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("mötör")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("😀")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("😀 🍺")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("maçã")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, false, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(DatabaseNameValidatorTest, test_isAllowedName_extendedNames) { // direct (non-system) std::string const borderline(128, 'x'); std::string const tooLong(borderline.size() + 1, 'x'); { EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( false, true, std::string_view(tooLong)) .ok()); } // direct (system) { EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(tooLong)) .ok()); } // special characters EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(" a + & ? = abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a + & ? = abc ")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a + & ? = abc")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("<script>alert(1);")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a b c")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("/")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a/")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a/b")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\\b")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a.b.c")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("\na")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("\ta")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("\ra")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("\ba")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("\fa")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\n")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\t")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\r")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\b")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a\f")) .ok()); // spaces EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a ")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("a b")) .ok()); // unicode EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("mötör")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("😀")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("😀 🍺")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("maçã")) .ok()); EXPECT_TRUE(arangodb::DatabaseNameValidator::validateName( true, true, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(CollectionNameValidatorTest, test_isAllowedName_traditionalNames) { // direct (non-system) std::string const borderline(256, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); { EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("_abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("_")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view(":")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view("abc:d")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, false, std::string_view(tooLong)) .ok()); } // direct (system) { EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(borderline)) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(tooLong)) .ok()); } // special characters EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("<script>alert(1);")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("a b c")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("a\0b", 3)) .ok()); // spaces EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("a ")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("a b")) .ok()); // unicode EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("mötör")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("😀")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("😀 🍺")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("maçã")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, false, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(CollectionNameValidatorTest, test_isAllowedName_extendedNames) { // direct (non-system) std::string const borderline(256, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); { EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("_abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("_")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view(":")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view("abc:d")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( false, true, std::string_view(tooLong)) .ok()); } // direct (system) { EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("abc123")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view(tooLong)) .ok()); } // special characters EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a + & ? = abc")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("<script>alert(1);")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a b c")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("/")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a/")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a/b")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a\\b")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a.b.c")) .ok()); // spaces EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a ")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("a b")) .ok()); // unicode EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("mötör")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("😀")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("😀 🍺")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("maçã")) .ok()); EXPECT_TRUE(arangodb::CollectionNameValidator::validateName( true, true, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(IndexNameValidatorTest, test_isAllowedName_traditionalNames) { // direct (non-system) std::string const borderline(256, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( false, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( false, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("123abc")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( false, std::string_view("abc_")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( false, std::string_view("abc-")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("_")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view(":")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("abc:d")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( false, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view(tooLong)) .ok()); // special characters EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("<script>alert(1);")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("a b c")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("a/b")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("//")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("/\\")) .ok()); // spaces EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view(" a")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("a ")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("a b")) .ok()); // unicode EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("mötör")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("😀")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(false, std::string_view("😀 🍺")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("maçã")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( false, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(IndexNameValidatorTest, test_isAllowedName_extendedNames) { // direct (non-system) std::string const borderline(256, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( true, std::string_view("123abc")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("123")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("_123")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("_abc")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("abc_")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("abc-")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view(borderline)) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( true, std::string_view(tooLong)) .ok()); // special characters EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("a + & ? = abc")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("<script>alert(1);")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("a b c")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("abc:cde")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::IndexNameValidator::validateName( true, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("/")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("/\\")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("a/")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("a/b")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("a\\b")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("a.b.c")) .ok()); // spaces EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view(" a")) .ok()); EXPECT_FALSE( arangodb::IndexNameValidator::validateName(true, std::string_view("a ")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("a b")) .ok()); // unicode EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("mötör")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("😀")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("😀 🍺")) .ok()); EXPECT_TRUE( arangodb::IndexNameValidator::validateName(true, std::string_view("maçã")) .ok()); EXPECT_TRUE(arangodb::IndexNameValidator::validateName( true, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(AnalyzerNameValidatorTest, test_isAllowedName_traditionalNames) { // direct (non-system) std::string const borderline(64, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE( arangodb::AnalyzerNameValidator::validateName(false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("abc_")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("abc-")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("_")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(":")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("abc:d")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(tooLong)) .ok()); // special characters EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("<script>alert(1);")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("a b c")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("a/b")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("//")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("/\\")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("a:b")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(":")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("aaaa::")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view(":aaaa")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("abcdef::gghh")) .ok()); // unicode EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("mötör")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("😀")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("😀 🍺")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("maçã")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( false, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(AnalyzerNameValidatorTest, test_isAllowedName_extendedNames) { // direct (non-system) std::string const borderline(64, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE( arangodb::AnalyzerNameValidator::validateName(true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("abc_")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("abc-")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(borderline)) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(tooLong)) .ok()); // special characters EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("<script>alert(1);")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a b c")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE( arangodb::AnalyzerNameValidator::validateName(true, std::string_view("/")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("/\\")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a/")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a/b")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a\\b")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a.b.c")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("a:b")) .ok()); EXPECT_FALSE( arangodb::AnalyzerNameValidator::validateName(true, std::string_view(":")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("aaaa::")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view(":aaaa")) .ok()); EXPECT_FALSE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("abcdef::gghh")) .ok()); // unicode EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("mötör")) .ok()); EXPECT_TRUE( arangodb::AnalyzerNameValidator::validateName(true, std::string_view("😀")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("😀 🍺")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("maçã")) .ok()); EXPECT_TRUE(arangodb::AnalyzerNameValidator::validateName( true, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(ViewNameValidatorTest, test_isAllowedName_traditionalNames) { // direct (non-system) std::string const borderline(64, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); { EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(false, false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("_abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("_")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view(":")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view("abc:d")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, false, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, false, std::string_view(tooLong)) .ok()); } // direct (system) { EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, false, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(borderline)) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(borderlineSystem)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(tooLong)) .ok()); } // special characters EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(" a + & ? = abc ")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("<script>alert(1);")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("a b c")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view(".123abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("a\0b", 3)) .ok()); // spaces EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, false, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, false, std::string_view("a ")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("a b")) .ok()); // unicode EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("mötör")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, false, std::string_view("😀")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("😀 🍺")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("maçã")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, false, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); } TEST(ViewNameValidatorTest, test_isAllowedName_extendedNames) { // direct (non-system) std::string const borderline(256, 'x'); std::string const borderlineSystem(std::string("_") + std::string(borderline.size() - 1, 'x')); std::string const tooLong(borderline.size() + 1, 'x'); { EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(false, true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("_123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("_abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("_")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName(false, true, std::string_view(":")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, true, std::string_view("abc:d")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( false, true, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( false, true, std::string_view(tooLong)) .ok()); } // direct (system) { EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view(nullptr, 0)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, true, std::string_view("")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("abc123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("Abc123")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("123abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("_123")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("_abc")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view(borderline)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view(tooLong)) .ok()); } // special characters EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a + & ? = abc")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("<script>alert(1);")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a b c")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("test123 & ' \" < > abc")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("abc:cde")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view(".abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view(".123abc")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a\0b", 3)) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, true, std::string_view("/")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, true, std::string_view("a/")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a/b")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a\\b")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a.b.c")) .ok()); // spaces EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, true, std::string_view(" a")) .ok()); EXPECT_FALSE(arangodb::ViewNameValidator::validateName(true, true, std::string_view("a ")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("a b")) .ok()); // unicode EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("mötör")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName(true, true, std::string_view("😀")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName(true, true, std::string_view("😀 🍺")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("maçã")) .ok()); EXPECT_TRUE(arangodb::ViewNameValidator::validateName( true, true, std::string_view("ﻚﻠﺑ ﻞﻄﻴﻓ")) .ok()); }
[ "noreply@github.com" ]
arangodb.noreply@github.com
5f1a6d865005f2de48d73017c27afa1380a23910
09ea1901af1caa0cd7a6977209c384e08278a371
/code/Ardupilot/libraries/AP_InertialSensor/AP_InertialSensor_UserInteract_MAVLink.cpp
60272dd0567685b92f08b861cc46d46d48435cee
[]
no_license
sid1980/JAGUAR
e038e048a0542d7f3b67c480d27881f91ef42e4e
2dc262fdc10a600335f71878e092265bc9da77c2
refs/heads/master
2021-12-03T05:19:44.367320
2014-05-01T23:21:27
2014-05-01T23:21:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,586
cpp
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include <stdarg.h> #include <AP_HAL.h> #include <GCS_MAVLink.h> #include "AP_InertialSensor_UserInteract_MAVLink.h" extern const AP_HAL::HAL& hal; uint8_t AP_InertialSensor_UserInteract_MAVLink::blocking_read(void) { uint32_t start_ms = hal.scheduler->millis(); /* Wait for a COMMAND_ACK message to be received from the ground station */ while (hal.scheduler->millis() - start_ms < 30000U) { while (!comm_get_available(_chan)) { hal.scheduler->delay(1); } uint8_t c = comm_receive_ch(_chan); mavlink_message_t msg; mavlink_status_t status; if (mavlink_parse_char(_chan, c, &msg, &status)) { if (msg.msgid == MAVLINK_MSG_ID_COMMAND_ACK) { return 0; } } } hal.console->println_P(PSTR("Timed out waiting for user response")); return 0; } void AP_InertialSensor_UserInteract_MAVLink::_printf_P(const prog_char* fmt, ...) { char msg[50]; va_list ap; va_start(ap, fmt); hal.util->vsnprintf_P(msg, sizeof(msg), (const prog_char_t *)fmt, ap); va_end(ap); if (msg[strlen(msg)-1] == '\n') { // STATUSTEXT messages should not add linefeed msg[strlen(msg)-1] = 0; } while (comm_get_txspace(_chan) - MAVLINK_NUM_NON_PAYLOAD_BYTES < (int)sizeof(mavlink_statustext_t)) { hal.scheduler->delay(1); } mavlink_msg_statustext_send(_chan, SEVERITY_USER_RESPONSE, msg); }
[ "jonathan2@Jonathans-MacBook-Pro.local" ]
jonathan2@Jonathans-MacBook-Pro.local
44b0f7125194375a06e2ca4d91337b18d02c8c2c
24a0e03c45f95d5bf36422653792f79105bc9491
/Leetcode/198_HouseRobber.cc
4d621482edcc69bf8c484d5084fe6530885b275f
[]
no_license
csc19960608/Wu-Algorithm
f7e58d1d604fef2e4bf005c5a2a99119bdd8550e
facaba3e0fc9b57fff9ce4e2b384796ea8d45a99
refs/heads/master
2021-09-01T17:19:24.724575
2017-12-28T03:03:09
2017-12-28T03:03:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
428
cc
#include<vector> using namespace std; //数组中的最大和序列,要求序列中元素不能相邻 class Solution { public: int rob(vector<int>& nums) { int taken=0; int nontaken=0; int maxprofit=0; for(int i=0;i<nums.size();++i){ taken=nums[i]+nontaken; nontaken=maxprofit; maxprofit=max(taken,nontaken); } return maxprofit; } };
[ "jt26wzz@icloud.com" ]
jt26wzz@icloud.com
071fda499d8c193b5ca8db5a76c5e5877f772be0
872f24199d847f05ddb4d8f7ac69eaed9336a0d5
/code/synthesis/ImagerObjects/SIImageStoreMultiTerm.cc
eb4efa3562bc1b7840f39e626a5b6c983677bfd8
[]
no_license
schiebel/casa
8004f7d63ca037b4579af8a8bbfb4fa08e87ced4
e2ced7349036d8fc13d0a65aad9a77b76bfe55d1
refs/heads/master
2016-09-05T16:20:59.022063
2015-08-26T18:46:26
2015-08-26T18:46:26
41,441,084
1
1
null
null
null
null
UTF-8
C++
false
false
37,972
cc
//# SIImageStoreMultiTerm.cc: Implementation of Imager.h //# Copyright (C) 1997-2008 //# Associated Universities, Inc. Washington DC, USA. //# //# This program is free software; you can redistribute it and/or modify it //# under the terms of the GNU General Public License as published by the Free //# Software Foundation; either version 2 of the License, or (at your option) //# any later version. //# //# This program is distributed in the hope that it will be useful, but WITHOUT //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or //# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for //# more details. //# //# You should have received a copy of the GNU General Public License along //# with this program; if not, write to the Free Software Foundation, Inc., //# 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be addressed as follows: //# Internet email: aips2-request@nrao.edu. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# $Id$ #include <casa/Exceptions/Error.h> #include <casa/iostream.h> #include <casa/sstream.h> #include <casa/Arrays/Matrix.h> #include <casa/Arrays/ArrayMath.h> #include <casa/Arrays/ArrayLogical.h> #include <casa/Logging.h> #include <casa/Logging/LogIO.h> #include <casa/Logging/LogMessage.h> #include <casa/Logging/LogSink.h> #include <casa/Logging/LogMessage.h> #include <casa/OS/DirectoryIterator.h> #include <casa/OS/File.h> #include <casa/OS/Path.h> #include <casa/OS/HostInfo.h> #include <images/Images/TempImage.h> #include <images/Images/PagedImage.h> #include <ms/MeasurementSets/MSHistoryHandler.h> #include <ms/MeasurementSets/MeasurementSet.h> #include <synthesis/TransformMachines/StokesImageUtil.h> #include <images/Images/TempImage.h> #include <images/Images/SubImage.h> #include <images/Regions/ImageRegion.h> #include <synthesis/ImagerObjects/SIImageStoreMultiTerm.h> #include <casa/Arrays/MatrixMath.h> #include <scimath/Mathematics/MatrixMathLA.h> #include <sys/types.h> #include <unistd.h> using namespace std; namespace casa { //# NAMESPACE CASA - BEGIN ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// SIImageStoreMultiTerm::SIImageStoreMultiTerm():SIImageStore() { itsPsfs.resize(0); itsModels.resize(0); itsResiduals.resize(0); itsWeights.resize(0); itsImages.resize(0); itsSumWts.resize(0); itsMask.reset( ); itsGridWt.reset( ); itsPB.reset( ); itsForwardGrids.resize(0); itsBackwardGrids.resize(0); itsNTerms=0; itsNFacets=1; itsFacetId=0; itsNChanChunks = 1; itsChanId = 0; itsNPolChunks = 1; itsPolId = 0; itsUseWeight=False; itsImageShape=IPosition(4,0,0,0,0); itsImageName=String(""); itsCoordSys=CoordinateSystem(); itsMiscInfo=Record(); // itsValidity = False; init(); validate(); } SIImageStoreMultiTerm::SIImageStoreMultiTerm(String imagename, CoordinateSystem &imcoordsys, IPosition imshape, const Int /*nfacets*/, const Bool /*overwrite*/, uInt ntaylorterms, Bool useweightimage) { LogIO os( LogOrigin("SIImageStoreMultiTerm","Open new Images",WHERE) ); itsNTerms = ntaylorterms; itsPsfs.resize(2 * itsNTerms - 1); itsModels.resize(itsNTerms); itsResiduals.resize(itsNTerms); itsWeights.resize(2 * itsNTerms - 1); itsImages.resize(itsNTerms); itsSumWts.resize(2 * itsNTerms - 1); itsMask.reset( ); itsGridWt.reset( ); itsPB.reset( ); itsForwardGrids.resize(itsNTerms); itsBackwardGrids.resize(2 * itsNTerms - 1); //cout << "Input imshape : " << imshape << endl; itsImageName = imagename; itsImageShape = imshape; itsCoordSys = imcoordsys; // itsNFacets = nfacets; // So that sumwt shape happens properly, via checkValidity // itsFacetId = -1; itsNFacets=1; itsFacetId=0; itsNChanChunks = 1; itsChanId = 0; itsNPolChunks = 1; itsPolId = 0; itsUseWeight = useweightimage; itsMiscInfo=Record(); init(); validate(); } SIImageStoreMultiTerm::SIImageStoreMultiTerm(String imagename, uInt ntaylorterms,const Bool ignorefacets) { LogIO os( LogOrigin("SIImageStoreMultiTerm","Open existing Images",WHERE) ); itsNTerms = ntaylorterms; itsPsfs.resize(2 * itsNTerms - 1); itsModels.resize(itsNTerms); itsResiduals.resize(itsNTerms); itsWeights.resize(2 * itsNTerms - 1); itsImages.resize(itsNTerms); itsSumWts.resize(2 * itsNTerms - 1); itsMask.reset( ); itsGridWt.reset( ); itsPB.reset( ); itsMiscInfo=Record(); itsForwardGrids.resize(itsNTerms); itsBackwardGrids.resize(2 * itsNTerms - 1); itsImageName = imagename; itsNFacets=1; itsFacetId=0; itsNChanChunks = 1; itsChanId = 0; itsNPolChunks = 1; itsPolId = 0; Bool exists=True; Bool sumwtexists=True; for(uInt tix=0;tix<2*itsNTerms-1;tix++) { if( tix<itsNTerms ) { exists &= ( doesImageExist( itsImageName+String(".residual.tt")+String::toString(tix) ) || doesImageExist( itsImageName+String(".psf.tt")+String::toString(tix) ) ); }else { exists &= ( doesImageExist( itsImageName+String(".psf.tt")+String::toString(tix) ) ); sumwtexists &= ( doesImageExist( itsImageName+String(".sumwt.tt")+String::toString(tix) ) ); } } // The PSF or Residual images must exist. ( or the gridwt image) // All this is just for the shape and coordinate system. if( exists || doesImageExist(itsImageName+String(".gridwt")) ) { SHARED_PTR<ImageInterface<Float> > imptr; if( doesImageExist(itsImageName+String(".psf.tt0")) ) imptr.reset( new PagedImage<Float> (itsImageName+String(".psf.tt0")) ); else if( doesImageExist(itsImageName+String(".residual.tt0")) ) imptr.reset( new PagedImage<Float> (itsImageName+String(".residual.tt0")) ); else imptr.reset( new PagedImage<Float> (itsImageName+String(".gridwt")) ); itsImageShape = imptr->shape(); itsCoordSys = imptr->coordinates(); } else { throw( AipsError( "Multi-term PSF or Residual Images do not exist. Please create one of them." ) ); } if( doesImageExist(itsImageName+String(".residual.tt0")) || doesImageExist(itsImageName+String(".psf.tt0")) ) { if( sumwtexists ) { SHARED_PTR<ImageInterface<Float> > imptr; imptr.reset( new PagedImage<Float> (itsImageName+String(".sumwt.tt0")) ); itsNFacets = imptr->shape()[0]; itsFacetId = 0; itsUseWeight = getUseWeightImage( *imptr ); if( itsUseWeight && ! doesImageExist(itsImageName+String(".weight.tt0")) ) { throw(AipsError("Internal error : MultiTerm Sumwt has a useweightimage=True but the weight image does not exist.")); } } else { throw( AipsError( "Multi-term SumWt does not exist. Please create PSFs or Residuals." ) ); } }// if psf0 or res0 exist if( ignorefacets==True ) itsNFacets=1; init(); validate(); } /* /////////////Constructor with pointers already created else where but taken over here SIImageStoreMultiTerm::SIImageStoreMultiTerm(Block<SHARED_PTR<ImageInterface<Float> > > modelims, Block<SHARED_PTR<ImageInterface<Float> > >residims, Block<SHARED_PTR<ImageInterface<Float> > >psfims, Block<SHARED_PTR<ImageInterface<Float> > >weightims, Block<SHARED_PTR<ImageInterface<Float> > >restoredims, Block<SHARED_PTR<ImageInterface<Float> > >sumwtims, SHARED_PTR<ImageInterface<Float> > newmask, SHARED_PTR<ImageInterface<Float> > newalpha, SHARED_PTR<ImageInterface<Float> > newbeta) { itsPsfs=psfims; itsModels=modelims; itsResiduals=residims; itsWeights=weightims; itsImages=restoredims; itsSumWts=sumwtims; itsMask = newmask; itsAlpha = newalpha; itsBeta = newbeta; itsNTerms = itsResiduals.nelements(); itsMiscInfo=Record(); AlwaysAssert( itsPsfs.nelements() == 2*itsNTerms-1 , AipsError ); AlwaysAssert( itsPsfs.nelements()>0 && itsPsfs[0] , AipsError ); AlwaysAssert( itsSumWts.nelements()>0 && itsSumWts[0] , AipsError ); itsForwardGrids.resize( itsNTerms ); itsBackwardGrids.resize( 2 * itsNTerms - 1 ); itsImageShape=psfims[0]->shape(); itsCoordSys = psfims[0]->coordinates(); itsMiscInfo = psfims[0]->miscInfo(); itsNFacets=sumwtims[0]->shape()[0]; itsUseWeight=getUseWeightImage( *(sumwtims[0]) ); itsImageName = String("reference"); // This is what the access functions use to guard against allocs... init(); validate(); } */ ////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////Constructor with pointers already created else where but taken over here SIImageStoreMultiTerm::SIImageStoreMultiTerm(Block<SHARED_PTR<ImageInterface<Float> > > modelims, Block<SHARED_PTR<ImageInterface<Float> > >residims, Block<SHARED_PTR<ImageInterface<Float> > >psfims, Block<SHARED_PTR<ImageInterface<Float> > >weightims, Block<SHARED_PTR<ImageInterface<Float> > >restoredims, Block<SHARED_PTR<ImageInterface<Float> > >sumwtims, SHARED_PTR<ImageInterface<Float> > newmask, SHARED_PTR<ImageInterface<Float> > newalpha, SHARED_PTR<ImageInterface<Float> > newbeta, SHARED_PTR<ImageInterface<Float> > newalphaerror, CoordinateSystem& csys, IPosition imshape, String imagename, const Int facet, const Int nfacets, const Int chan, const Int nchanchunks, const Int pol, const Int npolchunks) { itsPsfs=psfims; itsModels=modelims; itsResiduals=residims; itsWeights=weightims; itsImages=restoredims; itsSumWts=sumwtims; itsMask = newmask; itsAlpha = newalpha; itsBeta = newbeta; itsAlphaError = newalphaerror; itsNTerms = itsResiduals.nelements(); itsMiscInfo=Record(); AlwaysAssert( itsPsfs.nelements() == 2*itsNTerms-1 , AipsError ); // AlwaysAssert( itsPsfs.nelements()>0 && itsPsfs[0] , AipsError ); // AlwaysAssert( itsSumWts.nelements()>0 && itsSumWts[0] , AipsError ); itsForwardGrids.resize( itsNTerms ); itsBackwardGrids.resize( 2 * itsNTerms - 1 ); itsNFacets = nfacets; itsFacetId = facet; itsNChanChunks = nchanchunks; itsChanId = chan; itsNPolChunks = npolchunks; itsPolId = pol; itsParentImageShape = imshape; itsImageShape = imshape; ///// itsImageShape = IPosition(4,0,0,0,0); itsCoordSys = csys; // Hopefully this doesn't change for a reference image itsImageName = imagename; //----------------------- init(); // Connect parent pointers to the images. //----------------------- // Set these to null, to be set later upon first access. // Setting to null will hopefully set all elements of each array, to NULL. itsPsfs=SHARED_PTR<ImageInterface<Float> >(); itsModels=SHARED_PTR<ImageInterface<Float> >(); itsResiduals=SHARED_PTR<ImageInterface<Float> >(); itsWeights=SHARED_PTR<ImageInterface<Float> >(); itsImages=SHARED_PTR<ImageInterface<Float> >(); itsSumWts=SHARED_PTR<ImageInterface<Float> >(); itsMask.reset( ); validate(); } ////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// uInt SIImageStoreMultiTerm::getNTaylorTerms(Bool dopsf) { return dopsf ? (2*itsNTerms-1) : itsNTerms; } // Check if images that are asked-for are ready and all have the same shape. /* Bool SIImageStoreMultiTerm::checkValidity(const Bool ipsf, const Bool iresidual, const Bool iweight, const Bool imodel, const Bool irestored, const Bool imask,const Bool isumwt, const Bool ialpha, const Bool ibeta) { // cout << "In MT::checkValidity imask is " << imask << endl; Bool valid = True; for(uInt tix=0; tix<2*itsNTerms-1; tix++) { if(ipsf==True) { psf(tix); valid = valid & ( itsPsfs[tix] && itsPsfs[tix]->shape()==itsImageShape ); } if(iweight==True) { weight(tix); valid = valid & ( itsWeights[tix] && itsWeights[tix]->shape()==itsImageShape ); } if(isumwt==True) { IPosition useShape(itsImageShape); useShape[0]=itsNFacets; useShape[1]=itsNFacets; sumwt(tix); valid = valid & ( itsSumWts[tix] && itsSumWts[tix]->shape()==useShape ); } if( tix< itsNTerms ) { if(iresidual==True) { residual(tix); valid = valid & ( itsResiduals[tix] && itsResiduals[tix]->shape()==itsImageShape ); } if(imodel==True) { model(tix); valid = valid & ( itsModels[tix] && itsModels[tix]->shape()==itsImageShape); } if(irestored==True) { image(tix); valid = valid & ( itsImages[tix] && itsImages[tix]->shape()==itsImageShape); } } } if(imask==True) { mask(); valid = valid & ( itsMask && itsMask->shape()==itsImageShape); // cout << " Mask null ? " << (bool) itsMask << endl; } if(ialpha==True) { alpha(); valid = valid & ( itsAlpha && itsAlpha->shape()==itsImageShape ); } if(ibeta==True) { beta(); valid = valid & ( itsBeta && itsBeta->shape()==itsImageShape ); } return valid; } */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// SIImageStoreMultiTerm::~SIImageStoreMultiTerm() { } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// Bool SIImageStoreMultiTerm::releaseLocks() { LogIO os( LogOrigin("SIImageStoreMultiTerm","releaseLocks",WHERE) ); for(uInt tix=0; tix<2*itsNTerms-1; tix++) { if( itsPsfs[tix] ) releaseImage( itsPsfs[tix] ); if( itsWeights[tix] ) releaseImage( itsWeights[tix] ); if( itsSumWts[tix] ) releaseImage( itsSumWts[tix] ); if( tix < itsNTerms ) { if( itsModels[tix] ) releaseImage( itsModels[tix] ); if( itsResiduals[tix] ) releaseImage( itsResiduals[tix] ); if( itsImages[tix] ) releaseImage( itsImages[tix] ); } } if( itsMask ) releaseImage( itsMask ); if( itsAlpha ) releaseImage( itsAlpha ); if( itsBeta ) releaseImage( itsBeta ); if( itsAlphaError ) releaseImage( itsAlphaError ); if( itsGridWt ) releaseImage( itsGridWt ); if( itsPB ) releaseImage( itsPB ); return True; // do something more intelligent here. } Double SIImageStoreMultiTerm::getReferenceFrequency() { Double theRefFreq; Vector<Double> refpix = (itsCoordSys.spectralCoordinate()).referencePixel(); AlwaysAssert( refpix.nelements()>0, AipsError ); (itsCoordSys.spectralCoordinate()).toWorld( theRefFreq, refpix[0] ); // cout << "Reading ref freq as : " << theRefFreq << endl; return theRefFreq; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// void SIImageStoreMultiTerm::setModelImage( String modelname ) { LogIO os( LogOrigin("SIImageStoreMultiTerm","setModelImage",WHERE) ); for(uInt tix=0;tix<itsNTerms;tix++) { Directory immodel( modelname+String(".model.tt")+String::toString(tix) ); if( !immodel.exists() ) { os << "Starting model image does not exist for term : " << tix << LogIO::POST; } else { SHARED_PTR<PagedImage<Float> > newmodel( new PagedImage<Float>( modelname+String(".model.tt")+String::toString(tix) ) ); // Check shapes, coordsys with those of other images. If different, try to re-grid here. if( newmodel->shape() != model(tix)->shape() ) { os << "Regridding input model to target coordinate system for term " << tix << LogIO::POST; regridToModelImage( *newmodel , tix); // For now, throw an exception. //throw( AipsError( "Input model image "+modelname+".model.tt"+String::toString(tix)+" is not the same shape as that defined for output in "+ itsImageName + ".model" ) ); } else { os << "Setting " << modelname << " as model for term " << tix << LogIO::POST; // Then, add its contents to itsModel. //itsModel->put( itsModel->get() + model->get() ); ( model(tix) )->put( newmodel->get() ); } } }//nterms } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::psf(uInt term) { AlwaysAssert( itsPsfs.nelements() > term, AipsError ); accessImage( itsPsfs[term], itsParentPsfs[term], imageExts(PSF)+".tt"+String::toString(term) ); return itsPsfs[term]; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::residual(uInt term) { accessImage( itsResiduals[term], itsParentResiduals[term], imageExts(RESIDUAL)+".tt"+String::toString(term) ); return itsResiduals[term]; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::weight(uInt term) { accessImage( itsWeights[term], itsParentWeights[term], imageExts(WEIGHT)+".tt"+String::toString(term) ); return itsWeights[term]; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::sumwt(uInt term) { accessImage( itsSumWts[term], itsParentSumWts[term], imageExts(SUMWT)+".tt"+String::toString(term) ); if( itsNFacets>1 || itsNChanChunks>1 || itsNPolChunks>1 ) {itsUseWeight = getUseWeightImage( *itsParentSumWts[0] );} setUseWeightImage( *(itsSumWts[term]) , itsUseWeight); // Sets a flag in the SumWt image. return itsSumWts[term]; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::model(uInt term) { accessImage( itsModels[term], itsParentModels[term], imageExts(MODEL)+".tt"+String::toString(term) ); // Set up header info the first time. ImageInfo info = itsModels[term]->imageInfo(); String objectName(""); if( itsMiscInfo.isDefined("OBJECT") ){ itsMiscInfo.get("OBJECT", objectName); } info.setObjectName(objectName); itsModels[term]->setImageInfo( info ); itsModels[term]->setMiscInfo( itsMiscInfo ); itsModels[term]->setUnits("Jy/pixel"); return itsModels[term]; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::image(uInt term) { accessImage( itsImages[term], itsParentImages[term], imageExts(IMAGE)+".tt"+String::toString(term) ); itsImages[term]->setUnits("Jy/beam"); return itsImages[term]; } SHARED_PTR<ImageInterface<Complex> > SIImageStoreMultiTerm::forwardGrid(uInt term){ if( itsForwardGrids[term] )// && (itsForwardGrids[term]->shape() == itsImageShape)) return itsForwardGrids[term]; Vector<Int> whichStokes(0); IPosition cimageShape; cimageShape=itsImageShape; CoordinateSystem cimageCoord = StokesImageUtil::CStokesCoord( itsCoordSys, whichStokes, itsDataPolRep); cimageShape(2)=whichStokes.nelements(); itsForwardGrids[term].reset(new TempImage<Complex>(TiledShape(cimageShape, tileShape()), cimageCoord, memoryBeforeLattice())); return itsForwardGrids[term]; } SHARED_PTR<ImageInterface<Complex> > SIImageStoreMultiTerm::backwardGrid(uInt term){ if( itsBackwardGrids[term] && (itsBackwardGrids[term]->shape() == itsImageShape)) return itsBackwardGrids[term]; // cout << "MT : Making backward grid of shape : " << itsImageShape << endl; Vector<Int> whichStokes(0); IPosition cimageShape; cimageShape=itsImageShape; CoordinateSystem cimageCoord = StokesImageUtil::CStokesCoord( itsCoordSys, whichStokes, itsDataPolRep); cimageShape(2)=whichStokes.nelements(); itsBackwardGrids[term].reset(new TempImage<Complex>(TiledShape(cimageShape, tileShape()), cimageCoord, memoryBeforeLattice())); return itsBackwardGrids[term]; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::alpha() { if( itsAlpha && itsAlpha->shape() == itsImageShape ) { return itsAlpha; } // checkRef( itsAlpha , "alpha" ); itsAlpha = openImage( itsImageName+String(".alpha"), False ); // itsAlpha->setUnits("Alpha"); return itsAlpha; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::beta() { if( itsBeta && itsBeta->shape() == itsImageShape ) { return itsBeta; } // checkRef( itsBeta , "beta" ); itsBeta = openImage( itsImageName+String(".beta"), False ); // itsBeta->setUnits("Beta"); return itsBeta; } SHARED_PTR<ImageInterface<Float> > SIImageStoreMultiTerm::alphaerror() { if( itsAlphaError && itsAlphaError->shape() == itsImageShape ) { return itsAlphaError; } // checkRef( itsAlpha , "alpha" ); itsAlphaError = openImage( itsImageName+String(".alpha.error"), False ); // itsAlpha->setUnits("Alpha"); return itsAlphaError; } // TODO : Move to an image-wrapper class ? Same function exists in SynthesisDeconvolver. Bool SIImageStoreMultiTerm::doesImageExist(String imagename) { LogIO os( LogOrigin("SIImageStoreMultiTerm","doesImageExist",WHERE) ); Directory image( imagename ); return image.exists(); } void SIImageStoreMultiTerm::resetImages( Bool resetpsf, Bool resetresidual, Bool resetweight ) { for(uInt tix=0;tix<2*itsNTerms-1;tix++) { if( resetpsf ) psf(tix)->set(0.0); if( resetweight && itsWeights[tix] ) weight(tix)->set(0.0); if( tix < itsNTerms ) { if( resetresidual ) residual(tix)->set(0.0); } } } void SIImageStoreMultiTerm::addImages( SHARED_PTR<SIImageStore> imagestoadd, Bool addpsf, Bool addresidual, Bool addweight, Bool adddensity) { for(uInt tix=0;tix<2*itsNTerms-1;tix++) { if(addpsf) { LatticeExpr<Float> adderPsf( *(psf(tix)) + *(imagestoadd->psf(tix)) ); psf(tix)->copyData(adderPsf); } if(addweight) { if(getUseWeightImage( *(imagestoadd->sumwt(tix)) ) ) // Access and add weight only if it is needed. { LatticeExpr<Float> adderWeight( *(weight(tix)) + *(imagestoadd->weight(tix)) ); weight(tix)->copyData(adderWeight); } LatticeExpr<Float> adderSumWt( *(sumwt(tix)) + *(imagestoadd->sumwt(tix)) ); sumwt(tix)->copyData(adderSumWt); } if(tix < itsNTerms && addresidual) { LatticeExpr<Float> adderRes( *(residual(tix)) + *(imagestoadd->residual(tix)) ); residual(tix)->copyData(adderRes); } if( tix==0 && adddensity ) { LatticeExpr<Float> adderDensity( *(gridwt()) + *(imagestoadd->gridwt()) ); gridwt()->copyData(adderDensity); } } } void SIImageStoreMultiTerm::dividePSFByWeight(const Float pblimit) { LogIO os( LogOrigin("SIImageStoreMultiTerm","dividePSFByWeight",WHERE) ); //// for(uInt tix=0;tix<2*itsNTerms-1;tix++) for(Int tix=2*itsNTerms-1-1;tix>-1;tix--) // AAH go backwards so that zeroth term is normalized last..... sigh sigh sigh. { //cout << "npsfs : " << itsPsfs.nelements() << " and tix : " << tix << endl; normPSF(tix); if( itsUseWeight ) { divideImageByWeightVal( *weight(tix) ); } } if ( itsUseWeight) { makePBFromWeight(pblimit); } // calcSensitivity(); // createMask } // Make another for the PSF too. void SIImageStoreMultiTerm::divideResidualByWeight(Float pblimit, const String normtype) { LogIO os( LogOrigin("SIImageStoreMultiTerm","divideResidualByWeight",WHERE) ); if( itsUseWeight ) { itsPBScaleFactor = getPbMax(); } for(uInt tix=0;tix<itsNTerms;tix++) { divideImageByWeightVal( *residual(tix) ); // if(doesImageExist(itsImageName+String(".weight.tt0")) ) if( itsUseWeight ) { LatticeExpr<Float> deno; if( normtype=="flatnoise"){ deno = LatticeExpr<Float> ( sqrt( abs(*(weight(0)) ) ) * itsPBScaleFactor ); os << LogIO::NORMAL1 << "Dividing " << itsImageName+String(".residual.tt")+String::toString(tix) ; os << " by [ sqrt(weightimage) * " << itsPBScaleFactor ; os << " ] to get flat noise with unit pb peak."<< LogIO::POST; } if( normtype=="flatsky") { deno = LatticeExpr<Float> ( *(weight(0)) ); os << LogIO::NORMAL1 << "Dividing " << itsImageName+String(".residual.tt")+String::toString(tix) ; os << " by [ weight ] to get flat sky"<< LogIO::POST; } LatticeExpr<Float> mask( iif( (deno) > pblimit , 1.0, 0.0 ) ); LatticeExpr<Float> maskinv( iif( (deno) > pblimit , 0.0, 1.0 ) ); LatticeExpr<Float> ratio( ( (*(residual(tix))) * mask ) / ( deno + maskinv ) ); residual(tix)->copyData(ratio); } } // createMask } void SIImageStoreMultiTerm::divideModelByWeight(Float pblimit, const String normtype) { LogIO os( LogOrigin("SIImageStoreMultiTerm","divideModelByWeight",WHERE) ); if( itsUseWeight // only when needed && hasSensitivity() )// i.e. only when possible. For an initial starting model, don't need wt anyway. { if( normtype=="flatsky") { Array<Float> arrmod; model(0)->get( arrmod, True ); os << "Model is already flat sky with peak flux : " << max(arrmod); os << ". No need to divide before prediction" << LogIO::POST; return; } itsPBScaleFactor = getPbMax(); for(uInt tix=0;tix<itsNTerms;tix++) { os << LogIO::NORMAL1 << "Dividing " << itsImageName+String(".model")+String::toString(tix); os << " by [ sqrt(weight) / " << itsPBScaleFactor ; os <<" ] to get to flat sky model before prediction" << LogIO::POST; LatticeExpr<Float> deno( sqrt( abs(*(weight(0))) ) / itsPBScaleFactor ); LatticeExpr<Float> mask( iif( (deno) > pblimit , 1.0, 0.0 ) ); LatticeExpr<Float> maskinv( iif( (deno) > pblimit , 0.0, 1.0 ) ); LatticeExpr<Float> ratio( ( (*(model(tix))) * mask ) / ( deno + maskinv ) ); itsModels[tix]->copyData(ratio); } } // createMask } void SIImageStoreMultiTerm::multiplyModelByWeight(Float pblimit, const String normtype) { LogIO os( LogOrigin("SIImageStoreMultiTerm","multiplyModelByWeight",WHERE) ); if( itsUseWeight // only when needed && hasSensitivity() )// i.e. only when possible. For an initial starting model, don't need wt anyway. { if( normtype=="flatsky") { os << "Model is already flat sky. No need to multiply back after prediction" << LogIO::POST; return; } itsPBScaleFactor = getPbMax(); for(uInt tix=0;tix<itsNTerms;tix++) { os << LogIO::NORMAL1 << "Multiplying " << itsImageName+String(".model")+String::toString(tix); os << " by [ sqrt(weight) / " << itsPBScaleFactor; os << " ] to take model back to flat noise with unit pb peak." << LogIO::POST; LatticeExpr<Float> deno( sqrt( abs(*(weight(0)) ) ) / itsPBScaleFactor ); LatticeExpr<Float> mask( iif( (deno) > pblimit , 1.0, 0.0 ) ); LatticeExpr<Float> maskinv( iif( (deno) > pblimit , 0.0, 1.0 ) ); LatticeExpr<Float> ratio( ( (*(model(tix))) * mask ) * ( deno + maskinv ) ); itsModels[tix]->copyData(ratio); } } // createMask } void SIImageStoreMultiTerm::restore(GaussianBeam& rbeam, String& usebeam, uInt /*term*/) { LogIO os( LogOrigin("SIImageStoreMultiTerm","restore",WHERE) ); for(uInt tix=0; tix<itsNTerms; tix++) { SIImageStore::restore(rbeam, usebeam, tix); } try { if( itsNTerms > 1) { // Calculate alpha and beta LatticeExprNode leMaxRes = max( *( residual(0) ) ); Float maxres = leMaxRes.getFloat(); Float specthreshold = maxres/10.0; //////////// do something better here..... os << "Calculating spectral parameters for Intensity > peakresidual/10 = " << specthreshold << " Jy/beam" << LogIO::POST; LatticeExpr<Float> mask1(iif(((*(image(0))))>(specthreshold),1.0,0.0)); LatticeExpr<Float> mask0(iif(((*(image(0))))>(specthreshold),0.0,1.0)); ///////////////////////////////////////////////////////// /////// Calculate alpha LatticeExpr<Float> alphacalc( (((*(image(1))))*mask1)/(((*(image(0))))+(mask0)) ); alpha()->copyData(alphacalc); ImageInfo ii = image(0)->imageInfo(); // Set the restoring beam for alpha alpha()->setImageInfo(ii); //alpha()->table().unmarkForDelete(); // Make a mask for the alpha image LatticeExpr<Bool> lemask(iif(((*(image(0))) > specthreshold) , True, False)); createMask( lemask, (alpha()) ); ///////////////////////////////////////////////////////// /////// Calculate alpha error Bool writeerror=True; if(writeerror) { // String alphaerrorname( alpha()->name() + ".error" ); //PagedImage<Float> imalphaerror(itsImageShape,itsCoordSys,alphaerrorname); alphaerror()->set(0.0); // PagedImage<Float> residual1(residualNames[getModelIndex(field,1)]); LatticeExpr<Float> alphacalcerror( abs(alphacalc) * sqrt( ( (*residual(0)*mask1)/(*image(0)+mask0) )*( (*residual(0)*mask1)/(*image(0)+mask0) ) + ( (*residual(1)*mask1)/(*image(1)+mask0) )*( (*residual(1)*mask1)/(*image(1)+mask0) ) ) ); alphaerror()->copyData(alphacalcerror); alphaerror()->setImageInfo(ii); createMask(lemask, alphaerror()); // alphaerror()->table().unmarkForDelete(); os << "Written Spectral Index Error Image : " << alphaerror()->name() << LogIO::POST; }//if writeerror if(itsNTerms>2) // calculate beta too. { beta()->set(0.0); //PagedImage<Float> imtaylor2(restoredNames[getModelIndex(field,2)]); LatticeExpr<Float> betacalc( (*image(2)*mask1)/((*image(0))+(mask0))-0.5*(*alpha())*((*alpha())-1.0) ); beta()->copyData(betacalc); beta()->setImageInfo(ii); //imbeta.setUnits(Unit("Spectral Curvature")); createMask(lemask, beta()); // beta()->table().unmarkForDelete(); os << "Written Spectral Curvature Image : " << beta()->name() << LogIO::POST; } }//if nterms>1 } catch(AipsError &x) { throw( AipsError("Multi-Term Restoration Error : " + x.getMesg() ) ); } } void SIImageStoreMultiTerm::pbcorPlane() { LogIO os( LogOrigin("SIImageStoreMultiTerm","pbcorPlane",WHERE) ); } void SIImageStoreMultiTerm::calcSensitivity() { LogIO os( LogOrigin("SIImageStoreMultiTerm","calcSensitivity",WHERE) ); // Construct Hessian. Matrix<Float> hess(IPosition(2,itsNTerms,itsNTerms)); for(uInt tay1=0;tay1<itsNTerms;tay1++) for(uInt tay2=0;tay2<itsNTerms;tay2++) { //uInt taymin = (tay1<=tay2)? tay1 : tay2; //uInt taymax = (tay1>=tay2)? tay1 : tay2; //uInt ind = (taymax*(taymax+1)/2)+taymin; uInt ind = tay1+tay2; AlwaysAssert( ind < 2*itsNTerms-1, AipsError ); Array<Float> lsumwt; sumwt( ind )->get( lsumwt, False ); // cout << "lsumwt shape : " << lsumwt.shape() << endl; AlwaysAssert( lsumwt.shape().nelements()==4, AipsError ); AlwaysAssert( lsumwt.shape()[0]>0, AipsError ); // hess(tay1,tay2) = lsumwt(IPosition(1,0)); //Always pick sumwt from first facet only. hess(tay1,tay2) = lsumwt(IPosition(4,0,0,0,0)); //Always pick sumwt from first facet only. } os << "Multi-Term Hessian Matrix : " << hess << LogIO::POST; // Invert Hessian. try { Float deter=0.0; Matrix<Float> invhess; invertSymPosDef(invhess,deter,hess); os << "Multi-Term Covariance Matrix : " << invhess << LogIO::POST; // Just print the sqrt of the diagonal elements. for(uInt tix=0;tix<itsNTerms;tix++) { os << "[" << itsImageName << "][Taylor"<< tix << "] Theoretical sensitivity (Jy/bm):" ; if( invhess(tix,tix) > 0.0 ) { os << sqrt(invhess(tix,tix)) << LogIO::POST; } else { os << "none" << LogIO::POST; } } } catch(AipsError &x) { os << LogIO::WARN << "Cannot invert Hessian Matrix : " << x.getMesg() << " || Calculating approximate sensitivity " << LogIO::POST; // Approximate : 1/h^2 for(uInt tix=0;tix<itsNTerms;tix++) { Array<Float> lsumwt; AlwaysAssert( 2*tix < 2*itsNTerms-1, AipsError ); sumwt(2*tix)->get( lsumwt , False ); IPosition shp( lsumwt.shape() ); //cout << "Sumwt shape : " << shp << " : " << lsumwt << endl; //AlwaysAssert( shp.nelements()==4 , AipsError ); os << "[" << itsImageName << "][Taylor"<< tix << "] Approx Theoretical sensitivity (Jy/bm):" ; IPosition it(4,0,0,0,0); for ( it[0]=0; it[0]<shp[0]; it[0]++) for ( it[1]=0; it[1]<shp[1]; it[1]++) for ( it[2]=0; it[2]<shp[2]; it[2]++) for ( it[3]=0; it[3]<shp[3]; it[3]++) { if( shp[0]>1 ){os << "f"<< it[0]+(it[1]*shp[0]) << ":" ;} if( lsumwt( it ) > 1e-07 ) { os << 1.0/(sqrt(lsumwt(it))) << " " ; } else { os << "none" << " "; } } os << LogIO::POST; } } } // Check for non-zero model (this is different from getting model flux, for derived SIIMMT) Bool SIImageStoreMultiTerm::isModelEmpty() { /// There MUST be a more efficient way to do this !!!!! I hope. /// Maybe save this info and change it anytime model() is accessed.... Bool emptymodel=True; for(uInt tix=0;tix<itsNTerms;tix++) { if( fabs( sum(model(tix)->get()) ) > 1e-08 ) emptymodel=False; } return emptymodel; } void SIImageStoreMultiTerm::printImageStats() { LogIO os( LogOrigin("SIImageStoreMultiTerm","printImageStats",WHERE) ); Float minresmask, maxresmask, minres, maxres; findMinMax( residual()->get(), mask()->get(), minres, maxres, minresmask, maxresmask ); os << "[" << itsImageName << "]" ; os << " Peak residual (max,min) " ; if( minresmask!=0.0 || maxresmask!=0.0 ) { os << "within mask : (" << maxresmask << "," << minresmask << ") "; } os << "over full image : (" << maxres << "," << minres << ")" << LogIO::POST; os << "[" << itsImageName << "] Total Model Flux : " ; for(uInt tix=0;tix<itsNTerms;tix++) {os << getModelFlux(tix) << "(tt" << String::toString(tix) << ")"; } os<<LogIO::POST; } SHARED_PTR<SIImageStore> SIImageStoreMultiTerm::getSubImageStore(const Int facet, const Int nfacets, const Int chan, const Int nchanchunks, const Int pol, const Int npolchunks) { return SHARED_PTR<SIImageStore>(new SIImageStoreMultiTerm(itsModels, itsResiduals, itsPsfs, itsWeights, itsImages, itsSumWts, itsMask, itsAlpha, itsBeta, itsAlphaError, itsCoordSys,itsParentImageShape, itsImageName, facet, nfacets,chan,nchanchunks,pol,npolchunks)); } ////////////////////////////////////////////////////////////////////////////////////////////////////// // //------------------------------------------------------------- // Initialize the internals of the object. Perhaps other such // initializations in the constructors can be moved here too. // void SIImageStoreMultiTerm::init() { imageExts.resize(MAX_IMAGE_IDS); imageExts(MASK)=".mask"; imageExts(PSF)=".psf"; imageExts(MODEL)=".model"; imageExts(RESIDUAL)=".residual"; imageExts(WEIGHT)=".weight"; imageExts(IMAGE)=".image"; imageExts(SUMWT)=".sumwt"; imageExts(GRIDWT)=".gridwt"; imageExts(PB)=".pb"; imageExts(FORWARDGRID)=".forward"; imageExts(BACKWARDGRID)=".backward"; itsParentPsfs.resize(itsPsfs.nelements()); itsParentModels.resize(itsModels.nelements()); itsParentResiduals.resize(itsResiduals.nelements()); itsParentWeights.resize(itsWeights.nelements()); itsParentImages.resize(itsImages.nelements()); itsParentSumWts.resize(itsSumWts.nelements()); itsParentPsfs = itsPsfs; itsParentModels=itsModels; itsParentResiduals=itsResiduals; itsParentWeights=itsWeights; itsParentImages=itsImages; itsParentSumWts=itsSumWts; itsParentMask=itsMask; itsParentImageShape = itsImageShape; if( itsNFacets>1 || itsNChanChunks>1 || itsNPolChunks>1 ) { itsImageShape=IPosition(4,0,0,0,0); } } /* Bool SIImageStoreMultiTerm::getUseWeightImage() { if( itsParentSumWts.nelements()==0 || ! itsParentSumWts[0] ) {return False;} else { Bool ret = SIImageStore::getUseWeightImage( *(itsParentSumWts[0]) ); return ret; } } */ ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// } //# NAMESPACE CASA - END
[ "darrell@schiebel.us" ]
darrell@schiebel.us
5c747cf2c831a3386873e8acc98af24f4874c901
49eb0d08311529b1d2375429a9cbb5582d77fd2d
/src/bench/ccoins_caching.cpp
62a326d2ae05d3718f7de9c61c673e5b179bf074
[ "MIT" ]
permissive
mario1987/deimos
bcbaa7b4ed617a70c37047e6590264941b94a170
72cb8c33b5a6d4e09e4019602db7cea8c686d505
refs/heads/master
2020-03-19T23:11:08.313125
2018-06-11T23:06:30
2018-06-11T23:06:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,476
cpp
// Copyright (c) 2016 The DeiMos Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "coins.h" #include "policy/policy.h" #include "wallet/crypter.h" #include <vector> // FIXME: Dedup with SetupDummyInputs in test/transaction_tests.cpp. // // Helper: create two dummy transactions, each with // two outputs. The first has 11 and 50 CENT outputs // paid to a TX_PUBKEY, the second 21 and 22 CENT outputs // paid to a TX_PUBKEYHASH. // static std::vector<CMutableTransaction> SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsViewCache& coinsRet) { std::vector<CMutableTransaction> dummyTransactions; dummyTransactions.resize(2); // Add some keys to the keystore: CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(i % 2); keystoreRet.AddKey(key[i]); } // Create some dummy input transactions dummyTransactions[0].vout.resize(2); dummyTransactions[0].vout[0].nValue = 11 * CENT; dummyTransactions[0].vout[0].scriptPubKey << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; dummyTransactions[0].vout[1].nValue = 50 * CENT; dummyTransactions[0].vout[1].scriptPubKey << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG; coinsRet.ModifyCoins(dummyTransactions[0].GetHash())->FromTx(dummyTransactions[0], 0); dummyTransactions[1].vout.resize(2); dummyTransactions[1].vout[0].nValue = 21 * CENT; dummyTransactions[1].vout[0].scriptPubKey = GetScriptForDestination(key[2].GetPubKey().GetID()); dummyTransactions[1].vout[1].nValue = 22 * CENT; dummyTransactions[1].vout[1].scriptPubKey = GetScriptForDestination(key[3].GetPubKey().GetID()); coinsRet.ModifyCoins(dummyTransactions[1].GetHash())->FromTx(dummyTransactions[1], 0); return dummyTransactions; } // Microbenchmark for simple accesses to a CCoinsViewCache database. Note from // laanwj, "replicating the actual usage patterns of the client is hard though, // many times micro-benchmarks of the database showed completely different // characteristics than e.g. reindex timings. But that's not a requirement of // every benchmark." // (https://github.com/deimos/deimos/issues/7883#issuecomment-224807484) static void CCoinsCaching(benchmark::State& state) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); std::vector<CMutableTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CMutableTransaction t1; t1.vin.resize(3); t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t1.vin[0].prevout.n = 1; t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[1].prevout.n = 0; t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[2].prevout.n = 1; t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vout.resize(2); t1.vout[0].nValue = 90 * CENT; t1.vout[0].scriptPubKey << OP_1; // Benchmark. while (state.KeepRunning()) { bool success = AreInputsStandard(t1, coins); assert(success); CAmount value = coins.GetValueIn(t1); assert(value == (50 + 21 + 22) * CENT); } } BENCHMARK(CCoinsCaching);
[ "support@lipcoins.org" ]
support@lipcoins.org
0bbec4e1cd02ba01ea57b6784b06dc62464ea3cf
85ec0860a0a9f5c0c0f0d81ce3cc0baf4b2a812e
/soulng/spg/Domain.hpp
c1bb264bdbc5ebcf3453ee67026124cd6dfda265
[]
no_license
slaakko/soulng
3218185dc808fba63e2574b3a158fa1a9f0b2661
a128a1190ccf71794f1bcbd420357f2c85fd75f1
refs/heads/master
2022-07-27T07:30:20.813581
2022-04-30T14:22:44
2022-04-30T14:22:44
197,632,580
2
0
null
null
null
null
UTF-8
C++
false
false
2,020
hpp
// ================================= // Copyright (c) 2022 Seppo Laakko // Distributed under the MIT license // ================================= #ifndef SOULNG_SPG_DOMAIN_INCLUDED #define SOULNG_SPG_DOMAIN_INCLUDED #include <soulng/spg/ParserFile.hpp> #include <soulng/spg/Tokens.hpp> #include <soulng/util/CodeFormatter.hpp> #include <map> namespace soulng { namespace spg { class Domain { public: Domain(); void SetName(const std::string& name_); void Accept(Visitor& visitor); void AddParserFile(ParserFile* parserFile); const std::vector<ParserFile*>& ParserFiles() const { return parserFiles; } void AddParser(GrammarParser* parser); GrammarParser* GetParser(const std::u32string& parserName) const; const std::string& RuleHeaderFilePath() const { return ruleHeaderFilePath; } void SetRuleHeaderFilePath(const std::string& ruleHeaderFilePath_); const std::string& RuleSourceFilePath() const { return ruleSourceFilePath; } void SetRuleSourceFilePath(const std::string& ruleSourceFilePath_); void SetRecovery() { recovery = true; } bool Recovery() const { return recovery; } bool InverseAdded() const { return inverseAdded; } void SetInverseAdded() { inverseAdded = true; } void SetTokens(Tokens* tokens_) { tokens.reset(tokens_); } Tokens* GetTokens() const { return tokens.get(); } void Write(CodeFormatter& formatter); RuleParser* Start() const { return start; } void SetStart(RuleParser* start_) { start = start_; } void AddRule(RuleParser* rule); const std::vector<RuleParser*>& Rules() const { return rules; } private: std::string name; std::vector<ParserFile*> parserFiles; std::unique_ptr<Tokens> tokens; std::string ruleHeaderFilePath; std::string ruleSourceFilePath; std::map<std::u32string, GrammarParser*> parserMap; bool recovery; bool inverseAdded; RuleParser* start; std::vector<RuleParser*> rules; }; } } // namespae soulng::spg #endif // SOULNG_SPG_DOMAIN_INCLUDED
[ "slaakko@gmail.com" ]
slaakko@gmail.com
17166d98a3c37ea1a43cfedaee2e6284f259f4d9
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/wget/old_hunk_2796.cpp
8fbc6c55b2e02e67b7908b0c76e61772516b5ad3
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
PRINT being the host name we're connecting to. */ if (print) { const char *txt_addr = pretty_print_address (ip); if (print && 0 != strcmp (print, txt_addr)) logprintf (LOG_VERBOSE, _("Connecting to %s|%s|:%d... "), escnonprint (print), txt_addr, port);
[ "993273596@qq.com" ]
993273596@qq.com
6022ee97664c2fb79d5ad240d6f99ae5bec0aa8c
325d0ecf79bec8e3d630c26195da689ea5bb567e
/nimbro/motion/indep_cpg_gait/src/gaitcode/RobotControl/Percept.h
95c40c6c0f0a26dd072a8fdebae38eede4d85db1
[]
no_license
nvtienanh/Hitechlab_humanoid
ccaac64885967334f41a161f1684ff3a1571ab0f
34c899f70af7390b9fbdb1a1ad03faf864a550be
refs/heads/master
2020-04-22T10:34:21.944422
2016-08-28T06:02:00
2016-08-28T06:02:00
66,521,772
2
0
null
null
null
null
UTF-8
C++
false
false
319
h
#ifndef PERCEPT_H_ #define PERCEPT_H_ #include "Action.h" #include "util/Vec2f.h" // The percept struct contains the raw sensor data received from the robot / simulation. namespace indep_cpg_gait { struct Percept { Vec2f fusedAngle; Vec2f DfusedAngle; Pose pose; }; } #endif // PERCEPT_H_
[ "nvtienanh@gmail.com" ]
nvtienanh@gmail.com
124f3bc736f3f923884c640177201c11c6d329da
77a0ccdb3c430aea86f50d6888694ce4d91e2d33
/Heracles/TopLevelController.cc
0fe6d3419d39e1954ba7dfe1af96e477fd79746b
[]
no_license
zeronek501/mutilate
216d96a7716b020eb70b11023890d23ab361c35b
86458eaa01ecac8b33cfe89a016d8de973f530ea
refs/heads/master
2020-03-27T01:23:06.206942
2018-09-19T15:38:20
2018-09-19T15:38:20
145,705,671
0
0
null
null
null
null
UTF-8
C++
false
false
6,575
cc
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/socket.h> #include <time.h> #include <cstring> #include <string> #include <cstdlib> #include <assert.h> #include <arpa/inet.h> #include <pthread.h> #include <fstream> #include <iostream> #include <vector> #include <vector> #include "CoreMemController.h" #include "Task.h" #include "Util.h" // libzmq is necessary #include <zmq.hpp> #define CAN_GROW 0 #define CANNOT_GROW 1 #define DISABLED 2 #define LOAD_MAX 250000 zmq::context_t *context = NULL; zmq::socket_t *my_socket = NULL; std::string port; int wait_time; int n = 95; double nth; double lat = -1, load = -1; double qps = -1; double target_lat = 2000, slack = -1; CoreMemController *cm; Task *lc, *be; int g_be_status; // pthread pthread_mutex_t l_mutex; // mutex for latency poll pthread_cond_t cond; // Convert string to 0MQ string and send to socket static bool s_send (zmq::socket_t &_socket, const std::string &str) { zmq::message_t message(str.size()); memcpy(message.data(), str.data(), str.size()); return _socket.send(message); } void be_unpause() { system(std::string("docker unpause inmemory").c_str()); } void be_pause() { std::string cmd; int core_num = cm->be_cores->size() - 1; int llc_num = cm->be_llc->size() - 1; if(core_num > 0) { cm->be_cores->remove(core_num); cm->lc_cores->add(core_num); } if(llc_num > 0) { cm->be_llc->remove(llc_num); cm->lc_llc->add(llc_num); } system(std::string("docker pause inmemory").c_str()); } void be_exec() { printf("executing be\n"); int pid; pid = fork(); if(pid == 0) { // child process int mypid = getpid(); s_write("/sys/fs/cgroup/cpuset/be/tasks", std::to_string(mypid)); system("./setting/set_inmemory_solo.sh"); execl("/home/janux/mutilate/Heracles/setting/run_inmemory_solo.sh", "run_inmemory_solo.sh", NULL); } else if(pid == -1) { // fork error printf("fork error!\n"); exit(1); } } void poll(double &_lat, double &_qps) { printf("polling...\n"); zmq::message_t request; my_socket->recv(&request); s_send(*my_socket, "ACK"); memcpy(&_lat, request.data(), sizeof(double)); my_socket->recv(&request); s_send(*my_socket, "ACK"); memcpy(&_qps, request.data(), sizeof(double)); } void enable_be() { printf("enable_be\n"); be_unpause(); g_be_status = CAN_GROW; } void disallow_be_growth() { printf("disallow_be_growth\n"); g_be_status = CANNOT_GROW; } void disable_be() { printf("disable_be\n"); g_be_status = DISABLED; be_pause(); } void enter_cooldown() { printf("cooldown\n"); sleep(300); // sleep 5 min } void lc_init() { printf("lc_init..\n"); // create cgroup cos s_sudo_cmd("mkdir -p /sys/fs/cgroup/cpuset/lc"); s_sudo_cmd("mkdir -p /sys/fs/resctrl/lc"); // allocate cores and ways lc = new Task("lc", "lc"); // fork and exec process and attach the task pids to cgroup and resctrl printf("executing lc\n"); int pid; int status; pid = fork(); if(pid == 0) { // child process int mypid = getpid(); printf("mypid: %d\n", mypid); s_write("/sys/fs/cgroup/cpuset/lc/cpuset.cpus", "0"); s_write("/sys/fs/cgroup/cpuset/lc/cpuset.mems", "0"); s_write("/sys/fs/cgroup/cpuset/lc/tasks", std::to_string(mypid)); s_write("/sys/fs/resctrl/lc/tasks", std::to_string(mypid)); system("sudo pkill -9 memcached"); execlp("memcached", "memcached", "-t", "4", "-c", "32768", "-p", "11212", NULL); } else if(pid == -1) { // fork error printf("fork error!\n"); exit(1); } else { sleep(5); std::string value; std::fstream fs; std::string filepath = std::string("/sys/fs/cgroup/cpuset/lc/tasks"); fs.open(filepath, std::fstream::in); while(!fs.eof()) { fs >> value; printf("%s\n",value.c_str()); lc->pids.push_back(std::stoi(value)); } //waitpid(pid, &status, 0); } } void be_init() { std::string be_cgroup; std::fstream fs; std::string value; printf("be_init..\n"); // docker run and pause -> cgroup is created based on their cid. s_sudo_cmd("mkdir -p /sys/fs/resctrl/be"); system(std::string("./setting/set_inmemory_solo.sh").c_str()); s_read("./cids.txt", be_cgroup); printf("be_cgroup: %s\n", be_cgroup.c_str()); be = new Task(std::string("docker/") + be_cgroup, "be"); // attach task pids. copy to resctrl tasks std::string filepath = std::string("/sys/fs/cgroup/cpuset/") + be->cgroup + std::string("/tasks"); std::string resctrlpath = std::string("/sys/fs/resctrl/be/tasks"); fs.open(filepath, std::fstream::in); while(!fs.eof()) { fs >> value; printf("%s\n",value.c_str()); be->pids.push_back(std::stoi(value)); s_write(resctrlpath, value); } fs.close(); enable_be(); } void *top_control(void *threadid) { printf("top_controlling...\n"); while (true) { poll(lat, qps); load = qps / LOAD_MAX; slack = (target_lat - lat) / target_lat; printf("nth lat: %f, slack: %f, qps: %f, load: %f\n", lat, slack, qps, load); if(slack < 0) { disable_be(); enter_cooldown(); } else if(load > 0.85) { disable_be(); } else if(load < 0.8) { enable_be(); } else if(slack < 0.1) { disallow_be_growth(); if(slack < 0.05) { int num = cm->be_cores->size() - 2; if(num > 0) { cm->be_cores->remove(num); cm->lc_cores->add(num); } } } // else: enable_be()? pthread_cond_signal(&cond); sleep(wait_time); } } void *core_mem_control(void *threadid) { printf("core_mem_controlling...\n"); pthread_mutex_lock(&l_mutex); while(lat == -1) { pthread_cond_wait(&cond, &l_mutex); } pthread_mutex_unlock(&l_mutex); printf("core_mem_repeating...\n"); cm->start_loop(); } void init() { printf("initializing...\n"); int status; // Init LC and BE task lc_init(); be_init(); // Init Controller instances cm = new CoreMemController(lc, be, g_be_status, slack, qps); // Init socket settings context = new zmq::context_t(1); my_socket = new zmq::socket_t(*context, ZMQ_REP); port = "10123"; // arbitrarily set wait_time = 15; my_socket->bind((std::string("tcp://*:") + port).c_str()); sleep(500); /* // Create pthreads pthread_t top_level, core_mem; if(pthread_create(&top_level, NULL, top_control, NULL) < 0) { perror("thread create error:"); exit(0); } if(pthread_create(&core_mem, NULL, core_mem_control, NULL) < 0) { perror("thread create error:"); exit(0); } pthread_join(core_mem, (void **)&status); printf("Core Thread End %d\n", status); pthread_join(top_level, (void **)&status); printf("Top Thread End %d\n", status); */ } int main(int argc, char **argv) { init(); }
[ "zeronek501@gmail.com" ]
zeronek501@gmail.com
9a408cefe6fc301d4dc58a8866cae5221e915263
fe73b179108ab6c0b5eed9c7decee2817a237f5f
/include/tpf/math/tpf_quaternion.inl
1d74aa948af3bef2a6e619a530eea832d56e54b6
[ "MIT" ]
permissive
UniStuttgart-VISUS/tpf
d9c7f275e7b1e1a7609afb5ee69b8b48e779b450
7563000f1f7abca2156b3b1f6393f2db3c1c1f3d
refs/heads/master
2023-08-03T17:36:30.897646
2023-07-24T18:35:34
2023-07-24T18:35:34
159,207,802
0
3
MIT
2023-05-17T16:46:24
2018-11-26T17:31:02
C++
UTF-8
C++
false
false
8,055
inl
#include "tpf_quaternion.h" #include "tpf_math_defines.h" #include "Eigen/Dense" #include <cmath> #include <iostream> namespace tpf { namespace math { template <typename floatp_t> inline quaternion<floatp_t>::quaternion() : real(1.0), imaginary(0.0, 0.0, 0.0) { } template <typename floatp_t> inline quaternion<floatp_t>::quaternion(floatp_t real) : real(real), imaginary(0.0, 0.0, 0.0) { } template <typename floatp_t> inline quaternion<floatp_t>::quaternion(const Eigen::Matrix<floatp_t, 3, 1>& imaginary) : real(1.0), imaginary(imaginary) { } template <typename floatp_t> inline quaternion<floatp_t>::quaternion(floatp_t real, const Eigen::Matrix<floatp_t, 3, 1>& imaginary) : real(real), imaginary(imaginary) { } template <typename floatp_t> inline quaternion<floatp_t>::quaternion(const quaternion<floatp_t>& copy) { this->real = copy.real; this->imaginary = copy.imaginary; } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::operator=(const quaternion<floatp_t>& copy) { this->real = copy.real; this->imaginary = copy.imaginary; return *this; } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::operator=(floatp_t new_real) { this->real = new_real; this->imaginary.setZero(); return *this; } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::operator=(const Eigen::Matrix<floatp_t, 3, 1>& new_imaginary) { this->real = 1.0; this->imaginary = new_imaginary; return *this; } template <typename floatp_t> inline quaternion<floatp_t> quaternion<floatp_t>::operator*(const quaternion<floatp_t>& other) const { quaternion<floatp_t> copy(*this); return copy *= other; } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::operator*=(const quaternion<floatp_t>& other) { const floatp_t real = this->real * other.real - this->imaginary.dot(other.imaginary); const Eigen::Matrix<floatp_t, 3, 1> imaginary = this->real * other.imaginary + other.real * this->imaginary + this->imaginary.cross(other.imaginary); this->real = real; this->imaginary = imaginary; return *this; } template <typename floatp_t> template <typename U> inline Eigen::Matrix<U, 3, 1> quaternion<floatp_t>::rotate(const Eigen::Matrix<U, 3, 1>& vec) const { return ((*this) * quaternion<floatp_t>(static_cast<floatp_t>(0.0), vec) * this->inverse()).get_imaginary(); } template <typename floatp_t> inline bool quaternion<floatp_t>::operator==(const quaternion& other) const { return equals(this->real, other.real, static_cast<floatp_t>(std::min(this->real, other.real) * 0.00001)) && this->imaginary.isApprox(other.imaginary); } template <typename floatp_t> inline const floatp_t& quaternion<floatp_t>::get_real() const { return this->real; } template <typename floatp_t> inline floatp_t& quaternion<floatp_t>::get_real() { return this->real; } template <typename floatp_t> inline void quaternion<floatp_t>::set_real(floatp_t new_real) { this->real = new_real; } template <typename floatp_t> inline const Eigen::Matrix<floatp_t, 3, 1>& quaternion<floatp_t>::get_imaginary() const { return this->imaginary; } template <typename floatp_t> inline Eigen::Matrix<floatp_t, 3, 1>& quaternion<floatp_t>::get_imaginary() { return this->imaginary; } template <typename floatp_t> inline void quaternion<floatp_t>::set_imaginary(const Eigen::Matrix<floatp_t, 3, 1>& new_imaginary) { this->imaginary = new_imaginary; } template <typename floatp_t> inline quaternion<floatp_t> quaternion<floatp_t>::inverse() const { quaternion<floatp_t> copy(*this); return copy.invert(); } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::invert() { const floatp_t sqr_norm = squared_norm(); conjugate(); this->real /= sqr_norm; this->imaginary /= sqr_norm; return *this; } template <typename floatp_t> inline quaternion<floatp_t> quaternion<floatp_t>::conjugation() const { quaternion<floatp_t> copy(*this); return copy.conjugate(); } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::conjugate() { this->imaginary *= -1.0; return *this; } template <typename floatp_t> inline quaternion<floatp_t> quaternion<floatp_t>::normalized() const { quaternion<floatp_t> copy(*this); return copy.normalize(); } template <typename floatp_t> inline quaternion<floatp_t>& quaternion<floatp_t>::normalize() { const floatp_t my_norm = norm(); this->real /= my_norm; this->imaginary /= my_norm; return *this; } template <typename floatp_t> inline floatp_t quaternion<floatp_t>::norm() const { return std::sqrt(squared_norm()); } template <typename floatp_t> inline floatp_t quaternion<floatp_t>::squared_norm() const { return this->real * this->real + this->imaginary.squaredNorm(); } template <typename floatp_t> inline Eigen::Matrix<floatp_t, 3, 1> quaternion<floatp_t>::to_axis() const { return Eigen::Matrix<floatp_t, 3, 1>(static_cast<floatp_t>(2.0L) * std::atan2(this->imaginary.norm(), this->real) * this->imaginary.normalized()); } template <typename floatp_t> inline void quaternion<floatp_t>::from_axis(const Eigen::Matrix<floatp_t, 3, 1>& axis, const floatp_t scaling) { const auto theta = scaling * axis.norm(); this->real = std::cos(theta / static_cast<floatp_t>(2.0)); this->imaginary = axis.normalized() * std::sin(theta / static_cast<floatp_t>(2.0)); } template <typename floatp_t> inline Eigen::Matrix<floatp_t, 3, 3> quaternion<floatp_t>::to_matrix() const { Eigen::Matrix<floatp_t, 3, 3> cross_matrix; cross_matrix.setZero(); cross_matrix(0, 1) = -this->imaginary[2]; cross_matrix(0, 2) = this->imaginary[1]; cross_matrix(1, 0) = this->imaginary[2]; cross_matrix(1, 2) = -this->imaginary[0]; cross_matrix(2, 0) = -this->imaginary[1]; cross_matrix(2, 1) = this->imaginary[0]; const auto s = (1.0 / squared_norm()); return s * ( this->imaginary * this->imaginary.transpose() + this->real * this->real * Eigen::Matrix<floatp_t, 3, 3>::Identity() + 2.0 * this->real * cross_matrix + cross_matrix * cross_matrix); } template <typename floatp_t> inline std::ostream& operator<<(std::ostream& stream, const quaternion<floatp_t>& quaternion) { stream << "[" << quaternion.get_real() << ", (" << quaternion.get_imaginary()[0] << ", " << quaternion.get_imaginary()[1] << ", " << quaternion.get_imaginary()[2] << ")]"; return stream; } } }
[ "alexander.straub@visus.uni-stuttgart.de" ]
alexander.straub@visus.uni-stuttgart.de
d6bfab750726ba66463d716ecab703e2f149d029
153b7c2a47d97c9f4d1b35784d35b74a1a76ae89
/html/HTMLImageLoader.cpp
710c1777083722725b9ac9fa1221f620b5d1a1c0
[]
no_license
planetsong/cs5231-browser-acl
46eabe1969fcfeceb5ecd54058e6dfebb14261d4
17119f1a8563232eb76468e9df19c9282fafacf7
refs/heads/master
2021-01-01T16:14:09.760358
2012-03-27T15:38:24
2012-03-27T15:38:24
32,124,589
0
0
null
null
null
null
UTF-8
C++
false
false
2,936
cpp
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2010 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. */ #include "config.h" #include "HTMLImageLoader.h" #include "CachedImage.h" #include "Element.h" #include "Event.h" #include "EventNames.h" #include "HTMLNames.h" #include "HTMLObjectElement.h" #include "HTMLParserIdioms.h" #include "Settings.h" #if USE(JSC) #include "JSDOMWindowBase.h" #endif namespace WebCore { HTMLImageLoader::HTMLImageLoader(Element* node) : ImageLoader(node) { } HTMLImageLoader::~HTMLImageLoader() { } void HTMLImageLoader::dispatchLoadEvent() { bool errorOccurred = image()->errorOccurred(); if (!errorOccurred && image()->response().httpStatusCode() >= 400) errorOccurred = element()->hasTagName(HTMLNames::objectTag); // An <object> considers a 404 to be an error and should fire onerror. element()->dispatchEvent(Event::create(errorOccurred ? eventNames().errorEvent : eventNames().loadEvent, false, false)); } String HTMLImageLoader::sourceURI(const AtomicString& attr) const { #if ENABLE(DASHBOARD_SUPPORT) Settings* settings = element()->document()->settings(); if (settings && settings->usesDashboardBackwardCompatibilityMode() && attr.length() > 7 && attr.startsWith("url(\"") && attr.endsWith("\")")) return attr.string().substring(5, attr.length() - 7); #endif return stripLeadingAndTrailingHTMLSpaces(attr); } void HTMLImageLoader::notifyFinished(CachedResource*) { CachedImage* cachedImage = image(); Element* elem = element(); ImageLoader::notifyFinished(cachedImage); bool loadError = cachedImage->errorOccurred() || cachedImage->response().httpStatusCode() >= 400; #if USE(JSC) if (!loadError) { if (!elem->inDocument()) { JSC::JSGlobalData* globalData = JSDOMWindowBase::commonJSGlobalData(); globalData->heap.reportExtraMemoryCost(cachedImage->encodedSize()); } } #endif if (loadError && elem->hasTagName(HTMLNames::objectTag)) static_cast<HTMLObjectElement*>(elem)->renderFallbackContent(); } }
[ "happyyesg2011@gmail.com@347aa7df-b7d0-cf80-a8c3-eaa8d009e25a" ]
happyyesg2011@gmail.com@347aa7df-b7d0-cf80-a8c3-eaa8d009e25a
28218a366ed51a24a1e96f1be1c923057f2528cd
070e98268ebf06e9bd4520a66302ba8ce6474706
/Cuidar.h
22e731b9b5a950dbf348af5d93815591b3a059cf
[]
no_license
rNexeR/Estructura-Proyecto1
53c689b47cf5266dc2109411693523391ee75a52
fbfd1a794741f4c6c45f5aae4f44982b21f67b0a
refs/heads/master
2021-01-20T11:05:36.662784
2015-06-01T04:42:55
2015-06-01T04:42:55
36,203,555
0
0
null
null
null
null
UTF-8
C++
false
false
852
h
#ifndef CUIDAR_H #define CUIDAR_H #include <QWidget> #include <QTimer> #include <list> #include "tamagotchi.h" namespace Ui { class Cuidar; } class Cuidar : public QWidget { Q_OBJECT public: explicit Cuidar(QWidget *parent = 0); ~Cuidar(); public slots: void setParametros(list<Tamagotchi*>* animales, Tamagotchi* actual); void update(); void closeEvent (QCloseEvent *event); void closeWindow(); void changeButtonsState(bool state); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_pushButton_6_clicked(); private: Ui::Cuidar *ui; QTimer* timer; list<Tamagotchi*>* animales; Tamagotchi* actual; int segundos; }; #endif // CUIDAR_H
[ "rnexer@gmail.com" ]
rnexer@gmail.com
bb073348928e973ec20c340279d3d360f699f60f
522c568e8920d76a94198599614e9315f575ce23
/Temp/Trigger/Node/Special/WRTriggerSpecialNodeBase.h
91788896bdc3d2c50ec5ac6c47a3464aba39c870
[]
no_license
kyukyu86/Demo
2ba6fe1f2264f9d4820437736c9870a5c59960cb
d2bb86e623ec5f621e860aa5defe335ee672ca53
refs/heads/master
2023-01-07T11:46:08.313633
2020-11-06T08:59:06
2020-11-06T08:59:06
269,510,905
0
0
null
null
null
null
UTF-8
C++
false
false
733
h
#pragma once #include "../WRTriggerBaseNode.h" class WR_API WRTriggerSpecialNodeBase : public WRTriggerBaseNode { public: WRTriggerSpecialNodeBase(/*int32 InUid, const FString& InNodeName, EWRTriggerNodeType::en InNodeType*/); ~WRTriggerSpecialNodeBase(); virtual void Signal(class WRTriggerNodeBase* CallFrom/*, WRTriggerBaseNode* PreNode*/); virtual void ImportDataFromJson(const TSharedPtr<FJsonObject>* InJsonObject); bool SetTransition(const EWRTriggerTransitionType::en Type, class WRTriggerTransitionNodeBase* InTransition); protected: virtual void SendSignalToTriggerNode(class WRTriggerNodeBase* InTriggerNode) {} private: TMap<EWRTriggerTransitionType::en, class WRTriggerTransitionNodeBase*> Transitions; };
[ "pelpin2080@gmail.com" ]
pelpin2080@gmail.com
5d06cfa52ee97d4665de0fbfa8af341bfd3eb822
2a603ffd23cdac093d3bb579d1a0539b59c16b08
/Mondrian.h
ad3a95a862e73f2a574968d1b8f3e6871e8d80a3
[]
no_license
gdiakidis/Mondrian-algorithm
70dc15abedabacad5a72e9a50401f06d8f7b7cee
f274b9681e5060cc313b14d497f4a17b467fa758
refs/heads/master
2022-03-01T11:40:29.261508
2019-09-26T12:09:26
2019-09-26T12:09:26
92,457,498
1
0
null
null
null
null
UTF-8
C++
false
false
763
h
/* * File: Mondrian.h * Author: george * */ #include <iostream> #include <iomanip> #include <fstream> #include <map> #include <vector> using namespace std; #ifndef MONDRIAN_H #define MONDRIAN_H class Mondrian { public: Mondrian(map<int,string> data,int k); vector< vector<int> > InitiateArrays(); void Anonymize(vector<vector<int> > R2data); float find_median(vector< vector<int> > dt,int selectedRow); vector< vector<int> > BubbleSort(vector< vector<int> > dt,int selectedRow); int minf(vector<int> tmp); int maxf(vector<int> tmp); void print_meanAverage(); private: int k; map<int,string> data; vector< vector<int> > Rdata; float total_eq = 0; int total_classes = 0; }; #endif /* MONDRIAN_H */
[ "gdiakidis19@gmail.com" ]
gdiakidis19@gmail.com
f95280e4c2b1b36071b352e2817a8521e69a53f4
72736ca51d4b27665c45c349d5cac6f1355d75a7
/source/engine/include/whery/db/base/FieldManipulator.h
fc3163bf17ead852a52e8b6e870c15c7f298bdf4
[]
no_license
sgolodetz/whery
0c1535eb8e94afa70562240efdb5636c803bf0ec
6b469ef3d2a8198fffe07ba5788b71642c8f5ed2
refs/heads/master
2020-05-26T23:59:17.496633
2013-07-02T15:08:06
2013-07-02T15:08:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,570
h
/** * whery: FieldManipulator.h * Copyright Stuart Golodetz, 2013. All rights reserved. */ #ifndef H_WHERY_FIELDMANIPULATOR #define H_WHERY_FIELDMANIPULATOR #include <functional> #include <string> #include <boost/uuid/uuid.hpp> namespace whery { /** \brief An instance of a class deriving from this one is used to manipulate fields of a particular type at some location in memory (e.g. an int field manipulator treats the pointed-to memory as an int). Field manipulators hold no state - their member functions accept pointers to the memory on which to work. (The intention is to separate the concerns of field manipulation and field storage - the latter may vary, but the manipulation of individual fields must be consistent.) As a result, we only actually need a single instance of each type of field manipulator. */ class FieldManipulator { //#################### DESTRUCTOR #################### protected: /** Protected to prevent deletion via a FieldManipulator pointer. */ ~FieldManipulator(); //#################### PUBLIC ABSTRACT METHODS #################### public: /** Returns the size (in bytes) of the alignment boundary required for fields of the manipulated type. For example, a 32-bit int would need to be aligned on a 4-byte boundary. \return The size (in bytes) of the alignment boundary required for fields of the manipulated type. */ virtual unsigned int alignment_requirement() const = 0; /** Compares the field at location (as manipulated by this manipulator) with the field at otherLocation (as manipulated by otherManipulator). The value of the field at otherLocation is first converted to the type of the field at location, if possible, after which the two are compared using std::less. If the type conversion fails, then the two fields cannot be compared, and an exception will be thrown. \param location The memory location of the field on which this manipulator should operate. \param otherManipulator The manipulator to use for the other field being compared. \param otherLocation The memory location of the other field being compared. \return -1, if the field at location is ordered before that at otherLocation; 1, if the field at location is ordered after that at otherLocation; 0, otherwise. \throw std::bad_cast If the type conversion fails. */ virtual int compare_to(const char *location, const FieldManipulator& otherManipulator, const char *otherLocation) const = 0; /** Sets the field at location (as manipulated by this manipulator) to the value of the field at otherLocation (as manipulated by otherManipulator), after first converting it to the right type. If the type conversion fails, an exception will be thrown. \param location The memory location of the field on which this manipulator should operate. \param sourceManipulator The manipulator to use for the source field. \param sourceLocation The memory location of the source field. \throw std::bad_cast If the type conversion fails. */ virtual void set_from(char *location, const FieldManipulator& sourceManipulator, const char *sourceLocation) const = 0; /** Returns the size (in bytes) of the manipulated type. For example, a 32-bit int would have size 4. \return The size (in bytes) of the manipulated type. */ virtual unsigned int size() const = 0; //#################### PUBLIC METHODS #################### /** Gets the value of the field at location as a double, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \return The value of the field as a double. \throw std::bad_cast If the type conversion fails. */ virtual double get_double(const char *location) const; /** Gets the value of the field at location as an int, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \return The value of the field as an int. \throw std::bad_cast If the type conversion fails. */ virtual int get_int(const char *location) const; /** Gets the value of the field at location as a std::string, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \return The value of the field as a std::string. \throw std::bad_cast If the type conversion fails. */ virtual std::string get_string(const char *location) const; /** Gets the value of the field at location as a Boost UUID, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \return The value of the field as a Boost UUID. \throw std::bad_cast If the type conversion fails. */ virtual boost::uuids::uuid get_uuid(const char *location) const; /** Sets the field at location to the specified value, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \param value The value to which to set the field. \throw std::bad_cast If the type conversion fails. */ virtual void set_double(char *location, double value) const; /** Sets the field at location to the specified value, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \param value The value to which to set the field. \throw std::bad_cast If the type conversion fails. */ virtual void set_int(char *location, int value) const; /** Sets the field at location to the specified value, performing type conversion where necessary. If the type conversion fails, an exception will be thrown. \param location The location of the field. \param value The value to which to set the field. \throw std::bad_cast If the type conversion fails. */ virtual void set_uuid(char *location, const boost::uuids::uuid& value) const; //#################### PROTECTED METHODS #################### protected: /** Compares two values of type T using std::less<T>. \param lhs The left-hand operand of the comparison. \param rhs The right-hand operand of the comparison. \return -1, if lhs < rhs; 1, if rhs < lhs; 0, otherwise. */ template <typename T> static int compare_with_less(const T& lhs, const T& rhs) { std::less<T> comp; if(comp(lhs, rhs)) return -1; else if(comp(rhs, lhs)) return 1; else return 0; } }; } #endif
[ "sgolodetz@gxstudios.net" ]
sgolodetz@gxstudios.net
09dcc8a764c08c29d4457e586332837afd88cfba
45d19fe4f3cea15d7c2c667feb334d49bca5872c
/Src/FactoryPattern/MethodFactory/cproductafactory.cpp
42e559be60deb727a3ef6892461bb8501824adc9
[ "MIT" ]
permissive
whuer-xiaojie/Design_Patterns_C_Plus_Plus
a9c198b3719331658fe83fb37883beb9fe2ecef2
467459e4f62ee5b0e4ce682c55a8f7f8ae986167
refs/heads/master
2022-04-11T12:40:19.497613
2020-04-05T06:47:29
2020-04-05T06:47:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,422
cpp
/* * MIT License * * Copyright (c) 2018 Whuer_XiaoJie <1939346428@qq.com> * * 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 "cproductafactory.h" #include "../Product/cproductbase.h" #include "../Product/cproducta.h" CProductAFactory::CProductAFactory() { } CProductAFactory::~CProductAFactory() { } CProductBase* CProductAFactory::createProduct() { return new CProductA(); }
[ "xiojie@sansi.com" ]
xiojie@sansi.com
bd06a7e74a9d30edbc502160f5f7e3eaa3a4bea6
2e0a6fd5767ee4551d370f682910702be9095d73
/Base/Segmentation/itktubeRadiusExtractor2.hxx
91b6867139f9448ef6f761d3f463b22cb2209d5c
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LucasGandel/TubeTK
ee0ce6a378aab732a3ee051ecd2ea36332d4943a
50682d4d8b30b0392575685e11e16a1086790bc8
refs/heads/master
2021-01-18T09:29:06.802793
2016-01-30T04:11:39
2016-01-30T04:11:39
40,605,754
1
1
null
2015-08-12T14:39:59
2015-08-12T14:39:59
null
UTF-8
C++
false
false
27,259
hxx
/*========================================================================= Library: TubeTK/VTree3D Authors: Stephen Aylward, Julien Jomier, and Elizabeth Bullitt Original implementation: Copyright University of North Carolina, Chapel Hill, NC, USA. Revised implementation: Copyright Kitware Inc., Carrboro, NC, USA. 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 __itktubeRadiusExtractor2_hxx #define __itktubeRadiusExtractor2_hxx #include "itktubeRadiusExtractor2.h" #include "tubeMatrixMath.h" #include "tubeTubeMath.h" #include "tubeUserFunction.h" #include "tubeGoldenMeanOptimizer1D.h" #include "tubeSplineApproximation1D.h" #include <itkMinimumMaximumImageFilter.h> #include <vnl/vnl_math.h> namespace itk { namespace tube { template< class TInputImage > class LocalMedialnessSplineValueFunction : public ::tube::UserFunction< int, double > { public: LocalMedialnessSplineValueFunction( RadiusExtractor2< TInputImage > * _radiusExtractor ) { m_Value = 0; m_RadiusExtractor = _radiusExtractor; } const double & Value( const int & x ) { m_Value = m_RadiusExtractor->GetKernelMedialness( x * m_RadiusExtractor->GetRadiusTolerance() ); return m_Value; } private: double m_Value; typename RadiusExtractor2< TInputImage >::Pointer m_RadiusExtractor; }; /** Constructor */ template< class TInputImage > RadiusExtractor2<TInputImage> ::RadiusExtractor2( void ) { m_Image = NULL; m_DataMin = 0; m_DataMax = -1; m_RadiusStart = 1.5; m_RadiusMin = 0.33; m_RadiusMax = 15.0; m_RadiusStep = 0.25; m_RadiusTolerance = 0.125; m_RadiusCorrectionFunction = RADIUS_CORRECTION_NONE; m_MinMedialness = 0.15; // 0.015; larger = harder m_MinMedialnessStart = 0.1; m_NumKernelPoints = 7; m_KernelTubePoints.resize( m_NumKernelPoints ); m_KernelPointStep = 14; m_KernelStep = 30; m_KernelExtent = 1.6; m_KernelValues.clear(); m_KernelDistances.clear(); m_KernelTangentDistances.clear(); m_KernelOptimalRadius = 0; m_KernelOptimalRadiusMedialness = 0; m_KernelOptimalRadiusBranchness = 0; m_IdleCallBack = NULL; m_StatusCallBack = NULL; } /** Destructor */ template< class TInputImage > RadiusExtractor2<TInputImage> ::~RadiusExtractor2( void ) { } /** Set the input image */ template< class TInputImage > void RadiusExtractor2<TInputImage> ::SetInputImage( typename ImageType::Pointer inputImage ) { m_Image = inputImage; if( m_Image ) { typedef MinimumMaximumImageFilter<ImageType> MinMaxFilterType; typename MinMaxFilterType::Pointer minMaxFilter = MinMaxFilterType::New(); minMaxFilter->SetInput( m_Image ); minMaxFilter->Update(); m_DataMin = minMaxFilter->GetMinimum(); m_DataMax = minMaxFilter->GetMaximum(); if( this->GetDebug() ) { std::cout << "RadiusExtractor2: SetInputImage: Minimum = " << m_DataMin << std::endl; std::cout << "RadiusExtractor2: SetInputImage: Maximum = " << m_DataMax << std::endl; } } } /** Compute the medialness at a kernel */ template< class TInputImage > void RadiusExtractor2<TInputImage> ::GetPointVectorMeasures( std::vector< TubePointType > & points, double pntR, double & mness, double & bness, bool doBNess ) { ::tube::ComputeVectorTangentsAndNormals( points ); if( this->GetDebug() ) { std::cout << "Compute values at point" << std::endl; } unsigned int tempNumPoints = this->GetNumKernelPoints(); int numPoints = points.size(); this->SetNumKernelPoints( numPoints ); this->SetKernelTubePoints( points ); this->GenerateKernel(); mness = this->GetKernelMedialness( pntR ); if( doBNess ) { bness = this->GetKernelBranchness( pntR ); } this->SetNumKernelPoints( tempNumPoints ); } /** Compute the Optimal scale */ template< class TInputImage > bool RadiusExtractor2<TInputImage> ::GetPointVectorOptimalRadius( std::vector< TubePointType > & points, double & r0, double rMin, double rMax, double rStep, double rTolerance ) { unsigned int tempNumPoints = this->GetNumKernelPoints(); unsigned int numPoints = points.size(); this->SetNumKernelPoints( numPoints ); this->SetKernelTubePoints( points ); double tempXStart = this->GetRadiusStart(); this->SetRadiusStart( r0 ); double tempXMin = this->GetRadiusMin(); this->SetRadiusMin( rMin ); double tempXMax = this->GetRadiusMax(); this->SetRadiusMax( rMax ); double tempXStep = this->GetRadiusStep(); this->SetRadiusStep( rStep ); double tempXTolerance = this->GetRadiusTolerance(); this->SetRadiusTolerance( rTolerance ); this->GenerateKernel(); this->UpdateKernelOptimalRadius(); this->SetRadiusStart( tempXStart ); this->SetRadiusMin( tempXMin ); this->SetRadiusMax( tempXMax ); this->SetRadiusStep( tempXStep ); this->SetRadiusTolerance( tempXTolerance ); if( tempNumPoints != numPoints ) { this->SetNumKernelPoints( tempNumPoints ); } r0 = this->GetKernelOptimalRadius(); return true; } template< class TInputImage > void RadiusExtractor2<TInputImage> ::SetNumKernelPoints( unsigned int _numPoints ) { m_NumKernelPoints = _numPoints; m_KernelTubePoints.resize( m_NumKernelPoints ); } template< class TInputImage > void RadiusExtractor2<TInputImage> ::GenerateKernel( void ) { ITKIndexType minX; ITKIndexType maxX; unsigned int dimension = m_Image->GetImageDimension(); ITKIndexType buffer; for( unsigned int i = 0; i < dimension; ++i ) { buffer[i] = static_cast< unsigned int >( this->GetKernelExtent() * this->GetRadiusMax() ); } typename std::vector< TubePointType >::iterator pntIter; pntIter = m_KernelTubePoints.begin(); for( unsigned int i = 0; i < dimension; ++i ) { minX[i] = static_cast< int >( m_KernelTubePoints[0].GetPosition()[i] - buffer[i] ); maxX[i] = static_cast< int >( m_KernelTubePoints[0].GetPosition()[i] + buffer[i] ); } ++pntIter; int tempI; while( pntIter != m_KernelTubePoints.end() ) { for( unsigned int i = 0; i < dimension; ++i ) { tempI = static_cast< int >( pntIter->GetPosition()[i] - buffer[i] ); if( tempI < minX[i] ) { minX[i] = tempI; } tempI = static_cast< int >( pntIter->GetPosition()[i] + buffer[i] ); if( tempI > maxX[i] ) { maxX[i] = tempI; } } ++pntIter; } unsigned int kernelSize = maxX[0] - minX[0] + 1; for( unsigned int i = 1; i < dimension; ++i ) { kernelSize *= ( maxX[i] - minX[i] + 1 ); } m_KernelValues.resize( kernelSize ); m_KernelDistances.resize( kernelSize ); m_KernelTangentDistances.resize( kernelSize ); unsigned int count = 0; ITKIndexType x = minX; bool done = false; while( !done ) { if( m_Image->GetLargestPossibleRegion().IsInside( x ) ) { m_KernelValues[ count ] = ( m_Image->GetPixel( x ) - m_DataMin ) / ( m_DataMax - m_DataMin ); if( m_KernelValues[ count ] < 0 ) { m_KernelValues[ count ] = 0; } else if( m_KernelValues[ count ] > 1 ) { m_KernelValues[ count ] = 1; } ITKPointType p; for( unsigned int i = 0; i < dimension; ++i ) { p[ i ] = x[ i ]; } unsigned int pntCount = 0; pntIter = m_KernelTubePoints.begin(); double pntTangentDist = 0; double minTangentDist = 0; double minNormalDist = 0; int minTangentDistCount = -1; while( pntIter != m_KernelTubePoints.end() ) { ITKVectorType pDiff = pntIter->GetPosition() - p; double d1 = 0; for( unsigned int i = 0; i < dimension; ++i ) { d1 += pDiff[i] * pntIter->GetTangent()[i]; } pntTangentDist = d1 * d1; if( pntTangentDist < minTangentDist || minTangentDistCount == -1 ) { minTangentDist = pntTangentDist; minTangentDistCount = pntCount; d1 = 0; for( unsigned int i = 0; i < dimension; ++i ) { d1 += pDiff[i] * pntIter->GetNormal1()[i]; } minNormalDist = d1 * d1; if( dimension == 3 ) { double d2 = 0; for( unsigned int i = 0; i < dimension; ++i ) { d2 += pDiff[i] * pntIter->GetNormal2()[i]; } minNormalDist += d2 * d2; } } ++pntIter; ++pntCount; } m_KernelDistances[ count ] = vcl_sqrt( minNormalDist ); m_KernelTangentDistances[ count ] = vcl_sqrt( minTangentDist ); } else { m_KernelValues[ count ] = 0; m_KernelDistances[ count ] = this->GetKernelExtent() * this->GetRadiusMax() + 1; m_KernelTangentDistances[ count ] = this->GetKernelExtent() * this->GetRadiusMax() + 1; } ++count; unsigned int d = 0; while( d < dimension && ++x[d] > maxX[d] ) { x[d] = minX[d]; ++d; } if( d >= dimension ) { done = true; } } } template< class TInputImage > void RadiusExtractor2<TInputImage> ::SetKernelTubePoints( const std::vector< TubePointType > & tubePoints ) { if( tubePoints.size() != m_NumKernelPoints ) { std::cerr << "Error: number of kernel points not equal to expected." << std::endl; std::cerr << " TubePointsSize = " << tubePoints.size() << std::endl; std::cerr << " NumKernelPoints = " << m_NumKernelPoints << std::endl; } for( unsigned int i=0; i<m_NumKernelPoints; ++i ) { m_KernelTubePoints[ i ] = tubePoints[ i ]; } ::tube::ComputeVectorTangentsAndNormals( m_KernelTubePoints ); } template< class TInputImage > double RadiusExtractor2<TInputImage> ::GetKernelMedialness( double r ) { if( r < m_RadiusMin ) { double factor = ( m_RadiusMin - r ) / m_RadiusTolerance; double m0 = this->GetKernelMedialness( m_RadiusMin ); double m1 = this->GetKernelMedialness( m_RadiusMin + m_RadiusTolerance ); return m0 - factor * vnl_math_abs(m0 - m1); } else if( r > m_RadiusMax ) { double factor = ( r - m_RadiusMax ) / m_RadiusTolerance; double m0 = this->GetKernelMedialness( m_RadiusMax ); double m1 = this->GetKernelMedialness( m_RadiusMax - m_RadiusTolerance ); return m0 - factor * vnl_math_abs(m0 - m1); } double pVal = 0; double nVal = 0; std::vector< double >::iterator iterDist; std::vector< double >::iterator iterTanDist; std::vector< double >::iterator iterValue; double areaR = r * r * vnl_math::pi; double distMax = ( r + 1.0 ); double areaMax = distMax * distMax * vnl_math::pi; double areaNeg = areaMax - areaR; double distMin2 = ( areaR - areaNeg ) / vnl_math::pi; double distMin = 0; if( distMin2 > 0 ) { distMin = vcl_sqrt( distMin2 ); } double areaMin = distMin * distMin * vnl_math::pi; double areaPos = areaR - areaMin; if ( this->GetDebug() ) { std::cout << "R = " << r << std::endl; std::cout << " Dist = " << distMin << " - " << distMax << std::endl; std::cout << " Area = " << areaPos << " - " << areaNeg << std::endl; } const int histoBins = 500; unsigned int histoPos[histoBins]; unsigned int histoNeg[histoBins]; unsigned int histoPosCount = 0; unsigned int histoNegCount = 0; for( int i=0; i<histoBins; ++i ) { histoPos[i] = 0; histoNeg[i] = 0; } int bin = 0; iterDist = m_KernelDistances.begin(); iterTanDist = m_KernelTangentDistances.begin(); iterValue = m_KernelValues.begin(); while( iterDist != m_KernelDistances.end() ) { if( ( ( *iterTanDist ) < r || ( *iterTanDist ) < 1 ) && ( *iterDist ) >= distMin && ( *iterDist ) <= distMax ) { bin = ( *iterValue ) * histoBins; if( bin < 0 ) { bin = 0; } else if( bin > histoBins - 1 ) { bin = histoBins - 1; } if( (*iterDist) <= r ) { ++histoPos[bin]; ++histoPosCount; } else { ++histoNeg[bin]; ++histoNegCount; } } ++iterValue; ++iterDist; ++iterTanDist; } int binCount = 0; pVal = 0; if( histoPosCount > 2 ) { bin = histoBins - 1; while( binCount < 0.5 * histoPosCount && bin > 0 ) { binCount += histoPos[bin]; --bin; } pVal = ( bin + 0.5 ) / histoBins; } nVal = 1; if( histoNegCount > 2 ) { binCount = 0; bin = 0; while( binCount < 0.5 * histoNegCount && bin < histoBins ) { binCount += histoNeg[bin]; ++bin; } nVal = ( bin - 0.5 ) / histoBins; } if ( this->GetDebug() ) { std::cout << " Count = " << histoPosCount << " - " << histoNegCount << std::endl; std::cout << " Val = " << pVal << " - " << nVal << " = " << pVal-nVal << std::endl; } double medialness = pVal - nVal; return medialness; } template< class TInputImage > double RadiusExtractor2<TInputImage> ::GetKernelBranchness( double r ) { if( r < m_RadiusMin ) { double factor = ( m_RadiusMin - r ) / m_RadiusTolerance; double m0 = this->GetKernelBranchness( m_RadiusMin ); double m1 = this->GetKernelBranchness( m_RadiusMin + m_RadiusTolerance ); return m0 - factor * vnl_math_abs(m0 - m1); } else if( r > m_RadiusMax ) { double factor = ( r - m_RadiusMax ) / m_RadiusTolerance; double m0 = this->GetKernelBranchness( m_RadiusMax ); double m1 = this->GetKernelBranchness( m_RadiusMax - m_RadiusTolerance ); return m0 - factor * vnl_math_abs(m0 - m1); } double pVal = 0; double nVal = 0; std::vector< double >::iterator iterDist; std::vector< double >::iterator iterTanDist; std::vector< double >::iterator iterValue; double distMax = r * this->GetKernelExtent(); double distMin = 0; const int histoBins = 500; unsigned int histoPos[histoBins]; unsigned int histoNeg[histoBins]; unsigned int histoPosCount = 0; unsigned int histoNegCount = 0; for( unsigned int i=0; i<histoBins; ++i ) { histoPos[i] = 0; histoNeg[i] = 0; } int bin = 0; iterDist = m_KernelDistances.begin(); iterTanDist = m_KernelTangentDistances.begin(); iterValue = m_KernelValues.begin(); while( iterDist != m_KernelDistances.end() ) { if( ( *iterTanDist ) < r && ( *iterDist ) >= distMin && ( *iterDist ) <= distMax ) { bin = ( *iterValue ) * histoBins; if( bin < 0 ) { bin = 0; } else if( bin > histoBins - 1 ) { bin = histoBins - 1; } if( (*iterDist) <= r ) { ++histoPos[bin]; ++histoPosCount; } else { ++histoNeg[bin]; ++histoNegCount; } } ++iterValue; ++iterDist; ++iterTanDist; } int binCount = 0; pVal = 0; if( histoPosCount > 1 ) { bin = 0; while( binCount < 0.5 * histoPosCount && bin < histoBins ) { binCount += histoPos[bin]; ++bin; } pVal = ( bin + 0.5 ) / histoBins; } nVal = 1; if( histoNegCount > 1 ) { binCount = 0; bin = histoBins - 1; while( binCount < 0.75 * histoNegCount && bin > 1 ) { binCount += histoNeg[bin]; --bin; } nVal = ( bin - 0.5 ) / histoBins; } double branchness = 1.0 - vnl_math_abs( pVal - nVal ); return branchness; } template< class TInputImage > bool RadiusExtractor2<TInputImage> ::UpdateKernelOptimalRadius( void ) { ::tube::UserFunction< int, double > * myFunc = new LocalMedialnessSplineValueFunction< TInputImage >( this ); ::tube::GoldenMeanOptimizer1D * opt = new ::tube::GoldenMeanOptimizer1D(); opt->SetXStep( m_RadiusStep / m_RadiusTolerance ); opt->SetTolerance( 1 ); opt->SetMaxIterations( 20 ); opt->SetSearchForMin( false ); int xMin = 0; int xMax = 1; double x = 0.5; switch( m_RadiusCorrectionFunction ) { default: case RADIUS_CORRECTION_NONE: { xMin = (int)vnl_math_ceil( m_RadiusMin / m_RadiusTolerance ); xMax = (int)vnl_math_floor( m_RadiusMax / m_RadiusTolerance ); x = m_RadiusStart / m_RadiusTolerance; break; } case RADIUS_CORRECTION_FOR_BINARY_IMAGE: { xMin = (int)vnl_math_ceil( m_RadiusMin / m_RadiusTolerance ); xMax = (int)vnl_math_floor( m_RadiusMax / m_RadiusTolerance ); x = m_RadiusStart / m_RadiusTolerance; break; } case RADIUS_CORRECTION_FOR_CTA: { xMin = (int)vnl_math_ceil( m_RadiusMin / m_RadiusTolerance ); xMax = (int)vnl_math_floor( m_RadiusMax / m_RadiusTolerance ); x = m_RadiusStart / m_RadiusTolerance; break; } case RADIUS_CORRECTION_FOR_MRA: { xMin = (int)vnl_math_ceil( m_RadiusMin / m_RadiusTolerance ); xMax = (int)vnl_math_floor( m_RadiusMax / m_RadiusTolerance ); x = m_RadiusStart / m_RadiusTolerance; break; } }; opt->SetXMin( xMin ); opt->SetXMax( xMax ); ::tube::SplineApproximation1D * spline = new ::tube::SplineApproximation1D( myFunc, opt ); //spline->SetClip( true ); spline->SetXMin( xMin ); spline->SetXMax( xMax ); double xVal = myFunc->Value( x ); bool result = spline->Extreme( &x, &xVal ); switch( m_RadiusCorrectionFunction ) { default: case RADIUS_CORRECTION_NONE: { m_KernelOptimalRadius = x * m_RadiusTolerance; break; } case RADIUS_CORRECTION_FOR_BINARY_IMAGE: { m_KernelOptimalRadius = ( x * m_RadiusTolerance * x * m_RadiusTolerance ) / 24 + 0.5; break; } case RADIUS_CORRECTION_FOR_CTA: { m_KernelOptimalRadius = x * m_RadiusTolerance; break; } case RADIUS_CORRECTION_FOR_MRA: { m_KernelOptimalRadius = x * m_RadiusTolerance; break; } }; m_KernelOptimalRadiusMedialness = xVal; delete spline; delete opt; delete myFunc; return result; } template< class TInputImage > bool RadiusExtractor2<TInputImage> ::ExtractRadii( TubeType * tube ) { if( tube->GetPoints().size() == 0 ) { return false; } tube->RemoveDuplicatePoints(); ::tube::ComputeVectorTangentsAndNormals< TubePointType >( tube->GetPoints() ); typename std::vector< TubePointType >::iterator pntIter; pntIter = tube->GetPoints().begin(); while( pntIter != tube->GetPoints().end() ) { pntIter->SetRadius( 0 ); ++pntIter; } int pntCount = 0; pntIter = tube->GetPoints().begin(); while( pntIter != tube->GetPoints().end() && pntIter->GetID() != 0 ) { ++pntIter; ++pntCount; } if( pntIter == tube->GetPoints().end() ) { if ( this->GetDebug() ) { std::cout << "Warning: PointID 0 not found. Using mid-point of tube." << std::endl; } pntIter = tube->GetPoints().begin(); unsigned int psize = tube->GetPoints().size(); for( unsigned int i=0; i<psize/2; i++ ) { ++pntIter; } } else if( this->GetDebug() ) { std::cout << "Found point " << ( *pntIter ).GetID() << std::endl; } double rStart0 = this->GetRadiusStart(); double rStart = rStart0; for( int p = static_cast< int >( pntCount ); p < static_cast< int >( tube->GetPoints().size() ); p += this->GetKernelStep() ) { this->SetRadiusStart( rStart ); this->GenerateKernelTubePoints( p, tube ); this->GenerateKernel(); this->UpdateKernelOptimalRadius(); this->RecordOptimaAtTubePoints( p, tube ); rStart = this->GetKernelOptimalRadius(); } rStart = rStart0; for( int p = static_cast< int >( pntCount ) - this->GetKernelPointStep(); p >= 0; p -= this->GetKernelStep() ) { this->SetRadiusStart( rStart ); this->GenerateKernelTubePoints( p, tube ); this->GenerateKernel(); this->UpdateKernelOptimalRadius(); this->RecordOptimaAtTubePoints( p, tube ); rStart = this->GetKernelOptimalRadius(); } if( this->GetDebug() ) { std::cout << "Radius results:" << std::endl; pntIter = tube->GetPoints().begin(); while( pntIter != tube->GetPoints().end() ) { std::cout << " " << pntIter->GetID() << " : " << pntIter->GetRadius() << std::endl; ++pntIter; } } return true; } template< class TInputImage > void RadiusExtractor2<TInputImage> ::GenerateKernelTubePoints( unsigned int tubePointNum, TubeType * tube ) { unsigned int tubeSize = tube->GetPoints().size(); if( tubeSize < m_NumKernelPoints * m_KernelPointStep ) { std::cerr << "RadiusExtractor: Tube length is too short" << std::endl; return; } int startP = tubePointNum - ( m_NumKernelPoints / 2 ) * m_KernelPointStep; int endP = startP + ( m_NumKernelPoints - 1 ) * m_KernelPointStep; unsigned int count = 0; for( int p = startP; p <= endP; p += m_KernelPointStep ) { if( p < 0 ) { typename TubeType::PointType p1 = tube->GetPoints()[ 0 ].GetPosition(); typename TubeType::PointType p2 = tube->GetPoints()[ m_NumKernelPoints / 2 * m_KernelPointStep ].GetPosition(); for( unsigned int i = 0; i < ImageDimension; ++i ) { p2[i] = p1[i] - ( ( p2[i] - p1[i] ) * ( -p / m_KernelPointStep ) ); } m_KernelTubePoints[ count ].SetPosition( p2 ); } else if( p > static_cast< int >( tubeSize ) - 1 ) { typename TubeType::PointType p1 = tube->GetPoints()[ tubeSize - 1 ].GetPosition(); typename TubeType::PointType p2 = tube->GetPoints()[ tubeSize - 1 - m_NumKernelPoints / 2 * m_KernelPointStep ].GetPosition(); for( unsigned int i = 0; i < ImageDimension; ++i ) { p2[i] = p1[i] - ( ( p2[i] - p1[i] ) * ( ( p - (tubeSize-1) ) / m_KernelPointStep ) ); } m_KernelTubePoints[ count ].SetPosition( p2 ); } else { m_KernelTubePoints[ count ] = tube->GetPoints()[ p ]; } ++count; } ::tube::ComputeVectorTangentsAndNormals( m_KernelTubePoints ); } template< class TInputImage > void RadiusExtractor2<TInputImage> ::RecordOptimaAtTubePoints( unsigned int tubePointNum, TubeType * tube ) { int tubeSize = tube->GetPoints().size(); double r1 = this->GetKernelOptimalRadius(); double m1 = this->GetKernelOptimalRadiusMedialness(); double b1 = this->GetKernelOptimalRadiusBranchness(); int startP = tubePointNum - ( m_NumKernelPoints / 2 ) * m_KernelPointStep; if( startP < 0 ) { startP = 0; } double r0 = tube->GetPoints()[ startP ].GetRadius(); double m0 = tube->GetPoints()[ startP ].GetMedialness(); double b0 = tube->GetPoints()[ startP ].GetBranchness(); if( r0 == 0 ) { r0 = r1; m0 = m1; b0 = b1; } int endP = startP + ( m_NumKernelPoints - 1 ) * m_KernelPointStep; if( endP > tubeSize-1 ) { endP = tubeSize-1; } double r2 = tube->GetPoints()[ endP ].GetRadius(); double m2 = tube->GetPoints()[ endP ].GetMedialness(); double b2 = tube->GetPoints()[ endP ].GetBranchness(); if( r2 == 0 ) { r2 = r1; m2 = m1; b2 = b1; } for( int p = startP; p <= endP; ++p ) { if( p < static_cast< int >( tubePointNum ) ) { double d = 1; if( static_cast< int >( tubePointNum ) != startP ) { d = static_cast< double >( tubePointNum - p ) / ( tubePointNum - startP ); } tube->GetPoints()[ p ].SetRadius( d * r0 + (1 - d) * r1 ); tube->GetPoints()[ p ].SetMedialness( d * m0 + (1 - d) * m1 ); tube->GetPoints()[ p ].SetBranchness( d * b0 + (1 - d) * b1 ); } else { double d = 1; if( static_cast< int >( tubePointNum ) != endP ) { d = static_cast< double >( p - tubePointNum ) / ( endP - tubePointNum ); } tube->GetPoints()[ p ].SetRadius( d * r2 + (1 - d) * r1 ); tube->GetPoints()[ p ].SetMedialness( d * m2 + (1 - d) * m1 ); tube->GetPoints()[ p ].SetBranchness( d * b2 + (1 - d) * b1 ); } } } template< class TInputImage > void RadiusExtractor2<TInputImage> ::PrintSelf( std::ostream & os, Indent indent ) const { Superclass::PrintSelf( os, indent ); if( m_Image.IsNotNull() ) { os << indent << "Image = " << m_Image << std::endl; } else { os << indent << "Image = NULL" << std::endl; } os << indent << "DataMin = " << m_DataMin << std::endl; os << indent << "DataMax = " << m_DataMax << std::endl; os << indent << "RadiusStart = " << m_RadiusStart << std::endl; os << indent << "RadiusMin = " << m_RadiusMin << std::endl; os << indent << "RadiusMax = " << m_RadiusMax << std::endl; os << indent << "RadiusStep = " << m_RadiusStep << std::endl; os << indent << "RadiusTolerance = " << m_RadiusTolerance << std::endl; os << indent << "MinMedialness = " << m_MinMedialness << std::endl; os << indent << "MinMedialnessStart = " << m_MinMedialnessStart << std::endl; os << indent << "NumKernelPoints = " << m_NumKernelPoints << std::endl; os << indent << "KernelTubePoints = " << m_KernelTubePoints.size() << std::endl; os << indent << "KernelPointStep = " << m_KernelPointStep << std::endl; os << indent << "KernelStep = " << m_KernelStep << std::endl; os << indent << "KernelExtent = " << m_KernelExtent << std::endl; os << indent << "KernelValues = " << m_KernelValues.size() << std::endl; os << indent << "KernelDistances = " << m_KernelDistances.size() << std::endl; os << indent << "KernelTangentDistances = " << m_KernelTangentDistances.size() << std::endl; os << indent << "KernelOptimalRadius = " << m_KernelOptimalRadius << std::endl; os << indent << "KernelOptimalRadiusMedialness = " << m_KernelOptimalRadiusMedialness << std::endl; os << indent << "KernelOptimalRadiusBranchness = " << m_KernelOptimalRadiusBranchness << std::endl; os << indent << "IdleCallBack = " << m_IdleCallBack << std::endl; os << indent << "StatusCallBack = " << m_StatusCallBack << std::endl; } /** * Idle callback */ template< class TInputImage > void RadiusExtractor2<TInputImage> ::SetIdleCallBack( bool ( *idleCallBack )() ) { m_IdleCallBack = idleCallBack; } /** * Status Call back */ template< class TInputImage > void RadiusExtractor2<TInputImage> ::SetStatusCallBack( void ( *statusCallBack )( const char *, const char *, int ) ) { m_StatusCallBack = statusCallBack; } } // End namespace tube } // End namespace itk #endif // End !defined(__itktubeRadiusExtractor2_hxx)
[ "stephen.aylward@kitware.com" ]
stephen.aylward@kitware.com
efcdc63f79623dc31404dcce42d30b8a24b9dfe1
6dfd52d6fba36acc5a3c5ecaa497de97bc976e4e
/SdlBreakout/SdlBreakout/SerializableLevel.h
c8b90f3f369355da5da0f51c23873fd656353d7b
[]
no_license
Autoquark/SdlBreakout
4a0939abd80efa1c58dfb334f0990f6e0ebf9638
d63d274f0832436eb6cd3baa43a7ab854dcd4c29
refs/heads/master
2023-02-26T08:03:59.280927
2021-02-04T15:19:44
2021-02-04T15:19:44
221,943,204
0
0
null
2021-02-04T13:58:42
2019-11-15T14:44:36
C++
UTF-8
C++
false
false
261
h
#pragma once #include "stdafx.h" #include <nlohmann/json.hpp> #include "LegendEntry.h" struct SerializableLevel { public: std::vector<std::string> grid; std::vector<LegendEntry> legend; NLOHMANN_DEFINE_TYPE_INTRUSIVE(SerializableLevel, grid, legend) };
[ "github@autoquark.33mail.com" ]
github@autoquark.33mail.com
d2c31ceed2b41553302a6a16fbcb17fa362d6fc5
c1ce1b303de794a4dc8f0d2f2d14e9d771d5e754
/ABC/ABC046/D2.cpp
96748638afed303338cb831bb5cee93a07ede7d6
[]
no_license
reiya0104/AtCoder
8790f302e31fa95aaf9ea16e443802d7b9f34bbf
16d6257b82a0807fa07d830e22d1143c32173072
refs/heads/master
2023-05-09T17:29:12.394495
2021-06-21T02:39:16
2021-06-21T02:39:16
342,526,657
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
/** * author: reiya0104 * created: 05.04.2021 01:19:38 **/ #include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; const int INF = 1001001000; int main() { string s; cin >> s; int count_p = 0; int count_g = 0; int count_win = 0; int count_lose = 0; for (int i = 0; i < s.size(); ++i) { if (s.at(i) == 'p') { if (count_p < count_g) { ++count_p; } else { ++count_g; ++count_lose; } } else if (s.at(i) == 'g') { if (count_p < count_g) { ++count_p; ++count_win; } else { ++count_g; } } } int res = count_win - count_lose; cout << res << endl; }
[ "reiya0104@ezweb.ne.jp" ]
reiya0104@ezweb.ne.jp
9ec3dc7990ab8ddafb5fa037a2cb7e18995c33ed
e08ebd3daae7d0c9a578aced6be490ef9c560fdc
/Source/Atomic/IO/Serializer.cpp
3951e0da5b5281242a05282a14a550525b292045
[ "MIT", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-openssl", "LicenseRef-scancode-khronos", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NTP" ]
permissive
bryant1410/AtomicGameEngine
86070cb6f575c9d6fdb0de12b66ac1ec295e55c8
51286ffc4102dcf2b633d36d5c0cb2dae9817302
refs/heads/master
2021-01-19T19:56:23.085734
2017-04-17T03:41:20
2017-04-17T03:41:20
88,465,101
1
0
null
2017-04-17T03:41:21
2017-04-17T03:41:21
null
UTF-8
C++
false
false
10,781
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 "../Precompiled.h" #include "../IO/Serializer.h" #include "../DebugNew.h" namespace Atomic { static const float q = 32767.0f; Serializer::~Serializer() { } bool Serializer::WriteInt64(long long value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteInt(int value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteShort(short value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteByte(signed char value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteUInt64(unsigned long long value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteUInt(unsigned value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteUShort(unsigned short value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteUByte(unsigned char value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteBool(bool value) { return WriteUByte((unsigned char)(value ? 1 : 0)) == 1; } bool Serializer::WriteFloat(float value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteDouble(double value) { return Write(&value, sizeof value) == sizeof value; } bool Serializer::WriteIntRect(const IntRect& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteIntVector2(const IntVector2& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteRect(const Rect& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteVector2(const Vector2& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteVector3(const Vector3& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WritePackedVector3(const Vector3& value, float maxAbsCoord) { short coords[3]; float v = 32767.0f / maxAbsCoord; coords[0] = (short)(Clamp(value.x_, -maxAbsCoord, maxAbsCoord) * v + 0.5f); coords[1] = (short)(Clamp(value.y_, -maxAbsCoord, maxAbsCoord) * v + 0.5f); coords[2] = (short)(Clamp(value.z_, -maxAbsCoord, maxAbsCoord) * v + 0.5f); return Write(&coords[0], sizeof coords) == sizeof coords; } bool Serializer::WriteVector4(const Vector4& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteQuaternion(const Quaternion& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WritePackedQuaternion(const Quaternion& value) { short coords[4]; Quaternion norm = value.Normalized(); coords[0] = (short)(Clamp(norm.w_, -1.0f, 1.0f) * q + 0.5f); coords[1] = (short)(Clamp(norm.x_, -1.0f, 1.0f) * q + 0.5f); coords[2] = (short)(Clamp(norm.y_, -1.0f, 1.0f) * q + 0.5f); coords[3] = (short)(Clamp(norm.z_, -1.0f, 1.0f) * q + 0.5f); return Write(&coords[0], sizeof coords) == sizeof coords; } bool Serializer::WriteMatrix3(const Matrix3& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteMatrix3x4(const Matrix3x4& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteMatrix4(const Matrix4& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteColor(const Color& value) { return Write(value.Data(), sizeof value) == sizeof value; } bool Serializer::WriteBoundingBox(const BoundingBox& value) { bool success = true; success &= WriteVector3(value.min_); success &= WriteVector3(value.max_); return success; } bool Serializer::WriteString(const String& value) { const char* chars = value.CString(); // Count length to the first zero, because ReadString() does the same unsigned length = String::CStringLength(chars); return Write(chars, length + 1) == length + 1; } bool Serializer::WriteFileID(const String& value) { bool success = true; unsigned length = Min(value.Length(), 4U); success &= Write(value.CString(), length) == length; for (unsigned i = value.Length(); i < 4; ++i) success &= WriteByte(' '); return success; } bool Serializer::WriteStringHash(const StringHash& value) { return WriteUInt(value.Value()); } bool Serializer::WriteBuffer(const PODVector<unsigned char>& value) { bool success = true; unsigned size = value.Size(); success &= WriteVLE(size); if (size) success &= Write(&value[0], size) == size; return success; } bool Serializer::WriteResourceRef(const ResourceRef& value) { bool success = true; success &= WriteStringHash(value.type_); success &= WriteString(value.name_); return success; } bool Serializer::WriteResourceRefList(const ResourceRefList& value) { bool success = true; success &= WriteStringHash(value.type_); success &= WriteVLE(value.names_.Size()); for (unsigned i = 0; i < value.names_.Size(); ++i) success &= WriteString(value.names_[i]); return success; } bool Serializer::WriteVariant(const Variant& value) { bool success = true; VariantType type = value.GetType(); success &= WriteUByte((unsigned char)type); success &= WriteVariantData(value); return success; } bool Serializer::WriteVariantData(const Variant& value) { switch (value.GetType()) { case VAR_NONE: return true; case VAR_INT: return WriteInt(value.GetInt()); case VAR_BOOL: return WriteBool(value.GetBool()); case VAR_FLOAT: return WriteFloat(value.GetFloat()); case VAR_VECTOR2: return WriteVector2(value.GetVector2()); case VAR_VECTOR3: return WriteVector3(value.GetVector3()); case VAR_VECTOR4: return WriteVector4(value.GetVector4()); case VAR_QUATERNION: return WriteQuaternion(value.GetQuaternion()); case VAR_COLOR: return WriteColor(value.GetColor()); case VAR_STRING: return WriteString(value.GetString()); case VAR_BUFFER: return WriteBuffer(value.GetBuffer()); // Serializing pointers is not supported. Write null case VAR_VOIDPTR: case VAR_PTR: return WriteUInt(0); case VAR_RESOURCEREF: return WriteResourceRef(value.GetResourceRef()); case VAR_RESOURCEREFLIST: return WriteResourceRefList(value.GetResourceRefList()); case VAR_VARIANTVECTOR: return WriteVariantVector(value.GetVariantVector()); case VAR_STRINGVECTOR: return WriteStringVector(value.GetStringVector()); case VAR_VARIANTMAP: return WriteVariantMap(value.GetVariantMap()); case VAR_INTRECT: return WriteIntRect(value.GetIntRect()); case VAR_INTVECTOR2: return WriteIntVector2(value.GetIntVector2()); case VAR_MATRIX3: return WriteMatrix3(value.GetMatrix3()); case VAR_MATRIX3X4: return WriteMatrix3x4(value.GetMatrix3x4()); case VAR_MATRIX4: return WriteMatrix4(value.GetMatrix4()); case VAR_DOUBLE: return WriteDouble(value.GetDouble()); default: return false; } } bool Serializer::WriteVariantVector(const VariantVector& value) { bool success = true; success &= WriteVLE(value.Size()); for (VariantVector::ConstIterator i = value.Begin(); i != value.End(); ++i) success &= WriteVariant(*i); return success; } bool Serializer::WriteStringVector(const StringVector& value) { bool success = true; success &= WriteVLE(value.Size()); for (StringVector::ConstIterator i = value.Begin(); i != value.End(); ++i) success &= WriteString(*i); return success; } bool Serializer::WriteVariantMap(const VariantMap& value) { bool success = true; success &= WriteVLE(value.Size()); for (VariantMap::ConstIterator i = value.Begin(); i != value.End(); ++i) { WriteStringHash(i->first_); WriteVariant(i->second_); } return success; } bool Serializer::WriteVLE(unsigned value) { unsigned char data[4]; if (value < 0x80) return WriteUByte((unsigned char)value); else if (value < 0x4000) { data[0] = (unsigned char)(value | 0x80); data[1] = (unsigned char)(value >> 7); return Write(data, 2) == 2; } else if (value < 0x200000) { data[0] = (unsigned char)(value | 0x80); data[1] = (unsigned char)((value >> 7) | 0x80); data[2] = (unsigned char)(value >> 14); return Write(data, 3) == 3; } else { data[0] = (unsigned char)(value | 0x80); data[1] = (unsigned char)((value >> 7) | 0x80); data[2] = (unsigned char)((value >> 14) | 0x80); data[3] = (unsigned char)(value >> 21); return Write(data, 4) == 4; } } bool Serializer::WriteNetID(unsigned value) { return Write(&value, 3) == 3; } bool Serializer::WriteLine(const String& value) { bool success = true; success &= Write(value.CString(), value.Length()) == value.Length(); success &= WriteUByte(13); success &= WriteUByte(10); return success; } }
[ "josh@galaxyfarfaraway.com" ]
josh@galaxyfarfaraway.com
90687af94347b35f0d7ba217466a338ac19f6054
fb383048bc12afd0b303f1f25816c8ee6910b20c
/cpp_primer/chaper9/927.cpp
71dd776ec2d6246bdca7b05c78d9b5bc72513673
[]
no_license
linw/cpp
cf02aac2df2a07a71dc70593315b11d889d6c237
5bf054eef413ed5e7a80b6c837ee92b51b13a7a3
refs/heads/master
2016-08-08T12:12:06.995979
2012-01-02T13:21:25
2012-01-02T13:21:25
3,087,582
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
cpp
/* * File name: 927.cpp * Author: linwei * E-mail: kinglw8729@gmail.com * Date: 2011-12-5 * */ #include <vector> #include <list> #include <deque> #include <iostream> #include <string> #include <algorithm> using namespace std; int FindAndErase(list<string> &source, const string &s){ int count = 0; list<string>::iterator iter = source.begin(); while(iter != source.end()){ if(*iter == s){ iter = source.erase(iter); count++; } else ++iter; } return count; } int FindAndErase_deque(deque<string> &source, const string &s){ int count = 0; deque<string>::iterator iter = source.begin(); while(iter != source.end()){ if(*iter == s){ iter = source.erase(iter); ++count; } else ++iter; } return count; } int main() { string a[10] = {"linv", "king", "monkey", "linw", "haohao", "apple", "king", "linwei", "chihao", "light"}; list<string> source(a, a + 10); FindAndErase(source, "king"); cout<<"size: "<<source.size()<<endl; return 0; }
[ "kinglw8729@gmail.com" ]
kinglw8729@gmail.com
b0efe47ad575d5e79104c6c78f6dd661368d837b
0c153f489e523afdc33b950a6b9ee21af09e968e
/cpp/src/burgers1d_input_parser.hpp
b0ca5febcc53e48ed2d7d37a30f3beabbe369c6d
[]
no_license
Pressio/pressio-sisc-burgers1d
86f1acb31d40d1aefa83b61bb4e8a7d70621cf1a
671f45b7abd5dc59d574b6d26cc4a5f23ee90306
refs/heads/master
2021-01-26T01:04:20.594259
2020-04-26T11:32:00
2020-04-26T11:32:00
243,249,905
0
0
null
null
null
null
UTF-8
C++
false
false
3,355
hpp
#ifndef BURGERS1DCPP_INPUT_HPP_ #define BURGERS1DCPP_INPUT_HPP_ #include <sstream> struct InputParser{ using scalar_t = double; std::string fileName_ = "empty"; int32_t numCell_ = {}; scalar_t dt_ = {}; scalar_t finalT_ = {}; int32_t numSteps_ = {}; int32_t observerOn_ = 0; int32_t snapshotsFreq_ = {}; // freq of collecting snapshots std::string shapshotsFileName_ = "empty"; std::string basisFileName_ = "empty"; int32_t romOn_ = 0; int32_t romSize_ = {}; InputParser() = default; ~InputParser() = default; int32_t parse(int32_t argc, char *argv[]) { if (argc != 2){ std::cerr << "Usage: " << argv[0] << " inputFile " << std::endl; std::cerr << "invalid number of argments" << std::endl; return 1; } const std::string inputFile = argv[1]; std::ifstream source; source.open( inputFile, std::ios_base::in); std::string line; while (std::getline(source, line) ) { //make a stream for the line itself std::istringstream in(line); // tmp variable to store each entry of the file std::string col1, col2; // column 0, index in >> col1; in >> col2; if (col1 == "numCell"){ numCell_ = std::stoi(col2); } if (col1 == "dt"){ dt_ = std::stod(col2); } if (col1 == "finalTime"){ finalT_ = std::stod(col2); } if (col1 == "observerOn"){ observerOn_ = std::stoi(col2); } if (observerOn_==1){ if (col1 == "shapshotsFreq"){ snapshotsFreq_ = std::stoi(col2); } if (col1 == "shapshotsFileName"){ shapshotsFileName_ = col2; } if (col1 == "basisFileName"){ basisFileName_ = col2; } } if (col1 == "romOn"){ romOn_ = std::stoi(col2); } if (romOn_==1){ if (col1 == "romSize"){ romSize_ = std::stoi(col2); } if (col1 == "basisFileName"){ basisFileName_ = col2; } } } numSteps_ = static_cast<int32_t>(finalT_/dt_); source.close(); std::cout << "Ncell = " << numCell_ << " \n" << "dt = " << dt_ << " \n" << "finalT = " << finalT_ << " \n" << "numSteps = " << numSteps_ << " \n" << "observerOn " << observerOn_ << " \n" << "shapshotsFileName_ = "<< shapshotsFileName_ << " \n" << "snapshotsFreq_ = " << snapshotsFreq_ << " \n" << "romOn_ = " << romOn_ << " \n" << "romSize_ = " << romSize_ << " \n" << "basisFileName_ = " << basisFileName_ << std::endl; if (numCell_==0){ std::cerr << "Invalid numCell" << std::endl; return 1; } if (dt_==0.){ std::cerr << "Invalid dt" << std::endl; return 1; } if (finalT_==0.){ std::cerr << "Invalid finalT" << std::endl; return 1; } if (observerOn_==1){ if (snapshotsFreq_==0){ std::cerr << "Invalid snapshotsFreq" << std::endl; return 1; } if (shapshotsFileName_=="empty"){ std::cerr << "Invalid shapshotsFileName" << std::endl; return 1; } if (basisFileName_=="empty"){ std::cerr << "Invalid basisFileName" << std::endl; return 1; } } if (romOn_==1){ if (romSize_==0){ std::cerr << "Invalid rom size" << std::endl; return 1; } if (basisFileName_=="empty"){ std::cerr << "Invalid basisFileName" << std::endl; return 1; } } return 0; } }; #endif
[ "fnrizzi@sandia.gov" ]
fnrizzi@sandia.gov
a785177706e2aa861621b094cfb1dfb22d4fc193
776f5892f1395bb8d30731a60466e4c756a44c8c
/contests/abc215/abc215_a/main.cc
e6ced2ebc38afff7d078d7e50f18e17b54418988
[]
no_license
kkishi/atcoder
fae494af4b47a9f39f05e7536e93d5c4dd21555b
f21d22095699dbf064c0d084a5ce5a09a252dc6b
refs/heads/master
2023-08-31T18:37:13.293499
2023-08-27T21:33:43
2023-08-27T21:33:43
264,760,383
0
0
null
2023-03-10T05:24:07
2020-05-17T21:30:14
C++
UTF-8
C++
false
false
119
cc
#include <bits/stdc++.h> #include "atcoder.h" void Main() { strings(s); wt(s == "Hello,World!" ? "AC" : "WA"); }
[ "keisuke.kishimoto@gmail.com" ]
keisuke.kishimoto@gmail.com
b23ca1fcaca947594efcfa6436b8a170cb42aec1
39a1d46fdf2acb22759774a027a09aa9d10103ba
/ngraph/core/reference/include/ngraph/runtime/reference/transpose.hpp
bf3a016ea9223162b6ee597c1a8f0c84ae31b5bc
[ "Apache-2.0" ]
permissive
mashoujiang/openvino
32c9c325ffe44f93a15e87305affd6099d40f3bc
bc3642538190a622265560be6d88096a18d8a842
refs/heads/master
2023-07-28T19:39:36.803623
2021-07-16T15:55:05
2021-07-16T15:55:05
355,786,209
1
3
Apache-2.0
2021-06-30T01:32:47
2021-04-08T06:22:16
C++
UTF-8
C++
false
false
656
hpp
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <cfenv> #include <cmath> #include <numeric> #include <vector> #include "ngraph/shape.hpp" namespace ngraph { namespace runtime { namespace reference { void transpose(const char* data, char* out, const Shape& data_shape, size_t element_size, const int64_t* axes_order, Shape out_shape); } // namespace reference } // namespace runtime } // namespace ngraph
[ "noreply@github.com" ]
mashoujiang.noreply@github.com
548d04068851caef4819a597f02ddbd4bffe7d39
afee22fe8845a736b9916b64cecfe686f2491065
/ContainerWithMostWater/ContainerWithMostWater.cpp
1771fc1109ed39641372a1d0cd7493bdba442f46
[]
no_license
felixfqiu/leetcode-havefun
40e6e5225fc713304db1b9c346abc8f0482f6e1c
996a167763696f488c6889d20311b590aaf158d1
refs/heads/master
2021-01-12T12:17:57.648499
2016-12-27T09:26:15
2016-12-27T09:26:15
72,419,580
0
0
null
null
null
null
GB18030
C++
false
false
664
cpp
// ContainerWithMostWater.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <vector> using namespace std; int min(int a, int b) { return a < b ? a : b; } int max(int a, int b) { return a > b ? a : b; } int area(vector<int>& height, int l, int r) { int h = min(height[r], height[l]); return (r - l) * h; } int maxArea(vector<int>& height) { vector<int>& h = height; int l = 0; int r = height.size() - 1; int s = 0; while (r > l) { s = max(area(height, l, r), s); height[l] < height[r] ? l++ : r--; } return s; } int main() { vector<int> height{2,3,4,5,18,17,6}; int area = maxArea(height); return 0; }
[ "felixfqiu@gmail.com" ]
felixfqiu@gmail.com
c6b7aa14ae9c9c5bb80a90d2894fd236d82d26e6
43e28ce11f5ddd07407a87385809c5e3933f348f
/mhdlc/src/vpp_interface.cc
7fe8cdf210e1e1d85cd01dbdd6982bb5c101632f
[]
no_license
xinmeng/metahdl
5d3421a5f06521d821d089efd94958abf78816f3
b9465b3b44c1069382286365211ffb328a0b657f
refs/heads/master
2022-06-29T18:15:11.937153
2015-07-01T06:31:52
2015-07-01T06:31:52
32,431,363
7
0
null
null
null
null
UTF-8
C++
false
false
1,555
cc
/* Copyright (C) 1996 Himanshu M. Thaker This file is part of vpp. Vpp is distributed in the hope that it will be useful, but without any warranty. No author or distributor accepts responsibility to anyone for the consequences of using it or for whether it serves any particular purpose or works at all, unless he says so in writing. Everyone is granted permission to copy, modify and redistribute vpp, but only under the conditions described in the document "vpp copying permission notice". An exact copy of the document is supposed to have been given to you along with vpp so that you can know how you may redistribute it all. It should be in a file named COPYING. Among other things, the copyright notice and this notice must be preserved on all copies. */ /* * Program : vpp * Author : Himanshu M. Thaker * Date : Apr. 16, 1995 * Description : */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include "common.h" #include "yacc_stuff.h" #include "proto.h" #include <string.h> #include <stdio.h> #include <string> using namespace std; extern FILE *yyout; extern char *current_file; extern int yyerror_count; extern int yy_flex_debug; #include "Mfunc.hh" int preprocess(FILE *in, const string &f, FILE *out) { yyin = in; yyout = out; current_file = (char*) malloc(f.length()+1); strcpy(current_file, f.c_str()); nl_count = 1; do_comment_count(TRUE, nl_count); yy_flex_debug = DebugPPLexer; yyparse(); return yyerror_count; }
[ "zinces@cd89b550-3133-0410-a459-13e4e5e64c7f" ]
zinces@cd89b550-3133-0410-a459-13e4e5e64c7f
38c7c41be02b38d5c119e44e630c839318ce43dc
8b930c0ced69054f02ed32fa5913f62a8cc86446
/NodemcuSerialArduino/NodemcuSerialArduino.ino
f608d7bbeda1deb39ef681d8df16aef473d388ff
[]
no_license
Arion12112/HardwareCodeSimpleAWS
99e7b1eb9c2bf54b88872b49904fa9ba40f8d7cd
c5ac5a1673d27156804df6912da27cf54a747f7f
refs/heads/master
2020-08-31T20:17:18.120657
2019-11-28T15:59:15
2019-11-28T15:59:15
218,776,156
1
0
null
null
null
null
UTF-8
C++
false
false
6,188
ino
#include <ESP8266WiFi.h> #include <WiFiClientSecure.h> #include <PubSubClient.h> #include <SoftwareSerial.h> SoftwareSerial s(D6,D5); #include <ArduinoJson.h> #include <NTPClient.h> #include <WiFiUdp.h> #include <Wire.h> #include <DNSServer.h> #include <ESP8266WebServer.h> #include <WiFiManager.h> #define emptyString String() #include "secrets.h" char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; const long utcOffsetInSeconds = 25200; //WIB +07.00 const int MQTT_PORT = 8883; const char MQTT_SUB_TOPIC[] = "simpleaws";//"$aws/things/" THINGNAME "/shadow/update"; const char MQTT_PUB_TOPIC[] = "simpleaws";//"$aws/things/" THINGNAME "/shadow/update"; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds); #ifdef USE_SUMMER_TIME_DST uint8_t DST = 1; #else uint8_t DST = 0; #endif WiFiClientSecure net; #ifdef ESP8266 BearSSL::X509List cert(cacert); BearSSL::X509List client_crt(client_cert); BearSSL::PrivateKey key(privkey); #endif PubSubClient client(net); unsigned long lastMillis = 0; time_t now; time_t nowish = 1510592825; void NTPConnect(void) { Serial.print("Setting time using SNTP"); configTime(TIME_ZONE * 3600, DST * 3600, "pool.ntp.org", "time.nist.gov"); now = time(nullptr); while (now < nowish) { delay(500); Serial.print("."); now = time(nullptr); } Serial.println("done!"); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print("Current time: "); Serial.print(asctime(&timeinfo)); } void messageReceived(char *topic, byte *payload, unsigned int length) { Serial.print("Received ["); Serial.print(topic); Serial.print("]: "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); } void pubSubErr(int8_t MQTTErr) { if (MQTTErr == MQTT_CONNECTION_TIMEOUT) Serial.print("Connection tiemout"); else if (MQTTErr == MQTT_CONNECTION_LOST) Serial.print("Connection lost"); else if (MQTTErr == MQTT_CONNECT_FAILED) Serial.print("Connect failed"); else if (MQTTErr == MQTT_DISCONNECTED) Serial.print("Disconnected"); else if (MQTTErr == MQTT_CONNECTED) Serial.print("Connected"); else if (MQTTErr == MQTT_CONNECT_BAD_PROTOCOL) Serial.print("Connect bad protocol"); else if (MQTTErr == MQTT_CONNECT_BAD_CLIENT_ID) Serial.print("Connect bad Client-ID"); else if (MQTTErr == MQTT_CONNECT_UNAVAILABLE) Serial.print("Connect unavailable"); else if (MQTTErr == MQTT_CONNECT_BAD_CREDENTIALS) Serial.print("Connect bad credentials"); else if (MQTTErr == MQTT_CONNECT_UNAUTHORIZED) Serial.print("Connect unauthorized"); } void connectToMqtt(bool nonBlocking = false) { Serial.print("MQTT connecting "); while (!client.connected()) { if (client.connect(THINGNAME)) { Serial.println("connected!"); if (!client.subscribe(MQTT_SUB_TOPIC)) pubSubErr(client.state()); } else { Serial.print("failed, reason -> "); pubSubErr(client.state()); if (!nonBlocking) { Serial.println(" < try again in 5 seconds"); delay(5000); } else { Serial.println(" <"); } } if (nonBlocking) break; } } void connectToWiFi(String init_str) { if (init_str != emptyString) Serial.print(init_str); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(1000); } if (init_str != emptyString) Serial.println("ok!"); } void checkWiFiThenMQTT(void) { connectToWiFi("Checking WiFi"); connectToMqtt(); } unsigned long previousMillis = 0; const long interval = 5000; void checkWiFiThenMQTTNonBlocking(void) { connectToWiFi(emptyString); if (millis() - previousMillis >= interval && !client.connected()) { previousMillis = millis(); connectToMqtt(true); } } void checkWiFiThenReboot(void) { connectToWiFi("Checking WiFi"); Serial.print("Rebooting"); ESP.restart(); } //masukkan data pembacaan sensor ke fungsi ini void sendDataSensor(void) { //update waktu untuk pengiriman data //DynamicJsonDocument doc(1024); //DeserializationError error = deserializeJson(doc, s); //if (error) //{ // Serial.println("error"); // return; //} //String value = doc["value"]; String value = s.readString(); Serial.println(value); delay(5000); now = time(nullptr); timeClient.update(); //inisialisasi payload untuk dikirim String message = value; String formattedDate = String(timeClient.getFullFormattedTime()); //jadikan data sensor sebagai bentuk string message += ","; //tambahkan koma jika ingin menambah sensor //format untuk tanggal jangan diubah message += formattedDate;//tanggal ditaruh di bagian akhir string if (!client.publish(MQTT_PUB_TOPIC, message.c_str(), false)) //contoh data yg terkirim (100, 2019-10-30 00:00:00) pubSubErr(client.state()); } void setup() { // Initialize Serial port Serial.begin(115200); s.begin(9600); timeClient.begin(); //WiFi.hostname(THINGNAME); //WiFi.mode(WIFI_STA); //WiFi.begin(ssid, pass); //connectToWiFi(String("Attempting to connect to SSID: ") + String(ssid)); WiFiManager wifiManager; wifiManager.autoConnect(THINGNAME); //reset saved settings //wifiManager.resetSettings(); Serial.println("connected...yeey :)"); NTPConnect(); #ifdef ESP32 net.setCACert(cacert); net.setCertificate(client_cert); net.setPrivateKey(privkey); #else net.setTrustAnchors(&cert); net.setClientRSACert(&client_crt, &key); #endif client.setServer(MQTT_HOST, MQTT_PORT); client.setCallback(messageReceived); connectToMqtt(); while (!Serial) continue; } void loop() { now = time(nullptr); if (!client.connected()) { checkWiFiThenMQTT(); //checkWiFiThenMQTTNonBlocking(); //checkWiFiThenReboot(); } else { client.loop(); while(s.available()) sendDataSensor(); } }
[ "noreply@github.com" ]
Arion12112.noreply@github.com
e5c5610babe44fe01c020471e3db3bfa1ededfe0
e299f83b4dee33bdb986ac0de214b18380d63cf2
/builder.cpp
4a757aaa9a97ca1e32b8a96c00faae9ec537ad57
[]
no_license
GabrielInTheWorld/pva-exam
85bce2ff45866fe7afaffe8b8f957debb9205c76
bf80210642f2bd02cb03f4c6ec234e479b4a4ab5
refs/heads/master
2020-11-25T10:51:45.004052
2020-02-12T14:48:28
2020-02-12T14:48:28
228,627,369
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
cpp
#include "builder.h" // Gebaut von Michael Sieb con_set Builder::buildPeriodicFreeUnorderedSet(concurrent_vector<string>* wordList, const int& k) { this->k = k; con_set result; auto callback = [&](int index) { string word = (*wordList)[index]; if ( !checkIfPeriod(word) ) { result.insert(word); } }; parallel_for(0, (int)wordList->size(), callback); return result; } // Gebaut von Gabriel Meyer bool Builder::checkIfPeriod(const string& word) { bool isPeriodic = true; concurrent_queue<int> q; const int MIDDLE = k / 2 + 1; auto findDivider = [&](int index) { if ( k % index == 0 ) { q.push(index); } }; parallel_for(1, MIDDLE, findDivider); int i = 0; while ( !q.empty() ) { if ( q.try_pop(i) ) { isPeriodic = true; string substr = word.substr(0, i); int subLength = (int)substr.length(); auto callback = [&](int index) { isPeriodic = isPeriodic && substr == word.substr(subLength * index, i); }; parallel_for(1, k / subLength, callback); if ( isPeriodic ) { break; } } } return isPeriodic; }
[ "meyergabriel@live.de" ]
meyergabriel@live.de
26ce4798b5ae425da2a001d2e5e11ff940735bf0
95d11da11488128cc5b983236c5b821a3c4fb9aa
/cocos2d-x-2.1.4/extensions/CCBReader/actCatmullRomToLoader.h
170b543947a8c80963277f9ba042cedbe6e82c9c
[]
no_license
masteage/AceCocosBuilder
0874fb6e85d2057847926ee11bd289d3f7e92c4b
4a09d428f67898754b167a14584592777e8c2dfd
refs/heads/master
2021-01-11T21:42:50.851594
2017-01-12T01:21:12
2017-01-12T01:21:12
78,837,294
0
0
null
2017-01-13T09:58:06
2017-01-13T09:58:06
null
UTF-8
C++
false
false
875
h
// // actCatmullRomToLoader.h // ScrollViewTest // // Created by 허정목 on 2014. 1. 13.. // // #ifndef ScrollViewTest_actCatmullRomToLoader_h #define ScrollViewTest_actCatmullRomToLoader_h #include "actCatmullRomTo.h" USING_NS_CC; USING_NS_CC_EXT; NS_CC_EXT_BEGIN /* Forward declaration. */ class CCBReader; class actCatmullRomToLoader : public CCNodeLoader { public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(actCatmullRomToLoader, loader); protected: CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(actCatmullRomTo); virtual void onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, const char* pPropertyName, float pFloat, CCBReader * pCCBReader); virtual void onHandlePropTypeString(CCNode * pNode, CCNode * pParent, const char * pPropertyName, const char * pString, CCBReader * pCCBReader); }; NS_CC_EXT_END #endif
[ "hsahn@aceproject.co.kr" ]
hsahn@aceproject.co.kr
8a713dd98fe7df58c3006b8383c7430c24f0ad89
9185e2aefea655690f26571848cccd12a4145d2a
/analysis/calibration/Th_calibScript_Int.cpp
a04a6ee8133e5e6052bfedea7d6bb006aab95a32
[]
no_license
yannmu/Gator_2020
f7460509f8df984bf3b895f0adc1e1964b16351f
8042371ec8d8ca63fe6b0fa75cf1ad6a90572ac4
refs/heads/master
2023-04-19T02:13:53.520283
2021-05-04T14:53:35
2021-05-04T14:53:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,016
cpp
//========This script should be used as the first part of a wider script for each data taking========// // For this script is required the header: header_Th_lines.h // // To run this script are required the functions contained in the following libraries: // - myFuncs.cpp // - myFitFunctions.c { TCanvas* c1 = new TCanvas("Canv1","228Th source Calibration"); gROOT -> ProcessLine(".L myFuncs.cpp");//All the functions used here gROOT -> ProcessLine(".L myFitFunctions.c");//for the function "peakFitFunc" and "initFitFunc" //Creation of an histogram with the ASCII data of the Th228 source. Draw it in the second pad. Double_t time = 0; //Acquisition time in seconds of the source string filename("228Th-TF656_20120316_FT.txt"); TH1F* h = histogen(filename,time); TF1* ff = new TF1("ff",peakFitFunc,(Double_t)h->GetXaxis()->GetFirst(),(Double_t)h->GetXaxis()->GetLast(),8); ff->SetParNames("Mean","Ampl","A","Sigma","Beta","S","Slope","Intercept"); ff->SetLineColor(2); //Vectors where I'll put all the parameters I want from the peaks vector<Double_t>* ADCcenters = new vector<Double_t>; vector<Double_t>* ADCcenters_err = new vector<Double_t>; vector<Double_t>* ADCwidths = new vector<Double_t>; vector<Double_t>* ADCwidths_err = new vector<Double_t>; vector<Double_t>* ADCresol = new vector<Double_t>; //vector<Double_t>* ADCresol_err = new vector<Double_t>; vector<Double_t>* ENRresol = new vector<Double_t>; //vector<Double_t>* ENRresol_err = new vector<Double_t>; //The lines to be searched for the calibration are (in ascending energy order): //===Pb239=== Range (1360,1440)// //===Tl277=== Range (1610,1670)// //===Pb300=== Range (1745,1800)// //===Tl583=== Range (3380,3500)// //===Bi727=== Range (4200,4340)// //===Tl763=== Range (4350,4500) ==> NO// //===Bi785=== Range (4500,4650) ==> NO// //===Tl861=== Range (5000,5200)// //===Bi1621=== Range (9340,9480)// //===Tl2615=== Range (15200,15600)// //Here follow the array of the litterature e corresponding energy lines (in KeV): Double_t ENR_litt[] = {238.632,277.37,300.089,583.187,727.33,860.53,1620.738,2614.511}; Double_t ENR_litt_err[] = {0.002,0.02,0.012,0.002,0.01,0.02,0.010,0.010}; Int_t nlines = sizeof(ENR_litt)/sizeof(Double_t); TFitResultPtr resFit; h -> GetXaxis() -> SetRangeUser(1360,1490); //ff -> SetRange(1360,1490); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); h -> GetXaxis() -> SetRangeUser(1610,1670); //ff -> SetRange(1610,1670); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); h -> GetXaxis() -> SetRangeUser(1745,1800); //ff -> SetRange(1745,1800); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); //===ee511===// //Range (2850,3050) --> Use line analisys functions..... //h2->SetAxisRange(2220,2320); //ff->SetParameters(2274,5,4500,150,-0.01); //ff->SetRange(2220,2320); //h2->Fit(ff,"R+"); //linesADC[ee511]=ff->GetParameter(0); //linesADCerr[ee511]=ff->GetParError(0); h -> GetXaxis() -> SetRangeUser(3380,3500); //ff->SetRange(3380,3500); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); h -> GetXaxis() -> SetRangeUser(4200,4340); //ff->SetRange(4200,4340); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); h -> GetXaxis() -> SetRangeUser(5000,5200); //ff->SetRange(5000,5200); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); h -> GetXaxis() -> SetRangeUser(9300,9500); //ff->SetRange(9300,9500); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); h -> GetXaxis() -> SetRangeUser(15200,15600); //ff->SetRange(15200,15600); initFitFunc(h,ff); resFit = h -> Fit(ff,"BS+"); ADCcenters -> push_back(ff->GetParameter(0)); ADCcenters_err -> push_back(ff->GetParError(0)); ADCwidths -> push_back(ff->GetParameter(3)); ADCwidths_err -> push_back(ff->GetParError(3)); ADCresol -> push_back((ff->GetParameter(3))/(ff->GetParameter(0))); //ADCresol_err -> push_back(resolError(ff,resFit)); TF1* gausFunc = new TF1("gausFunc",gausFunc,(Double_t)h->GetXaxis()->GetFirst(),(Double_t)h->GetXaxis()->GetLast(),3); gausFunc -> SetRange(15200,15600); gausFunc -> SetLineColor(3); gausFunc -> SetLineWidth(1); gausFunc -> SetParameters(ff->GetParameter(0),ff->GetParameter(3),ff->GetParameter(1)*(1-ff->GetParameter(2))); gausFunc -> Draw("same"); TF1* tailFunc = new TF1("tailFunc",tailFunc,(Double_t)h->GetXaxis()->GetFirst(),(Double_t)h->GetXaxis()->GetLast(),4); tailFunc -> SetRange(15200,15600); tailFunc -> SetLineColor(4); tailFunc -> SetLineWidth(1); tailFunc -> SetParameters(ff->GetParameter(0),ff->GetParameter(3),ff->GetParameter(4),ff->GetParameter(1)*ff->GetParameter(2)); tailFunc -> Draw("same"); TF1* stepFunc = new TF1("stepFunc",tailFunc,(Double_t)h->GetXaxis()->GetFirst(),(Double_t)h->GetXaxis()->GetLast(),3); stepFunc -> SetRange(15200,15600); stepFunc -> SetLineColor(6); stepFunc -> SetLineWidth(1); stepFunc -> SetParameters(ff->GetParameter(0),ff->GetParameter(3),ff->GetParameter(5)); stepFunc -> Draw("same"); TF1* linFunc = new TF1("linFunc","pol1"); linFunc -> SetRange(15200,15600); linFunc -> SetLineColor(7); linFunc -> SetLineWidth(1); linFunc -> SetParameters(ff->GetParameter(7),ff->GetParameter(6)); linFunc -> Draw("same"); h -> GetXaxis()->SetTitle("ADC channel"); h -> GetYaxis()->SetTitle("Entries"); // ADC => Energy conversion TCanvas* c2 = new TCanvas("c2","ADC -> Energy conversion"); c2 -> cd(); TGraphErrors* gr_cal_fw = new TGraphErrors(nlines,&(ADCcenters->at(0)),ENR_litt,&(ADCcenters_err->at(0)),ENR_litt_err); gr_cal_fw -> Draw("AP"); TF1* calib_fcn_fw = new TF1("calib_fcn_fw","pol2"); calib_fcn_fw -> SetLineColor(2); calib_fcn_fw -> SetLineWidth(1); gr_cal_fw -> Fit(calib_fcn_fw,"F"); gr_cal_fw -> GetXaxis()->SetTitle("ADC channel"); gr_cal_fw -> GetYaxis()->SetTitle("Energy [KeV]"); //Creating an "inverse calibration" from Energy to ADC (can be usefull). TCanvas* c3 = new TCanvas("c3","Energy -> ADC conversion"); c3 -> cd(); TGraphErrors* gr_cal_bw = new TGraphErrors(nlines,ENR_litt,&(ADCcenters->at(0)),ENR_litt_err,&(ADCcenters_err->at(0))); gr_cal_bw -> Draw("AP"); TF1* calib_fcn_bw = new TF1("calib_fcn_bw","pol2"); calib_fcn_bw -> SetLineColor(2); calib_fcn_bw -> SetLineWidth(1); gr_cal_bw -> Fit(calib_fcn_bw,"F"); gr_cal_bw -> GetXaxis()->SetTitle("Energy [KeV]"); gr_cal_bw -> GetYaxis()->SetTitle("ADC channel"); /* // Contruction of the ADC resolution function (errors still missing) TCanvas* c3 = new TCanvas("c3","ADC line resolution"); c3 -> cd(); TGraphErrors* gr_resol_ADC = new TGraphErrors(nlines,&(ADCcenters->at(0)),&(ADCresol->at(0)),&(ADCcenters_err->at(0)),&(ADCresol_err->at(0))); gr_resol_ADC -> SetMarkerStyle(7); gr_resol_ADC -> Draw("AP"); TF1* resol_ADC_fnc = new TF1("resol_ADC_fnc","pol2"); resol_ADC_fnc -> SetRange(1500,16000); resol_ADC_fnc -> SetLineColor(2); resol_ADC_fnc -> SetLineWidth(1); gr_resol_ADC -> Fit(resol_ADC_fnc,"M"); gr_resol_ADC -> GetXaxis()->SetTitle("ADC channel"); gr_resol_ADC -> GetYaxis()->SetTitle("Resolution"); */ //====== Here a new Canvas with the scatter plot of the residuals is generated ======// //====== Here the errors for the poins are not taken in account and a manual ========// //====== manual procedure is required ===============================================// /* TCanvas* canv3 = new TCanvas("Canv3","Calibration residuals",1); canv3 -> cd(); Double_t residuals[NLINES]; //Double_t* xbins = new Double_t[1+h2 -> GetNbinsX()]; for (i=0; i<NLINES; i++){ residuals[i] = linesThEn[i] - (ff2->Eval(linesADC[i])); } for(i = 0; i < h2 -> GetNbinsX(); i++){ xbins[i] = 0; } for(i = 0; i < h2 -> GetNbinsX(); i++){ xbins[i] = (Double_t)((ff2 -> GetParameter(0)) + i*(ff2 -> GetParameter(1)))-(ff2 -> GetParameter(1))/2; } */ /* TGraph* gr2 = new TGraph(NLINES,linesADC,residuals); gr2 -> Draw("AP"); TF1* zeroln = new TF1("ZeroLine",linearFit,0,h2->GetNbinsX(),2); zeroln -> SetParameters(0,0); zeroln -> SetLineColor(2); zeroln -> Draw("SAME"); */ /* TH1F* hcal = new TH1F(h2->GetNbinsX()); hcal -> SetName("hcal"); hcal -> SetNameTitle("Calibrated Histogram"); //hcal -> SetBins(h2 -> GetNbinsX(),xbins); cout << "ch" << "\t" << "xbins[i]" << "\t" << "BinCenter" << "\t" << "BinContent\t" << "BinContent (cal)" << endl; for(i = 0; i < h2 -> GetNbinsX(); i++){ hcal -> SetBinContent(i,h2->GetBinContent(i)); if (i < 16 || i > h2 -> GetNbinsX()-16) { cout << i << "\t" << xbins[i] << "\t" << hcal->GetBinCenter(i) << "\t" << h2->GetBinContent(i) << "\t" << hcal->GetBinContent(i) << endl; } } TCanvas* canv4 = new TCanvas("Canv4","Calibrated histogram"); canv4 -> cd(); //There is a problem in drawing the histogram //hcal -> Draw(); */ } //end of the script
[ "grodriguesaraujo@protonmail.com" ]
grodriguesaraujo@protonmail.com
ce06b533c875b6b62d9c235f533ad9c498715e0a
2fa764b33e15edd3b53175456f7df61a594f0bb5
/appseed/image_png/axis_image_png/ca_os_ca_dll.cpp
84dfe81c394f01da52525afb42d8f6449b426468
[]
no_license
PeterAlfonsLoch/app
5f6ac8f92d7f468bc99e0811537380fcbd828f65
268d0c7083d9be366529e4049adedc71d90e516e
refs/heads/master
2021-01-01T17:44:15.914503
2017-07-23T16:58:08
2017-07-23T16:58:08
98,142,329
1
0
null
2017-07-24T02:44:10
2017-07-24T02:44:10
null
UTF-8
C++
false
false
447
cpp
#include "StdAfx.h" extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { // remove this if you use lpReserved UNREFERENCED_PARAMETER(lpReserved); if (dwReason == DLL_PROCESS_ATTACH) { ::OutputDebugString("::ca2:: ca.dll :: initializing!\n"); } else if (dwReason == DLL_PROCESS_DETACH) { ::OutputDebugString("::ca2:: ca.dll :: terminating!\n"); } return 1; // ok }
[ "camilo@ca2.email" ]
camilo@ca2.email
21c676494284b1e0abb1fe9bc665570cbb16ce1e
68c67b6e72d338e94373955e915cf9e4d74a0f8e
/ABC174/B.cpp
7e26a3e7f2923db5b3b7c8e7fb50d9b6fc621fc4
[]
no_license
mi-wada/AtCoder
c28a291572c99325e203e80059cc867f26681cfe
a71a59ad65429a857aad3e0885c1d35447e2eec2
refs/heads/master
2022-12-16T19:00:25.028634
2020-09-14T11:33:01
2020-09-14T11:33:01
260,203,313
0
0
null
null
null
null
UTF-8
C++
false
false
837
cpp
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<queue> #include<deque> #include<cmath> #include<map> #include<unordered_map> #include<set> #include<cstring> #include<iomanip> //cout << fixed << setprecision(15) << x << endl; using namespace std; typedef long long ll; const ll INF = 1e9 + 6; const ll MOD = 1e9 + 7; const ll LLINF = 1e18; #define Pint pair<int, int> #define rng(i,a,b) for(int i=int(a);i<int(b);i++) #define rnr(i,a,b) for(int i=int(a);i>=int(b);i--) #define rep(i,b) rng(i,0,b) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() /* -- template -- */ int main() { ll n, d; cin >> n >> d; int ans = 0; rep(i, n) { ll x, y; cin >> x >> y; if(x * x + y * y <= d * d) { ++ans; } } cout << ans << endl; }
[ "mitsu.lol.0223@gmail.com" ]
mitsu.lol.0223@gmail.com
011fd9b76c660019c9df6404fe3698a102b5343f
7cce8432ca971ae442f093a7b1c72d078c5ec69d
/ex1/fcfs.cpp
8496304e93083e61147a3f8b9c515c830c4c6698
[]
no_license
sauravsb99/SSLAB
b1bd7929c7efd5bdd6464c5bde765d0e1e4050b0
24e85b53c0f7d7ea247b8daad0314d6bf125a5f0
refs/heads/master
2020-07-08T08:18:01.849268
2019-11-25T19:51:51
2019-11-25T19:51:51
203,615,291
0
1
null
2019-10-18T10:12:16
2019-08-21T15:40:54
C++
UTF-8
C++
false
false
3,315
cpp
#include<bits/stdc++.h> using namespace std; void print(int n, vector<int> v){ for(int i=0;i<n;i++){ cout << v.at(i) << "\t"; } cout << "\n"; } void gantt(int n, vector<int> process, vector<int> cmplt_time, vector<int> burst_time){ int count = 0; int scale = 1; cout << "\n|"; while(count < 5){ for(int i=0;i<(burst_time[count]*scale)/2+1;i++) cout << " "; cout << "P" << process[count] << "(" << cmplt_time[count] << ")"; for(int i=0;i<(burst_time[count]*scale)/2+1;i++) cout << " "; cout << "|"; count++; } cout << "\n\n"; } vector<int> cal_cmplt(int n, vector<int> process, vector<int> burst_time, vector<int> arrival_time){ vector<int> cmplt_time; int total_time = 0; for(int i=0;i<n;i++){ if(arrival_time[i]<=total_time){ total_time += burst_time.at(i); cmplt_time.push_back(total_time); } } return cmplt_time; } void srt(int n, vector<int> &process, vector<int> &burst_time, vector<int> &arrival_time){ int temp,pos; for(int i=0;i<n-1;i++){ pos = i; for(int j=i;j<n;j++){ if(arrival_time.at(j)<arrival_time.at(pos)){ pos = j; } } temp = arrival_time.at(pos); arrival_time.at(pos) = arrival_time.at(i); arrival_time.at(i) = temp; temp = process.at(pos); process.at(pos) = process.at(i); process.at(i) = temp; temp = burst_time.at(pos); burst_time.at(pos) = burst_time.at(i); burst_time.at(i) = temp; } } float cal_avg_wait(int n, vector<int> burst_time, vector<int> cmplt_time, vector<int> arrival_time){ float sum = 0.0; for(int i=0;i<n;i++){ sum += cmplt_time.at(i) - burst_time.at(i) - arrival_time[i]; } return sum/n; } float cal_avg_turn(int n, vector<int> burst_time, vector<int> cmplt_time, vector<int> arrival_time){ float sum = 0.0f; for(int i=0;i<n;i++){ sum += cmplt_time.at(i) - arrival_time[i]; } return sum/n; } int main(){ int p, a, b; vector<int> cmplt_time; vector<int> burst_time, arrival_time, process, wait_time; cout << "Enter the number of processes: "; cin >> p; for(int i=0;i<p;i++){ cout << "Enter arrival time and burst time for process " << i + 1 << ":"; cin >> a >> b; burst_time.push_back(b); arrival_time.push_back(a); process.push_back(i+1); } srt(p,process,burst_time,arrival_time); cmplt_time = cal_cmplt(p,process,burst_time,arrival_time); cout << "The process order:\t"; print(p,process); cout << "The arrival time:\t"; print(p,arrival_time); cout << "The burst time:\t\t"; print(p,burst_time); cout << "The turnaround time:\t"; print(p,cmplt_time); cout << "The waiting time is:\t"; for(int i=0;i<p;i++){ wait_time.push_back(cmplt_time[i]-burst_time[i] - arrival_time[i]); } print(p,wait_time); cout << "The average waiting time:\t" << cal_avg_wait(p,burst_time,cmplt_time,arrival_time) << "\n"; cout << "The average turnaround time:\t" << cal_avg_turn(p,burst_time,cmplt_time,arrival_time) << "\n"; gantt(p,process,cmplt_time,burst_time); return 0; }
[ "sauravsb99@gmail.com" ]
sauravsb99@gmail.com
8b0f3a717b1f94baf2fc7b9ead11a9c1c1c16fd3
65025edce8120ec0c601bd5e6485553697c5c132
/Engine/app/terrainfeature/components/TerrainNodeTree.h
f333a0ef2690cbee6aabeb01dda2d3d4967bae0c
[ "MIT" ]
permissive
stonejiang/genesis-3d
babfc99cfc9085527dff35c7c8662d931fbb1780
df5741e7003ba8e21d21557d42f637cfe0f6133c
refs/heads/master
2020-12-25T18:22:32.752912
2013-12-13T07:45:17
2013-12-13T07:45:17
15,157,071
4
4
null
null
null
null
UTF-8
C++
false
false
3,149
h
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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 __TerrainNodeTree_H__ #define __TerrainNodeTree_H__ #include "terrainfeature/components/TerrainNode.h" #include "util/mipmaparray.h" #include "terrainsystem/TerrainDataSource.h" namespace App { struct NodePos { int x; int y; }; class TerrainNodeTree: public Core::RefCounted { __DeclareSubClass(TerrainNodeTree, Core::RefCounted); public: TerrainNodeTree(); virtual ~TerrainNodeTree(); /// Reset terrain node tree to default, 0 node void Reset(); /// Get tree's depth. [ 0,GetDepth() ) SizeT GetDepth() const; /// get some level node count in X dir SizeT GetRowSize(int depth) const; /// get some level node count in Y dir SizeT GetColSize(int depth) const; /// Using heightMap to rebuild all terrain node. Offset is all node's offset void RebuildAllNodes(const GPtr<Terrain::TerrainDataSource>& terrainDataSource); /// Get root node, return NULL if invalid TerrainNode* GetRootNode(); /// Get node in pos(row,col) in level, return NULL if invalid TerrainNode* GetNode(IndexT row, IndexT col, IndexT level); protected: typedef Util::MipmapArray<TerrainNode*> TerrainTree; TerrainTree m_TerrainTree; }; //------------------------------------------------------------------------ inline SizeT TerrainNodeTree::GetDepth() const { return m_TerrainTree.GetMipCount(); } //------------------------------------------------------------------------ inline SizeT TerrainNodeTree::GetRowSize(int depth) const { if ( depth < m_TerrainTree.GetMipCount() ) { return m_TerrainTree.RowSize(depth); } return 0; } //------------------------------------------------------------------------ inline SizeT TerrainNodeTree::GetColSize(int depth) const { if ( depth < m_TerrainTree.GetMipCount() ) { return m_TerrainTree.ColSize(depth); } return 0; } } #endif // __TerrainNodeTree_H__
[ "jiangtao@tao-studio.net" ]
jiangtao@tao-studio.net
b9fda0763151afdc938f441196f0e12fb639fdee
d928ac698895ec2a276b2549ce8c0f2cf39d4e03
/CodeForces/CF650Div3/650Div3D.cpp
113147712deccfc9ec5f4a8f2bdfe5f84405519e
[]
no_license
BlowHail/record-in-oj
bb066c979a804f8c957290544c74b8f3da28c2e8
2182145cbb03b4f8382eb927d2291b92e5c01b59
refs/heads/master
2023-03-18T23:44:56.351907
2021-03-13T06:33:50
2021-03-13T06:33:50
287,764,353
1
0
null
null
null
null
UTF-8
C++
false
false
1,541
cpp
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <string> #include <stack> #include <queue> #include <cmath> #define ll long long #define pi 3.1415927 #define inf 0x3f3f3f3f #define mod 1000000007 using namespace std; struct node { int a,b; }a[55],b[55]; string s; int aa[55],out[55]; int main () { int T,n,m,i,t,j,k,p; cin>>T; while (T--) { cin>>s; p=s.length(); cin>>n; for(i=0;i<n;++i) { cin>>a[i].a; a[i].b=0; } memset(aa,0,sizeof(aa)); memset(out,0,sizeof(out)); for(i=0;i<p;++i) aa[s[i]-96]++; p=26; while(p) { //cout<<"!!"<<endl; int cnt=0; for(i=0;i<n;++i) if(a[i].a==0&&a[i].b==0) cnt++; for(i=p;i>=1;i--) if(aa[i]>=cnt) { p=i-1; break; } memset(b,0,sizeof(b)); for(i=0;i<n;++i) if(a[i].a==0 && a[i].b==0) { out[i]=p+97; a[i].b=1; for(j=0;j<n;++j) if(a[j].a>0) b[j].a+=abs(j-i); } for(j=0;j<n;++j) a[j].a-=b[j].a; } for(i=0;i<n;++i) printf("%c",out[i]); cout<<endl; } return 0; }
[ "1144062115@qq.com" ]
1144062115@qq.com
dcd186ddfe6d860424fc18a1d4c3cd1de105af0f
0329788a6657e212944fd1dffb818111e62ee2b0
/docs/snippets/cpp/VS_Snippets_Winforms/DataFormats_StringFormat/CPP/dataformats_stringformat.cpp
d2f936944f9f4651cb74a304e99588fc63474495
[ "CC-BY-4.0", "MIT" ]
permissive
MicrosoftDocs/visualstudio-docs
3e506da16412dfee1f83e82a600c7ce0041c0f33
bff072c38fcfc60cd02c9d1d4a7959ae26a8e23c
refs/heads/main
2023-09-01T16:13:32.046442
2023-09-01T14:26:34
2023-09-01T14:26:34
73,740,273
1,050
1,984
CC-BY-4.0
2023-09-14T17:04:58
2016-11-14T19:36:53
Python
UTF-8
C++
false
false
1,502
cpp
// System::Windows::Forms::DataFormats::StringFormat /* * The following example demonstrates the 'StringFormat' field of 'DataFormats' class. * It stores a String Object^ in Clipboard using the Clipboard's 'SetDataObject' method. * It retrieves the String Object^ stored in the Clipboard by using the GetDataObject method * which returns the 'IDataObject^'. It checks the String^ data is available or not * by using the 'GetDataPresent' method of 'IDataObject^'. If data is there then it * displays the data to the console. */ #using <System.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Drawing::Imaging; using namespace System::Windows::Forms; int main() { // <Snippet1> try { String^ myString = "This is a String from the ClipBoard"; // Sets the data to the Clipboard. Clipboard::SetDataObject( myString ); IDataObject^ myDataObject = Clipboard::GetDataObject(); // Checks whether the data is present or not in the Clipboard. if ( myDataObject->GetDataPresent( DataFormats::StringFormat ) ) { String^ clipString = (String^)(myDataObject->GetData( DataFormats::StringFormat )); Console::WriteLine( clipString ); } else { Console::WriteLine( "No String information was contained in the clipboard." ); } } catch ( Exception^ e ) { Console::WriteLine( e->Message ); } // </Snippet1> }
[ "v-zhecai@microsoft.com" ]
v-zhecai@microsoft.com
47f9f3cb8aa74d084baa116bdf84d08579538bca
d5da09aff917eba8e85b9e4d9057ca1ace59d735
/tr69profile/hwst_diag_tuner.cpp
097328cda50e68106c10d09ae07ea1fccee10866
[ "Apache-2.0" ]
permissive
rdkcmf/rdk-hwselftest
68b8703161686f435dd18c09cee7a9d53aaf1f54
b0f104a5f24d74ac7187f10b609adb9c3765b677
refs/heads/master
2023-02-05T05:53:22.968221
2018-10-03T17:47:56
2018-10-03T17:48:43
106,031,597
0
2
null
null
null
null
UTF-8
C++
false
false
1,722
cpp
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2017 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <memory> #include <sstream> #include "hwst_diag_tuner.hpp" #include "hwst_comm.hpp" #include "hwst_log.hpp" using hwst::Comm; namespace hwst { DiagTuner::DiagTuner(const std::string &params_): Diag("tuner_status", params_) { presentationResult.insert(std::pair<int, const std::string>(SI_CACHE_MISSING, "WARNING")); presentationResult.insert(std::pair<int, const std::string>(TUNER_NO_LOCK, "WARNING")); presentationResult.insert(std::pair<int, const std::string>(TUNER_BUSY, "WARNING")); presentationComment.insert(std::pair<int, const std::string>(SI_CACHE_MISSING, "Missing Channel Map")); presentationComment.insert(std::pair<int, const std::string>(TUNER_NO_LOCK, "Lock Failed - Check Cable")); presentationComment.insert(std::pair<int, const std::string>(TUNER_BUSY, "One or more tuners are busy. All tuners were not tested")); } std::string DiagTuner::getPresentationName() const { return "QAM Tuner"; }; } // namespace hwst
[ "jim.lawton@accenture.com" ]
jim.lawton@accenture.com
b3c3027d358768cc23e59e2d09847d060d025635
dc3b1b231ee872d5d4d2e2433ed8a2d8fb740307
/chapter17/ex04.h
2326d355c3b333221f7f9e11b20f02b23e58387d
[]
no_license
coder-e1adbc/CppPrimer
d2b62b49f20892c5e53a78de0c807b168373bfc6
33ffd4fc39f4bccf4e107aec2d8dc6ed4e9d7447
refs/heads/master
2021-01-17T08:54:23.438341
2016-08-13T03:21:08
2016-08-13T03:21:08
61,343,967
0
0
null
2016-06-29T14:37:16
2016-06-17T03:49:23
C++
UTF-8
C++
false
false
601
h
#include <iostream> #include <initializer_list> #include <string> #include <tuple> #include <vector> #include "Sales_data.h" using matches = std::tuple<std::vector<Sales_data>::size_type, std::vector<Sales_data>::const_iterator, std::vector<Sales_data>::const_iterator>; std::vector<std::vector<Sales_data>> createFiles( std::initializer_list<std::string>); std::vector<matches> findBook(const std::vector<std::vector<Sales_data>> &, const std::string &); void reportResults(std::istream &, std::ostream &, const std::vector<std::vector<Sales_data>> &);
[ "mengxianghua1995+github@gmail.com" ]
mengxianghua1995+github@gmail.com
e0897ad871033ac3b0bcbae0e04111e78ed852b1
4c606ff1f36895b3ae3232a293001e988f95d954
/JZOF/旋转数组的最小数字.cc
b9a6eb7b3cda75f0064f7aa70b3852c2c4973d0c
[]
no_license
HCMY/InteletTree
26692dbaffe32c8fbd144dd7a1a1081f5a860716
8d28c9dd87986a3bfc20dc826b12af7fb904aefb
refs/heads/master
2020-07-20T01:04:48.045059
2020-06-10T13:28:44
2020-06-10T13:28:44
206,544,501
0
1
null
null
null
null
UTF-8
C++
false
false
1,110
cc
/** 题目是输入一个旋转好了的数组如:{3,4,5,1,2} 要求输出最小的元素: 1. 直接排序? 显然题目的意思并不是这样, 虽然这样也能做, 但有可能会导致时间不足 2.二分法 这样的旋转数组有一个特性: 2部分都是递增的,那么我们可以确定的是:前半部分一定比后半部分要大,因为是非递减的 可以通过二分查找: 定义low, high,mid_location - 当 mid_location>high的时候,我们要查找的范围在后面 - 当 mid_location<high的时候,我们要查找的范围在前面 终止条件:low<high */ class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.size()==0) return 0; int low=0; int high = rotateArray.size()-1; while(low<high){ int mid_location = (low+high)/2; if(rotateArray[mid_location]>rotateArray[high]) low = mid_location+1; else if(rotateArray[mid_location]==rotateArray[high]) high--; else high = mid_location; } return rotateArray[low]; } };
[ "noreply@github.com" ]
HCMY.noreply@github.com
2414d781e118bed8f7d7c4a1c53a4311c7f84dd8
45674116e3c708effcc0274946b436fdd5d2d266
/Pattern printing/Letter_X.cpp
bf9d433491b4fcbae95b783196a6de81e99dcbda
[ "MIT" ]
permissive
SarthakKeshari/CPP-Questions-and-Solutions
80741c00d6a9f95553e87a6687df0fef441e337f
b3097685322caac5124ecfbfd41a221fb6bc8318
refs/heads/main
2023-08-30T22:26:53.918764
2021-10-31T09:34:39
2021-10-31T09:34:39
397,938,992
52
144
MIT
2021-10-31T09:34:40
2021-08-19T12:41:04
C++
UTF-8
C++
false
false
1,060
cpp
//C++ program to print the below pattern :- /* @@ ## @@ ## @@ ## @@ ## @@@ ## @@ ## @@ ## @@ ## @@ */ #include <iostream> using namespace std; int main() { int row,coloumn; for(row=0; row<9; row++) // here 9 is the total no. of rows. { for(coloumn=0; coloumn<9; coloumn++) // here 9 is the total no. of coloumns. { if(row==4 && coloumn==4) cout << "@@@"; // printing @@@ in the middle of the letter when rows=4 & coloumns=4 else if(row==coloumn) // prints the required characters when number of rows equals number of columns cout << "@@"; else if((row+coloumn)==8) // prints the required characters when number of rows + number of columns equals (total rows-1) cout << "##"; else cout << " "; // prints a whitespace at places where characters are not printed. } cout << "\n"; // prints a newline at the end of each row. } return 0; } // This Code is contributed by Harshvardhan Singh (Username ----> cyberskull99297)
[ "noreply@github.com" ]
SarthakKeshari.noreply@github.com
d5c3fecbdfe228beb318af03e7999703be03386c
8c0ad19e076ac6c96aadd18d1ecd748e950a3a4d
/prelude/prelude.cpp
bee47a328d17d8b4d7f5dfa3d4a8a9fa9db868b8
[ "LicenseRef-scancode-public-domain" ]
permissive
APTX/geordi
55be821b0387313f5ca2e59e28c93ba4f2c880a8
fb68f233bee8d0d5f2c794f4687a37ad1cbb4b8e
refs/heads/master
2021-01-16T22:05:59.132444
2015-10-18T15:14:38
2015-10-19T13:48:50
44,536,228
0
0
null
2015-10-19T13:21:33
2015-10-19T13:21:32
null
UTF-8
C++
false
false
5,901
cpp
#include <iostream> #include <algorithm> #include <iterator> #include <string> #include <fstream> #include <stdexcept> #include <vector> #include <cerrno> #include <cstring> #include <cstdlib> #include <cstdio> #include <ctime> #include <cassert> #include <ios> #include <set> #include <functional> #include <clocale> #include <stdlib.h> #include <regex> #include <cxxabi.h> #include <ext/malloc_allocator.h> #include <boost/noncopyable.hpp> #include "geordi.hpp" #include "bin_iomanip.hpp" template class std::basic_regex<char>; template std::string std::regex_replace<std::regex_traits<char>, char>( char const *, std::regex const &, char const *, std::regex_constants::match_flag_type); namespace geordi { namespace { bool is_prefix_of(char const * a, char const * b) { while(*a && *b == *a) { ++a; ++b; } return !*a; } void terminate_handler(bool const unexp) { // We use printf because cout/cerr may be dead. std::printf("%sterminated", parsep); if(std::type_info const * const t = abi::__cxa_current_exception_type()) { int status = 0; char const * const name = abi::__cxa_demangle(t->name(), 0, 0, &status); // In OOM conditions, the above call to __cxa_demangle will fail (and name will be 0). Supplying a preallocated buffer using __cxa_demangle's second and third parameters does not help, because it performs additional internal allocations. std::printf(" by "); if(unexp) std::printf("unexpected "); try { throw; } catch(std::exception const & e) { char const * const what = e.what(); if(!name) std::printf("exception: "); else if(!is_prefix_of(name, what)) std::printf("%s: ", name); std::printf("%s", what); } catch(char const * const s) { std::printf("exception: %s", s); } catch(int const i) { std::printf("exception: %d", i); } catch(...) { std::printf("exception"); if(name) std::printf(" of type %s", name); } } std::fclose(stdout); std::abort(); } void terminate_handler() { terminate_handler(false); } void unexpected_handler() { terminate_handler(true); } void maybe_show_asm() { std::ifstream f("0.s"); std::string line; while (std::getline(f, line) && line.find("unassembled") == std::string::npos); if (!f) return; while (std::getline(f, line) && line != "\t.cfi_startproc"); bool first = true; while (std::getline(f, line) && line != "\t.cfi_endproc") { if (line.find("\t.cfi") == 0) continue; std::replace(line.begin(), line.end(), '\t', ' '); if (line.substr(0, 1) == " ") line = line.substr(1); if (first) first = false; else std::cout << "; "; std::cout << line; } } struct initializer { initializer() { std::ios_base::Init const i; std::boolalpha(std::cout); std::boolalpha(std::wcout); std::boolalpha(std::cerr); std::boolalpha(std::wcerr); std::boolalpha(std::clog); std::boolalpha(std::wclog); std::unitbuf(std::cout); std::unitbuf(std::wcout); std::unitbuf(std::cerr); std::unitbuf(std::wcerr); std::unitbuf(std::clog); std::unitbuf(std::wclog); static bin_num_put<> bnp(1); static bin_num_put<wchar_t> wbnp(1); std::cout.imbue(std::locale(std::cout.getloc(), &bnp)); std::wcout.imbue(std::locale(std::wcout.getloc(), &wbnp)); std::cerr.imbue(std::locale(std::cerr.getloc(), &bnp)); std::wcerr.imbue(std::locale(std::wcerr.getloc(), &wbnp)); std::clog.imbue(std::locale(std::clog.getloc(), &bnp)); std::wclog.imbue(std::locale(std::wclog.getloc(), &wbnp)); // Having this compiled separately saves more than a full second per request. std::set_terminate(terminate_handler); std::set_unexpected(unexpected_handler); std::setlocale(LC_ALL, ""); maybe_show_asm(); } }; } utsname uname() { utsname r; if (uname(&r)) throw std::runtime_error(std::strerror(errno)); return r; } char const * demangle(char const * const name) { int st; char * const p = abi::__cxa_demangle(name, 0, 0, &st); switch (st) { case 0: return p; case -1: throw std::runtime_error("A memory allocation failure occurred."); case -2: throw std::runtime_error("Not a valid name under the GCC C++ ABI mangling rules."); case -3: throw std::runtime_error("One of the arguments is invalid."); default: assert(!"unexpected demangle status"); } // We could return a std::string and free p, but since deallocation is not a concern (and is even a no-op) in geordi anyway, we don't bother. } std::map<std::string, std::string> depersist() { std::ifstream f("data"); std::map<std::string, std::string> r; std::string k, v; while (getline(f, k) && getline(f, v)) r[k] = v; return r; } void persist(std::string const k, std::string const v) { auto m = depersist(); m[k] = v; std::ofstream f("data"); for (auto && p : m) f << p.first << '\n' << p.second << '\n'; } } // namespace geordi extern "C" { geordi::initializer geordi_init __attribute__((init_priority(102))); } std::ostream & operator<<(std::ostream & o, wchar_t const c) { char buf[MB_LEN_MAX]; int const i = wctomb(buf, c); if(i < 0) o << '?'; else std::copy(buf, buf + i, std::ostreambuf_iterator<char>(o)); return o; } std::ostream & operator<<(std::ostream & o, wchar_t const * s) { for(; *s; ++s) o << *s; return o; } std::ostream & operator<<(std::ostream & o, std::wstring const & s) { for(std::wstring::const_iterator i = s.begin(); i != s.end(); ++i) o << *i; return o; }
[ "eelis@eelis.net" ]
eelis@eelis.net
3f5472004901004b2eb8c8d004676686d777ad22
0d60ce9b935b4e688b83bab3b89a1ded4725174c
/examples/allegro5_example/imgui_impl_allegro5.cpp
1c9165254183b6ca816b91b2365d8de172416dbf
[ "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
azsry/imgui
24f087030e576463bb83412e364c9c82bda7ff27
08e20ae4653a603ebc581c8900a4fe90f3101697
refs/heads/master
2020-03-18T20:27:45.169363
2018-01-05T14:33:24
2018-05-28T19:48:25
135,217,408
1
0
MIT
2018-05-28T23:14:18
2018-05-28T23:14:17
null
UTF-8
C++
false
false
12,517
cpp
// ImGui Allegro 5 bindings // Implemented features: // [X] User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // Missing features: // [ ] Clipboard support via al_set_clipboard_text/al_clipboard_has_text. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui, Original code by @birthggd // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp. // 2018-04-18: Misc: Added support for 32-bits vertex indices to avoid conversion at runtime. Added imconfig_allegro5.h to enforce 32-bit indices when included from imgui.h. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplA5_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. #include <stdint.h> // uint64_t #include <cstring> // memcpy #include "imgui.h" #include "imgui_impl_allegro5.h" #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #ifdef _WIN32 #include <allegro5/allegro_windows.h> #endif // Data static ALLEGRO_DISPLAY* g_Display = NULL; static ALLEGRO_BITMAP* g_Texture = NULL; static double g_Time = 0.0; static ALLEGRO_MOUSE_CURSOR* g_MouseCursorInvisible = NULL; static ALLEGRO_VERTEX_DECL* g_VertexDecl = NULL; struct ImDrawVertAllegro { ImVec2 pos; ImVec2 uv; ALLEGRO_COLOR col; }; // Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplA5_RenderDrawData(ImDrawData* draw_data) { int op, src, dst; al_get_blender(&op, &src, &dst); al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; // FIXME-OPT: Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 floats static ImVector<ImDrawVertAllegro> vertices; vertices.resize(cmd_list->VtxBuffer.Size); for (int i = 0; i < cmd_list->VtxBuffer.Size; ++i) { const ImDrawVert &dv = cmd_list->VtxBuffer[i]; ImDrawVertAllegro v; v.pos = dv.pos; v.uv = dv.uv; unsigned char *c = (unsigned char*)&dv.col; v.col = al_map_rgba(c[0], c[1], c[2], c[3]); vertices[i] = v; } const int* indices = NULL; if (sizeof(ImDrawIdx) == 2) { // FIXME-OPT: Unfortunately Allegro doesn't support 16-bit indices.. You can '#define ImDrawIdx int' in imconfig.h to request ImGui to output 32-bit indices. // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful. static ImVector<int> indices_converted; indices_converted.resize(cmd_list->IdxBuffer.Size); for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i) indices_converted[i] = (int)cmd_list->IdxBuffer.Data[i]; indices = indices_converted.Data; } else if (sizeof(ImDrawIdx) == 4) { indices = (const int*)cmd_list->IdxBuffer.Data; } int idx_offset = 0; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->TextureId; al_set_clipping_rectangle(pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z-pcmd->ClipRect.x, pcmd->ClipRect.w-pcmd->ClipRect.y); al_draw_indexed_prim(&vertices[0], g_VertexDecl, texture, &indices[idx_offset], pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); } idx_offset += pcmd->ElemCount; } } // Restore modified state al_set_blender(op, src, dst); al_set_clipping_rectangle(0, 0, al_get_display_width(g_Display), al_get_display_height(g_Display)); } bool Imgui_ImplA5_CreateDeviceObjects() { // Build texture atlas ImGuiIO &io = ImGui::GetIO(); unsigned char *pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Create texture int flags = al_get_new_bitmap_flags(); int fmt = al_get_new_bitmap_format(); al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP|ALLEGRO_MIN_LINEAR|ALLEGRO_MAG_LINEAR); al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); ALLEGRO_BITMAP* img = al_create_bitmap(width, height); al_set_new_bitmap_flags(flags); al_set_new_bitmap_format(fmt); if (!img) return false; ALLEGRO_LOCKED_REGION *locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); if (!locked_img) { al_destroy_bitmap(img); return false; } memcpy(locked_img->data, pixels, sizeof(int)*width*height); al_unlock_bitmap(img); // Convert software texture to hardware texture. ALLEGRO_BITMAP* cloned_img = al_clone_bitmap(img); al_destroy_bitmap(img); if (!cloned_img) return false; // Store our identifier io.Fonts->TexID = (void*)cloned_img; g_Texture = cloned_img; // Create an invisible mouse cursor // Because al_hide_mouse_cursor() seems to mess up with the actual inputs.. ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8,8); g_MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0); al_destroy_bitmap(mouse_cursor); return true; } void ImGui_ImplA5_InvalidateDeviceObjects() { if (g_Texture) { al_destroy_bitmap(g_Texture); ImGui::GetIO().Fonts->TexID = NULL; g_Texture = NULL; } if (g_MouseCursorInvisible) { al_destroy_mouse_cursor(g_MouseCursorInvisible); g_MouseCursorInvisible = NULL; } } bool ImGui_ImplA5_Init(ALLEGRO_DISPLAY* display) { g_Display = display; // Create custom vertex declaration. // Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 floats. // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. ALLEGRO_VERTEX_ELEMENT elems[] = { { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) }, { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) }, { ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) }, { 0, 0, 0 } }; g_VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = ALLEGRO_KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = ALLEGRO_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = ALLEGRO_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = ALLEGRO_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = ALLEGRO_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = ALLEGRO_KEY_PGUP; io.KeyMap[ImGuiKey_PageDown] = ALLEGRO_KEY_PGDN; io.KeyMap[ImGuiKey_Home] = ALLEGRO_KEY_HOME; io.KeyMap[ImGuiKey_End] = ALLEGRO_KEY_END; io.KeyMap[ImGuiKey_Insert] = ALLEGRO_KEY_INSERT; io.KeyMap[ImGuiKey_Delete] = ALLEGRO_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = ALLEGRO_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = ALLEGRO_KEY_SPACE; io.KeyMap[ImGuiKey_Enter] = ALLEGRO_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = ALLEGRO_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = ALLEGRO_KEY_A; io.KeyMap[ImGuiKey_C] = ALLEGRO_KEY_C; io.KeyMap[ImGuiKey_V] = ALLEGRO_KEY_V; io.KeyMap[ImGuiKey_X] = ALLEGRO_KEY_X; io.KeyMap[ImGuiKey_Y] = ALLEGRO_KEY_Y; io.KeyMap[ImGuiKey_Z] = ALLEGRO_KEY_Z; #ifdef _WIN32 io.ImeWindowHandle = al_get_win_window_handle(g_Display); #endif return true; } void ImGui_ImplA5_Shutdown() { ImGui_ImplA5_InvalidateDeviceObjects(); } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. bool ImGui_ImplA5_ProcessEvent(ALLEGRO_EVENT *ev) { ImGuiIO &io = ImGui::GetIO(); switch (ev->type) { case ALLEGRO_EVENT_MOUSE_AXES: io.MouseWheel += ev->mouse.dz; io.MouseWheelH += ev->mouse.dw; return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == g_Display) if (ev->keyboard.unichar > 0 && ev->keyboard.unichar < 0x10000) io.AddInputCharacter((unsigned short)ev->keyboard.unichar); return true; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: if (ev->keyboard.display == g_Display) io.KeysDown[ev->keyboard.keycode] = (ev->type == ALLEGRO_EVENT_KEY_DOWN); return true; } return false; } void ImGui_ImplA5_NewFrame() { if (!g_Texture) Imgui_ImplA5_CreateDeviceObjects(); ImGuiIO &io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; w = al_get_display_width(g_Display); h = al_get_display_height(g_Display); io.DisplaySize = ImVec2((float)w, (float)h); // Setup time step double current_time = al_get_time(); io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); g_Time = current_time; // Setup inputs ALLEGRO_KEYBOARD_STATE keys; al_get_keyboard_state(&keys); io.KeyCtrl = al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL); io.KeyShift = al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT); io.KeyAlt = al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR); io.KeySuper = al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN); ALLEGRO_MOUSE_STATE mouse; if (keys.display == g_Display) { al_get_mouse_state(&mouse); io.MousePos = ImVec2((float)mouse.x, (float)mouse.y); } else { io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); } al_get_mouse_state(&mouse); io.MouseDown[0] = mouse.buttons & (1 << 0); io.MouseDown[1] = mouse.buttons & (1 << 1); io.MouseDown[2] = mouse.buttons & (1 << 2); // Hide OS mouse cursor if ImGui is drawing it if (io.MouseDrawCursor) { al_set_mouse_cursor(g_Display, g_MouseCursorInvisible); } else { ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT; switch (ImGui::GetMouseCursor()) { case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break; case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break; case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break; case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break; case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break; case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break; } al_set_system_mouse_cursor(g_Display, cursor_id); } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); }
[ "omarcornut@gmail.com" ]
omarcornut@gmail.com
a49bfa733aa6ac2df42f767294880fc4cbd4657b
1300358e915ec390bfd4eef88c1ead89b8bf3ba2
/quote_tunnels/my_tunnel_lib_sgit/src/sgit_data_formater.cpp
7ee996a325c97798826597d76a88a1f34d438a85
[]
no_license
19199883/gangof4
d04e7a5fb4b556a7ee29410e83b7761fb25fecbd
24370d709056fae7ff7085581a4d72478ce6ad3e
refs/heads/master
2020-05-21T19:15:21.073690
2019-10-30T10:26:25
2019-10-30T10:26:25
64,183,829
0
5
null
null
null
null
UTF-8
C++
false
false
33,809
cpp
#include "sgit_data_formater.h" #include <iostream> #include <sstream> using namespace std; static std::string indent_string = " "; static std::string newline_string = "\n"; std::string DatatypeFormater::ToString(const CSgitFtdcReqUserLoginField *pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcReqUserLoginField ///Login Request" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "Password=" << pdata->Password << endl; ss << indent_string << "UserProductInfo=" << pdata->UserProductInfo << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcQryTradingAccountField *pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcQryTradingAccountField ///Capital account query" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcQryOrderField *pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcQryOrderField ///Order query" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; ss << indent_string << "ExchangeID=" << pdata->ExchangeID << endl; ss << indent_string << "OrderSysID=" << pdata->OrderSysID << endl; ss << indent_string << "InsertTimeStart=" << pdata->InsertTimeStart << endl; ss << indent_string << "InsertTimeEnd=" << pdata->InsertTimeEnd << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcQryInvestorPositionField *pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcQryInvestorPositionField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; return ss.str(); } std::string ToString(const CSgitFtdcQryInvestorPositionDetailField *p) { char buf[2048]; if (p) { snprintf(buf, sizeof(buf), "structName=CSgitFtdcQryInvestorPositionDetailField\n" " BrokerID=%s\n" " InvestorID=%s\n" " InstrumentID=%s\n", p->BrokerID, //请求ID p->InvestorID, //资金账户ID p->InstrumentID //合约代码 ); } else { snprintf(buf, sizeof(buf), "structName=CSgitFtdcQryInvestorPositionDetailField <null>"); } return buf; } std::string DatatypeFormater::ToString(const CSgitFtdcRspUserLoginField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcRspUserLoginField ///Login Respond" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "TradingDay=" << pdata->TradingDay << endl; ss << indent_string << "LoginTime=" << pdata->LoginTime << endl; ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "SystemName=" << pdata->SystemName << endl; ss << indent_string << "FrontID=" << pdata->FrontID << endl; ss << indent_string << "SessionID=" << pdata->SessionID << endl; ss << indent_string << "MaxOrderRef=" << pdata->MaxOrderRef << endl; ss << indent_string << "SHFETime=" << pdata->SHFETime << endl; ss << indent_string << "DCETime=" << pdata->DCETime << endl; ss << indent_string << "CZCETime=" << pdata->CZCETime << endl; ss << indent_string << "FFEXTime=" << pdata->FFEXTime << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcUserLogoutField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcUserLogoutField ///Logout Request" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcUserPasswordUpdateField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcUserPasswordUpdateField ///Password change" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "OldPassword=" << pdata->OldPassword << endl; ss << indent_string << "NewPassword=" << pdata->NewPassword << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcInputOrderField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcInputOrderField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; ss << indent_string << "OrderRef=" << pdata->OrderRef << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "OrderPriceType=" << pdata->OrderPriceType << endl; ss << indent_string << "Direction=" << pdata->Direction << endl; ss << indent_string << "CombOffsetFlag=" << pdata->CombOffsetFlag << endl; ss << indent_string << "CombHedgeFlag=" << pdata->CombHedgeFlag << endl; ss << indent_string << "LimitPrice=" << pdata->LimitPrice << endl; ss << indent_string << "VolumeTotalOriginal=" << pdata->VolumeTotalOriginal << endl; ss << indent_string << "TimeCondition=" << pdata->TimeCondition << endl; ss << indent_string << "GTDDate=" << pdata->GTDDate << endl; ss << indent_string << "VolumeCondition=" << pdata->VolumeCondition << endl; ss << indent_string << "MinVolume=" << pdata->MinVolume << endl; ss << indent_string << "ContingentCondition=" << pdata->ContingentCondition << endl; ss << indent_string << "StopPrice=" << pdata->StopPrice << endl; ss << indent_string << "ForceCloseReason=" << pdata->ForceCloseReason << endl; ss << indent_string << "IsAutoSuspend=" << pdata->IsAutoSuspend << endl; ss << indent_string << "BusinessUnit=" << pdata->BusinessUnit << endl; ss << indent_string << "RequestID=" << pdata->RequestID << endl; ss << indent_string << "UserForceClose=" << pdata->UserForceClose << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcInputOrderActionField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcInputOrderActionField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "OrderActionRef=" << pdata->OrderActionRef << endl; ss << indent_string << "OrderRef=" << pdata->OrderRef << endl; ss << indent_string << "RequestID=" << pdata->RequestID << endl; ss << indent_string << "FrontID=" << pdata->FrontID << endl; ss << indent_string << "SessionID=" << pdata->SessionID << endl; ss << indent_string << "ExchangeID=" << pdata->ExchangeID << endl; ss << indent_string << "OrderSysID=" << pdata->OrderSysID << endl; ss << indent_string << "ActionFlag=" << pdata->ActionFlag << endl; ss << indent_string << "LimitPrice=" << pdata->LimitPrice << endl; ss << indent_string << "VolumeChange=" << pdata->VolumeChange << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcOrderActionField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcOrderActionField " << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "OrderActionRef=" << pdata->OrderActionRef << endl; ss << indent_string << "OrderRef=" << pdata->OrderRef << endl; ss << indent_string << "RequestID=" << pdata->RequestID << endl; ss << indent_string << "FrontID=" << pdata->FrontID << endl; ss << indent_string << "SessionID=" << pdata->SessionID << endl; ss << indent_string << "ExchangeID=" << pdata->ExchangeID << endl; ss << indent_string << "OrderSysID=" << pdata->OrderSysID << endl; ss << indent_string << "ActionFlag=" << pdata->ActionFlag << endl; ss << indent_string << "LimitPrice=" << pdata->LimitPrice << endl; ss << indent_string << "VolumeChange=" << pdata->VolumeChange << endl; ss << indent_string << "ActionDate=" << pdata->ActionDate << endl; ss << indent_string << "ActionTime=" << pdata->ActionTime << endl; ss << indent_string << "TraderID=" << pdata->TraderID << endl; ss << indent_string << "InstallID=" << pdata->InstallID << endl; ss << indent_string << "OrderLocalID=" << pdata->OrderLocalID << endl; ss << indent_string << "ActionLocalID=" << pdata->ActionLocalID << endl; ss << indent_string << "ParticipantID=" << pdata->ParticipantID << " ///会员代码: " << endl; ss << indent_string << "ClientID=" << pdata->ClientID << endl; ss << indent_string << "BusinessUnit=" << pdata->BusinessUnit << endl; ss << indent_string << "OrderActionStatus=" << pdata->OrderActionStatus << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "StatusMsg=" << pdata->StatusMsg << endl; ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; return ss.str(); } #if 0 std::string DatatypeFormater::ToString(const CSgitFtdcOrderField* p) { char buf[2048]; if (p) { snprintf(buf, sizeof(buf), "structName=CSgitFtdcOrderField\n" "\tBrokerID=%s\n" "\tInvestorID=%s\n" "\tInstrumentID=%s\n" "\tOrderRef=%s\n" "\tUserID=%s\n" "\tOrderPriceType=0x%02x\n" "\tDirection=0x%02x\n" "\tCombOffsetFlag=%s\n" "\tCombHedgeFlag=%s\n" "\tLimitPrice=%.4f\n" "\tVolumeTotalOriginal=%d\n" "\tTimeCondition=0x%02x\n" "\tGTDDate=%s\n" "\tVolumeCondition=0x%02x\n" "\tMinVolume=%d\n" "\tContingentCondition=0x%02x\n" "\tStopPrice=%.4f\n" "\tForceCloseReason=0x%02x\n" "\tIsAutoSuspend=%d\n" "\tBusinessUnit=%s\n" "\tRequestID=%d\n" "\tOrderLocalID=%s\n" "\tExchangeID=%s\n" "\tParticipantID=%s\n" "\tClientID=%s\n" "\tExchangeInstID=%s\n" "\tTraderID=%s\n" "\tInstallID=%d\n" "\tOrderSubmitStatus=0x%02x\n" "\tNotifySequence=%d\n" "\tTradingDay=%s\n" "\tSettlementID=%d\n" "\tOrderSysID=%s\n" "\tOrderSource=0x%02x\n" "\tOrderStatus=0x%02x\n" "\tOrderType=0x%02x\n" "\tVolumeTraded=%d\n" "\tVolumeTotal=%d\n" "\tInsertDate=%s\n" "\tInsertTime=%s\n" "\tActiveTime=%s\n" "\tSuspendTime=%s\n" "\tUpdateTime=%s\n" "\tCancelTime=%s\n" "\tActiveTraderID=%s\n" "\tClearingPartID=%s\n" "\tSequenceNo=%d\n" "\tFrontID=%d\n" "\tSessionID=%d\n" "\tUserProductInfo=%s\n" "\tStatusMsg=%s\n" "\tUserForceClose=%d\n" "\tActiveUserID=%s\n" "\tBrokerOrderSeq=%d\n" "\tRelativeOrderSysID=%s\n", p->BrokerID, p->InvestorID, p->InstrumentID, p->OrderRef, p->UserID, p->OrderPriceType, p->Direction, p->CombOffsetFlag, p->CombHedgeFlag, p->LimitPrice, p->VolumeTotalOriginal, p->TimeCondition, p->GTDDate, p->VolumeCondition, p->MinVolume, p->ContingentCondition, p->StopPrice, p->ForceCloseReason, p->IsAutoSuspend, p->BusinessUnit, p->RequestID, p->OrderLocalID, p->ExchangeID, p->ParticipantID, p->ClientID, p->ExchangeInstID, p->TraderID, p->InstallID, p->OrderSubmitStatus, p->NotifySequence, p->TradingDay, p->SettlementID, p->OrderSysID, p->OrderSource, p->OrderStatus, p->OrderType, p->VolumeTraded, p->VolumeTotal, p->InsertDate, p->InsertTime, p->ActiveTime, p->SuspendTime, p->UpdateTime, p->CancelTime, p->ActiveTraderID, p->ClearingPartID, p->SequenceNo, p->FrontID, p->SessionID, p->UserProductInfo, p->StatusMsg, p->UserForceClose, p->ActiveUserID, p->BrokerOrderSeq, p->RelativeOrderSysID ); } else { snprintf(buf, sizeof(buf), "structName=CSgitFtdcOrderField <null>"); } return buf; } #else // too much fields, delete useless fields std::string DatatypeFormater::ToString(const CSgitFtdcOrderField* p) { char buf[2048]; if (p) { snprintf(buf, sizeof(buf), "structName=CSgitFtdcOrderField\n" "\tBrokerID=%s\n" "\tInvestorID=%s\n" "\tInstrumentID=%s\n" "\tOrderRef=%s\n" "\tUserID=%s\n" "\tOrderPriceType=0x%02x\n" "\tDirection=0x%02x\n" "\tCombOffsetFlag=%s\n" "\tCombHedgeFlag=%s\n" "\tLimitPrice=%.4f\n" "\tVolumeTotalOriginal=%d\n" "\tTimeCondition=0x%02x\n" "\tGTDDate=%s\n" "\tVolumeCondition=0x%02x\n" "\tMinVolume=%d\n" "\tContingentCondition=0x%02x\n" "\tStopPrice=%.4f\n" "\tForceCloseReason=0x%02x\n" "\tOrderSysID=%s\n" "\tOrderSource=0x%02x\n" "\tOrderStatus=0x%02x\n" "\tOrderType=0x%02x\n" "\tVolumeTraded=%d\n" "\tVolumeTotal=%d\n" "\tInsertDate=%s\n" "\tInsertTime=%s\n" "\tActiveTime=%s\n", p->BrokerID, p->InvestorID, p->InstrumentID, p->OrderRef, p->UserID, p->OrderPriceType, p->Direction, p->CombOffsetFlag, p->CombHedgeFlag, p->LimitPrice, p->VolumeTotalOriginal, p->TimeCondition, p->GTDDate, p->VolumeCondition, p->MinVolume, p->ContingentCondition, p->StopPrice, p->ForceCloseReason, p->OrderSysID, p->OrderSource, p->OrderStatus, p->OrderType, p->VolumeTraded, p->VolumeTotal, p->InsertDate, p->InsertTime, p->ActiveTime ); } else { snprintf(buf, sizeof(buf), "structName=CSgitFtdcOrderField <null>"); } return buf; } #endif std::string DatatypeFormater::ToString(const CSgitFtdcTradeField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcTradeField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; ss << indent_string << "OrderRef=" << pdata->OrderRef << endl; ss << indent_string << "UserID=" << pdata->UserID << endl; ss << indent_string << "ExchangeID=" << pdata->ExchangeID << endl; ss << indent_string << "TradeID=" << pdata->TradeID << endl; ss << indent_string << "Direction=" << pdata->Direction << endl; ss << indent_string << "OrderSysID=" << pdata->OrderSysID << endl; ss << indent_string << "ParticipantID=" << pdata->ParticipantID << endl; ss << indent_string << "ClientID=" << pdata->ClientID << endl; //ss << indent_string << "TradingRole=" << pdata->TradingRole << " ///交易角色: " << endl; ss << indent_string << "TradingRole="; pdata->TradingRole == '\0' ? ss << "<null>" : ss << pdata->TradingRole << endl; ss << indent_string << "ExchangeInstID=" << pdata->ExchangeInstID << endl; ss << indent_string << "OffsetFlag=" << pdata->OffsetFlag << endl; ss << indent_string << "HedgeFlag=" << pdata->HedgeFlag << endl; ss << indent_string << "Price=" << pdata->Price << endl; ss << indent_string << "Volume=" << pdata->Volume << endl; ss << indent_string << "TradeDate=" << pdata->TradeDate << endl; ss << indent_string << "TradeTime=" << pdata->TradeTime << endl; //ss << indent_string << "TradeType=" << pdata->TradeType << " ///成交类型: " << endl; ss << indent_string << "TradeType="; pdata->TradeType == '\0' ? ss << "<null>" : ss << pdata->TradeType << endl; //ss << indent_string << "PriceSource=" << pdata->PriceSource << " ///成交价来源: " << endl; ss << indent_string << "PriceSource="; pdata->PriceSource == '\0' ? ss << "<null>" : ss << pdata->PriceSource << endl; ss << indent_string << "TraderID=" << pdata->TraderID << endl; ss << indent_string << "OrderLocalID=" << pdata->OrderLocalID << endl; ss << indent_string << "ClearingPartID=" << pdata->ClearingPartID << endl; ss << indent_string << "BusinessUnit=" << pdata->BusinessUnit << endl; ss << indent_string << "SequenceNo=" << pdata->SequenceNo << endl; ss << indent_string << "TradingDay=" << pdata->TradingDay << endl; ss << indent_string << "SettlementID=" << pdata->SettlementID << endl; ss << indent_string << "BrokerOrderSeq=" << pdata->BrokerOrderSeq << endl; ss << indent_string << "TradeSource=" << pdata->TradeSource << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcSettlementInfoConfirmField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcSettlementInfoConfirmField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "ConfirmDate=" << pdata->ConfirmDate << endl; ss << indent_string << "ConfirmTime=" << pdata->ConfirmTime << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcInvestorPositionField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcInvestorPositionField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "InstrumentID=" << pdata->InstrumentID << endl; ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "PosiDirection=" << pdata->PosiDirection << endl; ss << indent_string << "HedgeFlag=" << pdata->HedgeFlag << endl; ss << indent_string << "PositionDate=" << (int) pdata->PositionDate << endl; ss << indent_string << "YdPosition=" << pdata->YdPosition << endl; ss << indent_string << "Position=" << pdata->Position << endl; ss << indent_string << "LongFrozen=" << pdata->LongFrozen << endl; ss << indent_string << "ShortFrozen=" << pdata->ShortFrozen << endl; ss << indent_string << "LongFrozenAmount=" << pdata->LongFrozenAmount << endl; ss << indent_string << "ShortFrozenAmount=" << pdata->ShortFrozenAmount << endl; ss << indent_string << "OpenVolume=" << pdata->OpenVolume << endl; ss << indent_string << "CloseVolume=" << pdata->CloseVolume << endl; ss << indent_string << "OpenAmount=" << pdata->OpenAmount << endl; ss << indent_string << "CloseAmount=" << pdata->CloseAmount << endl; ss << indent_string << "PositionCost=" << pdata->PositionCost << endl; ss << indent_string << "PreMargin=" << pdata->PreMargin << endl; ss << indent_string << "UseMargin=" << pdata->UseMargin << endl; ss << indent_string << "FrozenMargin=" << pdata->FrozenMargin << endl; ss << indent_string << "FrozenCash=" << pdata->FrozenCash << endl; ss << indent_string << "FrozenCommission=" << pdata->FrozenCommission << endl; ss << indent_string << "CashIn=" << pdata->CashIn << endl; ss << indent_string << "Commission=" << pdata->Commission << endl; ss << indent_string << "CloseProfit=" << pdata->CloseProfit << endl; ss << indent_string << "PositionProfit=" << pdata->PositionProfit << endl; ss << indent_string << "PreSettlementPrice=" << pdata->PreSettlementPrice << endl; ss << indent_string << "SettlementPrice=" << pdata->SettlementPrice << endl; ss << indent_string << "TradingDay=" << pdata->TradingDay << endl; ss << indent_string << "SettlementID=" << pdata->SettlementID << endl; ss << indent_string << "OpenCost=" << pdata->OpenCost << endl; ss << indent_string << "ExchangeMargin=" << pdata->ExchangeMargin << endl; ss << indent_string << "CombPosition=" << pdata->CombPosition << endl; ss << indent_string << "CombLongFrozen=" << pdata->CombLongFrozen << endl; ss << indent_string << "CombShortFrozen=" << pdata->CombShortFrozen << endl; ss << indent_string << "CloseProfitByDate=" << pdata->CloseProfitByDate << endl; ss << indent_string << "CloseProfitByTrade=" << pdata->CloseProfitByTrade << endl; ss << indent_string << "TodayPosition=" << pdata->TodayPosition << endl; ss << indent_string << "MarginRateByMoney=" << pdata->MarginRateByMoney << endl; ss << indent_string << "MarginRateByVolume=" << pdata->MarginRateByVolume << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcRspInfoField* pdata) { stringstream ss; ss << newline_string << indent_string << "structName=CSgitFtdcRspInfoField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "ErrorID=" << pdata->ErrorID << endl; ss << indent_string << "ErrorMsg=" << pdata->ErrorMsg << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcTradingAccountField *pdata) { stringstream ss; ss << std::fixed << newline_string << "structName=CSgitFtdcTradingAccountField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "AccountID=" << pdata->AccountID << endl; ss << indent_string << "PreMortgage=" << pdata->PreMortgage << endl; ss << indent_string << "PreCredit=" << pdata->PreCredit << endl; ss << indent_string << "PreDeposit=" << pdata->PreDeposit << endl; ss << indent_string << "PreBalance=" << pdata->PreBalance << endl; ss << indent_string << "PreMargin=" << pdata->PreMargin << endl; ss << indent_string << "InterestBase=" << pdata->InterestBase << endl; ss << indent_string << "Interest=" << pdata->Interest << endl; ss << indent_string << "Deposit=" << pdata->Deposit << endl; ss << indent_string << "Withdraw=" << pdata->Withdraw << endl; ss << indent_string << "FrozenMargin=" << pdata->FrozenMargin << endl; ss << indent_string << "FrozenCash=" << pdata->FrozenCash << endl; ss << indent_string << "FrozenCommission=" << pdata->FrozenCommission << endl; ss << indent_string << "CurrMargin=" << pdata->CurrMargin << endl; ss << indent_string << "CashIn=" << pdata->CashIn << endl; ss << indent_string << "Commission=" << pdata->Commission << endl; ss << indent_string << "CloseProfit=" << pdata->CloseProfit << endl; ss << indent_string << "PositionProfit=" << pdata->PositionProfit << endl; ss << indent_string << "Balance=" << pdata->Balance << endl; ss << indent_string << "Available=" << pdata->Available << endl; ss << indent_string << "WithdrawQuota=" << pdata->WithdrawQuota << endl; ss << indent_string << "Reserve=" << pdata->Reserve << endl; ss << indent_string << "TradingDay=" << pdata->TradingDay << endl; ss << indent_string << "SettlementID=" << pdata->SettlementID << endl; ss << indent_string << "Credit=" << pdata->Credit << endl; ss << indent_string << "Mortgage=" << pdata->Mortgage << endl; ss << indent_string << "ExchangeMargin=" << pdata->ExchangeMargin << endl; ss << indent_string << "DeliveryMargin=" << pdata->DeliveryMargin << endl; ss << indent_string << "ExchangeDeliveryMargin=" << pdata->ExchangeDeliveryMargin << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcSettlementInfoField *pdata) { stringstream ss; ss << std::fixed << newline_string << "structName=CSgitFtdcSettlementInfoField" << endl; if (!pdata) { ss << "<null>" << endl; return ss.str(); } ss << indent_string << "TradingDay=" << pdata->TradingDay << endl; ss << indent_string << "SettlementID=" << pdata->SettlementID << endl; ss << indent_string << "BrokerID=" << pdata->BrokerID << endl; ss << indent_string << "InvestorID=" << pdata->InvestorID << endl; ss << indent_string << "SequenceNo=" << pdata->SequenceNo << endl; ss << indent_string << "Content=" << pdata->Content << endl; return ss.str(); } std::string DatatypeFormater::ToString(const CSgitFtdcInvestorPositionDetailField *p) { char buf[2048]; if (p) { snprintf(buf, sizeof(buf), "structName=CSgitFtdcInvestorPositionDetailField\n" " InstrumentID=%s\n" " BrokerID=%s\n" " InvestorID=%s\n" " HedgeFlag=0x%02x\n" " Direction=0x%02x\n" " OpenDate=%s\n" " TradeID=%s\n" " Volume=%d\n" " OpenPrice=%.4f\n" " TradingDay=%s\n" " SettlementID=%d\n" " TradeType=0x%02x\n" " CombInstrumentID=%s\n" " ExchangeID=%s\n" " CloseProfitByDate=%.4f\n" " CloseProfitByTrade=%.4f\n" " PositionProfitByDate=%.4f\n" " PositionProfitByTrade=%.4f\n" " Margin=%.4f\n" " ExchMargin=%.4f\n" " MarginRateByMoney=%.4f\n" " MarginRateByVolume=%.4f\n" " LastSettlementPrice=%.4f\n" " SettlementPrice=%.4f\n" " CloseVolume=%d\n" " CloseAmount=%.4f\n", p->InstrumentID, //合约代码 p->BrokerID, //经纪公司代码 p->InvestorID, //投资者代码 p->HedgeFlag, //投机套保标志 p->Direction, //买卖 p->OpenDate, //开仓日期 p->TradeID, //成交编号 p->Volume, //数量 p->OpenPrice, //开仓价 p->TradingDay, //交易日 p->SettlementID, //结算编号 p->TradeType, //成交类型 p->CombInstrumentID, //组合合约代码 p->ExchangeID, //交易所代码 p->CloseProfitByDate, //逐日盯市平仓盈亏 p->CloseProfitByTrade, //逐笔对冲平仓盈亏 p->PositionProfitByDate, //逐日盯市持仓盈亏 p->PositionProfitByTrade, //逐笔对冲持仓盈亏 p->Margin, //投资者保证金 p->ExchMargin, //交易所保证金 p->MarginRateByMoney, //保证金率 p->MarginRateByVolume, //保证金率(按手数) p->LastSettlementPrice, //昨结算价 p->SettlementPrice, //结算价 p->CloseVolume, //平仓量 p->CloseAmount //平仓金额 ); } else { snprintf(buf, sizeof(buf), "structName=CSgitFtdcInvestorPositionDetailField <null>"); } return buf; } std::string DatatypeFormater::ToString(const CSgitFtdcInstrumentField *p) { char buf[2048]; if (p) { snprintf(buf, sizeof(buf), "structName=CSgitFtdcInstrumentField\n" " InstrumentID=%s\n" " ExchangeID=%s\n" " InstrumentName=%s\n" " ExchangeInstID=%s\n" " ProductID=%s\n" " ProductClass=0X%02X\n" " DeliveryYear=%04d\n" " DeliveryMonth=%02d\n" " MaxMarketOrderVolume=%d\n" " MinMarketOrderVolume=%d\n" " MaxLimitOrderVolume=%d\n" " MinLimitOrderVolume=%d\n" " VolumeMultiple=%d\n" " PriceTick=%.4f\n" " CreateDate=%s\n" " OpenDate=%s\n" " ExpireDate=%s\n" " StartDelivDate=%s\n" " EndDelivDate=%s\n" " InstLifePhase=0X%02X\n" " IsTrading=%d\n" " PositionType=0X%02X\n" " PositionDateType=0X%02X\n" " LongMarginRatio=%.8f\n" " ShortMarginRatio=%.8f\n", p->InstrumentID, //合约代码 p->ExchangeID, //交易所代码 p->InstrumentName, //合约名称 p->ExchangeInstID, //合约在交易所的代码 p->ProductID, //产品代码 p->ProductClass, //产品类型 p->DeliveryYear, //交割年份 p->DeliveryMonth, //交割月 p->MaxMarketOrderVolume, //市价单最大下单量 p->MinMarketOrderVolume, //市价单最小下单量 p->MaxLimitOrderVolume, //限价单最大下单量 p->MinLimitOrderVolume, //限价单最小下单量 p->VolumeMultiple, //合约数量乘数 p->PriceTick, //最小变动价位 p->CreateDate, //创建日 p->OpenDate, //上市日 p->ExpireDate, //到期日 p->StartDelivDate, //开始交割日 p->EndDelivDate, //结束交割日 p->InstLifePhase, //合约生命周期状态 p->IsTrading, //当前是否交易 p->PositionType, //持仓类型 p->PositionDateType, //持仓日期类型 p->LongMarginRatio, //多头保证金率 p->ShortMarginRatio //空头保证金率 ); } else { snprintf(buf, sizeof(buf), "structName=CSgitFtdcInstrumentField <null>"); } return buf; }
[ "17199883@qq.com" ]
17199883@qq.com
01fd495b91830655f7e1994b80ec1e28b4b117d5
da6863c90ee854ceba9ae4f4d75c2c04df394dfd
/emaxx/bjp.cpp
ef2b8796c6212c2080cf6f962f495e2a0cb1d3c3
[]
no_license
iamrakesh28/Competitve-Programming
a9db8df3d4a90ea34bad982a5c9ff90da4f9708e
c7aec676acfee8d506e5cfbbd010bdb913d880e4
refs/heads/master
2021-06-11T03:27:31.364670
2021-04-04T11:54:55
2021-04-04T11:54:55
180,629,170
1
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
#include <bits/stdc++.h> using namespace std; long int ri[1000000], ci[1000000]; int main() { int t; scanf("%d", &t); while (t--) { long long r, c, sum1 = 0, sum2 = 0, mr = -1, mc = -1, mri, mci, a, b; cin>>r>>c; mri = r; mci = c; for (int i = 0; i < r; ++i) { cin>>a; ri[i] = a; sum1 += a; mr = max(mr, a); if (!a) mri--; } for (int i = 0; i < c; ++i) { cin>>b; ci[i] = b; sum2 += b; mc = max(mc, b); if (!b) mci--; } bool win = true; if (r * c <= 100000) { for (int i = 0; i < r; ++i) { int req = ri[i]; for (int j = 0; j < c; ++j) { if (req == 0) break; if (ci[j]) ci[j]--, req--; } if (req) { win = false; break; } } if(win) printf("YES\n"); else printf("NO\n"); continue; } if (mr > mci || mc > mri) win = false; if (sum1 != sum2) win = false; if(win) printf("YES\n"); else printf("NO\n"); } return 0; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
e6912e45621cd20efd85312fb49b4c0e0f6b8cf0
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFilter.hxx
d3324b3483437a38e92f7065653127b9654eaf10
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "...
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
20,835
hxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkBSplineControlPointImageFilter_hxx #define itkBSplineControlPointImageFilter_hxx #include "itkBSplineControlPointImageFilter.h" #include "itkMath.h" #include "itkImageDuplicator.h" #include "itkImageRegionConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkMath.h" namespace itk { template<typename TInputImage, typename TOutputImage> BSplineControlPointImageFilter<TInputImage, TOutputImage> ::BSplineControlPointImageFilter() : m_DoMultilevel( false ), m_MaximumNumberOfLevels( 1 ), m_NumberOfLevels( 1 ), m_BSplineEpsilon( 1e-3 ) { this->m_Size.Fill( 0 ); this->m_Spacing.Fill( 1.0 ); this->m_Origin.Fill( 0.0 ); this->m_Direction.SetIdentity(); this->m_CloseDimension.Fill( 0 ); this->m_SplineOrder.Fill( 3 ); for( unsigned int i = 0; i < ImageDimension; i++ ) { this->m_NumberOfControlPoints[i] = ( this->m_SplineOrder[i] + 1 ); this->m_Kernel[i] = KernelType::New(); this->m_Kernel[i]->SetSplineOrder( this->m_SplineOrder[i] ); } this->m_KernelOrder0 = KernelOrder0Type::New(); this->m_KernelOrder1 = KernelOrder1Type::New(); this->m_KernelOrder2 = KernelOrder2Type::New(); this->m_KernelOrder3 = KernelOrder3Type::New(); } template<typename InputImage, typename TOutputImage> BSplineControlPointImageFilter<InputImage, TOutputImage> ::~BSplineControlPointImageFilter() { } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::SetNumberOfLevels( ArrayType levels ) { this->m_NumberOfLevels = levels; this->m_MaximumNumberOfLevels = 1; for( unsigned int i = 0; i < ImageDimension; i++ ) { if( this->m_NumberOfLevels[i] == 0 ) { itkExceptionMacro( "The number of levels in each dimension must be greater than 0" ); } if( this->m_NumberOfLevels[i] > this->m_MaximumNumberOfLevels ) { this->m_MaximumNumberOfLevels = this->m_NumberOfLevels[i]; } } itkDebugMacro( "Setting m_NumberOfLevels to " << this->m_NumberOfLevels ); itkDebugMacro( "Setting m_MaximumNumberOfLevels to " << this-> m_MaximumNumberOfLevels ); if( this->m_MaximumNumberOfLevels > 1 ) { this->m_DoMultilevel = true; } else { this->m_DoMultilevel = false; } this->SetSplineOrder( this->m_SplineOrder ); this->Modified(); } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::SetSplineOrder( unsigned int order ) { this->m_SplineOrder.Fill( order ); this->SetSplineOrder( this->m_SplineOrder ); } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::SetSplineOrder( ArrayType order ) { itkDebugMacro( "Setting m_SplineOrder to " << order ); this->m_SplineOrder = order; for( unsigned int i = 0; i < ImageDimension; i++ ) { if( this->m_SplineOrder[i] == 0 ) { itkExceptionMacro( "The spline order in each dimension must be greater than 0" ); } this->m_Kernel[i] = KernelType::New(); this->m_Kernel[i]->SetSplineOrder( this->m_SplineOrder[i] ); if( this->m_DoMultilevel ) { typename KernelType::MatrixType C; C = this->m_Kernel[i]->GetShapeFunctionsInZeroToOneInterval(); vnl_matrix<RealType> R; vnl_matrix<RealType> S; R.set_size( C.rows(), C.cols() ); S.set_size( C.rows(), C.cols() ); for( unsigned int j = 0; j < C.rows(); j++ ) { for( unsigned int k = 0; k < C.cols(); k++ ) { R(j, k) = S(j, k) = static_cast<RealType>( C(j, k) ); } } for( unsigned int j = 0; j < C.cols(); j++ ) { RealType c = std::pow( static_cast<RealType>( 2.0 ), static_cast<RealType>( C.cols()-j-1 ) ); for( unsigned int k = 0; k < C.rows(); k++) { R(k, j) *= c; } } R = R.transpose(); R.flipud(); S = S.transpose(); S.flipud(); this->m_RefinedLatticeCoefficients[i] = ( vnl_svd<RealType>( R ).solve( S ) ).extract( 2, S.cols() ); } } this->Modified(); } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::BeforeThreadedGenerateData() { const TInputImage *inputPtr = this->GetInput(); TOutputImage *outputPtr = this->GetOutput(); for( unsigned int i = 0; i < ImageDimension; i++) { if( this->m_Size[i] == 0 ) { itkExceptionMacro( "Size must be specified." ); } } outputPtr->SetOrigin( this->m_Origin ); outputPtr->SetSpacing( this->m_Spacing ); outputPtr->SetRegions( this->m_Size ); outputPtr->SetDirection( this->m_Direction ); outputPtr->Allocate(); for( unsigned int i = 0; i < ImageDimension; i++) { this->m_NumberOfControlPoints[i] = inputPtr->GetLargestPossibleRegion().GetSize()[i]; } } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::ThreadedGenerateData( const OutputImageRegionType & region, ThreadIdType itkNotUsed( threadId ) ) { const TInputImage *inputPtr = this->GetInput(); TOutputImage *outputPtr = this->GetOutput(); typename PointDataImageType::Pointer collapsedPhiLattices[ImageDimension + 1]; for( unsigned int i = 0; i < ImageDimension; i++ ) { collapsedPhiLattices[i] = PointDataImageType::New(); collapsedPhiLattices[i]->CopyInformation( inputPtr ); typename PointDataImageType::SizeType size; size.Fill( 1 ); for( unsigned int j = 0; j < i; j++ ) { size[j] = inputPtr->GetLargestPossibleRegion().GetSize()[j]; } collapsedPhiLattices[i]->SetRegions( size ); collapsedPhiLattices[i]->Allocate(); } typedef ImageDuplicator<ControlPointLatticeType> ImageDuplicatorType; typename ImageDuplicatorType::Pointer duplicator = ImageDuplicatorType::New(); duplicator->SetInputImage( inputPtr ); duplicator->Update(); collapsedPhiLattices[ImageDimension] = duplicator->GetModifiableOutput(); ArrayType totalNumberOfSpans; for( unsigned int i = 0; i < ImageDimension; i++ ) { if( this->m_CloseDimension[i] ) { totalNumberOfSpans[i] = inputPtr->GetLargestPossibleRegion().GetSize()[i]; } else { totalNumberOfSpans[i] = inputPtr->GetLargestPossibleRegion().GetSize()[i] - this->m_SplineOrder[i]; } } FixedArray<RealType, ImageDimension> U; FixedArray<RealType, ImageDimension> currentU; currentU.Fill( -1 ); typename OutputImageType::IndexType startIndex = outputPtr->GetRequestedRegion().GetIndex(); typename PointDataImageType::IndexType startPhiIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); RealArrayType epsilon; for( unsigned int i = 0; i < ImageDimension; i++ ) { RealType r = static_cast<RealType>( this->m_NumberOfControlPoints[i] - this->m_SplineOrder[i] ) / ( static_cast<RealType>( this->m_Size[i] - 1 ) * this->m_Spacing[i] ); epsilon[i] = r * this->m_Spacing[i] * this->m_BSplineEpsilon; } ImageRegionIteratorWithIndex<OutputImageType> It( outputPtr, region ); for( It.GoToBegin(); !It.IsAtEnd(); ++It ) { typename OutputImageType::IndexType idx = It.GetIndex(); for( unsigned int i = 0; i < ImageDimension; i++ ) { U[i] = static_cast<RealType>( totalNumberOfSpans[i] ) * static_cast<RealType>( idx[i] - startIndex[i] ) / static_cast<RealType>( this->m_Size[i] - 1 ); if( std::abs( U[i] - static_cast<RealType>( totalNumberOfSpans[i] ) ) <= epsilon[i] ) { U[i] = static_cast<RealType>( totalNumberOfSpans[i] ) - epsilon[i]; } if( U[i] < NumericTraits<RealType>::ZeroValue() && std::abs( U[i] ) <= epsilon[i] ) { U[i] = NumericTraits<RealType>::ZeroValue(); } if( U[i] < NumericTraits<RealType>::ZeroValue() || U[i] >= static_cast<RealType>( totalNumberOfSpans[i] ) ) { itkExceptionMacro( "The collapse point component " << U[i] << " is outside the corresponding parametric domain of [0, " << totalNumberOfSpans[i] << ")." ); } } for( int i = ImageDimension - 1; i >= 0; i-- ) { if( Math::NotExactlyEquals(U[i], currentU[i]) ) { for( int j = i; j >= 0; j-- ) { this->CollapsePhiLattice( collapsedPhiLattices[j + 1], collapsedPhiLattices[j], U[j], j ); currentU[j] = U[j]; } break; } } It.Set( collapsedPhiLattices[0]->GetPixel( startPhiIndex ) ); } } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::CollapsePhiLattice( PointDataImageType *lattice, PointDataImageType *collapsedLattice, const RealType u, const unsigned int dimension ) { ImageRegionIteratorWithIndex< PointDataImageType > It( collapsedLattice, collapsedLattice->GetLargestPossibleRegion() ); for( It.GoToBegin(); !It.IsAtEnd(); ++It ) { PointDataType data; data.Fill( 0.0 ); typename PointDataImageType::IndexType idx = It.GetIndex(); for( unsigned int i = 0; i < this->m_SplineOrder[dimension] + 1; i++ ) { idx[dimension] = static_cast<unsigned int>( u ) + i; RealType v = u - idx[dimension] + 0.5 * static_cast<RealType>( this->m_SplineOrder[dimension] - 1 ); RealType B = 0.0; switch( this->m_SplineOrder[dimension] ) { case 0: { B = this->m_KernelOrder0->Evaluate( v ); break; } case 1: { B = this->m_KernelOrder1->Evaluate( v ); break; } case 2: { B = this->m_KernelOrder2->Evaluate( v ); break; } case 3: { B = this->m_KernelOrder3->Evaluate( v ); break; } default: { B = this->m_Kernel[dimension]->Evaluate( v ); break; } } if( this->m_CloseDimension[dimension] ) { idx[dimension] %= lattice->GetLargestPossibleRegion().GetSize()[dimension]; } data += ( lattice->GetPixel( idx ) * B ); } It.Set( data ); } } template<typename TInputImage, typename TOutputImage> unsigned int BSplineControlPointImageFilter<TInputImage, TOutputImage> ::SplitRequestedRegion( unsigned int i, unsigned int num, OutputImageRegionType &splitRegion ) { // Get the output pointer OutputImageType *outputPtr = this->GetOutput(); const SizeType requestedRegionSize = outputPtr->GetRequestedRegion().GetSize(); int splitAxis; typename TOutputImage::IndexType splitIndex; typename TOutputImage::SizeType splitSize; // Initialize the splitRegion to the output requested region splitRegion = outputPtr->GetRequestedRegion(); splitIndex = splitRegion.GetIndex(); splitSize = splitRegion.GetSize(); // split on the outermost dimension splitAxis = outputPtr->GetImageDimension() - 1; // determine the actual number of pieces that will be generated typename SizeType::SizeValueType range = requestedRegionSize[splitAxis]; unsigned int valuesPerThread = static_cast<unsigned int>( std::ceil( range / static_cast<double>( num ) ) ); unsigned int maxThreadIdUsed = static_cast<unsigned int>( std::ceil( range / static_cast<double>( valuesPerThread ) ) - 1 ); // Split the region if ( i < maxThreadIdUsed ) { splitIndex[splitAxis] += i * valuesPerThread; splitSize[splitAxis] = valuesPerThread; } if ( i == maxThreadIdUsed ) { splitIndex[splitAxis] += i * valuesPerThread; // last thread needs to process the "rest" dimension being split splitSize[splitAxis] = splitSize[splitAxis] - i * valuesPerThread; } // set the split region ivars splitRegion.SetIndex( splitIndex ); splitRegion.SetSize( splitSize ); itkDebugMacro( "Split piece: " << splitRegion ); return maxThreadIdUsed + 1; } template<typename TInputPointImage, typename TOutputImage> typename BSplineControlPointImageFilter<TInputPointImage, TOutputImage> ::ControlPointLatticeType::Pointer BSplineControlPointImageFilter<TInputPointImage, TOutputImage> ::RefineControlPointLattice( ArrayType numberOfLevels ) { this->SetNumberOfLevels( numberOfLevels ); typedef ImageDuplicator<ControlPointLatticeType> ImageDuplicatorType; typename ImageDuplicatorType::Pointer duplicator = ImageDuplicatorType::New(); duplicator->SetInputImage( this->GetInput() ); duplicator->Update(); typename ControlPointLatticeType::Pointer psiLattice = ControlPointLatticeType::New(); psiLattice = duplicator->GetModifiableOutput(); for( unsigned int m = 1; m < this->m_MaximumNumberOfLevels; m++ ) { ArrayType numberOfNewControlPoints; for( unsigned int i = 0; i < ImageDimension; i++ ) { numberOfNewControlPoints[i] = psiLattice->GetLargestPossibleRegion().GetSize()[i]; } for( unsigned int i = 0; i < ImageDimension; i++ ) { if( m < this->m_NumberOfLevels[i] ) { numberOfNewControlPoints[i] = 2 * numberOfNewControlPoints[i]-this->m_SplineOrder[i]; } } typename RealImageType::RegionType::SizeType size; for( unsigned int i = 0; i < ImageDimension; i++ ) { if( this->m_CloseDimension[i] ) { size[i] = numberOfNewControlPoints[i] - this->m_SplineOrder[i]; } else { size[i] = numberOfNewControlPoints[i]; } } typename ControlPointLatticeType::Pointer refinedLattice = ControlPointLatticeType::New(); refinedLattice->SetRegions( size ); refinedLattice->Allocate(); PixelType data; data.Fill( 0.0 ); refinedLattice->FillBuffer( data ); typename ControlPointLatticeType::IndexType idx; typename ControlPointLatticeType::IndexType idxPsi; typename ControlPointLatticeType::IndexType tmp; typename ControlPointLatticeType::IndexType tmpPsi; typename ControlPointLatticeType::IndexType off; typename ControlPointLatticeType::IndexType offPsi; typename ControlPointLatticeType::RegionType::SizeType sizePsi; size.Fill( 2 ); unsigned int N = 1; for( unsigned int i = 0; i < ImageDimension; i++ ) { N *= ( this->m_SplineOrder[i] + 1 ); sizePsi[i] = this->m_SplineOrder[i] + 1; } ImageRegionIteratorWithIndex<ControlPointLatticeType> It( refinedLattice, refinedLattice->GetLargestPossibleRegion() ); const TInputPointImage *input = this->GetInput(); It.GoToBegin(); while( !It.IsAtEnd() ) { idx = It.GetIndex(); for( unsigned int i = 0; i < ImageDimension; i++ ) { if( m < this->m_NumberOfLevels[i] ) { idxPsi[i] = static_cast<unsigned int>( 0.5 * idx[i] ); } else { idxPsi[i] = static_cast<unsigned int>( idx[i] ); } } for( unsigned int i = 0; i < ( 2 << ( ImageDimension - 1 ) ); i++ ) { PixelType sum( 0.0 ); PixelType val; off = this->NumberToIndex( i, size ); bool outOfBoundary = false; for( unsigned int j = 0; j < ImageDimension; j++ ) { tmp[j] = idx[j] + off[j]; if( tmp[j] >= static_cast<int>( numberOfNewControlPoints[j] ) && !this->m_CloseDimension[j] ) { outOfBoundary = true; break; } if( this->m_CloseDimension[j] ) { tmp[j] %= refinedLattice->GetLargestPossibleRegion().GetSize()[j]; } } if( outOfBoundary ) { continue; } for( unsigned int j = 0; j < N; j++ ) { offPsi = this->NumberToIndex( j, sizePsi ); bool outOfBoundary2 = false; for( unsigned int k = 0; k < ImageDimension; k++ ) { tmpPsi[k] = idxPsi[k] + offPsi[k]; if( tmpPsi[k] >= static_cast<int>( input->GetLargestPossibleRegion().GetSize()[k] ) && !this->m_CloseDimension[k] ) { outOfBoundary2 = true; break; } if( this->m_CloseDimension[k] ) { tmpPsi[k] %= psiLattice->GetLargestPossibleRegion().GetSize()[k]; } } if( outOfBoundary2 ) { continue; } RealType coeff = 1.0; for( unsigned int k = 0; k < ImageDimension; k++ ) { coeff *= this->m_RefinedLatticeCoefficients[k]( off[k], offPsi[k] ); } val = psiLattice->GetPixel( tmpPsi ); val *= coeff; sum += val; } refinedLattice->SetPixel( tmp, sum ); } bool IsEvenIndex = false; while( !IsEvenIndex && !It.IsAtEnd() ) { ++It; idx = It.GetIndex(); IsEvenIndex = true; for( unsigned int i = 0; i < ImageDimension; i++ ) { if( idx[i] % 2 ) { IsEvenIndex = false; } } } } typename ImageDuplicatorType::Pointer duplicator2 = ImageDuplicatorType::New(); duplicator2->SetInputImage( refinedLattice ); duplicator2->Update(); psiLattice = duplicator2->GetModifiableOutput(); } // Specify the pose parameters of the control point lattice typename PointDataImageType::PointType origin; typename PointDataImageType::SpacingType spacing; for( unsigned int i = 0; i < ImageDimension; i++ ) { RealType domain = this->m_Spacing[i] * static_cast<RealType>( this->m_Size[i] - 1 ); unsigned int totalNumberOfSpans = psiLattice->GetLargestPossibleRegion().GetSize()[i]; if( !this->m_CloseDimension[i] ) { totalNumberOfSpans -= this->m_SplineOrder[i]; } spacing[i] = domain / static_cast<RealType>( totalNumberOfSpans ); origin[i] = -0.5 * spacing[i] * ( this->m_SplineOrder[i] - 1 ); } origin = this->m_Direction * origin; psiLattice->SetOrigin( origin ); psiLattice->SetSpacing( spacing ); psiLattice->SetDirection( this->m_Direction ); return psiLattice; } template<typename TInputImage, typename TOutputImage> void BSplineControlPointImageFilter<TInputImage, TOutputImage> ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf( os, indent ); for( unsigned int i = 0; i < ImageDimension; i++ ) { this->m_Kernel[i]->Print( os, indent.GetNextIndent() ); } os << indent << "Spline order: " << this->m_SplineOrder << std::endl; os << indent << "Close dimension: " << this->m_CloseDimension << std::endl; os << indent << "Parametric domain" << std::endl; os << indent << " Origin: " << this->m_Origin << std::endl; os << indent << " Spacing: " << this->m_Spacing << std::endl; os << indent << " Size: " << this->m_Size << std::endl; os << indent << " Direction: " << this->m_Direction << std::endl; } } //end namespace itk #endif
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
3166edce661952d4cb958ad6d2193d1de186cd79
8776c2cd1b4d0054b8c59a0a22a1f37ae43c19ad
/ExpressCaptureServer/pmt.cpp
1b2948c9b2bfb4a5d9f10d026a6f98a637efaea8
[]
no_license
jocover/DatvExpressTransmitter
bef480a1c7b475954c75e17ea614998a28ae0e2a
ee4474610e5436e34c0719b337880c1457b53fe2
refs/heads/master
2021-01-21T21:25:46.302379
2017-06-16T17:39:00
2017-06-16T17:39:00
94,836,750
2
2
null
2017-06-20T01:33:30
2017-06-20T01:33:30
null
UTF-8
C++
false
false
6,144
cpp
#include "stdafx.h" #include <stdint.h> #include "Dvb.h" #include "tp.h" // // This module formats and sends PMT tables // static uint8_t m_pmt_seq; static uint8_t pmt_pkt[188]; int add_video_info( uint8_t *b, tp_v_desc *dec){ return 0; } int add_audio_info( uint8_t *b, tp_a_desc *dec){ return 0; } int pmt_add_es_desc( uint8_t *b, td_descriptor *s){ int len = 0; if(s->table_id == 0x02) len = add_video_info( b, &s->video ); if(s->table_id == 0x03) len = add_audio_info( b, &s->audio ); return len; } int tp_pmt_add_section( uint8_t *b, tp_pmt_section *s ) { int len = 0; int l_field; b[len++] = s->stream_type; b[len] = 0xE0; b[len++] |= s->elementary_pid>>8; b[len++] = s->elementary_pid&0xFF; l_field = 3;//Start of length filed len += 2;//Skip over length // Fill in the descriptors for( int i = 0; i < s->nr_descriptors; i++ ) { len += pmt_add_es_desc( &b[len], &s->desc[i] ); } // Fill in the ES info length field b[l_field] = (0xF0) | (len - 5)>>8; b[l_field+1] = (len - 5)&0xFF; return len; } int tp_pmt_fmt( uint8_t *b, tp_pmt *p ) { int len; b[0] = 0x02; b[1] = 0x30; if( p->section_syntax_indicator ) b[1] |= 0x80; b[3] = (p->program_number>>8); b[4] = (p->program_number&0xFF); b[5] = 0xC0; b[5] |= (p->version_number<<1); if(p->current_next_indicator) b[5] |= 0x01; b[6] = p->section_number; b[7] = p->last_section_number; // PCR PID b[8] = 0xE0; b[8] |= (p->pcr_pid>>8); b[9] = (p->pcr_pid&0xFF); // Program info length = 0 b[10] = 0xF0; b[11] = 0x00; len = 12; for( int i = 0; i < p->nr_elementary_streams; i++ ) { len += tp_pmt_add_section( &b[len], &p->stream[i] ); } // Add the length field b[1] |= ((len+1)>>8); b[2] = ((len+1)&0xFF); len = crc32_add( b, len ); return len; } void fmt_pmt( int video_stream_type, int audio_stream_type, int pmt_pid, int pcr_pid, int video_pid, int audio_pid, int program_nr ) { int len,i; tp_hdr hdr; tp_pmt pmt; hdr.transport_error_indicator = 0; hdr.payload_unit_start_indicator = 1; hdr.transport_priority = 0; hdr.pid = pmt_pid;//PAT table pid hdr.transport_scrambling_control = 0; hdr.adaption_field_control = ADAPTION_PAYLOAD_ONLY; hdr.continuity_counter = m_pmt_seq = 0; len = tp_fmt( pmt_pkt, &hdr ); pmt_pkt[len++] = 0; // Table starts immediately pmt.section_syntax_indicator = 1; pmt.program_number = program_nr; pmt.version_number = 2; pmt.current_next_indicator = 1; pmt.section_number = 0; pmt.last_section_number = 0; pmt.pcr_pid = pcr_pid; if(get_audio_status()==TRUE) pmt.nr_elementary_streams = 2; else pmt.nr_elementary_streams = 1; pmt.stream[0].stream_type = video_stream_type; pmt.stream[0].elementary_pid = video_pid; pmt.stream[0].nr_descriptors = 0; // Video information pmt.stream[0].desc[0].table_id = 0x02; pmt.stream[0].desc[0].video.multiple_frame_rate_flag = 0; pmt.stream[0].desc[0].video.frame_rate_code = 3; // 25 frames per sec pmt.stream[0].desc[0].video.mpeg_1_only_flag = 0; pmt.stream[0].desc[0].video.constrained_parameter_flag = 0; pmt.stream[0].desc[0].video.still_picture_flag = 0; pmt.stream[0].desc[0].video.profile_and_level_indication = 0xC8;// MP@ML esc = 1 pmt.stream[0].desc[0].video.chroma_format = 2;// 4:2:2, 4:2:0 == 1 pmt.stream[0].desc[0].video.frame_rate_extension_flag = 1;//not sure pmt.stream[1].stream_type = audio_stream_type; pmt.stream[1].elementary_pid = audio_pid; pmt.stream[1].nr_descriptors = 0; /* if( info.ebu_data_enabled ) { pmt.stream[2].stream_type = 0x06; // EBU private data pmt.stream[2].elementary_pid = info.ebu_data_pid; pmt.stream[2].nr_descriptors = 1; pmt.stream[2].descriptor[0].tag = SI_DESC_TELETEXT; pmt.stream[2].descriptor[0].ttd.nr_items = 0; pmt.nr_elementary_streams = 3; } */ // Audio information pmt.stream[1].desc[0].table_id = 0x03; pmt.stream[1].desc[0].audio.free_format_flag = 1;//dont know pmt.stream[1].desc[0].audio.id = 0;// don't know pmt.stream[1].desc[0].audio.layer = 0;//don't know pmt.stream[1].desc[0].audio.variable_rate_audio_indicator = 0; len+= tp_pmt_fmt( &pmt_pkt[len], &pmt ); // PAD out the unused bytes for( i = len; i < TP_LEN; i++ ) { pmt_pkt[i] = 0xFF; } } void pmt_fmt( int video_codec, int audio_codec, int pmt_pid, int pcr_pid, int video_pid, int audio_pid, int program_nr ) { int video,audio; //ISO 13818-2 MPEG2 Video (0x02) //ISO 13818-7 MPEG4 Video (0x10) //ISO 13818-7 HEVC Video (0x24) //ISO 13818-3 MPEG2 1/2 rate Audio (0x04) //ISO 11172-3 MPEG1 Audio (0x03) //ISO 14496-3 MPEG4 LAOS (0x11) // Default MPEG2 video and 13810 Audio video = 0x02; audio = 0x04; if( video_codec == AV_CODEC_ID_MPEG2VIDEO ) video = 0x02; if( video_codec == AV_CODEC_ID_MPEG4 ) video = 0x10; if( video_codec == AV_CODEC_ID_H264 ) video = 0x1B; if( video_codec == AV_CODEC_ID_HEVC ) video = 0x24; // if( audio_codec == CODEC_11172_3 ) audio = 0x03; if( audio_codec == AV_CODEC_ID_MP2 ) audio = 0x03; //if( audio_codec == AV_CODEC_ID_MP2 ) audio = 0x04; if( audio_codec == AV_CODEC_ID_AAC ) audio = 0x11; fmt_pmt( video, audio, pmt_pid, pcr_pid, video_pid, audio_pid, program_nr ); } // // Send a PMT transport packet via dvb encoder // void pmt_dvb( void ) { send_tp( pmt_pkt ); update_cont_counter( pmt_pkt ); }
[ "noreply@github.com" ]
jocover.noreply@github.com
57e2f240f2a24e3600df5d73ec45b8d24e252a75
24f26275ffcd9324998d7570ea9fda82578eeb9e
/chrome/browser/web_applications/test/test_system_web_app_manager.h
b007543f58773c4a4d02ef745c0df5af1821c829
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
1,225
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_WEB_APPLICATIONS_TEST_TEST_SYSTEM_WEB_APP_MANAGER_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_TEST_TEST_SYSTEM_WEB_APP_MANAGER_H_ #include <vector> #include "base/macros.h" #include "base/version.h" #include "chrome/browser/web_applications/system_web_app_manager.h" #include "url/gurl.h" class Profile; namespace web_app { class TestSystemWebAppManager : public SystemWebAppManager { public: explicit TestSystemWebAppManager(Profile* profile); ~TestSystemWebAppManager() override; void SetSystemApps(base::flat_map<SystemAppType, SystemAppInfo> system_apps); void SetUpdatePolicy(SystemWebAppManager::UpdatePolicy policy); void set_current_version(const base::Version& version) { current_version_ = version; } // SystemWebAppManager: const base::Version& CurrentVersion() const override; private: base::Version current_version_{"0.0.0.0"}; DISALLOW_COPY_AND_ASSIGN(TestSystemWebAppManager); }; } // namespace web_app #endif // CHROME_BROWSER_WEB_APPLICATIONS_TEST_TEST_SYSTEM_WEB_APP_MANAGER_H_
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
0f525144f5e68926e0163a89f013e59cecd21ed3
1ad60460a7c5b8cbf7b5a77746ac84274b0eed05
/cast_user.cpp
225944c6485c1474e70b745a725aa97186b70818
[]
no_license
ting2313/BallPool
e46c5632fe5a8a546ebde79653e5cf653a3e991d
d07ff004516a4fbd63ae36c37d096226e26feb18
refs/heads/master
2021-04-07T12:49:49.802766
2020-03-20T05:42:37
2020-03-20T05:42:37
248,677,033
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
#include"cast_user.h" #include"ball_enemy.h" #include"mainwindow.h" #include<QGraphicsScene> extern Score *score; extern Text *text; cast_user::cast_user() { hp=1; QTimer *timer= new QTimer(this); connect(timer, SIGNAL(timeout()),this, SLOT(hurt())); timer->start(50); } void cast_user::hurt() { QList<QGraphicsItem *> colliding_items = collidingItems(); for (int i = 0, n = colliding_items.size(); i < n; ++i) { if (typeid(*(colliding_items[i])) == typeid(ball_enemy)) { if(hp>0){ hp--; text->protect(); score->cost(50); } if(hp<=0){ return ; } } } }
[ "ting2313@gmail.com" ]
ting2313@gmail.com
dbcabe8a553c441a74c355e053b4cbaf87a10c9c
38bec23d83a79077f8a17d1b0089c59ac651e384
/gs-mirror-tree.cpp
bf0cad5ddafb80aa31d33c9f8ea812aedad5171b
[]
no_license
kwkwok1980/interview
bfc6c0566a96887f59e3c87f4aaf47c6ea3aa014
c21dc29c2e9cac3b122499082cfa05817de72807
refs/heads/master
2023-04-08T20:10:44.509183
2021-04-17T06:34:45
2021-04-17T06:34:45
61,633,244
0
0
null
null
null
null
UTF-8
C++
false
false
2,096
cpp
//https://practice.geeksforgeeks.org/problems/mirror-tree/1 { //Initial Template for C++ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; void mirror(struct Node* node); /* Helper function to test mirror(). Given a binary search tree, print out its data elements in increasing sorted order.*/ void inOrder(struct Node* node) { if (node == NULL) return; inOrder(node->left); printf("%d ", node->data); inOrder(node->right); } /* Driver program to test size function*/ int main() { int t; struct Node *child; scanf("%d ", &t); while (t--) { map<int, Node*> m; int n; scanf("%d",&n); struct Node *root = NULL; while (n--) { Node *parent; char lr; int n1, n2; scanf("%d %d %c", &n1, &n2, &lr); if (m.find(n1) == m.end()) { parent = new Node(n1); m[n1] = parent; if (root == NULL) root = parent; } else parent = m[n1]; child = new Node(n2); if (lr == 'L') parent->left = child; else parent->right = child; m[n2] = child; } mirror(root); inOrder(root); cout << endl; } return 0; } } /*This is a function problem.You only need to complete the function given below*/ //function Template for C++ /* A binary tree node has data, pointer to left child and a pointer to right child / struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; */ /* Should convert tree to its mirror */ void mirror(Node* node) { if (node == nullptr) { return; } mirror(node->right); mirror(node->left); std::swap(node->right, node->left); //node->right = left; //node->left = right; }
[ "noreply@github.com" ]
kwkwok1980.noreply@github.com