hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
597b4d6f08d110aee677c040bcc522ef9a6a829a
15,197
h
C
source/game/rules/GameRules.h
JasonHutton/QWTA
7f42dc70eb230cf69a8048fc98d647a486e752f1
[ "MIT" ]
2
2021-05-02T18:37:48.000Z
2021-07-18T16:18:14.000Z
source/game/rules/GameRules.h
JasonHutton/QWTA
7f42dc70eb230cf69a8048fc98d647a486e752f1
[ "MIT" ]
null
null
null
source/game/rules/GameRules.h
JasonHutton/QWTA
7f42dc70eb230cf69a8048fc98d647a486e752f1
[ "MIT" ]
null
null
null
// Copyright (C) 2007 Id Software, Inc. // #ifndef __GAME_RULES_GAMERULES_H__ #define __GAME_RULES_GAMERULES_H__ #include "../roles/Inventory.h" class sdTeamInfo; class idPlayer; class sdFireTeam; class sdCallVote; class sdGameRulesNetworkState : public sdEntityStateNetworkData { public: sdGameRulesNetworkState( void ) { ; } virtual void MakeDefault( void ); virtual void Write( idFile* file ) const; virtual void Read( idFile* file ); int pings[ MAX_CLIENTS ]; sdTeamInfo* teams[ MAX_CLIENTS ]; int userGroups[ MAX_CLIENTS ]; int state; int matchStartedTime; int nextStateSwitch; }; enum muteFlags_e { MF_CHAT = BITT< 0 >::VALUE, MF_AUDIO = BITT< 1 >::VALUE, }; enum readyState_e { RS_READY, RS_NOT_ENOUGH_CLIENTS, RS_NOT_ENOUGH_READY, }; /* ============ sdGameRules ============ */ class sdGameRules : public idClass { public: ABSTRACT_PROTOTYPE( sdGameRules ); struct fireTeamState_t { int fireTeamIndex; bool fireTeamLeader; bool fireTeamPublic; idStr fireTeamName; }; struct playerState_t { int ping; // player ping sdFireTeam* fireTeam; fireTeamState_t backupFireTeamState; // players fire team state qhandle_t userGroup; int muteStatus; int numWarnings; sdTeamInfo* backupTeam; sdPlayerClassSetup backupClass; }; typedef playerState_t playerStateList_t[ MAX_CLIENTS ]; // end game statistics struct teamMapData_t { idList< float > xp; }; struct mapData_t { idStr metaDataName; const sdDeclMapInfo* mapInfo; sdTeamInfo* winner; idList< teamMapData_t > teamData; bool written; }; // game state enum gameState_t { GS_INACTIVE = 0, // not running GS_WARMUP, // warming up GS_COUNTDOWN, // post warmup pre-game GS_GAMEON, // game is on GS_GAMEREVIEW, // game is over, scoreboard is up GS_NEXTGAME, GS_NEXTMAP, GS_STATE_COUNT, }; // report a simplified set of states // update PGS_NEXT_BIT below if more states are added! // the values must fit into a byte enum probeGameState_t { PGS_WARMUP = BITT< 0 >::VALUE, PGS_RUNNING = BITT< 1 >::VALUE, PGS_REVIEWING = BITT< 2 >::VALUE, PGS_LOADING = BITT< 3 >::VALUE, }; static const int PGS_NEXT_BIT = 4; enum chatMode_t { CHAT_MODE_DEFAULT = 0, CHAT_MODE_SAY, CHAT_MODE_SAY_TEAM, CHAT_MODE_SAY_FIRETEAM, CHAT_MODE_QUICK, CHAT_MODE_QUICK_TEAM, CHAT_MODE_QUICK_FIRETEAM, CHAT_MODE_MESSAGE, CHAT_MODE_OBITUARY, }; enum msgEvent_t { MSG_SUICIDE = 0, MSG_KILLED, MSG_KILLEDTEAM, MSG_DIED, MSG_COUNT }; enum shuffleMode_t { SM_XP = 0, SM_RANDOM, SM_SWAP, }; enum networkEvent_t { EVENT_CREATE = 0, EVENT_SETCAMERA, MAX_NET_EVENTS, }; typedef sdPair< int, idPlayer* > shuffleData_t; sdGameRules( void ); virtual ~sdGameRules( void ); // general virtual void Clear( void ); virtual void InitConsoleCommands( void ); virtual void InitVotes( void ); virtual void RemoveConsoleCommands( void ); virtual void DisconnectClient( int clientNum ); virtual void EnterGame( idPlayer* player ); virtual void WantKilled( idPlayer* player ); virtual void UpdateScoreboard( sdUIList* list, const char* teamName ); virtual void OnTeamChange( idPlayer* player, sdTeamInfo* oldteam, sdTeamInfo* team ); virtual void OnPlayerReady( idPlayer* player, bool ready ); void NewMap( bool isUserChange ); virtual void Shutdown( void ); virtual void Reset( void ); virtual void SpawnPlayer( idPlayer* player ); virtual void Run( void ); virtual void MapRestart( void ); virtual byte GetProbeState( void ) const; virtual int GetServerBrowserScore( const sdNetSession& session ) const; virtual void GetBrowserStatusString( idWStr& str, const sdNetSession& netSession ) const; virtual void OnNewScriptLoad( void ); virtual void OnLocalMapRestart( void ); virtual sdTeamInfo* GetWinningTeam( void ) const { return NULL; } virtual const sdDeclLocStr* GetWinningReason( void ) const { return NULL; } virtual int GetNumMaps( void ) const { return 0; } virtual const mapData_t* GetMapData( int index ) const { return NULL; } virtual const mapData_t* GetCurrentMapData() const { return NULL; } virtual void UpdateClientFromServerInfo( const idDict& serverInfo, bool allowMedia ); virtual bool InhibitEntitySpawn( idDict &spawnArgs ) const; virtual const char* GetKeySuffix( void ) const { return ""; } // chat virtual void ProcessChatMessage( idPlayer* player, gameReliableClientMessage_t mode, const wchar_t *text ); virtual void AddChatLine( chatMode_t chatMode, const idVec4& color, const wchar_t *fmt, ... ); virtual void AddChatLine( const idVec3& origin, chatMode_t chatMode, const int clientNum, const wchar_t *text ); virtual void AddRepeaterChatLine( const char* clientName, const int clientNum, const wchar_t *text ); virtual void MessageMode( const idCmdArgs &args ); virtual void WriteInitialReliableMessages( const sdReliableMessageClientInfoBase& target ); virtual bool HandleGuiEvent( const sdSysEvent* event ); virtual bool TranslateGuiBind( const idKey& key, sdKeyCommand** cmd ); virtual void ApplyNetworkState( const sdEntityStateNetworkData& newState ); virtual void ReadNetworkState( const sdEntityStateNetworkData& baseState, sdEntityStateNetworkData& newState, const idBitMsg& msg ) const; virtual void WriteNetworkState( const sdEntityStateNetworkData& baseState, sdEntityStateNetworkData& newState, idBitMsg& msg ) const; virtual bool CheckNetworkStateChanges( const sdEntityStateNetworkData& baseState ) const; virtual sdEntityStateNetworkData* CreateNetworkStructure( void ) const; virtual void EndGame( void ) = 0; virtual void SetWinner( sdTeamInfo* team ) = 0; virtual void SetAttacker( sdTeamInfo* team ) { } virtual void SetDefender( sdTeamInfo* team ) { } virtual userMapChangeResult_e OnUserStartMap( const char* text, idStr& reason, idStr& mapName ) = 0; virtual bool ChangeMap( const char* mapName ) { return false; } virtual void ReadCampaignInfo( const idBitMsg& msg ) { ; } virtual int GetGameTime( void ) const = 0; int GetNextStateTime( void ) { return nextStateSwitch; } void SetClientTeam( idPlayer* player, int index, bool force, const char* password ); static bool IsRuleType( const idTypeInfo& type ); const wchar_t* GetStatusText() const; virtual const sdDeclLocStr* GetTypeText( void ) const = 0; idEntity* GetEndGameCamera( void ) const { return endGameCamera; } void SetPlayerFireTeam( int clientNum, sdFireTeam* fireTeam ); sdFireTeam* GetPlayerFireTeam( int clientNum ) const { return playerState[ clientNum ].fireTeam; } void SetPlayerUserGroup( int clientNum, qhandle_t handle ) { playerState[ clientNum ].userGroup = handle; } qhandle_t GetPlayerUserGroup( int clientNum ) const { return playerState[ clientNum ].userGroup; } bool IsGameOn( void ) const { return gameState == GS_GAMEON; } bool IsWarmup( void ) const { return gameState == GS_WARMUP || gameState == GS_COUNTDOWN; } bool IsCountDown( void ) const { return gameState == GS_COUNTDOWN; } bool IsEndGame( void ) const { return gameState == GS_GAMEREVIEW; } bool IsPureReady( void ) const { return pureReady; } void BackupPlayerTeams( void ); void RestoreFireTeam( idPlayer* player ); virtual void OnScriptChange( void ); virtual void OnConnect( idPlayer* player ); virtual void OnNetworkEvent( const char* message ); virtual void OnObjectiveCompletion( int objectiveIndex ) {} void Event_SendNetworkEvent( int clientIndex, bool isRepeaterClient, const char* message ); void Event_SetEndGameCamera( idEntity* other ); void Event_SetWinningTeam( idScriptObject* object ); void Event_GetBeginObjective( void ); void Event_GetEndObjective( void ); void Event_EndGame( void ); void Event_GetKeySuffix( void ); int MuteStatus( idPlayer* player ) const; void Mute( idPlayer* player, int flags ); void UnMute( idPlayer* player, int flags ); void Warn( idPlayer* player ); void AdminStart( void ) { adminStarted = true; } void ShuffleTeams( shuffleMode_t sm ); static int SortPlayers_Random( const shuffleData_t* a, const shuffleData_t* b ); static int SortPlayers_XP( const shuffleData_t* a, const shuffleData_t* b ); gameState_t GetState( void ) const { return gameState; } static int TeamIndexForName( const char* teamname ); bool CanStartMatch( void ) const; void StartMatch( void ); void ClearPlayerReadyFlags( void ) const; void SavePlayerStates( playerStateList_t& states ); void RestorePlayerStates( const playerStateList_t& states ); const idList< sdCallVote* >& GetCallVotes( void ) const { return callVotes; } virtual void OnTimeLimitHit( void ); virtual int GetTimeLimit( void ) const; static int GetWarmupTime( void ); static readyState_e ArePlayersReady( bool readyIfNoPlayers = true, bool checkMin = false, int* numRequired = NULL ); static idCVar g_chatDefaultColor; static idCVar g_chatTeamColor; static idCVar g_chatFireTeamColor; static idCVar g_chatLineTimeout; static void ArgCompletion_RuleTypes( const idCmdArgs &args, void( *callback )( const char *s ) ); virtual void ArgCompletion_StartGame( const idCmdArgs& args, argCompletionCallback_t callback ) = 0; static bool ParseNetworkMessage( const idBitMsg& msg ); virtual bool ParseNetworkMessage( int msgType, const idBitMsg& msg ); sdTeamInfo* FindNeedyTeam( idPlayer* ignore = NULL ); const sdDeclPlayerClass* FindNeedyClassOnTeam( sdTeamInfo* team = NULL, idPlayer* ignore = NULL ); virtual const char* GetDemoNameInfo( void ) = 0; static int GetRoleLimitForTeam( playerClassTypes_t role, playerTeamTypes_t team ); protected: void NextStateDelayed( gameState_t state, int delay ); void NewState( gameState_t news ); void ClearChatData( void ); void CheckRespawns( bool force = false ); static int NumActualClients( bool countSpectators, bool countBots = false ); void UpdateChatLines(); void SendCameraEvent( idEntity* entity, const sdReliableMessageClientInfoBase& target ); void CallScriptEndGame( void ); static void RecordWinningTeam( sdTeamInfo* winner, const char* prefix, bool includeTeamName ); static void SetupLoadScreenUI( sdUserInterfaceScope& scope, const char* status, bool currentMap, int mapIndex, const idDict& metaData, const sdDeclMapInfo* mapInfo ); void SetWarmupStatusMessage(); static int NumReady( int& total ); protected: virtual void GameState_Review( void ) = 0; virtual void GameState_NextGame( void ) = 0; virtual void GameState_Warmup( void ) = 0; virtual void GameState_Countdown( void ) = 0; virtual void GameState_GameOn( void ) = 0; virtual void GameState_NextMap( void ) = 0; virtual void OnGameState_Review( void ) = 0; virtual void OnGameState_Warmup( void ); virtual void OnGameState_Countdown( void ) = 0; virtual void OnGameState_GameOn( void ) = 0; virtual void OnGameState_NextMap( void ) = 0; private: // commands static void MessageMode_f( const idCmdArgs &args ); static void QuickChat_f( const idCmdArgs& args ); static void SetTeam_f( const idCmdArgs &args ); static void SetClass_f( const idCmdArgs &args ); static void DefaultSpawn_f( const idCmdArgs &args ); static void WantSpawn_f( const idCmdArgs &args ); static void CreateChatList( sdUIList* list ); static int InsertScoreboardPlayer( sdUIList* list, const idPlayer* player, const sdFireTeam* fireTeam, const playerState_t& ps, const wchar_t* noMissionText, bool showClass, float& averagePing, float& averageXP, int& numInGamePlayers, int index ); protected: class sdChatLine { public: typedef idLinkList< sdChatLine > node_t; public: sdChatLine() : time( 0 ), color( colorWhite ), text( L"" ) { flags.expired = false; flags.team = false; flags.obituary = false; node.SetOwner( this ); } void Set( const wchar_t* text, chatMode_t mode ); bool IsExpired() const { return flags.expired; } bool IsTeam() const { return flags.team; } bool IsObituary() const { return flags.obituary; } void CheckExpired() { flags.expired = ( gameLocal.ToGuiTime( gameLocal.time ) - time ) >= SEC2MS( g_chatLineTimeout.GetFloat() ); } const idVec4& GetColor() const { return color; } const wchar_t* GetText() const { return text.c_str(); } node_t& GetNode() { return node; } const node_t& GetNode() const { return node; } int GetTime() const { return time; } private: struct flags_t { bool expired : 1; bool team : 1; bool obituary : 1; } flags; int time; idVec4 color; idWStr text; node_t node; }; protected: gameState_t gameState; // what state the current game is in gameState_t nextState; // state to switch to when nextStateSwitch is hit int pingUpdateTime; // time to update ping playerStateList_t playerState; idScriptObject* scriptObject; idEntityPtr< idEntity > endGameCamera; // time related int nextStateSwitch; // time next state switch int lastStateSwitchTime; int matchStartedTime; // time current match started bool needsRestart; bool adminStarted; bool pureReady; // defaults to false, set to true once server game is running with pure checksums bool commandsAdded; mutable int autoReadyStartTime; // static const char * gameStateStrings[ GS_STATE_COUNT ]; static const int MAX_CHAT_LINES = 128; idStaticList< sdChatLine, MAX_CHAT_LINES > chatLines; sdChatLine::node_t chatHead; sdChatLine::node_t chatFree; idList< sdCallVote* > callVotes; idWStr statusText; const sdDeclLocStr* noMission; const sdDeclLocStr* infinity; }; // Encapsulate some common behaviour for game types that manage a single map class sdGameRules_SingleMapHelper { public: static void ArgCompletion_StartGame( const idCmdArgs& args, argCompletionCallback_t callback ); static userMapChangeResult_e OnUserStartMap( const char* text, idStr& reason, idStr& mapName ); static void SanitizeMapName( idStr& mapName, bool setExtension ); }; #endif /* !__GAME_RULES_GAMERULES_H__ */
34.150562
172
0.683885
[ "object" ]
5984700c4f38177045aac10f10d5afa030d961c1
345
h
C
Source/URoboSim/Classes/ROSCommunication/Actions/PerceiveObjectAction/POAServer.h
K4R-IAI/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
1
2021-04-11T13:03:58.000Z
2021-04-11T13:03:58.000Z
Source/URoboSim/Classes/ROSCommunication/Actions/PerceiveObjectAction/POAServer.h
artnie/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
null
null
null
Source/URoboSim/Classes/ROSCommunication/Actions/PerceiveObjectAction/POAServer.h
artnie/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "ROSCommunication/Actions/RActionServer.h" #include "POAServer.generated.h" UCLASS(Blueprintable, DefaultToInstanced, collapsecategories, hidecategories = Object, editinlinenew) class UROBOSIM_API URPerceiveObjectActionServer : public URActionServer { GENERATED_BODY() public: URPerceiveObjectActionServer(); };
21.5625
101
0.814493
[ "object" ]
5988dd124634117c5a842832f9aadd9d6fed28f3
8,594
c
C
src/simple_seccomp.c
Leo1003/cjail
8c6f5fa6082514200a8e25258bd37c2d949d5b7f
[ "MIT" ]
7
2018-02-17T05:03:42.000Z
2021-01-11T03:45:13.000Z
src/simple_seccomp.c
Leo1003/cjail
8c6f5fa6082514200a8e25258bd37c2d949d5b7f
[ "MIT" ]
1
2018-12-16T06:55:53.000Z
2018-12-26T06:44:28.000Z
src/simple_seccomp.c
Leo1003/cjail
8c6f5fa6082514200a8e25258bd37c2d949d5b7f
[ "MIT" ]
2
2018-04-10T13:32:45.000Z
2019-09-08T10:03:24.000Z
/** * @internal * @file simple_seccomp.c * @brief basic seccomp rules source */ #include "simple_seccomp.h" #include "logger.h" #include "utils.h" #include <errno.h> #include <linux/filter.h> #include <linux/memfd.h> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> #include <seccomp.h> void default_cb(pid_t pid, unsigned long data, struct user_regs_struct *regs) { char *str = seccomp_syscall_resolve_num_arch(seccomp_arch_native(), regs->orig_rax); if (str) { infof("Process %d: triggered systemcall: %lld %s\n", pid, regs->orig_rax, str); } else { infof("Process %d: triggered systemcall: %lld\n", pid, regs->orig_rax); } free(str); } static int rule_compile_add(scmp_filter_ctx ctx, uint32_t denycode, const struct seccomp_rule rule) { struct scmp_arg_cmp args[6]; int args_cnt = 0; uint32_t action = denycode; if (rule.type == RULE_ALLOW) { action = SCMP_ACT_ALLOW; } for (int i = 0; i < 6; i++) { if (rule.args[i].cmp == CMP_NONE) { continue; } switch (rule.args[i].cmp) { case CMP_NONE: continue; case CMP_EQ: args[args_cnt].op = SCMP_CMP_EQ; break; case CMP_NE: args[args_cnt].op = SCMP_CMP_NE; break; case CMP_GT: args[args_cnt].op = SCMP_CMP_GT; break; case CMP_GE: args[args_cnt].op = SCMP_CMP_GE; break; case CMP_LT: args[args_cnt].op = SCMP_CMP_LT; break; case CMP_LE: args[args_cnt].op = SCMP_CMP_LE; break; case CMP_MASK: args[args_cnt].op = SCMP_CMP_MASKED_EQ; break; default: errno = EINVAL; return -1; } args[args_cnt].arg = i; if (rule.args[i].cmp == CMP_MASK) { args[args_cnt].datum_a = rule.args[i].mask; args[args_cnt].datum_b = rule.args[i].value; } else { args[args_cnt].datum_a = rule.args[i].value; } args_cnt++; } devf("action: 0x%08x; syscall: %3d; args_cnt: %2d\n", action, rule.syscall, args_cnt); int ret = seccomp_rule_add_array(ctx, action, rule.syscall, args_cnt, args); if (ret < 0) { errno = -ret; return -1; } return 0; } int scconfig_compile(const struct seccomp_config *cfg, struct sock_fprog *bpf) { if (!cfg) { errno = EINVAL; return -1; } scmp_filter_ctx ctx; uint32_t denycode = 0; switch (cfg->deny_action) { case DENY_KILL: denycode = SCMP_ACT_KILL; break; case DENY_TRAP: denycode = SCMP_ACT_TRAP; break; case DENY_ERRNO: denycode = SCMP_ACT_ERRNO(ENOSYS); break; case DENY_TRACE: denycode = SCMP_ACT_TRACE(TRACE_MAGIC); break; case DENY_TRACE_KILL: denycode = SCMP_ACT_TRACE(TRACE_KILL_MAGIC); break; } if (cfg->type == CFG_BLACKLIST) { ctx = seccomp_init(SCMP_ACT_ALLOW); } else { ctx = seccomp_init(denycode); } if (!ctx) { PFTL("init context"); goto error; } for (unsigned i = 0; i < cfg->rules_count; i++) { if ((cfg->rules[i].type == RULE_DENY && cfg->type == CFG_WHITELIST) || (cfg->rules[i].type == RULE_ALLOW && cfg->type == CFG_BLACKLIST)) { continue; } if (rule_compile_add(ctx, denycode, cfg->rules[i])) { PFTL("add rules"); goto error; } } // compile libseccomp rule to bpf program // libseccomp only accept fd, so we use memfd to generate bpf program int memfd = syscall(__NR_memfd_create, "", MFD_CLOEXEC | MFD_ALLOW_SEALING); if (memfd < 0) { PFTL("create memfd"); goto error; } seccomp_export_bpf(ctx, memfd); size_t bpf_size = lseek(memfd, 0, SEEK_END); if (bpf_size < 0) { PFTL("get memory file size"); goto error_memfd; } bpf->len = bpf_size / sizeof(struct sock_filter); bpf->filter = mmap(NULL, bpf_size, PROT_READ, MAP_PRIVATE, memfd, 0); if (bpf->filter == MAP_FAILED) { PFTL("mmap memfd"); goto error_memfd; } seccomp_release(ctx); close(memfd); return 0; error_memfd: close(memfd); error: PFTL("compile seccomp config"); seccomp_release(ctx); return -1; } struct seccomp_config *scconfig_init() { struct seccomp_config *cfg = malloc(sizeof(struct seccomp_config)); if (cfg == NULL) { PFTL("malloc memory"); return NULL; } cfg->type = CFG_WHITELIST; cfg->deny_action = DENY_KILL; cfg->rules_count = 0; cfg->rules_alloc = SC_ALLOC_BASE; cfg->callback = NULL; cfg->rules = malloc(SC_ALLOC_BASE * sizeof(struct seccomp_rule)); if (cfg->rules == NULL) { PFTL("malloc memory"); free(cfg); return NULL; } return cfg; } enum deny_method scconfig_get_deny(const struct seccomp_config *cfg) { if (!cfg) { errno = EINVAL; return 0; } return cfg->deny_action; } void scconfig_set_deny(struct seccomp_config *cfg, enum deny_method deny) { if (!cfg) { errno = EINVAL; return; } cfg->deny_action = deny; } enum config_type scconfig_get_type(const struct seccomp_config *cfg) { if (!cfg) { errno = EINVAL; return 0; } return cfg->type; } void scconfig_set_type(struct seccomp_config *cfg, enum config_type type) { if (!cfg) { errno = EINVAL; return; } cfg->type = type; } seccomp_cb scconfig_get_callback(const struct seccomp_config *cfg) { if (!cfg) { errno = EINVAL; return NULL; } return (cfg->callback ? cfg->callback : default_cb); } void scconfig_set_callback(struct seccomp_config *cfg, seccomp_cb callback) { if (!cfg) { errno = EINVAL; return; } cfg->callback = callback; } void scconfig_reset_callback(struct seccomp_config *cfg) { if (!cfg) { errno = EINVAL; return; } cfg->callback = NULL; } int scconfig_clear(struct seccomp_config *cfg) { if (!cfg) { errno = EINVAL; return -1; } memset(cfg->rules, 0, sizeof(struct seccomp_rule) * cfg->rules_count); cfg->rules_count = 0; return 0; } int scconfig_add(struct seccomp_config *cfg, const struct seccomp_rule *rules, size_t len) { if (!cfg) { errno = EINVAL; return -1; } if (len == 0) { return 0; } while (cfg->rules_alloc < cfg->rules_count + len) { size_t new_alloc = max(cfg->rules_alloc * 2, cfg->rules_count + len + SC_ALLOC_BASE); if (scconfig_allocate(cfg, new_alloc)) return -1; } memcpy(cfg->rules + cfg->rules_count, rules, len * sizeof(struct seccomp_rule)); cfg->rules_count += len; return 0; } int scconfig_remove(struct seccomp_config *cfg, size_t i, size_t len) { if (!cfg) { errno = EINVAL; return -1; } if (i + len > cfg->rules_count) { errno = EFAULT; return -1; } if (len == 0) { return 0; } memmove(cfg->rules + i, cfg->rules + (i + len), (cfg->rules_count - (i + len)) * sizeof(struct seccomp_rule)); cfg->rules_count -= len; return 0; } struct seccomp_rule *scconfig_get_rule(struct seccomp_config *cfg, size_t i) { if (!cfg) { errno = EINVAL; return NULL; } if (i >= cfg->rules_count) { return NULL; } return &cfg->rules[i]; } size_t scconfig_len(const struct seccomp_config *cfg) { if (!cfg) { errno = EINVAL; return 0; } return cfg->rules_count; } int scconfig_allocate(struct seccomp_config *cfg, size_t len) { if (!cfg) { errno = EINVAL; return -1; } if (len <= cfg->rules_alloc) { return 0; } struct seccomp_rule *tmp = (struct seccomp_rule *)realloc(cfg->rules, len * sizeof(struct seccomp_rule)); if (tmp == NULL) { PFTL("realloc memory"); return -1; } cfg->rules_alloc = len; cfg->rules = tmp; return 0; } void scconfig_free(struct seccomp_config *cfg) { if (!cfg) { return; } if (cfg->rules) { free(cfg->rules); cfg->rules = NULL; } free(cfg); }
24.624642
114
0.564231
[ "3d" ]
598ee43325c503bd4df63ef078ab79d20129a986
1,305
h
C
WinDBG/Exts/CodeAnalyzer/gdbplus/gdb-7.7/gdb/stl_container.h
QuincyWork/DebugExt
95fbd81aad609ed41853b5d25129d2385f5593b2
[ "MIT" ]
1
2019-01-15T14:36:41.000Z
2019-01-15T14:36:41.000Z
WinDBG/Exts/CodeAnalyzer/gdbplus/gdb-1824/src/gdb/stl_container.h
QuincyWork/DebugExt
95fbd81aad609ed41853b5d25129d2385f5593b2
[ "MIT" ]
null
null
null
WinDBG/Exts/CodeAnalyzer/gdbplus/gdb-1824/src/gdb/stl_container.h
QuincyWork/DebugExt
95fbd81aad609ed41853b5d25129d2385f5593b2
[ "MIT" ]
1
2019-01-15T14:36:42.000Z
2019-01-15T14:36:42.000Z
/* * stl_container.h * A wrapper of stl tree/vector/list etc. because gdb is a c program */ #ifndef _STL_CONTAINER_H #define _STL_CONTAINER_H #include "x_type.h" struct CA_SET; struct CA_LIST; #ifdef _SPLAY_TREE_H #define CA_USE_SPLAY_TREE #endif #ifdef CA_USE_SPLAY_TREE typedef int (*CA_CompareFunctionType) (splay_tree_key, splay_tree_key); CA_BOOL ca_set_insert_key_and_val(struct CA_SET* iset, void* key, void* val); #else typedef CA_BOOL (*CA_CompareFunctionType)(void *, void *); CA_BOOL ca_set_insert(struct CA_SET*, void*); #endif struct CA_SET* ca_set_new(CA_CompareFunctionType comp); void ca_set_delete(struct CA_SET*); void* ca_set_find(struct CA_SET*, void*); void ca_set_clear(struct CA_SET*); void ca_set_traverse_start(struct CA_SET*); void* ca_set_traverse_next(struct CA_SET*); void ca_list_traverse_start(struct CA_LIST*); void* ca_list_traverse_next(struct CA_LIST*); void* ca_list_find(struct CA_LIST*, void*); void ca_list_clear(struct CA_LIST*); void ca_list_push_front(struct CA_LIST*, void*); void ca_list_push_back(struct CA_LIST*, void*); void* ca_list_pop_front(struct CA_LIST*); struct CA_LIST* ca_list_new(void); void ca_list_delete(struct CA_LIST*); CA_BOOL ca_list_empty(struct CA_LIST*); size_t ca_list_size(struct CA_LIST*); #endif // _STL_CONTAINER_H
29
77
0.790038
[ "vector" ]
599202186ec69d5c75b1350ed80292404a4f1320
9,086
h
C
vtkm/exec/BoundaryState.h
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
1
2021-07-21T07:15:44.000Z
2021-07-21T07:15:44.000Z
vtkm/exec/BoundaryState.h
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
null
null
null
vtkm/exec/BoundaryState.h
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
2
2020-07-06T06:32:00.000Z
2020-08-24T14:08:15.000Z
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #ifndef vtk_m_exec_BoundaryState_h #define vtk_m_exec_BoundaryState_h #include <vtkm/Assert.h> #include <vtkm/Math.h> namespace vtkm { namespace exec { /// \brief Provides a neighborhood's placement with respect to the mesh's boundary. /// /// \c BoundaryState provides functionality for \c WorkletPointNeighborhood algorithms and Fetch's /// to determine if they are operating on a point near the boundary. It allows you to query about /// overlaps of the neighborhood and the mesh boundary. It also helps convert local neighborhood /// ids to the corresponding location in the mesh. /// /// This class is typically constructed using the \c Boundary tag in an \c ExecutionSignature. /// There is little reason to construct this in user code. /// struct BoundaryState { VTKM_EXEC BoundaryState(const vtkm::Id3& ijk, const vtkm::Id3& pdims) : IJK(ijk) , PointDimensions(pdims) { } //@{ /// Returns true if a neighborhood of the given radius is contained within the bounds of the cell /// set in the X, Y, or Z direction. Returns false if the neighborhood extends outside of the /// boundary of the data in the X, Y, or Z direction. /// /// The radius defines the size of the neighborhood in terms of how far away it extends from the /// center. So if there is a radius of 1, the neighborhood extends 1 unit away from the center in /// each direction and is 3x3x3. If there is a radius of 2, the neighborhood extends 2 units for /// a size of 5x5x5. /// VTKM_EXEC bool IsRadiusInXBoundary(vtkm::IdComponent radius) const { VTKM_ASSERT(radius >= 0); return (((this->IJK[0] - radius) >= 0) && ((this->IJK[0] + radius) < this->PointDimensions[0])); } VTKM_EXEC bool IsRadiusInYBoundary(vtkm::IdComponent radius) const { VTKM_ASSERT(radius >= 0); return (((this->IJK[1] - radius) >= 0) && ((this->IJK[1] + radius) < this->PointDimensions[1])); } VTKM_EXEC bool IsRadiusInZBoundary(vtkm::IdComponent radius) const { VTKM_ASSERT(radius >= 0); return (((this->IJK[2] - radius) >= 0) && ((this->IJK[2] + radius) < this->PointDimensions[2])); } //@} /// Returns true if a neighborhood of the given radius is contained within the bounds /// of the cell set. Returns false if the neighborhood extends outside of the boundary of the /// data. /// /// The radius defines the size of the neighborhood in terms of how far away it extends from the /// center. So if there is a radius of 1, the neighborhood extends 1 unit away from the center in /// each direction and is 3x3x3. If there is a radius of 2, the neighborhood extends 2 units for /// a size of 5x5x5. /// VTKM_EXEC bool IsRadiusInBoundary(vtkm::IdComponent radius) const { return this->IsRadiusInXBoundary(radius) && this->IsRadiusInYBoundary(radius) && this->IsRadiusInZBoundary(radius); } //@{ /// Returns true if the neighbor at the specified @a offset is contained /// within the bounds of the cell set in the X, Y, or Z direction. Returns /// false if the neighbor falls outside of the boundary of the data in the X, /// Y, or Z direction. /// VTKM_EXEC bool IsNeighborInXBoundary(vtkm::IdComponent offset) const { return (((this->IJK[0] + offset) >= 0) && ((this->IJK[0] + offset) < this->PointDimensions[0])); } VTKM_EXEC bool IsNeighborInYBoundary(vtkm::IdComponent offset) const { return (((this->IJK[1] + offset) >= 0) && ((this->IJK[1] + offset) < this->PointDimensions[1])); } VTKM_EXEC bool IsNeighborInZBoundary(vtkm::IdComponent offset) const { return (((this->IJK[2] + offset) >= 0) && ((this->IJK[2] + offset) < this->PointDimensions[2])); } //@} /// Returns true if the neighbor at the specified offset vector is contained /// within the bounds of the cell set. Returns false if the neighbor falls /// outside of the boundary of the data. /// VTKM_EXEC bool IsNeighborInBoundary(const vtkm::IdComponent3& neighbor) const { return this->IsNeighborInXBoundary(neighbor[0]) && this->IsNeighborInYBoundary(neighbor[1]) && this->IsNeighborInZBoundary(neighbor[2]); } /// Returns the minimum neighborhood indices that are within the bounds of the data. /// VTKM_EXEC vtkm::IdComponent3 MinNeighborIndices(vtkm::IdComponent radius) const { VTKM_ASSERT(radius >= 0); vtkm::IdComponent3 minIndices; for (vtkm::IdComponent component = 0; component < 3; ++component) { if (this->IJK[component] >= radius) { minIndices[component] = -radius; } else { minIndices[component] = static_cast<vtkm::IdComponent>(-this->IJK[component]); } } return minIndices; } /// Returns the minimum neighborhood indices that are within the bounds of the data. /// VTKM_EXEC vtkm::IdComponent3 MaxNeighborIndices(vtkm::IdComponent radius) const { VTKM_ASSERT(radius >= 0); vtkm::IdComponent3 maxIndices; for (vtkm::IdComponent component = 0; component < 3; ++component) { if ((this->PointDimensions[component] - this->IJK[component] - 1) >= radius) { maxIndices[component] = radius; } else { maxIndices[component] = static_cast<vtkm::IdComponent>(this->PointDimensions[component] - this->IJK[component] - 1); } } return maxIndices; } //@{ /// Takes a local neighborhood index (in the ranges of -neighborhood size to neighborhood size) /// and returns the ijk of the equivalent point in the full data set. If the given value is out /// of range, the value is clamped to the nearest boundary. For example, if given a neighbor /// index that is past the minimum x range of the data, the index at the minimum x boundary is /// returned. /// VTKM_EXEC vtkm::Id3 NeighborIndexToFullIndexClamp(const vtkm::IdComponent3& neighbor) const { vtkm::Id3 fullIndex = this->IJK + neighbor; return vtkm::Max(vtkm::Id3(0), vtkm::Min(this->PointDimensions - vtkm::Id3(1), fullIndex)); } VTKM_EXEC vtkm::Id3 NeighborIndexToFullIndexClamp(vtkm::IdComponent neighborI, vtkm::IdComponent neighborJ, vtkm::IdComponent neighborK) const { return this->NeighborIndexToFullIndexClamp(vtkm::make_Vec(neighborI, neighborJ, neighborK)); } //@} //@{ /// Takes a local neighborhood index (in the ranges of -neighborhood size to /// neighborhood size), clamps it to the dataset bounds, and returns a new /// neighborhood index. For example, if given a neighbor index that is past /// the minimum x range of the data, the neighbor index of the minimum x /// boundary is returned. /// VTKM_EXEC vtkm::IdComponent3 ClampNeighborIndex(const vtkm::IdComponent3& neighbor) const { const vtkm::Id3 fullIndex = this->IJK + neighbor; const vtkm::Id3 clampedFullIndex = vtkm::Max(vtkm::Id3(0), vtkm::Min(this->PointDimensions - vtkm::Id3(1), fullIndex)); return vtkm::IdComponent3{ clampedFullIndex - this->IJK }; } VTKM_EXEC vtkm::IdComponent3 ClampNeighborIndex(vtkm::IdComponent neighborI, vtkm::IdComponent neighborJ, vtkm::IdComponent neighborK) const { return this->ClampNeighborIndex(vtkm::make_Vec(neighborI, neighborJ, neighborK)); } //@} //@{ /// Takes a local neighborhood index (in the ranges of -neighborhood size to neighborhood size) /// and returns the flat index of the equivalent point in the full data set. If the given value /// is out of range, the value is clamped to the nearest boundary. For example, if given a /// neighbor index that is past the minimum x range of the data, the index at the minimum x /// boundary is returned. /// VTKM_EXEC vtkm::Id NeighborIndexToFlatIndexClamp(const vtkm::IdComponent3& neighbor) const { vtkm::Id3 full = this->NeighborIndexToFullIndexClamp(neighbor); return (full[2] * this->PointDimensions[1] + full[1]) * this->PointDimensions[0] + full[0]; } VTKM_EXEC vtkm::Id NeighborIndexToFlatIndexClamp(vtkm::IdComponent neighborI, vtkm::IdComponent neighborJ, vtkm::IdComponent neighborK) const { return this->NeighborIndexToFlatIndexClamp(vtkm::make_Vec(neighborI, neighborJ, neighborK)); } //@} vtkm::Id3 IJK; vtkm::Id3 PointDimensions; }; } } // namespace vtkm::exec #endif //vtk_m_exec_BoundaryState_h
39.333333
100
0.657715
[ "mesh", "vector" ]
59ab83ef864ed88fad8b78dc279fd30d9c399c22
103,819
c
C
tools-src/gnu/binutils/binutils/rcparse.c
enfoTek/tomato.linksys.e2000.nvram-mod
2ce3a5217def49d6df7348522e2bfda702b56029
[ "FSFAP" ]
80
2015-01-02T10:14:04.000Z
2021-06-07T06:29:49.000Z
tools-src/gnu/binutils/binutils/rcparse.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
9
2015-05-14T11:03:12.000Z
2018-01-04T07:12:58.000Z
tools-src/gnu/binutils/binutils/rcparse.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
69
2015-01-02T10:45:56.000Z
2021-09-06T07:52:13.000Z
/* A Bison parser, made from rcparse.y by GNU bison 1.35. */ #define YYBISON 1 /* Identify Bison output. */ # define BEG 257 # define END 258 # define ACCELERATORS 259 # define VIRTKEY 260 # define ASCII 261 # define NOINVERT 262 # define SHIFT 263 # define CONTROL 264 # define ALT 265 # define BITMAP 266 # define CURSOR 267 # define DIALOG 268 # define DIALOGEX 269 # define EXSTYLE 270 # define CAPTION 271 # define CLASS 272 # define STYLE 273 # define AUTO3STATE 274 # define AUTOCHECKBOX 275 # define AUTORADIOBUTTON 276 # define CHECKBOX 277 # define COMBOBOX 278 # define CTEXT 279 # define DEFPUSHBUTTON 280 # define EDITTEXT 281 # define GROUPBOX 282 # define LISTBOX 283 # define LTEXT 284 # define PUSHBOX 285 # define PUSHBUTTON 286 # define RADIOBUTTON 287 # define RTEXT 288 # define SCROLLBAR 289 # define STATE3 290 # define USERBUTTON 291 # define BEDIT 292 # define HEDIT 293 # define IEDIT 294 # define FONT 295 # define ICON 296 # define LANGUAGE 297 # define CHARACTERISTICS 298 # define VERSIONK 299 # define MENU 300 # define MENUEX 301 # define MENUITEM 302 # define SEPARATOR 303 # define POPUP 304 # define CHECKED 305 # define GRAYED 306 # define HELP 307 # define INACTIVE 308 # define MENUBARBREAK 309 # define MENUBREAK 310 # define MESSAGETABLE 311 # define RCDATA 312 # define STRINGTABLE 313 # define VERSIONINFO 314 # define FILEVERSION 315 # define PRODUCTVERSION 316 # define FILEFLAGSMASK 317 # define FILEFLAGS 318 # define FILEOS 319 # define FILETYPE 320 # define FILESUBTYPE 321 # define BLOCKSTRINGFILEINFO 322 # define BLOCKVARFILEINFO 323 # define VALUE 324 # define BLOCK 325 # define MOVEABLE 326 # define FIXED 327 # define PURE 328 # define IMPURE 329 # define PRELOAD 330 # define LOADONCALL 331 # define DISCARDABLE 332 # define NOT 333 # define QUOTEDSTRING 334 # define STRING 335 # define NUMBER 336 # define SIZEDSTRING 337 # define IGNORED_TOKEN 338 # define NEG 339 #line 1 "rcparse.y" /* rcparse.y -- parser for Windows rc files Copyright 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. Written by Ian Lance Taylor, Cygnus Support. This file is part of GNU Binutils. 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. */ /* This is a parser for Windows rc files. It is based on the parser by Gunther Ebert <gunther.ebert@ixos-leipzig.de>. */ #include "bfd.h" #include "bucomm.h" #include "libiberty.h" #include "windres.h" #include "safe-ctype.h" /* The current language. */ static unsigned short language; /* The resource information during a sub statement. */ static struct res_res_info sub_res_info; /* Dialog information. This is built by the nonterminals styles and controls. */ static struct dialog dialog; /* This is used when building a style. It is modified by the nonterminal styleexpr. */ static unsigned long style; /* These are used when building a control. They are set before using control_params. */ static unsigned long base_style; static unsigned long default_style; static unsigned long class; #line 58 "rcparse.y" #ifndef YYSTYPE typedef union { struct accelerator acc; struct accelerator *pacc; struct dialog_control *dialog_control; struct menuitem *menuitem; struct { struct rcdata_item *first; struct rcdata_item *last; } rcdata; struct rcdata_item *rcdata_item; struct stringtable_data *stringtable; struct fixed_versioninfo *fixver; struct ver_info *verinfo; struct ver_stringinfo *verstring; struct ver_varinfo *vervar; struct res_id id; struct res_res_info res_info; struct { unsigned short on; unsigned short off; } memflags; struct { unsigned long val; /* Nonzero if this number was explicitly specified as long. */ int dword; } i; unsigned long il; unsigned short is; const char *s; struct { unsigned long length; const char *s; } ss; } yystype; # define YYSTYPE yystype # define YYSTYPE_IS_TRIVIAL 1 #endif #ifndef YYDEBUG # define YYDEBUG 0 #endif #define YYFINAL 483 #define YYFLAG -32768 #define YYNTBASE 99 /* YYTRANSLATE(YYLEX) -- Bison token number corresponding to YYLEX. */ #define YYTRANSLATE(x) ((unsigned)(x) <= 339 ? yytranslate[x] : 189) /* YYTRANSLATE[YYLEX] -- Bison token number corresponding to YYLEX. */ static const char yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 92, 87, 2, 97, 98, 90, 88, 95, 89, 2, 91, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 96, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 86, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 85, 2, 93, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 94 }; #if YYDEBUG static const short yyprhs[] = { 0, 0, 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 53, 54, 57, 60, 65, 67, 69, 71, 75, 78, 80, 82, 84, 86, 88, 90, 95, 100, 101, 115, 116, 130, 131, 146, 147, 151, 152, 156, 160, 164, 168, 172, 178, 185, 193, 202, 206, 210, 215, 219, 220, 223, 224, 228, 229, 233, 234, 238, 239, 243, 244, 248, 249, 253, 265, 278, 291, 305, 306, 310, 311, 315, 316, 320, 321, 325, 326, 330, 337, 346, 357, 369, 370, 374, 375, 379, 380, 384, 385, 389, 390, 394, 395, 399, 400, 404, 405, 409, 410, 414, 415, 432, 440, 450, 461, 462, 464, 467, 468, 472, 473, 477, 478, 482, 483, 487, 492, 497, 501, 508, 509, 512, 517, 520, 527, 528, 532, 535, 537, 539, 541, 543, 545, 547, 554, 555, 558, 561, 565, 571, 574, 580, 587, 595, 605, 610, 617, 618, 621, 622, 624, 626, 628, 632, 636, 637, 644, 645, 649, 654, 661, 666, 673, 674, 681, 688, 692, 696, 700, 704, 708, 709, 718, 726, 727, 733, 734, 738, 740, 742, 744, 747, 750, 753, 755, 756, 759, 763, 768, 772, 773, 776, 777, 780, 782, 784, 786, 788, 790, 792, 794, 796, 798, 800, 803, 807, 812, 814, 818, 819, 821, 824, 826, 828, 832, 835, 838, 842, 846, 850, 854, 858, 862, 866, 870, 873, 875, 877, 881, 884, 888, 892, 896, 900, 904, 908, 912 }; static const short yyrhs[] = { -1, 99, 100, 0, 99, 106, 0, 99, 107, 0, 99, 108, 0, 99, 146, 0, 99, 147, 0, 99, 148, 0, 99, 149, 0, 99, 154, 0, 99, 157, 0, 99, 158, 0, 99, 163, 0, 99, 166, 0, 99, 167, 0, 99, 84, 0, 172, 5, 175, 3, 101, 4, 0, 0, 101, 102, 0, 103, 186, 0, 103, 186, 95, 104, 0, 80, 0, 187, 0, 105, 0, 104, 95, 105, 0, 104, 105, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0, 11, 0, 172, 12, 177, 179, 0, 172, 13, 176, 179, 0, 0, 172, 14, 177, 112, 187, 183, 183, 183, 109, 113, 3, 114, 4, 0, 0, 172, 15, 177, 112, 187, 183, 183, 183, 110, 113, 3, 114, 4, 0, 0, 172, 15, 177, 112, 187, 183, 183, 183, 183, 111, 113, 3, 114, 4, 0, 0, 16, 96, 184, 0, 0, 113, 17, 80, 0, 113, 18, 172, 0, 113, 19, 180, 0, 113, 16, 184, 0, 113, 18, 80, 0, 113, 41, 184, 95, 80, 0, 113, 41, 184, 95, 80, 183, 0, 113, 41, 184, 95, 80, 183, 183, 0, 113, 41, 184, 95, 80, 183, 183, 183, 0, 113, 46, 172, 0, 113, 44, 184, 0, 113, 43, 184, 183, 0, 113, 45, 184, 0, 0, 114, 115, 0, 0, 20, 116, 137, 0, 0, 21, 117, 137, 0, 0, 22, 118, 137, 0, 0, 38, 119, 137, 0, 0, 23, 120, 137, 0, 0, 24, 121, 137, 0, 10, 138, 184, 183, 140, 183, 183, 183, 183, 182, 139, 0, 10, 138, 184, 183, 140, 183, 183, 183, 183, 183, 183, 139, 0, 10, 138, 184, 95, 80, 140, 183, 183, 183, 183, 182, 139, 0, 10, 138, 184, 95, 80, 140, 183, 183, 183, 183, 183, 183, 139, 0, 0, 25, 122, 137, 0, 0, 26, 123, 137, 0, 0, 27, 124, 137, 0, 0, 28, 125, 137, 0, 0, 39, 126, 137, 0, 42, 174, 184, 183, 183, 139, 0, 42, 174, 184, 183, 183, 183, 183, 139, 0, 42, 174, 184, 183, 183, 183, 183, 142, 182, 139, 0, 42, 174, 184, 183, 183, 183, 183, 142, 183, 183, 139, 0, 0, 40, 127, 137, 0, 0, 29, 128, 137, 0, 0, 30, 129, 137, 0, 0, 31, 130, 137, 0, 0, 32, 131, 137, 0, 0, 33, 132, 137, 0, 0, 34, 133, 137, 0, 0, 35, 134, 137, 0, 0, 36, 135, 137, 0, 0, 37, 80, 95, 184, 95, 184, 95, 184, 95, 184, 95, 184, 95, 136, 180, 182, 0, 138, 184, 183, 183, 183, 183, 139, 0, 138, 184, 183, 183, 183, 183, 144, 182, 139, 0, 138, 184, 183, 183, 183, 183, 144, 183, 183, 139, 0, 0, 80, 0, 80, 95, 0, 0, 3, 159, 4, 0, 0, 95, 141, 180, 0, 0, 95, 143, 180, 0, 0, 95, 145, 180, 0, 172, 41, 176, 179, 0, 172, 42, 176, 179, 0, 43, 184, 183, 0, 172, 46, 175, 3, 150, 4, 0, 0, 150, 151, 0, 48, 80, 183, 152, 0, 48, 49, 0, 50, 80, 152, 3, 150, 4, 0, 0, 152, 95, 153, 0, 152, 153, 0, 51, 0, 52, 0, 53, 0, 54, 0, 55, 0, 56, 0, 172, 47, 175, 3, 155, 4, 0, 0, 155, 156, 0, 48, 80, 0, 48, 80, 183, 0, 48, 80, 183, 183, 182, 0, 48, 49, 0, 50, 80, 3, 155, 4, 0, 50, 80, 183, 3, 155, 4, 0, 50, 80, 183, 183, 3, 155, 4, 0, 50, 80, 183, 183, 183, 182, 3, 155, 4, 0, 172, 57, 177, 179, 0, 172, 58, 175, 3, 159, 4, 0, 0, 160, 161, 0, 0, 162, 0, 83, 0, 185, 0, 162, 95, 83, 0, 162, 95, 185, 0, 0, 59, 175, 3, 164, 165, 4, 0, 0, 165, 184, 80, 0, 165, 184, 95, 80, 0, 172, 172, 175, 3, 159, 4, 0, 172, 172, 175, 179, 0, 172, 60, 168, 3, 169, 4, 0, 0, 168, 61, 184, 183, 183, 183, 0, 168, 62, 184, 183, 183, 183, 0, 168, 63, 184, 0, 168, 64, 184, 0, 168, 65, 184, 0, 168, 66, 184, 0, 168, 67, 184, 0, 0, 169, 68, 3, 71, 3, 170, 4, 4, 0, 169, 69, 3, 70, 80, 171, 4, 0, 0, 170, 70, 80, 95, 80, 0, 0, 171, 183, 183, 0, 187, 0, 81, 0, 80, 0, 80, 95, 0, 81, 95, 0, 187, 95, 0, 173, 0, 0, 175, 178, 0, 175, 44, 184, 0, 175, 43, 184, 183, 0, 175, 45, 184, 0, 0, 176, 178, 0, 0, 177, 178, 0, 72, 0, 73, 0, 74, 0, 75, 0, 76, 0, 77, 0, 78, 0, 80, 0, 81, 0, 181, 0, 79, 181, 0, 180, 85, 181, 0, 180, 85, 79, 181, 0, 82, 0, 97, 184, 98, 0, 0, 183, 0, 95, 184, 0, 185, 0, 82, 0, 97, 185, 98, 0, 93, 185, 0, 89, 185, 0, 185, 90, 185, 0, 185, 91, 185, 0, 185, 92, 185, 0, 185, 88, 185, 0, 185, 89, 185, 0, 185, 87, 185, 0, 185, 86, 185, 0, 185, 85, 185, 0, 95, 187, 0, 188, 0, 82, 0, 97, 185, 98, 0, 93, 185, 0, 188, 90, 185, 0, 188, 91, 185, 0, 188, 92, 185, 0, 188, 88, 185, 0, 188, 89, 185, 0, 188, 87, 185, 0, 188, 86, 185, 0, 188, 85, 185, 0 }; #endif #if YYDEBUG /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const short yyrline[] = { 0, 154, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 175, 185, 190, 210, 216, 227, 249, 258, 263, 268, 274, 279, 284, 288, 292, 296, 304, 316, 328, 328, 354, 354, 381, 381, 411, 416, 422, 424, 430, 434, 439, 443, 447, 460, 475, 490, 505, 509, 513, 517, 523, 525, 535, 535, 546, 546, 556, 556, 566, 566, 579, 579, 589, 589, 599, 610, 619, 632, 643, 643, 653, 653, 663, 663, 673, 673, 683, 683, 696, 701, 707, 713, 719, 719, 732, 732, 742, 742, 752, 752, 762, 762, 772, 772, 782, 782, 792, 792, 802, 802, 812, 812, 829, 842, 853, 864, 869, 873, 879, 884, 892, 892, 898, 898, 904, 904, 912, 924, 937, 946, 956, 961, 977, 982, 986, 992, 997, 1001, 1007, 1012, 1016, 1020, 1024, 1028, 1036, 1046, 1051, 1067, 1072, 1076, 1080, 1084, 1088, 1092, 1096, 1105, 1117, 1130, 1130, 1141, 1147, 1153, 1162, 1170, 1179, 1192, 1192, 1198, 1200, 1207, 1219, 1227, 1238, 1248, 1255, 1261, 1267, 1272, 1277, 1282, 1287, 1300, 1305, 1309, 1315, 1320, 1326, 1331, 1339, 1345, 1360, 1365, 1369, 1376, 1382, 1398, 1406, 1412, 1417, 1422, 1431, 1438, 1448, 1455, 1466, 1472, 1477, 1482, 1487, 1492, 1497, 1506, 1511, 1527, 1532, 1536, 1540, 1546, 1551, 1559, 1564, 1572, 1581, 1590, 1595, 1599, 1604, 1609, 1614, 1619, 1624, 1629, 1634, 1639, 1644, 1654, 1663, 1674, 1679, 1683, 1688, 1693, 1698, 1703, 1708, 1713, 1718, 1723 }; #endif #if (YYDEBUG) || defined YYERROR_VERBOSE /* YYTNAME[TOKEN_NUM] -- String name of the token TOKEN_NUM. */ static const char *const yytname[] = { "$", "error", "$undefined.", "BEG", "END", "ACCELERATORS", "VIRTKEY", "ASCII", "NOINVERT", "SHIFT", "CONTROL", "ALT", "BITMAP", "CURSOR", "DIALOG", "DIALOGEX", "EXSTYLE", "CAPTION", "CLASS", "STYLE", "AUTO3STATE", "AUTOCHECKBOX", "AUTORADIOBUTTON", "CHECKBOX", "COMBOBOX", "CTEXT", "DEFPUSHBUTTON", "EDITTEXT", "GROUPBOX", "LISTBOX", "LTEXT", "PUSHBOX", "PUSHBUTTON", "RADIOBUTTON", "RTEXT", "SCROLLBAR", "STATE3", "USERBUTTON", "BEDIT", "HEDIT", "IEDIT", "FONT", "ICON", "LANGUAGE", "CHARACTERISTICS", "VERSIONK", "MENU", "MENUEX", "MENUITEM", "SEPARATOR", "POPUP", "CHECKED", "GRAYED", "HELP", "INACTIVE", "MENUBARBREAK", "MENUBREAK", "MESSAGETABLE", "RCDATA", "STRINGTABLE", "VERSIONINFO", "FILEVERSION", "PRODUCTVERSION", "FILEFLAGSMASK", "FILEFLAGS", "FILEOS", "FILETYPE", "FILESUBTYPE", "BLOCKSTRINGFILEINFO", "BLOCKVARFILEINFO", "VALUE", "BLOCK", "MOVEABLE", "FIXED", "PURE", "IMPURE", "PRELOAD", "LOADONCALL", "DISCARDABLE", "NOT", "QUOTEDSTRING", "STRING", "NUMBER", "SIZEDSTRING", "IGNORED_TOKEN", "'|'", "'^'", "'&'", "'+'", "'-'", "'*'", "'/'", "'%'", "'~'", "NEG", "','", "'='", "'('", "')'", "input", "accelerator", "acc_entries", "acc_entry", "acc_event", "acc_options", "acc_option", "bitmap", "cursor", "dialog", "@1", "@2", "@3", "exstyle", "styles", "controls", "control", "@4", "@5", "@6", "@7", "@8", "@9", "@10", "@11", "@12", "@13", "@14", "@15", "@16", "@17", "@18", "@19", "@20", "@21", "@22", "@23", "@24", "control_params", "optstringc", "opt_control_data", "control_styleexpr", "@25", "icon_styleexpr", "@26", "control_params_styleexpr", "@27", "font", "icon", "language", "menu", "menuitems", "menuitem", "menuitem_flags", "menuitem_flag", "menuex", "menuexitems", "menuexitem", "messagetable", "rcdata", "optrcdata_data", "@28", "optrcdata_data_int", "rcdata_data", "stringtable", "@29", "string_data", "user", "versioninfo", "fixedverinfo", "verblocks", "vervals", "vertrans", "id", "resname", "resref", "suboptions", "memflags_move_discard", "memflags_move", "memflag", "file_name", "styleexpr", "parennumber", "optcnumexpr", "cnumexpr", "numexpr", "sizednumexpr", "cposnumexpr", "posnumexpr", "sizedposnumexpr", 0 }; #endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const short yyr1[] = { 0, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 100, 101, 101, 102, 102, 103, 103, 104, 104, 104, 105, 105, 105, 105, 105, 105, 106, 107, 109, 108, 110, 108, 111, 108, 112, 112, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 114, 114, 116, 115, 117, 115, 118, 115, 119, 115, 120, 115, 121, 115, 115, 115, 115, 115, 122, 115, 123, 115, 124, 115, 125, 115, 126, 115, 115, 115, 115, 115, 127, 115, 128, 115, 129, 115, 130, 115, 131, 115, 132, 115, 133, 115, 134, 115, 135, 115, 136, 115, 137, 137, 137, 138, 138, 138, 139, 139, 141, 140, 143, 142, 145, 144, 146, 147, 148, 149, 150, 150, 151, 151, 151, 152, 152, 152, 153, 153, 153, 153, 153, 153, 154, 155, 155, 156, 156, 156, 156, 156, 156, 156, 156, 157, 158, 160, 159, 161, 161, 162, 162, 162, 162, 164, 163, 165, 165, 165, 166, 166, 167, 168, 168, 168, 168, 168, 168, 168, 168, 169, 169, 169, 170, 170, 171, 171, 172, 172, 173, 173, 173, 174, 174, 175, 175, 175, 175, 175, 176, 176, 177, 177, 178, 178, 178, 178, 178, 178, 178, 179, 179, 180, 180, 180, 180, 181, 181, 182, 182, 183, 184, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 186, 187, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const short yyr2[] = { 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 0, 2, 2, 4, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 4, 4, 0, 13, 0, 13, 0, 14, 0, 3, 0, 3, 3, 3, 3, 3, 5, 6, 7, 8, 3, 3, 4, 3, 0, 2, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 11, 12, 12, 13, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 6, 8, 10, 11, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 16, 7, 9, 10, 0, 1, 2, 0, 3, 0, 3, 0, 3, 0, 3, 4, 4, 3, 6, 0, 2, 4, 2, 6, 0, 3, 2, 1, 1, 1, 1, 1, 1, 6, 0, 2, 2, 3, 5, 2, 5, 6, 7, 9, 4, 6, 0, 2, 0, 1, 1, 1, 3, 3, 0, 6, 0, 3, 4, 6, 4, 6, 0, 6, 6, 3, 3, 3, 3, 3, 0, 8, 7, 0, 5, 0, 3, 1, 1, 1, 2, 2, 2, 1, 0, 2, 3, 4, 3, 0, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 3, 0, 1, 2, 1, 1, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3 }; /* YYDEFACT[S] -- default rule to reduce with in state S when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const short yydefact[] = { 1, 0, 0, 192, 186, 234, 16, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 185, 233, 220, 0, 0, 0, 0, 219, 0, 236, 0, 192, 199, 197, 199, 199, 197, 197, 192, 192, 199, 192, 170, 192, 0, 0, 0, 0, 0, 0, 0, 0, 223, 222, 0, 0, 125, 0, 0, 0, 0, 0, 0, 0, 0, 162, 0, 0, 0, 201, 202, 203, 204, 205, 206, 207, 193, 235, 0, 0, 0, 41, 41, 0, 0, 0, 0, 0, 0, 0, 0, 244, 243, 242, 240, 241, 237, 238, 239, 221, 218, 231, 230, 229, 227, 228, 224, 225, 226, 164, 0, 194, 196, 18, 208, 209, 200, 33, 198, 34, 0, 0, 0, 123, 124, 127, 142, 152, 154, 178, 0, 0, 0, 0, 0, 0, 0, 154, 168, 0, 195, 0, 0, 0, 0, 0, 0, 0, 156, 0, 0, 0, 173, 174, 175, 176, 177, 0, 163, 0, 17, 22, 19, 0, 23, 42, 0, 0, 126, 0, 0, 128, 141, 0, 0, 143, 153, 158, 155, 157, 159, 169, 0, 0, 0, 0, 167, 165, 0, 0, 20, 0, 0, 130, 0, 132, 147, 144, 0, 0, 0, 0, 0, 0, 166, 232, 0, 35, 37, 132, 0, 145, 142, 0, 160, 161, 0, 0, 171, 172, 27, 28, 29, 30, 31, 32, 21, 24, 43, 43, 39, 129, 127, 135, 136, 137, 138, 139, 140, 0, 134, 216, 0, 142, 0, 181, 183, 0, 26, 0, 0, 43, 0, 133, 146, 217, 148, 0, 142, 216, 0, 0, 25, 57, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, 0, 131, 149, 0, 0, 0, 0, 180, 0, 0, 47, 44, 48, 45, 0, 214, 0, 46, 210, 0, 0, 54, 56, 53, 0, 57, 150, 142, 179, 0, 184, 36, 112, 59, 61, 63, 67, 69, 75, 77, 79, 81, 91, 93, 95, 97, 99, 101, 103, 105, 0, 65, 83, 89, 0, 58, 211, 0, 0, 0, 55, 38, 0, 0, 0, 113, 0, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 0, 112, 112, 112, 187, 0, 191, 0, 0, 215, 0, 212, 49, 40, 151, 182, 114, 0, 60, 0, 62, 64, 68, 70, 76, 78, 80, 82, 92, 94, 96, 98, 100, 102, 104, 106, 0, 66, 84, 90, 188, 189, 0, 190, 213, 50, 0, 0, 0, 0, 0, 51, 0, 117, 0, 0, 0, 115, 52, 0, 0, 0, 0, 0, 154, 85, 0, 0, 118, 0, 0, 0, 0, 115, 0, 0, 115, 0, 116, 119, 86, 216, 0, 216, 121, 109, 216, 0, 0, 115, 217, 216, 115, 217, 0, 115, 217, 0, 120, 87, 115, 115, 217, 71, 115, 122, 110, 115, 0, 88, 73, 115, 72, 111, 0, 74, 107, 0, 216, 108, 0, 0 }; static const short yydefgoto[] = { 1, 9, 145, 166, 167, 230, 231, 10, 11, 12, 232, 233, 255, 125, 253, 287, 333, 345, 346, 347, 363, 348, 349, 350, 351, 352, 353, 364, 365, 354, 355, 356, 357, 358, 359, 360, 361, 479, 380, 381, 427, 416, 422, 443, 450, 448, 456, 13, 14, 15, 16, 149, 175, 214, 244, 17, 150, 179, 18, 19, 151, 152, 182, 183, 20, 113, 143, 21, 22, 93, 153, 264, 265, 23, 368, 369, 32, 84, 83, 80, 121, 295, 296, 258, 259, 104, 31, 194, 24, 25 }; static const short yypact[] = { -32768, 13, 412,-32768,-32768,-32768,-32768, 412, 412,-32768, -32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768, 111,-32768, 511,-32768, 412, 412, 412, -79, 600, 244,-32768, 562,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 412, 412, 412, 412, 412, 412, 412, 412,-32768,-32768, 576, 412, -32768, 412, 412, 412, 412, 412, 412, 412, 412,-32768, 412, 412, 412,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768,-32768, 256, 603, 603, 297, 297, 603, 603, 280, 337, 603, 345, 100, 231, 607, 613, 567, 172, 172, -32768,-32768,-32768,-32768,-32768, 607, 613, 567, 172, 172, -32768,-32768,-32768,-32768, -79,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768, -60, 63, 63,-32768,-32768,-32768, -32768,-32768,-32768,-32768, 412, 412, 412, 412, 412, 412, 412,-32768,-32768, 7,-32768, 5, 412, -79, -79, 33, 34, 35, 254, 51, -79, -79,-32768,-32768,-32768,-32768, -32768, 36,-32768, 60,-32768,-32768,-32768, -38,-32768,-32768, -79, -79,-32768, -39, 11,-32768,-32768, 59, 25,-32768, -32768,-32768,-32768, 27, 600,-32768, 127, 144, -79, -79, -32768,-32768, 74, 63, 87, -79, -79,-32768, -79,-32768, -32768, -79, 12, 294, 118, 128, -79, -79,-32768,-32768, 700,-32768, -79,-32768, 22, -79,-32768, 14,-32768, 600, 194, 121,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 23,-32768,-32768,-32768,-32768, 309,-32768,-32768,-32768,-32768, -32768,-32768,-32768, 661,-32768, -79, 38,-32768, 16,-32768, -32768, 700,-32768, 383, 472,-32768, 42,-32768,-32768,-32768, -32768, 124,-32768, -79, 10, 4,-32768,-32768, 412, 126, 187, 99, 412, 412, 412, 412, 200,-32768, 480,-32768, -32768, 125, 204, 207, 135,-32768, -79, 510,-32768,-32768, -32768,-32768, 49,-32768, 412, 136,-32768, 133, -79,-32768, -32768,-32768, 547,-32768,-32768,-32768,-32768, 134,-32768,-32768, 152,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 153,-32768, -32768,-32768, 374,-32768,-32768, 140, 112, 157,-32768,-32768, 584, 138, 160, 148, 412, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 158, 152, 152, 152, 161, 163,-32768, 412, 165,-32768, 49,-32768, -79,-32768,-32768,-32768,-32768, 170, -32768, 412,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 412,-32768, -32768,-32768,-32768,-32768, -79,-32768,-32768, -79, 123, 183, -79, 184, -79, -79, 183,-32768, -79, -79, 412, 17, -32768, -79, 99, -79, -79, 190,-32768,-32768, -79, -79, 136, -79, -79, 412, 248, 18, -79, -79, 19, 195, -32768,-32768,-32768, -79, -79, -79,-32768,-32768, -79, 412, 99, 245, -79, -79, 245, -79, 99, 245, -79, 196, 136,-32768, 245, 245, -79,-32768, 245, 136,-32768, 245, 412,-32768,-32768, 245,-32768,-32768, 201,-32768,-32768, 99, 64,-32768, 295,-32768 }; static const short yypgoto[] = { -32768,-32768,-32768,-32768,-32768,-32768, -206,-32768,-32768,-32768, -32768,-32768,-32768, 212, -85, -259,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 281, -8, -212, -104,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768, 78,-32768, 113, 92,-32768, -204,-32768,-32768,-32768, -140,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, -32768,-32768,-32768, -21,-32768,-32768, 350, 139, 175, 475, 416, -329, -257, -258, 29, -2, -1,-32768, -122,-32768 }; #define YYLAST 717 static const short yytable[] = { 30, 161, 47, 147, 148, 282, 33, 34, 285, 164, 197, 162, 246, 482, 283, 216, 59, 247, 302, 262, 426, 426, 426, 168, 252, 236, 56, 57, 58, 224, 225, 226, 227, 228, 229, 334, 146, 172, 176, 180, 190, 198, 260, 261, 340, 266, 279, 95, 96, 97, 98, 99, 100, 101, 102, 185, 2, 193, 281, 60, 105, 106, 107, 108, 109, 110, 111, 112, 114, 115, 116, 209, 3, 237, 238, 239, 240, 241, 242, 373, 284, 173, 177, 174, 178, 165, 177, 5, 178, 26, 173, 199, 174, 430, 4, 5, 27, 6, 7, 59, 28, 341, 8, 133, 29, 202, 7, 59, 200, 59, 8, 59, 59, 441, 446, 406, 35, 243, 251, 186, 187, 460, 203, 36, 37, 38, 39, 467, 280, 304, 204, 293, 154, 155, 156, 157, 158, 159, 160, 201, 191, 163, 376, 144, 169, 5, 294, 205, 254, 336, 480, 184, 40, 41, 208, 192, 7, 42, 43, 59, 8, 134, 135, 136, 137, 138, 139, 140, 44, 45, 278, 46, 177, 177, 178, 178, 170, 171, 292, 87, 88, 293, 210, 188, 189, 451, 177, 454, 178, 220, 457, 372, 4, 5, 293, 463, 294, 249, 221, 195, 196, 250, 219, 414, 7, 26, 289, 305, 8, 294, 370, 306, 27, 85, 86, 307, 28, 206, 207, 91, 29, 336, 481, 442, 211, 212, 447, 213, 337, 342, 215, 217, 343, 362, 141, 222, 223, 374, 371, 461, 377, 234, 465, 378, 245, 468, 248, 69, 426, 291, 471, 472, 440, 398, 474, 301, 402, 475, 403, 117, 405, 477, 66, 67, 68, 408, 288, 290, 4, 5, 297, 298, 299, 300, 70, 71, 72, 263, 415, 418, 7, 4, 5, 129, 8, 433, 434, 70, 71, 72, 449, 470, 335, 7, 286, 483, 478, 8, 126, 70, 71, 72, 344, 73, 74, 75, 76, 77, 78, 79, 421, 118, 119, 124, 256, 308, 73, 74, 75, 76, 77, 78, 79, 70, 71, 72, 235, 338, 73, 74, 75, 76, 77, 78, 79, 257, 26, 181, 0, 0, 130, 0, 379, 27, 0, 0, 0, 28, 132, 0, 0, 29, 73, 74, 75, 76, 77, 78, 79, 0, 237, 238, 239, 240, 241, 242, 0, 404, 0, 73, 74, 75, 76, 77, 78, 79, 26, 218, 0, 410, 70, 71, 72, 27, 0, 82, 267, 28, 70, 71, 72, 29, 89, 90, 0, 92, 411, 94, 0, 268, 269, 270, 271, 407, 243, 0, 0, 0, 409, 73, 74, 75, 76, 77, 78, 79, 425, 73, 74, 75, 76, 77, 78, 79, 272, 0, 273, 274, 275, 276, 0, 439, 0, 412, 0, 0, 413, 0, 0, 417, 0, 419, 420, 0, 0, 423, 424, 459, 428, 0, 429, 0, 431, 432, 366, 367, 5, 435, 436, 0, 437, 438, 0, 0, 0, 444, 445, 7, 476, 0, 0, 8, 452, 453, 455, 277, 0, 458, 0, 0, 0, 462, 464, 303, 466, 0, 0, 469, 268, 269, 270, 271, 0, 473, 26, 0, 268, 269, 270, 271, 123, 27, 0, 127, 128, 28, 0, 131, 0, 29, 142, 0, 0, 272, 309, 273, 274, 275, 276, 0, 310, 272, 0, 273, 274, 275, 276, 0, 0, 0, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 339, 332, 0, 0, 0, 0, 310, 120, 122, 120, 120, 122, 122, 0, 0, 120, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 375, 332, 0, 0, 0, 0, 310, 0, 48, 49, 50, 51, 52, 53, 54, 55, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 0, 332, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 0, 399, 400, 401, 61, 62, 63, 64, 65, 66, 67, 68, 64, 65, 66, 67, 68, 81, 61, 62, 63, 64, 65, 66, 67, 68, 0, 0, 0, 0, 0, 103, 73, 74, 75, 76, 77, 78, 79, 0, 118, 119, 61, 62, 63, 64, 65, 66, 67, 68, 62, 63, 64, 65, 66, 67, 68, 63, 64, 65, 66, 67, 68, 224, 225, 226, 227, 228, 229, 237, 238, 239, 240, 241, 242 }; static const short yycheck[] = { 2, 141, 23, 125, 126, 263, 7, 8, 4, 4, 49, 4, 216, 0, 4, 3, 95, 3, 277, 3, 3, 3, 3, 145, 230, 3, 27, 28, 29, 6, 7, 8, 9, 10, 11, 292, 96, 4, 4, 4, 4, 80, 4, 247, 303, 251, 4, 48, 49, 50, 51, 52, 53, 54, 55, 4, 43, 95, 262, 30, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 193, 59, 51, 52, 53, 54, 55, 56, 336, 70, 48, 48, 50, 50, 80, 48, 82, 50, 82, 48, 80, 50, 422, 81, 82, 89, 84, 93, 95, 93, 305, 97, 3, 97, 80, 93, 95, 49, 95, 97, 95, 95, 95, 95, 372, 5, 95, 95, 68, 69, 450, 95, 12, 13, 14, 15, 456, 4, 4, 3, 82, 134, 135, 136, 137, 138, 139, 140, 80, 80, 143, 4, 114, 146, 82, 97, 3, 233, 85, 479, 152, 41, 42, 80, 95, 93, 46, 47, 95, 97, 61, 62, 63, 64, 65, 66, 67, 57, 58, 255, 60, 48, 48, 50, 50, 147, 148, 79, 40, 41, 82, 95, 154, 155, 443, 48, 445, 50, 71, 448, 79, 81, 82, 82, 453, 97, 3, 70, 170, 171, 80, 203, 80, 93, 82, 80, 3, 97, 97, 332, 4, 89, 38, 39, 80, 93, 188, 189, 44, 97, 85, 480, 435, 195, 196, 438, 198, 95, 95, 201, 202, 80, 80, 3, 206, 207, 80, 98, 451, 80, 212, 454, 95, 215, 457, 217, 3, 3, 270, 462, 463, 4, 95, 466, 276, 95, 469, 95, 3, 95, 473, 90, 91, 92, 95, 268, 80, 81, 82, 272, 273, 274, 275, 43, 44, 45, 248, 95, 95, 93, 81, 82, 3, 97, 95, 426, 43, 44, 45, 95, 95, 294, 93, 265, 0, 95, 97, 86, 43, 44, 45, 310, 72, 73, 74, 75, 76, 77, 78, 414, 80, 81, 16, 236, 286, 72, 73, 74, 75, 76, 77, 78, 43, 44, 45, 213, 298, 72, 73, 74, 75, 76, 77, 78, 243, 82, 83, -1, -1, 3, -1, 344, 89, -1, -1, -1, 93, 3, -1, -1, 97, 72, 73, 74, 75, 76, 77, 78, -1, 51, 52, 53, 54, 55, 56, -1, 369, -1, 72, 73, 74, 75, 76, 77, 78, 82, 83, -1, 381, 43, 44, 45, 89, -1, 35, 3, 93, 43, 44, 45, 97, 42, 43, -1, 45, 398, 47, -1, 16, 17, 18, 19, 374, 95, -1, -1, -1, 379, 72, 73, 74, 75, 76, 77, 78, 418, 72, 73, 74, 75, 76, 77, 78, 41, -1, 43, 44, 45, 46, -1, 433, -1, 404, -1, -1, 407, -1, -1, 410, -1, 412, 413, -1, -1, 416, 417, 449, 419, -1, 421, -1, 423, 424, 80, 81, 82, 428, 429, -1, 431, 432, -1, -1, -1, 436, 437, 93, 470, -1, -1, 97, 443, 444, 445, 3, -1, 448, -1, -1, -1, 452, 453, 3, 455, -1, -1, 458, 16, 17, 18, 19, -1, 464, 82, -1, 16, 17, 18, 19, 84, 89, -1, 87, 88, 93, -1, 91, -1, 97, 94, -1, -1, 41, 4, 43, 44, 45, 46, -1, 10, 41, -1, 43, 44, 45, 46, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 4, 42, -1, -1, -1, -1, 10, 83, 84, 85, 86, 87, 88, -1, -1, 91, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 4, 42, -1, -1, -1, -1, 10, -1, 85, 86, 87, 88, 89, 90, 91, 92, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, 42, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, -1, 363, 364, 365, 85, 86, 87, 88, 89, 90, 91, 92, 88, 89, 90, 91, 92, 98, 85, 86, 87, 88, 89, 90, 91, 92, -1, -1, -1, -1, -1, 98, 72, 73, 74, 75, 76, 77, 78, -1, 80, 81, 85, 86, 87, 88, 89, 90, 91, 92, 86, 87, 88, 89, 90, 91, 92, 87, 88, 89, 90, 91, 92, 6, 7, 8, 9, 10, 11, 51, 52, 53, 54, 55, 56 }; /* -*-C-*- Note some compilers choke on comments on `#line' lines. */ #line 3 "/usr/share/bison-1.35/bison.simple" /* Skeleton output parser for bison, Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002 Free Software Foundation, Inc. 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, 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. */ /* As a special exception, when this file is copied by Bison into a Bison output file, you may use that output file without restriction. This special exception was added by the Free Software Foundation in version 1.24 of Bison. */ /* This is the parser code that is written into each bison parser when the %semantic_parser declaration is not specified in the grammar. It was written by Richard Stallman by simplifying the hairy parser used when %semantic_parser is specified. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ #if ! defined (yyoverflow) || defined (YYERROR_VERBOSE) /* The parser invokes alloca or malloc; define the necessary symbols. */ # if YYSTACK_USE_ALLOCA # define YYSTACK_ALLOC alloca # else # ifndef YYSTACK_USE_ALLOCA # if defined (alloca) || defined (_ALLOCA_H) # define YYSTACK_ALLOC alloca # else # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # else # if defined (__STDC__) || defined (__cplusplus) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # endif # define YYSTACK_ALLOC malloc # define YYSTACK_FREE free # endif #endif /* ! defined (yyoverflow) || defined (YYERROR_VERBOSE) */ #if (! defined (yyoverflow) \ && (! defined (__cplusplus) \ || (YYLTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { short yyss; YYSTYPE yyvs; # if YYLSP_NEEDED YYLTYPE yyls; # endif }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAX (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # if YYLSP_NEEDED # define YYSTACK_BYTES(N) \ ((N) * (sizeof (short) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAX) # else # define YYSTACK_BYTES(N) \ ((N) * (sizeof (short) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAX) # endif /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ register YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (0) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAX; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if ! defined (YYSIZE_T) && defined (__SIZE_TYPE__) # define YYSIZE_T __SIZE_TYPE__ #endif #if ! defined (YYSIZE_T) && defined (size_t) # define YYSIZE_T size_t #endif #if ! defined (YYSIZE_T) # if defined (__STDC__) || defined (__cplusplus) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # endif #endif #if ! defined (YYSIZE_T) # define YYSIZE_T unsigned int #endif #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY -2 #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrlab1 /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yychar1 = YYTRANSLATE (yychar); \ YYPOPSTACK; \ goto yybackup; \ } \ else \ { \ yyerror ("syntax error: cannot back up"); \ YYERROR; \ } \ while (0) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Compute the default location (before the actions are run). When YYLLOC_DEFAULT is run, CURRENT is set the location of the first token. By default, to implement support for ranges, extend its range to the last symbol. */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ Current.last_line = Rhs[N].last_line; \ Current.last_column = Rhs[N].last_column; #endif /* YYLEX -- calling `yylex' with the right arguments. */ #if YYPURE # if YYLSP_NEEDED # ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) # else # define YYLEX yylex (&yylval, &yylloc) # endif # else /* !YYLSP_NEEDED */ # ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, YYLEX_PARAM) # else # define YYLEX yylex (&yylval) # endif # endif /* !YYLSP_NEEDED */ #else /* !YYPURE */ # define YYLEX yylex () #endif /* !YYPURE */ /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if SIZE_MAX < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #if YYMAXDEPTH == 0 # undef YYMAXDEPTH #endif #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #ifdef YYERROR_VERBOSE # ifndef yystrlen # if defined (__GLIBC__) && defined (_STRING_H) # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T # if defined (__STDC__) || defined (__cplusplus) yystrlen (const char *yystr) # else yystrlen (yystr) const char *yystr; # endif { register const char *yys = yystr; while (*yys++ != '\0') continue; return yys - yystr - 1; } # endif # endif # ifndef yystpcpy # if defined (__GLIBC__) && defined (_STRING_H) && defined (_GNU_SOURCE) # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * # if defined (__STDC__) || defined (__cplusplus) yystpcpy (char *yydest, const char *yysrc) # else yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; # endif { register char *yyd = yydest; register const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif #endif #line 315 "/usr/share/bison-1.35/bison.simple" /* The user can define YYPARSE_PARAM as the name of an argument to be passed into yyparse. The argument should have type void *. It should actually point to an object. Grammar actions can access the variable by casting it to the proper pointer type. */ #ifdef YYPARSE_PARAM # if defined (__STDC__) || defined (__cplusplus) # define YYPARSE_PARAM_ARG void *YYPARSE_PARAM # define YYPARSE_PARAM_DECL # else # define YYPARSE_PARAM_ARG YYPARSE_PARAM # define YYPARSE_PARAM_DECL void *YYPARSE_PARAM; # endif #else /* !YYPARSE_PARAM */ # define YYPARSE_PARAM_ARG # define YYPARSE_PARAM_DECL #endif /* !YYPARSE_PARAM */ /* Prevent warning if -Wstrict-prototypes. */ #ifdef __GNUC__ # ifdef YYPARSE_PARAM int yyparse (void *); # else int yyparse (void); # endif #endif /* YY_DECL_VARIABLES -- depending whether we use a pure parser, variables are global, or local to YYPARSE. */ #define YY_DECL_NON_LSP_VARIABLES \ /* The lookahead symbol. */ \ int yychar; \ \ /* The semantic value of the lookahead symbol. */ \ YYSTYPE yylval; \ \ /* Number of parse errors so far. */ \ int yynerrs; #if YYLSP_NEEDED # define YY_DECL_VARIABLES \ YY_DECL_NON_LSP_VARIABLES \ \ /* Location data for the lookahead symbol. */ \ YYLTYPE yylloc; #else # define YY_DECL_VARIABLES \ YY_DECL_NON_LSP_VARIABLES #endif /* If nonreentrant, generate the variables here. */ #if !YYPURE YY_DECL_VARIABLES #endif /* !YYPURE */ int yyparse (YYPARSE_PARAM_ARG) YYPARSE_PARAM_DECL { /* If reentrant, generate the variables here. */ #if YYPURE YY_DECL_VARIABLES #endif /* !YYPURE */ register int yystate; register int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Lookahead token as an internal (translated) token number. */ int yychar1 = 0; /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ short yyssa[YYINITDEPTH]; short *yyss = yyssa; register short *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; register YYSTYPE *yyvsp; #if YYLSP_NEEDED /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; #endif #if YYLSP_NEEDED # define YYPOPSTACK (yyvsp--, yyssp--, yylsp--) #else # define YYPOPSTACK (yyvsp--, yyssp--) #endif YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYLSP_NEEDED YYLTYPE yyloc; #endif /* When reducing, the number of symbols on the RHS of the reduced rule. */ int yylen; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; #if YYLSP_NEEDED yylsp = yyls; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. so pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyssp >= yyss + yystacksize - 1) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; short *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. */ # if YYLSP_NEEDED YYLTYPE *yyls1 = yyls; /* This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow ("parser stack overflow", &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; # else yyoverflow ("parser stack overflow", &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); # endif yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyoverflowlab; # else /* Extend the stack our own way. */ if (yystacksize >= YYMAXDEPTH) goto yyoverflowlab; yystacksize *= 2; if (yystacksize > YYMAXDEPTH) yystacksize = YYMAXDEPTH; { short *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyoverflowlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); # if YYLSP_NEEDED YYSTACK_RELOCATE (yyls); # endif # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; #if YYLSP_NEEDED yylsp = yyls + yysize - 1; #endif YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyssp >= yyss + yystacksize - 1) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. */ /* Read a lookahead token if we need one and don't already have one. */ /* yyresume: */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYFLAG) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* yychar is either YYEMPTY or YYEOF or a valid token in external form. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } /* Convert token to internal form (in yychar1) for indexing tables with */ if (yychar <= 0) /* This means end of input. */ { yychar1 = 0; yychar = YYEOF; /* Don't call YYLEX any more */ YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yychar1 = YYTRANSLATE (yychar); #if YYDEBUG /* We have to keep this `#if YYDEBUG', since we use variables which are defined only if `YYDEBUG' is set. */ if (yydebug) { YYFPRINTF (stderr, "Next token is %d (%s", yychar, yytname[yychar1]); /* Give the individual parser a way to print the precise meaning of a token, for further debugging info. */ # ifdef YYPRINT YYPRINT (stderr, yychar, yylval); # endif YYFPRINTF (stderr, ")\n"); } #endif } yyn += yychar1; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1) goto yydefault; yyn = yytable[yyn]; /* yyn is what to do for this token type in this state. Negative => reduce, -yyn is rule number. Positive => shift, yyn is new state. New state is final state => don't bother to shift, just return success. 0, or most negative number => error. */ if (yyn < 0) { if (yyn == YYFLAG) goto yyerrlab; yyn = -yyn; goto yyreduce; } else if (yyn == 0) goto yyerrlab; if (yyn == YYFINAL) YYACCEPT; /* Shift the lookahead token. */ YYDPRINTF ((stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1])); /* Discard the token being shifted unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; *++yyvsp = yylval; #if YYLSP_NEEDED *++yylsp = yylloc; #endif /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; yystate = yyn; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to the semantic value of the lookahead token. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; #if YYLSP_NEEDED /* Similarly for the default location. Let the user run additional commands if for instance locations are ranges. */ yyloc = yylsp[1-yylen]; YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); #endif #if YYDEBUG /* We have to keep this `#if YYDEBUG', since we use variables which are defined only if `YYDEBUG' is set. */ if (yydebug) { int yyi; YYFPRINTF (stderr, "Reducing via rule %d (line %d), ", yyn, yyrline[yyn]); /* Print the symbols being reduced, and their result. */ for (yyi = yyprhs[yyn]; yyrhs[yyi] > 0; yyi++) YYFPRINTF (stderr, "%s ", yytname[yyrhs[yyi]]); YYFPRINTF (stderr, " -> %s\n", yytname[yyr1[yyn]]); } #endif switch (yyn) { case 17: #line 177 "rcparse.y" { define_accelerator (yyvsp[-5].id, &yyvsp[-3].res_info, yyvsp[-1].pacc); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 18: #line 187 "rcparse.y" { yyval.pacc = NULL; } break; case 19: #line 191 "rcparse.y" { struct accelerator *a; a = (struct accelerator *) res_alloc (sizeof *a); *a = yyvsp[0].acc; if (yyvsp[-1].pacc == NULL) yyval.pacc = a; else { struct accelerator **pp; for (pp = &yyvsp[-1].pacc->next; *pp != NULL; pp = &(*pp)->next) ; *pp = a; yyval.pacc = yyvsp[-1].pacc; } } break; case 20: #line 212 "rcparse.y" { yyval.acc = yyvsp[-1].acc; yyval.acc.id = yyvsp[0].il; } break; case 21: #line 217 "rcparse.y" { yyval.acc = yyvsp[-3].acc; yyval.acc.id = yyvsp[-2].il; yyval.acc.flags |= yyvsp[0].is; if ((yyval.acc.flags & ACC_VIRTKEY) == 0 && (yyval.acc.flags & (ACC_SHIFT | ACC_CONTROL)) != 0) rcparse_warning (_("inappropriate modifiers for non-VIRTKEY")); } break; case 22: #line 229 "rcparse.y" { const char *s = yyvsp[0].s; char ch; yyval.acc.next = NULL; yyval.acc.id = 0; ch = *s; if (ch != '^') yyval.acc.flags = 0; else { yyval.acc.flags = ACC_CONTROL | ACC_VIRTKEY; ++s; ch = *s; ch = TOUPPER (ch); } yyval.acc.key = ch; if (s[1] != '\0') rcparse_warning (_("accelerator should only be one character")); } break; case 23: #line 250 "rcparse.y" { yyval.acc.next = NULL; yyval.acc.flags = 0; yyval.acc.id = 0; yyval.acc.key = yyvsp[0].il; } break; case 24: #line 260 "rcparse.y" { yyval.is = yyvsp[0].is; } break; case 25: #line 264 "rcparse.y" { yyval.is = yyvsp[-2].is | yyvsp[0].is; } break; case 26: #line 269 "rcparse.y" { yyval.is = yyvsp[-1].is | yyvsp[0].is; } break; case 27: #line 276 "rcparse.y" { yyval.is = ACC_VIRTKEY; } break; case 28: #line 280 "rcparse.y" { /* This is just the absence of VIRTKEY. */ yyval.is = 0; } break; case 29: #line 285 "rcparse.y" { yyval.is = ACC_NOINVERT; } break; case 30: #line 289 "rcparse.y" { yyval.is = ACC_SHIFT; } break; case 31: #line 293 "rcparse.y" { yyval.is = ACC_CONTROL; } break; case 32: #line 297 "rcparse.y" { yyval.is = ACC_ALT; } break; case 33: #line 306 "rcparse.y" { define_bitmap (yyvsp[-3].id, &yyvsp[-1].res_info, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 34: #line 318 "rcparse.y" { define_cursor (yyvsp[-3].id, &yyvsp[-1].res_info, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 35: #line 331 "rcparse.y" { memset (&dialog, 0, sizeof dialog); dialog.x = yyvsp[-3].il; dialog.y = yyvsp[-2].il; dialog.width = yyvsp[-1].il; dialog.height = yyvsp[0].il; dialog.style = WS_POPUP | WS_BORDER | WS_SYSMENU; dialog.exstyle = yyvsp[-4].il; dialog.menu.named = 1; dialog.class.named = 1; dialog.font = NULL; dialog.ex = NULL; dialog.controls = NULL; sub_res_info = yyvsp[-5].res_info; style = 0; } break; case 36: #line 348 "rcparse.y" { define_dialog (yyvsp[-12].id, &sub_res_info, &dialog); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 37: #line 356 "rcparse.y" { memset (&dialog, 0, sizeof dialog); dialog.x = yyvsp[-3].il; dialog.y = yyvsp[-2].il; dialog.width = yyvsp[-1].il; dialog.height = yyvsp[0].il; dialog.style = WS_POPUP | WS_BORDER | WS_SYSMENU; dialog.exstyle = yyvsp[-4].il; dialog.menu.named = 1; dialog.class.named = 1; dialog.font = NULL; dialog.ex = ((struct dialog_ex *) res_alloc (sizeof (struct dialog_ex))); memset (dialog.ex, 0, sizeof (struct dialog_ex)); dialog.controls = NULL; sub_res_info = yyvsp[-5].res_info; style = 0; } break; case 38: #line 375 "rcparse.y" { define_dialog (yyvsp[-12].id, &sub_res_info, &dialog); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 39: #line 383 "rcparse.y" { memset (&dialog, 0, sizeof dialog); dialog.x = yyvsp[-4].il; dialog.y = yyvsp[-3].il; dialog.width = yyvsp[-2].il; dialog.height = yyvsp[-1].il; dialog.style = WS_POPUP | WS_BORDER | WS_SYSMENU; dialog.exstyle = yyvsp[-5].il; dialog.menu.named = 1; dialog.class.named = 1; dialog.font = NULL; dialog.ex = ((struct dialog_ex *) res_alloc (sizeof (struct dialog_ex))); memset (dialog.ex, 0, sizeof (struct dialog_ex)); dialog.ex->help = yyvsp[0].il; dialog.controls = NULL; sub_res_info = yyvsp[-6].res_info; style = 0; } break; case 40: #line 403 "rcparse.y" { define_dialog (yyvsp[-13].id, &sub_res_info, &dialog); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 41: #line 413 "rcparse.y" { yyval.il = 0; } break; case 42: #line 417 "rcparse.y" { yyval.il = yyvsp[0].il; } break; case 44: #line 425 "rcparse.y" { dialog.style |= WS_CAPTION; style |= WS_CAPTION; unicode_from_ascii ((int *) NULL, &dialog.caption, yyvsp[0].s); } break; case 45: #line 431 "rcparse.y" { dialog.class = yyvsp[0].id; } break; case 46: #line 436 "rcparse.y" { dialog.style = style; } break; case 47: #line 440 "rcparse.y" { dialog.exstyle = yyvsp[0].il; } break; case 48: #line 444 "rcparse.y" { res_string_to_id (& dialog.class, yyvsp[0].s); } break; case 49: #line 448 "rcparse.y" { dialog.style |= DS_SETFONT; style |= DS_SETFONT; dialog.pointsize = yyvsp[-2].il; unicode_from_ascii ((int *) NULL, &dialog.font, yyvsp[0].s); if (dialog.ex != NULL) { dialog.ex->weight = 0; dialog.ex->italic = 0; dialog.ex->charset = 1; } } break; case 50: #line 461 "rcparse.y" { dialog.style |= DS_SETFONT; style |= DS_SETFONT; dialog.pointsize = yyvsp[-3].il; unicode_from_ascii ((int *) NULL, &dialog.font, yyvsp[-1].s); if (dialog.ex == NULL) rcparse_warning (_("extended FONT requires DIALOGEX")); else { dialog.ex->weight = yyvsp[0].il; dialog.ex->italic = 0; dialog.ex->charset = 1; } } break; case 51: #line 476 "rcparse.y" { dialog.style |= DS_SETFONT; style |= DS_SETFONT; dialog.pointsize = yyvsp[-4].il; unicode_from_ascii ((int *) NULL, &dialog.font, yyvsp[-2].s); if (dialog.ex == NULL) rcparse_warning (_("extended FONT requires DIALOGEX")); else { dialog.ex->weight = yyvsp[-1].il; dialog.ex->italic = yyvsp[0].il; dialog.ex->charset = 1; } } break; case 52: #line 491 "rcparse.y" { dialog.style |= DS_SETFONT; style |= DS_SETFONT; dialog.pointsize = yyvsp[-5].il; unicode_from_ascii ((int *) NULL, &dialog.font, yyvsp[-3].s); if (dialog.ex == NULL) rcparse_warning (_("extended FONT requires DIALOGEX")); else { dialog.ex->weight = yyvsp[-2].il; dialog.ex->italic = yyvsp[-1].il; dialog.ex->charset = yyvsp[0].il; } } break; case 53: #line 506 "rcparse.y" { dialog.menu = yyvsp[0].id; } break; case 54: #line 510 "rcparse.y" { sub_res_info.characteristics = yyvsp[0].il; } break; case 55: #line 514 "rcparse.y" { sub_res_info.language = yyvsp[-1].il | (yyvsp[0].il << SUBLANG_SHIFT); } break; case 56: #line 518 "rcparse.y" { sub_res_info.version = yyvsp[0].il; } break; case 58: #line 526 "rcparse.y" { struct dialog_control **pp; for (pp = &dialog.controls; *pp != NULL; pp = &(*pp)->next) ; *pp = yyvsp[0].dialog_control; } break; case 59: #line 537 "rcparse.y" { default_style = BS_AUTO3STATE | WS_TABSTOP; base_style = BS_AUTO3STATE; class = CTL_BUTTON; } break; case 60: #line 543 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 61: #line 547 "rcparse.y" { default_style = BS_AUTOCHECKBOX | WS_TABSTOP; base_style = BS_AUTOCHECKBOX; class = CTL_BUTTON; } break; case 62: #line 553 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 63: #line 557 "rcparse.y" { default_style = BS_AUTORADIOBUTTON | WS_TABSTOP; base_style = BS_AUTORADIOBUTTON; class = CTL_BUTTON; } break; case 64: #line 563 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 65: #line 567 "rcparse.y" { default_style = ES_LEFT | WS_BORDER | WS_TABSTOP; base_style = ES_LEFT | WS_BORDER | WS_TABSTOP; class = CTL_EDIT; } break; case 66: #line 573 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; if (dialog.ex == NULL) rcparse_warning (_("BEDIT requires DIALOGEX")); res_string_to_id (&yyval.dialog_control->class, "BEDIT"); } break; case 67: #line 580 "rcparse.y" { default_style = BS_CHECKBOX | WS_TABSTOP; base_style = BS_CHECKBOX | WS_TABSTOP; class = CTL_BUTTON; } break; case 68: #line 586 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 69: #line 590 "rcparse.y" { default_style = CBS_SIMPLE | WS_TABSTOP; base_style = 0; class = CTL_COMBOBOX; } break; case 70: #line 596 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 71: #line 601 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-9].s, yyvsp[-8].il, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, yyvsp[-2].il, yyvsp[-7].il, style, yyvsp[-1].il); if (yyvsp[0].rcdata_item != NULL) { if (dialog.ex == NULL) rcparse_warning (_("control data requires DIALOGEX")); yyval.dialog_control->data = yyvsp[0].rcdata_item; } } break; case 72: #line 612 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-10].s, yyvsp[-9].il, yyvsp[-6].il, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, yyvsp[-8].il, style, yyvsp[-2].il); if (dialog.ex == NULL) rcparse_warning (_("help ID requires DIALOGEX")); yyval.dialog_control->help = yyvsp[-1].il; yyval.dialog_control->data = yyvsp[0].rcdata_item; } break; case 73: #line 621 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-10].s, yyvsp[-9].il, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, yyvsp[-2].il, 0, style, yyvsp[-1].il); if (yyvsp[0].rcdata_item != NULL) { if (dialog.ex == NULL) rcparse_warning ("control data requires DIALOGEX"); yyval.dialog_control->data = yyvsp[0].rcdata_item; } yyval.dialog_control->class.named = 1; unicode_from_ascii (&yyval.dialog_control->class.u.n.length, &yyval.dialog_control->class.u.n.name, yyvsp[-7].s); } break; case 74: #line 634 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-11].s, yyvsp[-10].il, yyvsp[-6].il, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, 0, style, yyvsp[-2].il); if (dialog.ex == NULL) rcparse_warning ("help ID requires DIALOGEX"); yyval.dialog_control->help = yyvsp[-1].il; yyval.dialog_control->data = yyvsp[0].rcdata_item; yyval.dialog_control->class.named = 1; unicode_from_ascii (&yyval.dialog_control->class.u.n.length, &yyval.dialog_control->class.u.n.name, yyvsp[-8].s); } break; case 75: #line 644 "rcparse.y" { default_style = SS_CENTER | WS_GROUP; base_style = SS_CENTER; class = CTL_STATIC; } break; case 76: #line 650 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 77: #line 654 "rcparse.y" { default_style = BS_DEFPUSHBUTTON | WS_TABSTOP; base_style = BS_DEFPUSHBUTTON | WS_TABSTOP; class = CTL_BUTTON; } break; case 78: #line 660 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 79: #line 664 "rcparse.y" { default_style = ES_LEFT | WS_BORDER | WS_TABSTOP; base_style = ES_LEFT | WS_BORDER | WS_TABSTOP; class = CTL_EDIT; } break; case 80: #line 670 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 81: #line 674 "rcparse.y" { default_style = BS_GROUPBOX; base_style = BS_GROUPBOX; class = CTL_BUTTON; } break; case 82: #line 680 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 83: #line 684 "rcparse.y" { default_style = ES_LEFT | WS_BORDER | WS_TABSTOP; base_style = ES_LEFT | WS_BORDER | WS_TABSTOP; class = CTL_EDIT; } break; case 84: #line 690 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; if (dialog.ex == NULL) rcparse_warning (_("IEDIT requires DIALOGEX")); res_string_to_id (&yyval.dialog_control->class, "HEDIT"); } break; case 85: #line 697 "rcparse.y" { yyval.dialog_control = define_icon_control (yyvsp[-4].id, yyvsp[-3].il, yyvsp[-2].il, yyvsp[-1].il, 0, 0, 0, yyvsp[0].rcdata_item, dialog.ex); } break; case 86: #line 703 "rcparse.y" { yyval.dialog_control = define_icon_control (yyvsp[-6].id, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, 0, 0, 0, yyvsp[0].rcdata_item, dialog.ex); } break; case 87: #line 709 "rcparse.y" { yyval.dialog_control = define_icon_control (yyvsp[-8].id, yyvsp[-7].il, yyvsp[-6].il, yyvsp[-5].il, style, yyvsp[-1].il, 0, yyvsp[0].rcdata_item, dialog.ex); } break; case 88: #line 715 "rcparse.y" { yyval.dialog_control = define_icon_control (yyvsp[-9].id, yyvsp[-8].il, yyvsp[-7].il, yyvsp[-6].il, style, yyvsp[-2].il, yyvsp[-1].il, yyvsp[0].rcdata_item, dialog.ex); } break; case 89: #line 720 "rcparse.y" { default_style = ES_LEFT | WS_BORDER | WS_TABSTOP; base_style = ES_LEFT | WS_BORDER | WS_TABSTOP; class = CTL_EDIT; } break; case 90: #line 726 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; if (dialog.ex == NULL) rcparse_warning (_("IEDIT requires DIALOGEX")); res_string_to_id (&yyval.dialog_control->class, "IEDIT"); } break; case 91: #line 733 "rcparse.y" { default_style = LBS_NOTIFY | WS_BORDER; base_style = LBS_NOTIFY | WS_BORDER; class = CTL_LISTBOX; } break; case 92: #line 739 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 93: #line 743 "rcparse.y" { default_style = SS_LEFT | WS_GROUP; base_style = SS_LEFT; class = CTL_STATIC; } break; case 94: #line 749 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 95: #line 753 "rcparse.y" { default_style = BS_PUSHBOX | WS_TABSTOP; base_style = BS_PUSHBOX; class = CTL_BUTTON; } break; case 96: #line 759 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 97: #line 763 "rcparse.y" { default_style = BS_PUSHBUTTON | WS_TABSTOP; base_style = BS_PUSHBUTTON | WS_TABSTOP; class = CTL_BUTTON; } break; case 98: #line 769 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 99: #line 773 "rcparse.y" { default_style = BS_RADIOBUTTON | WS_TABSTOP; base_style = BS_RADIOBUTTON; class = CTL_BUTTON; } break; case 100: #line 779 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 101: #line 783 "rcparse.y" { default_style = SS_RIGHT | WS_GROUP; base_style = SS_RIGHT; class = CTL_STATIC; } break; case 102: #line 789 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 103: #line 793 "rcparse.y" { default_style = SBS_HORZ; base_style = 0; class = CTL_SCROLLBAR; } break; case 104: #line 799 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 105: #line 803 "rcparse.y" { default_style = BS_3STATE | WS_TABSTOP; base_style = BS_3STATE; class = CTL_BUTTON; } break; case 106: #line 809 "rcparse.y" { yyval.dialog_control = yyvsp[0].dialog_control; } break; case 107: #line 814 "rcparse.y" { style = WS_CHILD | WS_VISIBLE; } break; case 108: #line 816 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-14].s, yyvsp[-12].il, yyvsp[-10].il, yyvsp[-8].il, yyvsp[-6].il, yyvsp[-4].il, CTL_BUTTON, style, yyvsp[0].il); } break; case 109: #line 832 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-6].s, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, yyvsp[-2].il, yyvsp[-1].il, class, default_style | WS_CHILD | WS_VISIBLE, 0); if (yyvsp[0].rcdata_item != NULL) { if (dialog.ex == NULL) rcparse_warning (_("control data requires DIALOGEX")); yyval.dialog_control->data = yyvsp[0].rcdata_item; } } break; case 110: #line 844 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-8].s, yyvsp[-7].il, yyvsp[-6].il, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, class, style, yyvsp[-1].il); if (yyvsp[0].rcdata_item != NULL) { if (dialog.ex == NULL) rcparse_warning (_("control data requires DIALOGEX")); yyval.dialog_control->data = yyvsp[0].rcdata_item; } } break; case 111: #line 855 "rcparse.y" { yyval.dialog_control = define_control (yyvsp[-9].s, yyvsp[-8].il, yyvsp[-7].il, yyvsp[-6].il, yyvsp[-5].il, yyvsp[-4].il, class, style, yyvsp[-2].il); if (dialog.ex == NULL) rcparse_warning (_("help ID requires DIALOGEX")); yyval.dialog_control->help = yyvsp[-1].il; yyval.dialog_control->data = yyvsp[0].rcdata_item; } break; case 112: #line 866 "rcparse.y" { yyval.s = NULL; } break; case 113: #line 870 "rcparse.y" { yyval.s = yyvsp[0].s; } break; case 114: #line 874 "rcparse.y" { yyval.s = yyvsp[-1].s; } break; case 115: #line 881 "rcparse.y" { yyval.rcdata_item = NULL; } break; case 116: #line 885 "rcparse.y" { yyval.rcdata_item = yyvsp[-1].rcdata.first; } break; case 117: #line 894 "rcparse.y" { style = WS_CHILD | WS_VISIBLE; } break; case 119: #line 900 "rcparse.y" { style = SS_ICON | WS_CHILD | WS_VISIBLE; } break; case 121: #line 906 "rcparse.y" { style = base_style | WS_CHILD | WS_VISIBLE; } break; case 123: #line 914 "rcparse.y" { define_font (yyvsp[-3].id, &yyvsp[-1].res_info, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 124: #line 926 "rcparse.y" { define_icon (yyvsp[-3].id, &yyvsp[-1].res_info, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 125: #line 939 "rcparse.y" { language = yyvsp[-1].il | (yyvsp[0].il << SUBLANG_SHIFT); } break; case 126: #line 948 "rcparse.y" { define_menu (yyvsp[-5].id, &yyvsp[-3].res_info, yyvsp[-1].menuitem); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 127: #line 958 "rcparse.y" { yyval.menuitem = NULL; } break; case 128: #line 962 "rcparse.y" { if (yyvsp[-1].menuitem == NULL) yyval.menuitem = yyvsp[0].menuitem; else { struct menuitem **pp; for (pp = &yyvsp[-1].menuitem->next; *pp != NULL; pp = &(*pp)->next) ; *pp = yyvsp[0].menuitem; yyval.menuitem = yyvsp[-1].menuitem; } } break; case 129: #line 979 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-2].s, yyvsp[-1].il, yyvsp[0].is, 0, 0, NULL); } break; case 130: #line 983 "rcparse.y" { yyval.menuitem = define_menuitem (NULL, 0, 0, 0, 0, NULL); } break; case 131: #line 987 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-4].s, 0, yyvsp[-3].is, 0, 0, yyvsp[-1].menuitem); } break; case 132: #line 994 "rcparse.y" { yyval.is = 0; } break; case 133: #line 998 "rcparse.y" { yyval.is = yyvsp[-2].is | yyvsp[0].is; } break; case 134: #line 1002 "rcparse.y" { yyval.is = yyvsp[-1].is | yyvsp[0].is; } break; case 135: #line 1009 "rcparse.y" { yyval.is = MENUITEM_CHECKED; } break; case 136: #line 1013 "rcparse.y" { yyval.is = MENUITEM_GRAYED; } break; case 137: #line 1017 "rcparse.y" { yyval.is = MENUITEM_HELP; } break; case 138: #line 1021 "rcparse.y" { yyval.is = MENUITEM_INACTIVE; } break; case 139: #line 1025 "rcparse.y" { yyval.is = MENUITEM_MENUBARBREAK; } break; case 140: #line 1029 "rcparse.y" { yyval.is = MENUITEM_MENUBREAK; } break; case 141: #line 1038 "rcparse.y" { define_menu (yyvsp[-5].id, &yyvsp[-3].res_info, yyvsp[-1].menuitem); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 142: #line 1048 "rcparse.y" { yyval.menuitem = NULL; } break; case 143: #line 1052 "rcparse.y" { if (yyvsp[-1].menuitem == NULL) yyval.menuitem = yyvsp[0].menuitem; else { struct menuitem **pp; for (pp = &yyvsp[-1].menuitem->next; *pp != NULL; pp = &(*pp)->next) ; *pp = yyvsp[0].menuitem; yyval.menuitem = yyvsp[-1].menuitem; } } break; case 144: #line 1069 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[0].s, 0, 0, 0, 0, NULL); } break; case 145: #line 1073 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-1].s, yyvsp[0].il, 0, 0, 0, NULL); } break; case 146: #line 1077 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-3].s, yyvsp[-2].il, yyvsp[-1].il, yyvsp[0].il, 0, NULL); } break; case 147: #line 1081 "rcparse.y" { yyval.menuitem = define_menuitem (NULL, 0, 0, 0, 0, NULL); } break; case 148: #line 1085 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-3].s, 0, 0, 0, 0, yyvsp[-1].menuitem); } break; case 149: #line 1089 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-4].s, yyvsp[-3].il, 0, 0, 0, yyvsp[-1].menuitem); } break; case 150: #line 1093 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-5].s, yyvsp[-4].il, yyvsp[-3].il, 0, 0, yyvsp[-1].menuitem); } break; case 151: #line 1098 "rcparse.y" { yyval.menuitem = define_menuitem (yyvsp[-7].s, yyvsp[-6].il, yyvsp[-5].il, yyvsp[-4].il, yyvsp[-3].il, yyvsp[-1].menuitem); } break; case 152: #line 1107 "rcparse.y" { define_messagetable (yyvsp[-3].id, &yyvsp[-1].res_info, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 153: #line 1119 "rcparse.y" { define_rcdata (yyvsp[-5].id, &yyvsp[-3].res_info, yyvsp[-1].rcdata.first); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 154: #line 1131 "rcparse.y" { rcparse_rcdata (); } break; case 155: #line 1135 "rcparse.y" { rcparse_normal (); yyval.rcdata = yyvsp[0].rcdata; } break; case 156: #line 1143 "rcparse.y" { yyval.rcdata.first = NULL; yyval.rcdata.last = NULL; } break; case 157: #line 1148 "rcparse.y" { yyval.rcdata = yyvsp[0].rcdata; } break; case 158: #line 1155 "rcparse.y" { struct rcdata_item *ri; ri = define_rcdata_string (yyvsp[0].ss.s, yyvsp[0].ss.length); yyval.rcdata.first = ri; yyval.rcdata.last = ri; } break; case 159: #line 1163 "rcparse.y" { struct rcdata_item *ri; ri = define_rcdata_number (yyvsp[0].i.val, yyvsp[0].i.dword); yyval.rcdata.first = ri; yyval.rcdata.last = ri; } break; case 160: #line 1171 "rcparse.y" { struct rcdata_item *ri; ri = define_rcdata_string (yyvsp[0].ss.s, yyvsp[0].ss.length); yyval.rcdata.first = yyvsp[-2].rcdata.first; yyvsp[-2].rcdata.last->next = ri; yyval.rcdata.last = ri; } break; case 161: #line 1180 "rcparse.y" { struct rcdata_item *ri; ri = define_rcdata_number (yyvsp[0].i.val, yyvsp[0].i.dword); yyval.rcdata.first = yyvsp[-2].rcdata.first; yyvsp[-2].rcdata.last->next = ri; yyval.rcdata.last = ri; } break; case 162: #line 1194 "rcparse.y" { sub_res_info = yyvsp[-1].res_info; } break; case 165: #line 1201 "rcparse.y" { define_stringtable (&sub_res_info, yyvsp[-1].il, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 166: #line 1208 "rcparse.y" { define_stringtable (&sub_res_info, yyvsp[-2].il, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 167: #line 1221 "rcparse.y" { define_user_data (yyvsp[-5].id, yyvsp[-4].id, &yyvsp[-3].res_info, yyvsp[-1].rcdata.first); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 168: #line 1228 "rcparse.y" { define_user_file (yyvsp[-3].id, yyvsp[-2].id, &yyvsp[-1].res_info, yyvsp[0].s); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 169: #line 1240 "rcparse.y" { define_versioninfo (yyvsp[-5].id, language, yyvsp[-3].fixver, yyvsp[-1].verinfo); if (yychar != YYEMPTY) YYERROR; rcparse_discard_strings (); } break; case 170: #line 1250 "rcparse.y" { yyval.fixver = ((struct fixed_versioninfo *) res_alloc (sizeof (struct fixed_versioninfo))); memset (yyval.fixver, 0, sizeof (struct fixed_versioninfo)); } break; case 171: #line 1256 "rcparse.y" { yyvsp[-5].fixver->file_version_ms = (yyvsp[-3].il << 16) | yyvsp[-2].il; yyvsp[-5].fixver->file_version_ls = (yyvsp[-1].il << 16) | yyvsp[0].il; yyval.fixver = yyvsp[-5].fixver; } break; case 172: #line 1262 "rcparse.y" { yyvsp[-5].fixver->product_version_ms = (yyvsp[-3].il << 16) | yyvsp[-2].il; yyvsp[-5].fixver->product_version_ls = (yyvsp[-1].il << 16) | yyvsp[0].il; yyval.fixver = yyvsp[-5].fixver; } break; case 173: #line 1268 "rcparse.y" { yyvsp[-2].fixver->file_flags_mask = yyvsp[0].il; yyval.fixver = yyvsp[-2].fixver; } break; case 174: #line 1273 "rcparse.y" { yyvsp[-2].fixver->file_flags = yyvsp[0].il; yyval.fixver = yyvsp[-2].fixver; } break; case 175: #line 1278 "rcparse.y" { yyvsp[-2].fixver->file_os = yyvsp[0].il; yyval.fixver = yyvsp[-2].fixver; } break; case 176: #line 1283 "rcparse.y" { yyvsp[-2].fixver->file_type = yyvsp[0].il; yyval.fixver = yyvsp[-2].fixver; } break; case 177: #line 1288 "rcparse.y" { yyvsp[-2].fixver->file_subtype = yyvsp[0].il; yyval.fixver = yyvsp[-2].fixver; } break; case 178: #line 1302 "rcparse.y" { yyval.verinfo = NULL; } break; case 179: #line 1306 "rcparse.y" { yyval.verinfo = append_ver_stringfileinfo (yyvsp[-7].verinfo, yyvsp[-4].s, yyvsp[-2].verstring); } break; case 180: #line 1310 "rcparse.y" { yyval.verinfo = append_ver_varfileinfo (yyvsp[-6].verinfo, yyvsp[-2].s, yyvsp[-1].vervar); } break; case 181: #line 1317 "rcparse.y" { yyval.verstring = NULL; } break; case 182: #line 1321 "rcparse.y" { yyval.verstring = append_verval (yyvsp[-4].verstring, yyvsp[-2].s, yyvsp[0].s); } break; case 183: #line 1328 "rcparse.y" { yyval.vervar = NULL; } break; case 184: #line 1332 "rcparse.y" { yyval.vervar = append_vertrans (yyvsp[-2].vervar, yyvsp[-1].il, yyvsp[0].il); } break; case 185: #line 1341 "rcparse.y" { yyval.id.named = 0; yyval.id.u.id = yyvsp[0].il; } break; case 186: #line 1346 "rcparse.y" { char *copy, *s; /* It seems that resource ID's are forced to upper case. */ copy = xstrdup (yyvsp[0].s); for (s = copy; *s != '\0'; s++) *s = TOUPPER (*s); res_string_to_id (&yyval.id, copy); free (copy); } break; case 187: #line 1362 "rcparse.y" { yyval.s = yyvsp[0].s; } break; case 188: #line 1366 "rcparse.y" { yyval.s = yyvsp[-1].s; } break; case 189: #line 1370 "rcparse.y" { yyval.s = yyvsp[-1].s; } break; case 190: #line 1378 "rcparse.y" { yyval.id.named = 0; yyval.id.u.id = yyvsp[-1].il; } break; case 191: #line 1383 "rcparse.y" { char *copy, *s; /* It seems that resource ID's are forced to upper case. */ copy = xstrdup (yyvsp[0].s); for (s = copy; *s != '\0'; s++) *s = TOUPPER (*s); res_string_to_id (&yyval.id, copy); free (copy); } break; case 192: #line 1400 "rcparse.y" { memset (&yyval.res_info, 0, sizeof (struct res_res_info)); yyval.res_info.language = language; /* FIXME: Is this the right default? */ yyval.res_info.memflags = MEMFLAG_MOVEABLE | MEMFLAG_PURE | MEMFLAG_DISCARDABLE; } break; case 193: #line 1407 "rcparse.y" { yyval.res_info = yyvsp[-1].res_info; yyval.res_info.memflags |= yyvsp[0].memflags.on; yyval.res_info.memflags &=~ yyvsp[0].memflags.off; } break; case 194: #line 1413 "rcparse.y" { yyval.res_info = yyvsp[-2].res_info; yyval.res_info.characteristics = yyvsp[0].il; } break; case 195: #line 1418 "rcparse.y" { yyval.res_info = yyvsp[-3].res_info; yyval.res_info.language = yyvsp[-1].il | (yyvsp[0].il << SUBLANG_SHIFT); } break; case 196: #line 1423 "rcparse.y" { yyval.res_info = yyvsp[-2].res_info; yyval.res_info.version = yyvsp[0].il; } break; case 197: #line 1433 "rcparse.y" { memset (&yyval.res_info, 0, sizeof (struct res_res_info)); yyval.res_info.language = language; yyval.res_info.memflags = MEMFLAG_MOVEABLE | MEMFLAG_DISCARDABLE; } break; case 198: #line 1439 "rcparse.y" { yyval.res_info = yyvsp[-1].res_info; yyval.res_info.memflags |= yyvsp[0].memflags.on; yyval.res_info.memflags &=~ yyvsp[0].memflags.off; } break; case 199: #line 1450 "rcparse.y" { memset (&yyval.res_info, 0, sizeof (struct res_res_info)); yyval.res_info.language = language; yyval.res_info.memflags = MEMFLAG_MOVEABLE | MEMFLAG_PURE | MEMFLAG_DISCARDABLE; } break; case 200: #line 1456 "rcparse.y" { yyval.res_info = yyvsp[-1].res_info; yyval.res_info.memflags |= yyvsp[0].memflags.on; yyval.res_info.memflags &=~ yyvsp[0].memflags.off; } break; case 201: #line 1468 "rcparse.y" { yyval.memflags.on = MEMFLAG_MOVEABLE; yyval.memflags.off = 0; } break; case 202: #line 1473 "rcparse.y" { yyval.memflags.on = 0; yyval.memflags.off = MEMFLAG_MOVEABLE; } break; case 203: #line 1478 "rcparse.y" { yyval.memflags.on = MEMFLAG_PURE; yyval.memflags.off = 0; } break; case 204: #line 1483 "rcparse.y" { yyval.memflags.on = 0; yyval.memflags.off = MEMFLAG_PURE; } break; case 205: #line 1488 "rcparse.y" { yyval.memflags.on = MEMFLAG_PRELOAD; yyval.memflags.off = 0; } break; case 206: #line 1493 "rcparse.y" { yyval.memflags.on = 0; yyval.memflags.off = MEMFLAG_PRELOAD; } break; case 207: #line 1498 "rcparse.y" { yyval.memflags.on = MEMFLAG_DISCARDABLE; yyval.memflags.off = 0; } break; case 208: #line 1508 "rcparse.y" { yyval.s = yyvsp[0].s; } break; case 209: #line 1512 "rcparse.y" { yyval.s = yyvsp[0].s; } break; case 210: #line 1529 "rcparse.y" { style |= yyvsp[0].il; } break; case 211: #line 1533 "rcparse.y" { style &=~ yyvsp[0].il; } break; case 212: #line 1537 "rcparse.y" { style |= yyvsp[0].il; } break; case 213: #line 1541 "rcparse.y" { style &=~ yyvsp[0].il; } break; case 214: #line 1548 "rcparse.y" { yyval.il = yyvsp[0].i.val; } break; case 215: #line 1552 "rcparse.y" { yyval.il = yyvsp[-1].il; } break; case 216: #line 1561 "rcparse.y" { yyval.il = 0; } break; case 217: #line 1565 "rcparse.y" { yyval.il = yyvsp[0].il; } break; case 218: #line 1574 "rcparse.y" { yyval.il = yyvsp[0].il; } break; case 219: #line 1583 "rcparse.y" { yyval.il = yyvsp[0].i.val; } break; case 220: #line 1592 "rcparse.y" { yyval.i = yyvsp[0].i; } break; case 221: #line 1596 "rcparse.y" { yyval.i = yyvsp[-1].i; } break; case 222: #line 1600 "rcparse.y" { yyval.i.val = ~ yyvsp[0].i.val; yyval.i.dword = yyvsp[0].i.dword; } break; case 223: #line 1605 "rcparse.y" { yyval.i.val = - yyvsp[0].i.val; yyval.i.dword = yyvsp[0].i.dword; } break; case 224: #line 1610 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val * yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 225: #line 1615 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val / yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 226: #line 1620 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val % yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 227: #line 1625 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val + yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 228: #line 1630 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val - yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 229: #line 1635 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val & yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 230: #line 1640 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val ^ yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 231: #line 1645 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val | yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 232: #line 1656 "rcparse.y" { yyval.il = yyvsp[0].il; } break; case 233: #line 1665 "rcparse.y" { yyval.il = yyvsp[0].i.val; } break; case 234: #line 1676 "rcparse.y" { yyval.i = yyvsp[0].i; } break; case 235: #line 1680 "rcparse.y" { yyval.i = yyvsp[-1].i; } break; case 236: #line 1684 "rcparse.y" { yyval.i.val = ~ yyvsp[0].i.val; yyval.i.dword = yyvsp[0].i.dword; } break; case 237: #line 1689 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val * yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 238: #line 1694 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val / yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 239: #line 1699 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val % yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 240: #line 1704 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val + yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 241: #line 1709 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val - yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 242: #line 1714 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val & yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 243: #line 1719 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val ^ yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; case 244: #line 1724 "rcparse.y" { yyval.i.val = yyvsp[-2].i.val | yyvsp[0].i.val; yyval.i.dword = yyvsp[-2].i.dword || yyvsp[0].i.dword; } break; } #line 705 "/usr/share/bison-1.35/bison.simple" yyvsp -= yylen; yyssp -= yylen; #if YYLSP_NEEDED yylsp -= yylen; #endif #if YYDEBUG if (yydebug) { short *yyssp1 = yyss - 1; YYFPRINTF (stderr, "state stack now"); while (yyssp1 != yyssp) YYFPRINTF (stderr, " %d", *++yyssp1); YYFPRINTF (stderr, "\n"); } #endif *++yyvsp = yyval; #if YYLSP_NEEDED *++yylsp = yyloc; #endif /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTBASE] + *yyssp; if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTBASE]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #ifdef YYERROR_VERBOSE yyn = yypact[yystate]; if (yyn > YYFLAG && yyn < YYLAST) { YYSIZE_T yysize = 0; char *yymsg; int yyx, yycount; yycount = 0; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ for (yyx = yyn < 0 ? -yyn : 0; yyx < (int) (sizeof (yytname) / sizeof (char *)); yyx++) if (yycheck[yyx + yyn] == yyx) yysize += yystrlen (yytname[yyx]) + 15, yycount++; yysize += yystrlen ("parse error, unexpected ") + 1; yysize += yystrlen (yytname[YYTRANSLATE (yychar)]); yymsg = (char *) YYSTACK_ALLOC (yysize); if (yymsg != 0) { char *yyp = yystpcpy (yymsg, "parse error, unexpected "); yyp = yystpcpy (yyp, yytname[YYTRANSLATE (yychar)]); if (yycount < 5) { yycount = 0; for (yyx = yyn < 0 ? -yyn : 0; yyx < (int) (sizeof (yytname) / sizeof (char *)); yyx++) if (yycheck[yyx + yyn] == yyx) { const char *yyq = ! yycount ? ", expecting " : " or "; yyp = yystpcpy (yyp, yyq); yyp = yystpcpy (yyp, yytname[yyx]); yycount++; } } yyerror (yymsg); YYSTACK_FREE (yymsg); } else yyerror ("parse error; also virtual memory exhausted"); } else #endif /* defined (YYERROR_VERBOSE) */ yyerror ("parse error"); } goto yyerrlab1; /*--------------------------------------------------. | yyerrlab1 -- error raised explicitly by an action | `--------------------------------------------------*/ yyerrlab1: if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ /* return failure if at end of input */ if (yychar == YYEOF) YYABORT; YYDPRINTF ((stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1])); yychar = YYEMPTY; } /* Else will try to reuse lookahead token after shifting the error token. */ yyerrstatus = 3; /* Each real token shifted decrements this */ goto yyerrhandle; /*-------------------------------------------------------------------. | yyerrdefault -- current state does not do anything special for the | | error token. | `-------------------------------------------------------------------*/ yyerrdefault: #if 0 /* This is wrong; only states that explicitly want error tokens should shift them. */ /* If its default is to accept any token, ok. Otherwise pop it. */ yyn = yydefact[yystate]; if (yyn) goto yydefault; #endif /*---------------------------------------------------------------. | yyerrpop -- pop the current state because it cannot handle the | | error token | `---------------------------------------------------------------*/ yyerrpop: if (yyssp == yyss) YYABORT; yyvsp--; yystate = *--yyssp; #if YYLSP_NEEDED yylsp--; #endif #if YYDEBUG if (yydebug) { short *yyssp1 = yyss - 1; YYFPRINTF (stderr, "Error: state stack now"); while (yyssp1 != yyssp) YYFPRINTF (stderr, " %d", *++yyssp1); YYFPRINTF (stderr, "\n"); } #endif /*--------------. | yyerrhandle. | `--------------*/ yyerrhandle: yyn = yypact[yystate]; if (yyn == YYFLAG) goto yyerrdefault; yyn += YYTERROR; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR) goto yyerrdefault; yyn = yytable[yyn]; if (yyn < 0) { if (yyn == YYFLAG) goto yyerrpop; yyn = -yyn; goto yyreduce; } else if (yyn == 0) goto yyerrpop; if (yyn == YYFINAL) YYACCEPT; YYDPRINTF ((stderr, "Shifting error token, ")); *++yyvsp = yylval; #if YYLSP_NEEDED *++yylsp = yylloc; #endif yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; /*---------------------------------------------. | yyoverflowab -- parser overflow comes here. | `---------------------------------------------*/ yyoverflowlab: yyerror ("parser stack overflow"); yyresult = 2; /* Fall through. */ yyreturn: #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif return yyresult; } #line 1730 "rcparse.y" /* Set the language from the command line. */ void rcparse_set_language (lang) int lang; { language = lang; }
30.109919
163
0.515041
[ "object" ]
59b2d7e33218c472c5aa262cfb2f4b0e414f8b0b
3,250
h
C
ReactiveObjC/RACBlockTrampoline.h
ofirgluzman/ReactiveObjC
cb3cdd6c056977c6b736ea9682af03218742846b
[ "MIT" ]
2
2017-11-02T18:03:54.000Z
2021-04-05T07:23:17.000Z
ReactiveObjC/RACBlockTrampoline.h
ofirgluzman/ReactiveObjC
cb3cdd6c056977c6b736ea9682af03218742846b
[ "MIT" ]
22
2017-07-24T12:22:30.000Z
2021-12-19T11:47:37.000Z
ReactiveObjC/RACBlockTrampoline.h
ofirgluzman/ReactiveObjC
cb3cdd6c056977c6b736ea9682af03218742846b
[ "MIT" ]
7
2017-10-26T09:24:39.000Z
2021-04-07T18:07:59.000Z
// // RACBlockTrampoline.h // ReactiveObjC // // Created by Josh Abernathy on 10/21/12. // Copyright (c) 2012 GitHub, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "RACTuple.h" // Invokes the given block with the given arguments. All of the block's // argument types must be objects and it must be typed to return an object. // // At this time, it only supports blocks that take up to 15 arguments. Any more // is just cray. // // block - The block to invoke. Must accept as many arguments as are given in // the arguments array. Cannot be nil. // args - The arguments with which to invoke the block. `RACTupleNil`s will // be passed as nils. // // Returns the return value of invoking the block. static inline id RACInvokeBlock(id block, RACTuple *args) { NSCParameterAssert(block != NULL && args.count > 0); switch (args.count) { case 0: return nil; case 1: return ((id(^)(id))block)(args[0]); case 2: return ((id(^)(id, id))block)(args[0], args[1]); case 3: return ((id(^)(id, id, id))block)(args[0], args[1], args[2]); case 4: return ((id(^)(id, id, id, id))block)(args[0], args[1], args[2], args[3]); case 5: return ((id(^)(id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4]); case 6: return ((id(^)(id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return ((id(^)(id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return ((id(^)(id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return ((id(^)(id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return ((id(^)(id, id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); case 11: return ((id(^)(id, id, id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10]); case 12: return ((id(^)(id, id, id, id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11]); case 13: return ((id(^)(id, id, id, id, id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12]); case 14: return ((id(^)(id, id, id, id, id, id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13]); case 15: return ((id(^)(id, id, id, id, id, id, id, id, id, id, id, id, id, id, id))block)(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14]); } NSCAssert(NO, @"The argument count is too damn high! Only blocks of up to 15 arguments are currently supported."); return nil; }
49.242424
228
0.573231
[ "object" ]
59b319cd692b3dc54d0eae5075b8401358093ce2
2,055
h
C
Objective-C/Internal/CBLJSON.h
muizidn/couchbase-lite-ios
f6728d287dc1de05dc36e519191fcbf65750797b
[ "Apache-2.0" ]
1,088
2015-01-01T02:58:17.000Z
2022-03-24T22:52:36.000Z
Objective-C/Internal/CBLJSON.h
muizidn/couchbase-lite-ios
f6728d287dc1de05dc36e519191fcbf65750797b
[ "Apache-2.0" ]
1,969
2015-01-02T06:15:36.000Z
2022-03-26T05:44:13.000Z
Objective-C/Internal/CBLJSON.h
muizidn/couchbase-lite-ios
f6728d287dc1de05dc36e519191fcbf65750797b
[ "Apache-2.0" ]
279
2015-01-05T09:55:32.000Z
2022-03-12T15:54:57.000Z
// // CBLJSON.h // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Identical to the corresponding NSJSON option flags, with one addition. */ enum { CBLJSONWritingPrettyPrinted = (1UL << 0), CBLJSONWritingAllowFragments = (1UL << 23) /**< Allows input to be an NSString or NSValue. */ }; typedef NSUInteger CBLJSONWritingOptions; /** Useful extensions for JSON serialization/parsing. */ @interface CBLJSON : NSJSONSerialization /** Encodes an NSDate as a string in ISO-8601 format. */ + (nullable NSString*) JSONObjectWithDate: (nullable NSDate*)date; + (nullable NSString*) JSONObjectWithDate: (nullable NSDate*)date timeZone:(NSTimeZone *)tz; /** Parses an ISO-8601 formatted date string to an NSDate object. If the object is not a string, or not valid ISO-8601, or nil, it returns nil. */ + (nullable NSDate*) dateWithJSONObject: (nullable id)jsonObject; /** Parses an ISO-8601 formatted date string to an absolute time (timeSinceReferenceDate). If the object is not a string, or not valid ISO-8601, or nil, it returns a NAN value. */ + (CFAbsoluteTime) absoluteTimeWithJSONObject: (nullable id)jsonObject; /** Encodes an object to a JSON string. */ + (nullable NSString *)stringWithJSONObject:(id)object options:(NSJSONWritingOptions)options error:(NSError **)error; @end NS_ASSUME_NONNULL_END
37.363636
98
0.715815
[ "object" ]
59c3870e8680c6e7c0235c68c68e97cfeed7ad16
689
h
C
lin-code-gen/Math.h
ZeraPain/Coding-Theory
34e6e43e6ed65405e3c388add912e6e775e54af5
[ "Apache-2.0" ]
null
null
null
lin-code-gen/Math.h
ZeraPain/Coding-Theory
34e6e43e6ed65405e3c388add912e6e775e54af5
[ "Apache-2.0" ]
null
null
null
lin-code-gen/Math.h
ZeraPain/Coding-Theory
34e6e43e6ed65405e3c388add912e6e775e54af5
[ "Apache-2.0" ]
1
2019-08-01T06:02:28.000Z
2019-08-01T06:02:28.000Z
#pragma once #include <armadillo> namespace Math { auto normalizeVector(arma::s32_vec& v, int q) -> void; auto isEqualVector(const arma::s32_vec& v1, const arma::s32_vec& v2) -> bool; auto isLinDependent(const arma::s32_vec& v1, const arma::s32_vec& v2, uint16_t q) -> bool; auto isNullVector(const arma::s32_vec& rVector) -> bool; auto getVectorIndex(const std::vector<arma::s32_vec>& rVector, const arma::s32_vec& rVec, int q) -> int; auto encode(const arma::s32_vec& word, const arma::s32_mat &G, int q) -> arma::s32_vec; auto generateCanonialRepresents(uint16_t q, uint16_t k)->std::vector<arma::s32_vec>; auto generateLanguage(int q, int k) -> std::vector<arma::s32_vec>; }
43.0625
105
0.725689
[ "vector" ]
59cd109ee824c58caf48040c474181d9f76f4f4a
2,047
h
C
src/cobj_rcboxt.h
jwebb68/c-objects
54397b93611403c01d9be80519caf7985de3fe35
[ "BSD-3-Clause" ]
null
null
null
src/cobj_rcboxt.h
jwebb68/c-objects
54397b93611403c01d9be80519caf7985de3fe35
[ "BSD-3-Clause" ]
null
null
null
src/cobj_rcboxt.h
jwebb68/c-objects
54397b93611403c01d9be80519caf7985de3fe35
[ "BSD-3-Clause" ]
null
null
null
#if !defined(COBJ_RCBOXT_H) # define COBJ_RCBOXT_H /** * RCBox<T>: object created and managed on the heap, with sharing. * * RCBox contents are not owned by the box and are shared using simple ref counting. * inherently Mutable; cannot move a const value into it, cannot copy into into a const box. * */ // because it's C there is no template mechanism, so this needs to be repeated for each type // being treated this way. // forward declares typedef struct RCNodeT_ RCNodeT; typedef struct RCBoxT_ RCBoxT; // includes # include "cobj_error.h" # include "t.h" # include <stdbool.h> // defines struct RCBoxT_ { RCNodeT *node; }; void RCBoxT_destroy(RCBoxT *const self); void RCBoxT_move(RCBoxT *const self, RCBoxT *const src); bool WARN_UNUSED_RESULT RCBoxT_try_copy(RCBoxT *const self, RCBoxT const *const src); T const *RCBoxT_deref(RCBoxT const *const self); T *RCBoxT_deref_mut(RCBoxT *const self); bool RCBoxT_is_eq(RCBoxT const *const self, RCBoxT const *const b); bool RCBoxT_is_lt(RCBoxT const *const self, RCBoxT const *const b); bool RCBoxT_is_gt(RCBoxT const *const self, RCBoxT const *const b); bool RCBoxT_is_le(RCBoxT const *const self, RCBoxT const *const b); bool RCBoxT_is_ge(RCBoxT const *const self, RCBoxT const *const b); bool RCBoxT_contains(RCBoxT const *const self, T const *const v); bool WARN_UNUSED_RESULT RCBoxT_try_new_from_T(RCBoxT *const self, T *const v, Error *const err); // new_copy variant? copy direct into dest without intermed storage? bool WARN_UNUSED_RESULT RCBoxT_try_new_copy_T(RCBoxT *const self, T const *const v, Error *const err); bool WARN_UNUSED_RESULT RCBoxT_try_new_int(RCBoxT *const self, int v, Error *const err); // no own of a ptr: that leads to heap fragmentation // no own of a value: that's a new_default + T_destroy + T_move // no disown of value: that requires only 1 ref so would be a try_disown, and also required as move. #endif //! defined(COBJ_RCBOXT_H)
35.293103
100
0.720078
[ "object" ]
59cd5b3408db38549c049eafcca8648a79194b10
4,480
h
C
dataAcquisition/ARFFWriter.h
ckingsford/CGE-API
b9de2daa3889adf7b048bb94592c69d32cca78db
[ "BSD-2-Clause" ]
null
null
null
dataAcquisition/ARFFWriter.h
ckingsford/CGE-API
b9de2daa3889adf7b048bb94592c69d32cca78db
[ "BSD-2-Clause" ]
null
null
null
dataAcquisition/ARFFWriter.h
ckingsford/CGE-API
b9de2daa3889adf7b048bb94592c69d32cca78db
[ "BSD-2-Clause" ]
null
null
null
#ifndef ARFFWRITER_H #define ARFFWRITER_H #include "Genotype.h" #include "StringFunctions.h" #include <iostream> #include <fstream> #include <sstream> using namespace cge::patients; namespace cge{ namespace dataaquisition{ bool writeARFFfromClinical(std::ostream& clin_file, Patient& P) { try{ std::shared_ptr<ClinicalRecord> clin_rec = P.clinicalRecord(); //header clin_file << "% 1. Title: CGE Clinical Record\n%\n"; clin_file << "@RELATION clinical_record\n\n"; //attributes clin_file << "@ATTRIBUTE string_value STRING\n"; clin_file << "@ATTRIBUTE bool_value {true, false}\n"; clin_file << "@ATTRIBUTE date_value date [yyyy-MM-dd]\n"; clin_file << "@ATTRIBUTE int_value NUMERIC\n"; clin_file << "@ATTRIBUTE double_value NUMERIC\n"; clin_file << "@ATTRIBUTE history_value STRING\n"; clin_file << "@ATTRIBUTE name STRING\n"; clin_file << "@ATTRIBUTE required {true,false}\n"; //get all info const std::vector<std::shared_ptr<const ClinicalValue>> values = clin_rec->valuesAsVector(); const std::vector<std::string> names= clin_rec->schema()->fieldNames(); std::vector<bool> requires; for(auto it = names.begin(); it != names.end(); ++it) requires.push_back(clin_rec->schema()->isRequired(*it)); //data writing clin_file << "@data\n"; for (size_t i = 0; i < values.size(); ++i){ std::string val = values.at(i)->toString(); if(values.at(i)->type().compare("String") == 0){ clin_file << "" + val + ",?,?,?,?,?,"; } else if (values.at(i)->type().compare("Bool") == 0){ clin_file << "?," + val + ",?,?,?,?,"; } else if (values.at(i)->type().compare("Double") == 0){ clin_file << "?,?," + val + ",?,?,?,"; } else if (values.at(i)->type().compare("Int") == 0){ clin_file << "?,?,?," + val + ",?,?,"; } else if (values.at(i)->type().compare("Date") == 0){ clin_file << "?,?,?,?," + val + ",?,"; } else if (values.at(i)->type().compare("History") == 0){ clin_file << "?,?,?,?,?," + val + ","; } else{ clin_file << "?,?,?,?,?,?,"; } std::string req; if (requires.at(i)) req = "true"; else req = "false"; clin_file << names.at(i) + ',' + req + '\n'; } return true; } catch(...){ return false; } } bool writeARFFfromGenomic(std::ostream& geno_file, Patient& P) { try{ std::shared_ptr<Genotype> geno = P.genotype(); //header geno_file << "% 1. Title: CGE Genotype\n%\n"; geno_file << "@RELATION genotype\n\n"; //attributes geno_file << "@ATTRIBUTE name STRING\n"; geno_file << "@ATTRIBUTE location STRING\n";//as chrom.pos.rs.ref geno_file << "@ATTRIBUTE variant_list STRING\n"; geno_file << "@ATTRIBUTE variant STRING\n"; //get info const std::vector<std::string> names = geno->schema()->fieldNames(); std::vector<std::string> locations; for (auto i = geno->schema()->begin(); i != geno->schema()->end(); ++i){ GenomicLocation loc = (*i)->location(); std::string loc_string = std::to_string(loc.chromosome()) + "."; loc_string += std::to_string(loc.position()) + "."; loc_string += loc.rsNumber() + "."; loc_string += loc.refGenome()->name(); locations.push_back(loc_string); } std::vector<std::string> variant_lists; for (auto i = geno->schema()->begin(); i != geno->schema()->end(); ++i){ std::vector<std::string> v_list = (*i)->variantList(); std::string result = ""; for (auto const& s : v_list) result += s + "\u001f"; result.pop_back(); variant_lists.push_back(result); } std::vector<char> variants = geno->variantsAsVector(); //data writing geno_file << "@data\n"; for (size_t i = 0; i < names.size(); ++i){ geno_file << names[i] + "," + locations[i] + "," + variant_lists[i] + ","; geno_file << variants[i] + "\n"; } return true; } catch(...){ return false; } } }//dataaquisition }//cge #endif
32.463768
83
0.51808
[ "vector" ]
59d0e52b3207add871f22cba9fc6619cce15e7df
1,882
h
C
adaptors/x11/x-events/x-input2-device.h
pwisbey/dali-adaptor
21d5e77316e53285fa1e210a93b13cf9889e3b54
[ "Apache-2.0" ]
null
null
null
adaptors/x11/x-events/x-input2-device.h
pwisbey/dali-adaptor
21d5e77316e53285fa1e210a93b13cf9889e3b54
[ "Apache-2.0" ]
null
null
null
adaptors/x11/x-events/x-input2-device.h
pwisbey/dali-adaptor
21d5e77316e53285fa1e210a93b13cf9889e3b54
[ "Apache-2.0" ]
null
null
null
#ifndef __DALI_INTERNAL_X_INPUT2_DEVICE_H__ #define __DALI_INTERNAL_X_INPUT2_DEVICE_H__ /* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. * */ // EXTERNAL INCLUDES #include <X11/extensions/XInput2.h> namespace Dali { namespace Internal { namespace Adaptor { /** * @brief struct used to encpasulate XIDeviceInfo information. * Kept as a POD so it can be used in a Dali::Vector */ struct XInput2Device { /** * @brief constructor */ XInput2Device() : deviceId(0), attachment(0), use(0), keyClass(false), touchClass(false), buttonClass(false), valuatorClass(false), scrollClass(false) {} /** * Assign device information to the object */ void AssignDeviceInfo( const XIDeviceInfo* device ); int deviceId; ///< X device ID int attachment; ///< see XI2 DEVICEINFO struct for details int use; ///< see XI2 DEVICEINFO struct for details bool keyClass:1; ///< device supports key input bool touchClass:1; ///< device supports touch input bool buttonClass:1; ///< device supports button input bool valuatorClass:1; ///< device supports an axis, e.g. mouse axis, tablet pen tilt angle.. bool scrollClass:1; ///< device supports scroll }; } // namespace Adaptor } // namespace Internal } // namespace Dali #endif
26.138889
96
0.696599
[ "object", "vector" ]
59dc9ceaa82f68195369ce89fb63e8a14f0c3b09
3,268
h
C
samples/include/zello_metrics.h
rscohn2/level-zero
91befa0ab3e05af05311b9df641066722881bbbc
[ "MIT" ]
null
null
null
samples/include/zello_metrics.h
rscohn2/level-zero
91befa0ab3e05af05311b9df641066722881bbbc
[ "MIT" ]
null
null
null
samples/include/zello_metrics.h
rscohn2/level-zero
91befa0ab3e05af05311b9df641066722881bbbc
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "zello_init.h" ////////////////////////////////////////////////////////////////////////// inline zet::MetricGroup* findMetricGroup( zet::Device* pDevice, const zet::MetricGroup::sampling_type_flags_t type, const char* name = "" ) { uint32_t groupCount = 0; zet::MetricGroup::Get( pDevice, &groupCount ); std::vector< zet::MetricGroup*> metricGroups( groupCount ); zet::MetricGroup::Get( pDevice, &groupCount, metricGroups.data() ); zet::MetricGroup* found = nullptr; // for each device group, find the first one matching the type for( uint32_t grp = 0; grp < groupCount; ++grp ) { auto pMetricGroup = metricGroups[ grp ]; zet::MetricGroup::properties_t metric_group_properties; pMetricGroup->GetProperties( &metric_group_properties ); if( 0 != ( static_cast<uint32_t>(type) & static_cast<uint32_t>(metric_group_properties.samplingType) ) ) { if( ( 0 == strlen(name) ) || ( 0 == strcmp( name, metric_group_properties.name ) ) ) { found = pMetricGroup; std::cout << "Found " << zet::to_string( type ) << " metric group..." << "\n"; std::cout << zet::to_string( metric_group_properties ) << "\n"; } } } if( !found ) { std::cout << "Did NOT find matching " << zet::to_string( type ) << " device group!" << "\n"; } return found; } ////////////////////////////////////////////////////////////////////////// inline void calculateResults( zet::MetricGroup* pMetricGroup, zet::MetricQuery* pQuery ) { // Read raw data from query size_t rawDataSize = 0; pQuery->GetData( &rawDataSize, nullptr ); std::vector<uint8_t> rawData( rawDataSize ); pQuery->GetData( &rawDataSize, rawData.data() ); // Calculate results uint32_t numMetricValues = 0; zet::MetricGroup::CalculateMetricValues( pMetricGroup, zet::MetricGroup::calculation_type_t::METRIC_VALUES, rawDataSize, rawData.data(), &numMetricValues ); std::vector<zet::typed_value_t> metricValues( numMetricValues ); zet::MetricGroup::CalculateMetricValues( pMetricGroup, zet::MetricGroup::calculation_type_t::METRIC_VALUES, rawDataSize, rawData.data(), &numMetricValues, metricValues.data() ); // get metric info uint32_t metricCount = 0; zet::Metric::Get( pMetricGroup, &metricCount, nullptr ); std::vector< zet::Metric* > metrics( metricCount ); zet::Metric::Get( pMetricGroup, &metricCount, metrics.data() ); // Report results std::cout << "Compute Basic results:\n"; uint32_t numReports = numMetricValues / metricCount; for( uint32_t report = 0; report < numReports; ++report ) { for( uint32_t metric = 0; metric < metricCount; ++metric ) { zet::Metric::properties_t metric_properties; metrics[ metric ]->GetProperties( &metric_properties ); auto& result = metricValues[ report * metricCount + metric ]; std::cout << metric_properties.name << " (" << metric_properties.resultUnits << ") :\n"; std::cout << zet::to_string( result ) << "\n"; } } }
37.563218
181
0.602815
[ "vector" ]
59e26f20f1074ffb22d9d696be67839f01057019
3,771
h
C
src/FergilnadEngine/Collidable.h
anunez97/fergilnad-game-engine
75528633d32aed41223e0f52d8d7715073d9210a
[ "MIT" ]
null
null
null
src/FergilnadEngine/Collidable.h
anunez97/fergilnad-game-engine
75528633d32aed41223e0f52d8d7715073d9210a
[ "MIT" ]
null
null
null
src/FergilnadEngine/Collidable.h
anunez97/fergilnad-game-engine
75528633d32aed41223e0f52d8d7715073d9210a
[ "MIT" ]
null
null
null
// Collidable #ifndef _Collidable #define _Collidable #include "CollisionManager.h" #include "CollidableGroup.h" #include "SceneAttorney.h" #include "RegistrationState.h" #include "CollisionVolumeBSphere.h" #include "CollisionVolumeAABB.h" #include "CollisionVolumeOBB.h" class CollisionRegistrationCommand; class CollisionDeregistrationCommand; class OctreeNode; class Collidable { friend class CollidableAttorney; public: Collidable(); virtual ~Collidable(); enum VolumeType { BSPHERE, AABB, OBB }; /// <summary> /// Submits a GameObject for Collision Registration. /// </summary> void SubmitCollisionRegistration(); /// <summary> /// Submits a GameObject for Collision Deregistration. /// </summary> void SubmitCollisionDeregistration(); /// <summary> /// Method that is called when the GameObject collides with another collidable GameObject. /// </summary> /// <param name=""> Can be any user defined GameObject that has Collision turned on. </param> virtual void Collision(Collidable*) {}; /// <summary> /// Method that is called when the GameObject collides with the Scene terrain /// </summary> /// <param name=""></param> virtual void CollisionTerrain() {}; /// <summary> /// Sets the GameObject's Collider model /// </summary> /// <param name="mod"> Pointer the model object of the GameObject. </param> void SetColliderModel(Model* mod, VolumeType type); /// <summary> /// Renders the node in the collision octree that the object is inside /// </summary> void ShowNode(); private: Collidable(const Collidable& other) = delete; Collidable& operator=(const Collidable& other) = delete; void SceneRegistration(); void SceneDeregistration(); /// <summary> /// Gives the selected collision volume of the Collidable /// </summary> /// <returns>A reference to the selected Collision Volume</returns> const CollisionVolume& GetCollisionVolume(); /// <summary> /// Gives the default BSphere of the Collidable /// </summary> /// <returns>A reference to the default BSphere</returns> const CollisionVolumeBSphere* GetCollisionSphere(); CollisionVolume* pColVolume; CollisionVolumeBSphere* pBSphere; CollisionVolumeAABB* pAABB; CollisionVolumeOBB* pOBB; Model* pColModel; CollisionRegistrationCommand* pRegCmd; CollisionDeregistrationCommand* pDeregCmd; CollidableGroup::CollidableCollectionRef pDeleteRef; RegistrationState RegStateCurr; CollisionManager::FGNTypeID myID; /* ---- Used for Collision Octree ---- */ struct OctreeData { OctreeNode* parentNode; // pointer to the node that the object is in bool inTree; // the collidable is in the octree }; /// <summary> /// Sets the parent node in the octree of the Collidable /// </summary> /// <param name="parent">Pointer to a node in the octree</param> void SetParentNode(OctreeNode* parent); /// <summary> /// Gives the node in the octree that the Collidable is in /// </summary> /// <returns>Pointer to the node</returns> OctreeNode* GetParentNode(); OctreeData octreeData; /// <summary> /// Inserts the Collidable into the octree /// </summary> void InsertIntoOctree(); /// <summary> /// Removes the Collidable from the octree /// </summary> void RemoveFromOctree(); protected: /// <summary> /// Updates the collision data matrix for a GameObject. /// </summary> /// <param name="mat"> Constant Matrix reference, usually a world matrix. </param> void UpdateCollisionData(const Matrix& mat); template <typename C> void SetCollidableGroup() { myID = SceneAttorney::Registration::GetCollisionManager()->GetTypeID<C>(); } }; #endif _Collidable
26.006897
95
0.696367
[ "object", "model" ]
daa3ad84a371bea7d302658a11646308ac15fcc6
210
h
C
include/spot/gfx/animations.h
Fahien/gfxspot
6f125706311ce7d37ca90d58082925ea691ffc98
[ "MIT" ]
1
2020-03-23T09:27:02.000Z
2020-03-23T09:27:02.000Z
include/spot/gfx/animations.h
Fahien/gfxspot
6f125706311ce7d37ca90d58082925ea691ffc98
[ "MIT" ]
null
null
null
include/spot/gfx/animations.h
Fahien/gfxspot
6f125706311ce7d37ca90d58082925ea691ffc98
[ "MIT" ]
null
null
null
#pragma once #include <spot/handle.h> namespace spot::gfx { class Gltf; class Animations { public: void update( float dt, const Handle<Gltf>& model ); bool pause = false; }; } // namespace gfx::spot
10.5
52
0.671429
[ "model" ]
daa87acfd4d1a846ebe357a3b8933445f7532670
905
h
C
src/VectorDisplacementHelperTypes.h
Zhibade/maya-vector-displacement-deformer
323a0e683590681ac4c837bb4b2b3f37c977d1f4
[ "MIT" ]
3
2020-09-01T04:26:49.000Z
2021-03-25T06:58:39.000Z
src/VectorDisplacementHelperTypes.h
Zhibade/maya-vector-displacement-deformer
323a0e683590681ac4c837bb4b2b3f37c977d1f4
[ "MIT" ]
1
2020-11-28T12:23:23.000Z
2020-11-29T16:55:16.000Z
src/VectorDisplacementHelperTypes.h
Zhibade/maya-vector-displacement-deformer
323a0e683590681ac4c837bb4b2b3f37c977d1f4
[ "MIT" ]
null
null
null
/* Copyright (C) 2020 - Jose Ivan Lopez Romo - All rights reserved * * This file is part of the MayaVectorDisplacementDeformer project found in the * following repository: https://github.com/Zhibade/maya-vector-displacement-deformer * * Released under MIT license. Please see LICENSE file for details. */ #pragma once #include <maya/MPoint.h> #include <maya/MVector.h> enum class VectorDisplacementMapType : int { OBJECT_SPACE = 0, TANGENT_SPACE = 1 }; struct VertexData { MPoint position; unsigned int index; MVector normal; MVector tangent; MVector binormal; }; struct GpuKernelData { MAutoCLMem* inputPositions; MAutoCLMem* outputPositions; MAutoCLMem* textureData; MAutoCLMem* paintWeightData; MAutoCLMem* normalData; MAutoCLMem* tangentData; MAutoCLMem* binormalData; unsigned int numOfElements = 0; float strength = 1.f; };
22.073171
85
0.721547
[ "vector" ]
dac804e867107dacc0772098223d413b062cc45d
309
h
C
tests/tests.h
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
1
2020-05-08T08:55:55.000Z
2020-05-08T08:55:55.000Z
tests/tests.h
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
1
2020-01-16T23:22:52.000Z
2020-01-16T23:22:52.000Z
tests/tests.h
USCbiostats/pruner
0f6b575a25292612a433f20cbc2fea5ba2a19e2e
[ "MIT" ]
2
2020-07-01T01:35:55.000Z
2022-03-09T14:58:27.000Z
#include <vector> #include <iostream> #include <type_traits> #ifndef H_PRUNER_TESTS #define H_PRUNER_TESTS template <class T> inline void print(std::vector< T > & x) { std::cout << "[ " ; for (auto i = x.begin(); i != x.end(); ++i) std::cout << *i << " "; std::cout << "]\n"; return; } #endif
16.263158
45
0.582524
[ "vector" ]
dad5dde0327a83cae13f9e90ef8a011269f38394
1,681
h
C
src/ofxAtem2.h
hanasaan/ofxAtem2
31f5dd866163c2615e94f748f5cb1ef3d70fe78e
[ "MIT" ]
null
null
null
src/ofxAtem2.h
hanasaan/ofxAtem2
31f5dd866163c2615e94f748f5cb1ef3d70fe78e
[ "MIT" ]
null
null
null
src/ofxAtem2.h
hanasaan/ofxAtem2
31f5dd866163c2615e94f748f5cb1ef3d70fe78e
[ "MIT" ]
null
null
null
#pragma once #include "BMDSwitcherAPI_h.h" #include "ofMain.h" class MixEffectBlockMonitor; class SwitcherMonitor; class InputMonitor; namespace ofxAtem2 { class Controller { public: friend class SwitcherMonitor; Controller() { init(); } ~Controller() { disconnect(); } bool connect(string ip, int mix_effect_block_index = 0); void reconnect(); void disconnect(); void update(); void performCut(); void performAuto(); void setProgramId(int id); void setPreviewId(int id); void setAutoRate(uint32_t frames); void setTransitionPosition(float pos); int getProgramId() const { return program; } int getPreviewId() const { return preview; } string getProductName() const { return product_name; } string getVideoModeString() const { return video_mode; } bool isInTransition() const; bool isConnected() const { return connectionStatus; } void setAutoReconnect(bool b) { b_autoreconnect = b; } bool isAutoReconnect() const { return b_autoreconnect; } int getAux(int index); void setAux(int index, int id); protected: void init(); int connectionStatus = 0; int64_t program = -1; int64_t preview = -1; string product_name; string video_mode; string ip_; bool b_autoreconnect = false; bool b_reconnect = false; IBMDSwitcherDiscovery* mSwitcherDiscovery; IBMDSwitcher* mSwitcher; IBMDSwitcherMixEffectBlock* mMixEffectBlock; SwitcherMonitor* mSwitcherMonitor; std::vector<InputMonitor* > mInputMonitors; std::vector<IBMDSwitcherInputAux*> mSwitcherInputAuxList; std::vector<BMDSwitcherInputId*> mInputIds; MixEffectBlockMonitor* mMixEffectBlockMonitor; vector<int64_t> auxoutputs; }; }
24.720588
59
0.738846
[ "vector" ]
dadaf6c1c624b037db0ca2a70895c2783cbbd0ef
8,521
h
C
oneEngine/oneGame/source/core/input/CInput.h
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/core/input/CInput.h
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/core/input/CInput.h
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
//===============================================================================================// // // CInput - Input backend // // Input backend. Forwards input that is captured from the OS's message loop. // On Windows, mouse input is hardware based. Unless configured, it does not correspond to the // system cursor. // //===============================================================================================// #ifndef CORE_INPUT_H_ #define CORE_INPUT_H_ #include "core/types.h" #include "core/containers/arsingleton.h" #include "core/math/Vector2.h" #include "core/math/vect2d_template.h" #include "core/debug.h" #include <vector> #include <array> namespace core { enum VirtualKey : int { kVkCount = 256, kVkBack = 0x08, kVkBackspace = 0x08, kVkTab = 0x09, kVkReturn = 0x0D, kVkEscape = 0x1B, kVkSpace = 0x20, kVkPageUp = 0x21, kVkPageDown = 0x22, kVkEnd = 0x23, kVkHome = 0x24, kVkPrintScreen = 0x2C, kVkInsert = 0x2D, kVkDelete = 0x2E, kVkCapital = 0x14, kVkCapslock = 0x14, kVkShift = 0x10, kVkControl = 0x11, kVkAlt = 0x12, kVkPause = 0x13, kVkLeft = 0x25, kVkUp = 0x26, kVkRight = 0x27, kVkDown = 0x28, kVkNumpad0 = 0x60, kVkNumpad1 = 0x61, kVkNumpad2 = 0x62, kVkNumpad3 = 0x63, kVkNumpad4 = 0x64, kVkNumpad5 = 0x65, kVkNumpad6 = 0x66, kVkNumpad7 = 0x67, kVkNumpad8 = 0x68, kVkNumpad9 = 0x69, kVkNumpadMultiply = 0x6A, kVkNumpadAdd = 0x6B, kVkNumpadSubtract = 0x6D, kVkNumpadDivide = 0x6F, kVkNumpadDecimal= 0x6E, kVkTilde = 0xC0, kVkF1 = 0x70, kVkF2 = 0x71, kVkF3 = 0x72, kVkF4 = 0x73, kVkF5 = 0x74, kVkF6 = 0x75, kVkF7 = 0x76, kVkF8 = 0x77, kVkF9 = 0x78, kVkF10 = 0x79, kVkF11 = 0x7A, kVkF12 = 0x7B, }; enum VirtualMouseButton : int { kMBLeft = 0, kMBRight = 1, kMBMiddle = 2, kMBBackward = 3, kMBForward = 4, kMBCount = 16, }; CORE_API extern unsigned char VkToAsciiTable [256]; extern void InitializeVkToAsciiTable ( void ); namespace internal_input { struct /*alignas(1)*/ KeyState // TODO: Fix alignment issue { uint key : 1; uint prev : 1; uint down : 1; uint up : 1; KeyState() : key(false) , prev(false) , down(false) , up(false) { } void PreUpdate ( void ) { prev = key; down = false; up = false; } void Make ( void ) { down = true; key = true; } void Break ( void ) { up = true; key = false; } }; struct KeypressEntry { uint code : 8; uint isMake : 1; }; struct InputState { // Keyboard state std::vector<KeypressEntry> m_keypressesLastFrame; std::string m_stringLastFrame; std::array<KeyState, kVkCount> m_keys; // Mouse state Vector2f m_mouse; Vector2i m_sysMouse; Vector2f m_deltaMouse; Vector2i m_rawDeltaMouse; Vector2i m_prevRawDeltaMouse; bool m_deltaMouseScrollChange = false; int m_deltaMouseScroll = 0; bool m_deltaMouseZoomChange = false; int m_deltaMouseZoom = 0; bool m_deltaMouseHScrollChange = false; int m_deltaMouseHScroll = 0; bool m_deltaMouseHZoomChange = false; int m_deltaMouseHZoom = 0; bool m_syncRawAndSystemMouse = false; std::array<KeyState, kMBCount> m_mouseButtons; }; } class Input { ARSINGLETON_H_STORAGE(Input,CORE_API) ARSINGLETON_H_ACCESS(Input) private: explicit Input ( void ) {} ~Input ( void ) {} public: int m_currentActiveWindow = 0; Vector2f m_mouseSensitivity = Vector2f( 1.0F, 1.0F ); public: // Initialize() : Initializes input system, allocating memory. CORE_API static void Initialize ( void ); // Free() : Frees input system. CORE_API static void Free ( void ); // ResizeInputState( count ) : Resizes input state count. CORE_API static void ResizeInputState ( int input_state_count ); // PreUpdate() : Resets the input system just before message loop updates. CORE_API static void PreUpdate ( void ); // Update() : Updates the input logic after the message loop updates. CORE_API static void Update ( void ); // Reset() : Zeroes out all the current input CORE_API static void Reset ( void ); public: // Key(virtual_keycode) : Checks if the key is currently down. CORE_API static bool Key ( const unsigned char vkeycode_ascii, const int windowIndex = -1 ); // Keydown(virtual_keycode) : Checks if the key was pressed in the previous frame. CORE_API static bool Keydown ( const unsigned char vkeycode_ascii, const int windowIndex = -1 ); // Keydown(virtual_keycode) : Checks if the key was released in the previous frame. CORE_API static bool Keyup ( const unsigned char vkeycode_ascii, const int windowIndex = -1 ); // KeypressAny() : Checks if any key is currently down. CORE_API static bool KeypressAny ( const int windowIndex = -1 ); // KeydownAny() : Checks if any key was pressed in the previous frame. CORE_API static bool KeydownAny ( const int windowIndex = -1 ); // KeyupAny() : Checks if any key was released in the previous frame. CORE_API static bool KeyupAny ( const int windowIndex = -1 ); // FrameInputString() : Returns the sum of all the inputs over the past frame. CORE_API static const std::string& FrameInputString ( const int windowIndex = -1 ); public: CORE_API static void WSetKeyMake ( const unsigned char vkeycode_ascii, const int windowIndex ); CORE_API static void WSetKeyBreak ( const unsigned char vkeycode_ascii, const int windowIndex ); public: // MouseX() : Current virtual mouse cursor X position CORE_API static float MouseX ( const int windowIndex = -1 ); // MouseY() : Current virtual mouse cursor Y position CORE_API static float MouseY ( const int windowIndex = -1 ); // SysMouseX() : Current local system mouse cursor X position CORE_API static int SysMouseX ( const int windowIndex = -1 ); // SysMouseY() : Current local system mouse cursor X position CORE_API static int SysMouseY ( const int windowIndex = -1 ); // DeltaMouseX() : Current virtual mouse cursor X delta CORE_API static float DeltaMouseX ( const int windowIndex = -1 ); // DeltaMouseY() : Current virtual mouse cursor Y delta CORE_API static float DeltaMouseY ( const int windowIndex = -1 ); // DeltaMouseScroll() : Current virtual mouse wheel delta. CORE_API static int DeltaMouseScroll ( const int windowIndex = -1 ); // DeltaMouseHScroll() : Current virtual mouse wheel delta. CORE_API static int DeltaMouseHScroll ( const int windowIndex = -1 ); // DeltaMouseZoom() : Current virtual mouse wheel zoom.; CORE_API static int DeltaMouseZoom ( const int windowIndex = -1 ); // Mouse(mousebutton) : Checks if the mouse button is currently down. CORE_API static bool Mouse ( const int mousebutton_id, const int windowIndex = -1 ); // MouseDown(mousebutton) : Checks if the mouse button was pressed in the previous frame. CORE_API static bool MouseDown ( const int mousebutton_id, const int windowIndex = -1 ); // MouseUp(mousebutton) : Checks if the mouse button was released in the previous frame. CORE_API static bool MouseUp ( const int mousebutton_id, const int windowIndex = -1 ); // SetMouseSensitivity(sensitivity) : Sets virtual mouse sensitivity. CORE_API static void SetMouseSensitivity ( const Real sensitivity ) { m_Active->m_mouseSensitivity = {sensitivity, sensitivity}; } // GetMouseSensitivity() : Returns current mouse sensitivity CORE_API static Real GetMouseSensitivity ( void ) { return m_Active->m_mouseSensitivity.x; } public: CORE_API static void WSetSysMouse ( const Vector2i mouse, const int windowIndex ); CORE_API static void WAddRawMouse ( const Vector2i deltamouse, const int windowIndex ); CORE_API static void WSetCurrMouseScroll ( const int mousew, const int windowIndex ); CORE_API static void WSetCurrMouseZoom ( const int mousew, const int windowIndex ); CORE_API static void WSetCurrMouseHScroll ( const int mousew, const int windowIndex ); CORE_API static void WSetCurrMouseHZoom ( const int mousew, const int windowIndex ); CORE_API static void WSetMouseMake ( const int mousebutton_id, const int windowIndex ); CORE_API static void WSetMouseBreak ( const int mousebutton_id, const int windowIndex ); CORE_API static void WSetSyncRawAndSystemMouse ( const bool sync, const int windowIndex ); }; } #endif//CORE_INPUT_H_
29.586806
99
0.679028
[ "vector" ]
dadd875c5a460c178b71d54e6d3e4a247bbb8fa2
3,502
h
C
library/engines/KrispyCrypto/Interface/i/engines/KrispyCrypto/IDecipher.h
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
[ "MIT" ]
null
null
null
library/engines/KrispyCrypto/Interface/i/engines/KrispyCrypto/IDecipher.h
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
[ "MIT" ]
null
null
null
library/engines/KrispyCrypto/Interface/i/engines/KrispyCrypto/IDecipher.h
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
[ "MIT" ]
null
null
null
/* MIT-LICENSE Copyright (c) 2017 Higher Edge Software, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, 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 _ENGINE_CRYPTO_IDECIPHER_h_ #define _ENGINE_CRYPTO_IDECIPHER_h_ #include <memory> #include <tuple> #include <string> namespace Engine { namespace Crypto { class IKey; /** * @class IDeipherMultipart * * @brief An interface to a decipher object which can decrypt data provided to it in multiple chunks. * * This is useful for dealing with large data or streaming. */ class IDecipherMultipart { public: /** * @brief Ensure destructor is virtual; */ virtual ~IDecipherMultipart() = default; /** * @brief Prepares object for another decryption operation. */ virtual void reset() = 0; /** * @brief Prepares object for another decryption operation. */ virtual std::tuple<std::shared_ptr<void>, unsigned int> update(const void* data, int dataLen) = 0; /** * @brief Decrypts a string. */ virtual std::tuple<std::shared_ptr<void>, unsigned int> update(const std::string& str) = 0; /** * @brief Finishes the decryption operation. * * @returns A tuple containing decrypted data and its size. * * The caller owns the resource. */ virtual std::tuple<std::shared_ptr<void>, unsigned int> finalize() = 0; }; /** * @class IDecipher * * @brief An interface to a cipher object which can decrypts data in one call. * * This is useful for dealing with smaller data, that fits in one buffer. */ class IDecipher { public: /** * @brief Ensure destructor is virtual; */ virtual ~IDecipher() = default; /** * @brief Decrypts a binary chunk of data. * * @param data Pointer to the buffer containing data. * @param dataLen Size of data to be decrypted. * * @returns A tuple containing decrypted data. */ virtual std::tuple<std::shared_ptr<void>, unsigned int> decipher(const void* data, int dataLen) = 0; /** * @brief Decrypts a string. * * @param str String to be decrypted. * * @returns A tuple containing decrypted data. */ virtual std::tuple<std::shared_ptr<void>, unsigned int> decipher(const std::string& str) = 0; }; } } #endif // _ENGINE_CRYPTO_IDECIPHER_h_
29.677966
105
0.653341
[ "object" ]
daeb0e59579626d98b0428f43a21184d2c1039d6
9,830
c
C
Fit_Contour2.c
matvii/adam-asteroid
b85287ba8077158c6f1525d11fc668673cefa332
[ "CC-BY-4.0" ]
16
2017-06-24T03:49:40.000Z
2022-01-31T21:47:17.000Z
Fit_Contour2.c
matvii/adam-asteroid
b85287ba8077158c6f1525d11fc668673cefa332
[ "CC-BY-4.0" ]
1
2018-01-12T13:18:51.000Z
2018-01-12T13:18:51.000Z
Fit_Contour2.c
matvii/adam-asteroid
b85287ba8077158c6f1525d11fc668673cefa332
[ "CC-BY-4.0" ]
6
2018-01-12T13:12:52.000Z
2021-09-24T12:27:39.000Z
#include"utils.h" #include"matrix_ops.h" #include"globals.h" void find_edge(int *tlist,double *vlist2,int nfac,int nvert,int *visible,double *offset,double *a,double *b,int *cledge,double *clpoint,int *inters,double *dclpx,double *dclpy,double *doffx,double *doffy); void Fit_Contour2(int *tlist,double *vlist,int nfac,int nvert,double *angles,double *up,double *E,double *E0,double TIME,double *offset,double *datax,double *datay,int npoints,double *dist,double *dx,double *dy,double *dz,double *dangles,double *dtox,double *dtoy) { /*INPUT: * TIMES nchordsx2 disappearance and appearance times * offset=[x,y] offset in plane * chords nchordsx4 coordinates, disappearance and appearance * Chordoffset nchords vector,containing chord offset in seconds * OUTPUT: * dist nchordsx4 matrix, x and y distance ofclosest model points to disappearance and appearance points * dx,dy,dz 4nchordsxnvert matrix * dangles 4nchordsx3 matrix * dtox,dtoy 2*npointsx1, derivatives wrt offsets * dCOdoff 2*npointsxnchords matrix, derivatives for chord offsets * */ double M[3][3],MRT[3][3],MRdb[3][3],MRdl[3][3],MRdo[3][3],MRTT[9]; double Er[3],E0r[3]; double MRdbT[9],MRdlT[9],MRdoT[9]; double R[3][3],Rb[3][3],Rl[3][3],Ro[3][3],Rt[3][3],RbT[3][3],RlT[3][3],RoT[3][3]; int cledge[2],inters; int edget[2]; int ic1,ic2,fa1,fa2; double LARGE_VALUE=1e4; double clpoint[2],dclpx[4],dclpy[4]; double temp4[4]; double V[3]; double off[]={0,0}; double nd_dist,nd_dx,nd_dy; int nd_vert; // int *Adj=calloc(nvert*nvert,sizeof(int)); // AdjFacet(tlist,vlist,nfac,nvert,Adj); Calculate_Frame_Matrix(E,up,M); rotate(angles[0],angles[1],angles[2],angles[3],TIME,R,Rb,Rl,Ro); //Here we determine which facets are visible //We rotate view/sun directions int *visible; visible=calloc(nfac,sizeof(int)); mult_vector(R,E,Er); mult_vector(R,E0,E0r); FindActualBlockers(tlist,vlist,nfac,nvert,Er,E0r,1,visible); //visible[j]==1 if jth facet is visible transpose(R,Rt); //Transpose, since we rotate the model, not view directions transpose(Rb,RbT); transpose(Rl,RlT); transpose(Ro,RoT); mult_mat(M,Rt,MRT); double mr11,mr12,mr13,mr21,mr22,mr23; mr11=MRT[0][0]; mr12=MRT[0][1]; mr13=MRT[0][2]; mr21=MRT[1][0]; mr22=MRT[1][1]; mr23=MRT[1][2]; mult_mat(M,RbT,MRdb); mult_mat(M,RlT,MRdl); mult_mat(M,RoT,MRdo); zero_array(dist,npoints); zero_array(dx,(npoints)*nvert); zero_array(dy,(npoints)*nvert); zero_array(dz,(npoints)*nvert); zero_array(dangles,(npoints)*3); zero_array(dtox,npoints); zero_array(dtox,npoints); transpose2(MRT,MRTT); transpose2(MRdb,MRdbT); transpose2(MRdl,MRdlT); transpose2(MRdo,MRdoT); double a[2],b[2]; double *vlist2=calloc(nvert*3,sizeof(double)); double *vlist2b=calloc(nvert*3,sizeof(double)); double *vlist2l=calloc(nvert*3,sizeof(double)); double *vlist2o=calloc(nvert*3,sizeof(double)); matrix_prod(vlist,nvert,3,MRTT,3,vlist2); //vlist2 contains rotated and projected model matrix_prod(vlist,nvert,3,MRdbT,3,vlist2b); matrix_prod(vlist,nvert,3,MRdlT,3,vlist2l); matrix_prod(vlist,nvert,3,MRdoT,3,vlist2o); double w; double el=0; double d2=0; double distx; double disty; double distxdx1,distxdy1,distxdz1,distxdx2,distxdy2,distxdz2; double distydx1,distydy1,distydz1,distydx2,distydy2,distydz2; double distxdox,distxdoy,distydox,distydoy; double distxdb,distxdl,distxdo; double distydb,distydl,distydo; double doffx[2],doffy[2]; a[0]=0; a[1]=0; double *dist2=calloc(nvert,sizeof(double)); int *vertices=calloc(nvert,sizeof(int)); for(int j=0;j<npoints;j++) { b[0]=datax[j]; b[1]=datay[j]; find_edge(tlist,vlist2,nfac,nvert,visible,offset,a,b,cledge,clpoint,&inters,dclpx,dclpy,doffx,doffy); if(inters==1) { distx=clpoint[0]-datax[j]; disty=clpoint[1]-datay[j]; distxdx1=dclpx[0]*mr11+dclpx[1]*mr21; //distx wrt ic1 distxdy1=dclpx[0]*mr12+dclpx[1]*mr22; distxdz1=dclpx[0]*mr13+dclpx[1]*mr23; distxdx2=dclpx[2]*mr11+dclpx[3]*mr21;//distx wrt ic2 distxdy2=dclpx[2]*mr12+dclpx[3]*mr22; distxdz2=dclpx[2]*mr13+dclpx[3]*mr23; distydx1=dclpy[0]*mr11+dclpy[1]*mr21; //disty wrt ic1 distydy1=dclpy[0]*mr12+dclpy[1]*mr22; distydz1=dclpy[0]*mr13+dclpy[1]*mr23; distydx2=dclpy[2]*mr11+dclpy[3]*mr21; distydy2=dclpy[2]*mr12+dclpy[3]*mr22; distydz2=dclpy[2]*mr13+dclpy[3]*mr23; d2=pow(distx,2)+pow(disty,2); dist[j]=sqrt(d2); //distance in x ic1=cledge[0]; ic2=cledge[1]; vertices[ic1]=1; vertices[ic2]=1; set_el(dx,nvert+npoints,nvert,pow(d2,-0.5)*(distx*distxdx1+disty*distydx1),j,ic1); set_el(dx,nvert+npoints,nvert,pow(d2,-0.5)*(distx*distxdx2+disty*distydx2),j,ic2); set_el(dy,nvert+npoints,nvert,pow(d2,-0.5)*(distx*distxdy1+disty*distydy1),j,ic1); set_el(dy,nvert+npoints,nvert,pow(d2,-0.5)*(distx*distxdy2+disty*distydy2),j,ic2); set_el(dz,nvert+npoints,nvert,pow(d2,-0.5)*(distx*distxdz1+disty*distydz1),j,ic1); set_el(dz,nvert+npoints,nvert,pow(d2,-0.5)*(distx*distxdz2+disty*distydz2),j,ic2); /* el=dclpx[0]*mr11+dclpx[1]*mr21; set_el(dx,2*npoints,nvert,el,2*j,ic1); el=dclpx[0]*mr12+dclpx[1]*mr22; set_el(dy,2*npoints,nvert,el,2*j,ic1); el=dclpx[0]*mr13+dclpx[1]*mr23; set_el(dz,2*npoints,nvert,el,2*j,ic1); el=dclpx[2]*mr11+dclpx[3]*mr21; set_el(dx,2*npoints,nvert,el,2*j,ic2); el=dclpx[2]*mr12+dclpx[3]*mr22; set_el(dy,2*npoints,nvert,el,2*j,ic2); el=dclpx[2]*mr13+dclpx[3]*mr23; set_el(dz,2*npoints,nvert,el,2*j,ic2); el=dclpy[0]*mr11+dclpy[1]*mr21; set_el(dx,2*npoints,nvert,el,2*j+1,ic1); el=dclpy[0]*mr12+dclpy[1]*mr22; set_el(dy,2*npoints,nvert,el,2*j+1,ic1); el=dclpy[0]*mr13+dclpy[1]*mr23; set_el(dz,2*npoints,nvert,el,2*j+1,ic1); el=dclpy[2]*mr11+dclpy[3]*mr21; set_el(dx,2*npoints,nvert,el,2*j+1,ic2); el=dclpy[2]*mr12+dclpy[3]*mr22; set_el(dy,2*npoints,nvert,el,2*j+1,ic2); el=dclpy[2]*mr13+dclpy[3]*mr23; set_el(dz,2*npoints,nvert,el,2*j+1,ic2); */ //Chords offset derivatives //Offset derivatives distxdox=(dclpx[0]+dclpx[2]); distydox=(dclpy[0]+dclpy[2]); distxdoy=(dclpx[1]+dclpx[3]); distydoy=(dclpy[1]+dclpy[3]); dtox[j]=pow(d2,-0.5)*(distx*doffx[0]+disty*doffx[1]); dtoy[j]=pow(d2,-0.5)*(distx*doffy[0]+disty*doffy[1]); /* dtox[2*j]=(dclpx[0]+dclpx[2]); dtox[2*j+1]=(dclpy[0]+dclpy[2]); dtoy[2*j]=(dclpx[1]+dclpx[3]); dtoy[2*j+1]=(dclpy[1]+dclpy[3]); */ distxdb=(dclpx[0]*get_el(vlist2b,nvert,3,ic1,0)+dclpx[1]*get_el(vlist2b,nvert,3,ic1,1)+dclpx[2]*get_el(vlist2b,nvert,3,ic2,0)+dclpx[3]*get_el(vlist2b,nvert,3,ic2,1)); distydb=(dclpy[0]*get_el(vlist2b,nvert,3,ic1,0)+dclpy[1]*get_el(vlist2b,nvert,3,ic1,1)+dclpy[2]*get_el(vlist2b,nvert,3,ic2,0)+dclpy[3]*get_el(vlist2b,nvert,3,ic2,1)); distxdl=(dclpx[0]*get_el(vlist2l,nvert,3,ic1,0)+dclpx[1]*get_el(vlist2l,nvert,3,ic1,1)+dclpx[2]*get_el(vlist2l,nvert,3,ic2,0)+dclpx[3]*get_el(vlist2l,nvert,3,ic2,1)); distydl=(dclpy[0]*get_el(vlist2l,nvert,3,ic1,0)+dclpy[1]*get_el(vlist2l,nvert,3,ic1,1)+dclpy[2]*get_el(vlist2l,nvert,3,ic2,0)+dclpy[3]*get_el(vlist2l,nvert,3,ic2,1)); distxdo=(dclpx[0]*get_el(vlist2o,nvert,3,ic1,0)+dclpx[1]*get_el(vlist2o,nvert,3,ic1,1)+dclpx[2]*get_el(vlist2o,nvert,3,ic2,0)+dclpx[3]*get_el(vlist2o,nvert,3,ic2,1)); distydo=(dclpy[0]*get_el(vlist2o,nvert,3,ic1,0)+dclpy[1]*get_el(vlist2o,nvert,3,ic1,1)+dclpy[2]*get_el(vlist2o,nvert,3,ic2,0)+dclpy[3]*get_el(vlist2o,nvert,3,ic2,1)); /* dangles[2*j*3]=(dclpx[0]*get_el(vlist2b,nvert,3,ic1,0)+dclpx[1]*get_el(vlist2b,nvert,3,ic1,1)+dclpx[2]*get_el(vlist2b,nvert,3,ic2,0)+dclpx[3]*get_el(vlist2b,nvert,3,ic2,1)); dangles[2*j*3+1]=(dclpx[0]*get_el(vlist2l,nvert,3,ic1,0)+dclpx[1]*get_el(vlist2l,nvert,3,ic1,1)+dclpx[2]*get_el(vlist2l,nvert,3,ic2,0)+dclpx[3]*get_el(vlist2l,nvert,3,ic2,1)); dangles[2*j*3+2]=(dclpx[0]*get_el(vlist2o,nvert,3,ic1,0)+dclpx[1]*get_el(vlist2o,nvert,3,ic1,1)+dclpx[2]*get_el(vlist2o,nvert,3,ic2,0)+dclpx[3]*get_el(vlist2o,nvert,3,ic2,1)); dangles[2*j*3+3+0]=(dclpy[0]*get_el(vlist2b,nvert,3,ic1,0)+dclpy[1]*get_el(vlist2b,nvert,3,ic1,1)+dclpy[2]*get_el(vlist2b,nvert,3,ic2,0)+dclpy[3]*get_el(vlist2b,nvert,3,ic2,1)); dangles[2*j*3+3+1]=(dclpy[0]*get_el(vlist2l,nvert,3,ic1,0)+dclpy[1]*get_el(vlist2l,nvert,3,ic1,1)+dclpy[2]*get_el(vlist2l,nvert,3,ic2,0)+dclpy[3]*get_el(vlist2l,nvert,3,ic2,1)); dangles[2*j*3+3+2]=(dclpy[0]*get_el(vlist2o,nvert,3,ic1,0)+dclpy[1]*get_el(vlist2o,nvert,3,ic1,1)+dclpy[2]*get_el(vlist2o,nvert,3,ic2,0)+dclpy[3]*get_el(vlist2o,nvert,3,ic2,1)); */ dangles[3*j]=pow(d2,-0.5)*(distx*distxdb+disty*distydb); dangles[3*j+1]=pow(d2,-0.5)*(distx*distxdl+disty*distydl); dangles[3*j+2]=pow(d2,-0.5)*(distx*distxdo+disty*distydo); } else { printf("No intersection with Boundary contour. j :%d \n",j); dist[j]=LARGE_VALUE; } } free(vlist2); free(vlist2b); free(vlist2l); free(vlist2o); }
40.958333
264
0.62706
[ "vector", "model" ]
daf6384b55875281d16848005284583dfcbdaf68
9,641
h
C
src/core/lifecycle/life_handler/nativeapp_life_handler.h
webosce/sam
bddc1e646d729920350f69e44105e02d1c5422d4
[ "Apache-2.0" ]
null
null
null
src/core/lifecycle/life_handler/nativeapp_life_handler.h
webosce/sam
bddc1e646d729920350f69e44105e02d1c5422d4
[ "Apache-2.0" ]
null
null
null
src/core/lifecycle/life_handler/nativeapp_life_handler.h
webosce/sam
bddc1e646d729920350f69e44105e02d1c5422d4
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2012-2018 LG Electronics, Inc. // // 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef NATIVEAPP_LIFE_HANDLER_H_ #define NATIVEAPP_LIFE_HANDLER_H_ #include <list> #include <memory> #include <vector> #include "core/lifecycle/life_handler/life_handler_interface.h" typedef std::vector<pid_t> PidVector; class KillingData { public: KillingData(const std::string& app_id, const std::string& pid, const PidVector& all_pids) : app_id_(app_id), pid_(pid), all_pids_(all_pids), timer_source_(0) {} ~KillingData() { if(timer_source_ != 0) { g_source_remove(timer_source_); timer_source_ = 0; } } public: std::string app_id_; std::string pid_; PidVector all_pids_; guint timer_source_; }; typedef std::shared_ptr<KillingData> KillingDataPtr; class NativeClientInfo; typedef std::shared_ptr<NativeClientInfo> NativeClientInfoPtr; typedef boost::function<void(NativeClientInfoPtr, AppLaunchingItemPtr)> NativeAppLaunchHandler; class NativeAppLifeHandler; // DesignPattern: Template Method class NativeAppLifeCycleInterface { public: NativeAppLifeCycleInterface(NativeAppLifeHandler* parent); virtual ~NativeAppLifeCycleInterface(); // Main methods void Launch(NativeClientInfoPtr client, AppLaunchingItemPtr item); void Close(NativeClientInfoPtr client, AppCloseItemPtr item, std::string& err_text); void Pause(NativeClientInfoPtr, const pbnjson::JValue& params, std::string& err_text, bool send_life_event); NativeAppLifeHandler* Parent() const { return parent_; } void AddLaunchHandler(RuntimeStatus status, NativeAppLaunchHandler handler); // launch template method void LaunchAsCommon(NativeClientInfoPtr client, AppLaunchingItemPtr item); virtual void LaunchAfterClosedAsPolicy(NativeClientInfoPtr client, AppLaunchingItemPtr item) = 0; virtual void LaunchNotRegisteredAppAsPolicy(NativeClientInfoPtr client, AppLaunchingItemPtr item) = 0; virtual bool CheckLaunchCondition(AppLaunchingItemPtr item) = 0; virtual std::string MakeForkArguments(AppLaunchingItemPtr item, AppDescPtr app_desc) = 0; // relaunch template method void RelaunchAsCommon(NativeClientInfoPtr client, AppLaunchingItemPtr item); virtual void MakeRelaunchParams(AppLaunchingItemPtr item, pbnjson::JValue& j_params) = 0; // close template method virtual void CloseAsPolicy(NativeClientInfoPtr client, AppCloseItemPtr item, std::string& err_text) = 0; // pause template method virtual void PauseAsPolicy(NativeClientInfoPtr client, const pbnjson::JValue& params, std::string& err_text, bool send_life_event) = 0; private: NativeAppLifeHandler* parent_; std::map<RuntimeStatus, NativeAppLaunchHandler> launch_handler_map_; }; class NativeAppLifeCycleInterfaceVer1: public NativeAppLifeCycleInterface { public: NativeAppLifeCycleInterfaceVer1(NativeAppLifeHandler* parent); virtual ~NativeAppLifeCycleInterfaceVer1() {} private: // launch virtual bool CheckLaunchCondition(AppLaunchingItemPtr item); virtual std::string MakeForkArguments(AppLaunchingItemPtr item, AppDescPtr app_desc); virtual void LaunchAfterClosedAsPolicy(NativeClientInfoPtr client, AppLaunchingItemPtr item); virtual void LaunchNotRegisteredAppAsPolicy(NativeClientInfoPtr client, AppLaunchingItemPtr item); // relaunch virtual void MakeRelaunchParams(AppLaunchingItemPtr item, pbnjson::JValue& j_params); // close virtual void CloseAsPolicy(NativeClientInfoPtr client, AppCloseItemPtr item, std::string& err_text); // pause virtual void PauseAsPolicy(NativeClientInfoPtr client, const pbnjson::JValue& params, std::string& err_text, bool send_life_event); }; class NativeAppLifeCycleInterfaceVer2: public NativeAppLifeCycleInterface { public: NativeAppLifeCycleInterfaceVer2(NativeAppLifeHandler* parent); virtual ~NativeAppLifeCycleInterfaceVer2() {} private: // launch virtual bool CheckLaunchCondition(AppLaunchingItemPtr item); virtual std::string MakeForkArguments(AppLaunchingItemPtr item, AppDescPtr app_desc); virtual void LaunchAfterClosedAsPolicy(NativeClientInfoPtr client, AppLaunchingItemPtr item); virtual void LaunchNotRegisteredAppAsPolicy(NativeClientInfoPtr client, AppLaunchingItemPtr item); // relaunch virtual void MakeRelaunchParams(AppLaunchingItemPtr item, pbnjson::JValue& j_params); // close virtual void CloseAsPolicy(NativeClientInfoPtr client, AppCloseItemPtr item, std::string& err_text); // pause virtual void PauseAsPolicy(NativeClientInfoPtr client, const pbnjson::JValue& params, std::string& err_text, bool send_life_event); }; ///////////////////////////////////////////////////////////////// class NativeClientInfo { public: NativeClientInfo(const std::string& app_id); ~NativeClientInfo(); void Register(LSMessage* lsmsg); void Unregister(); void StartTimerForCheckingRegistration(); void StopTimerForCheckingRegistration(); static gboolean CheckRegistration(gpointer user_data); void SetLifeCycleHandler(int ver, NativeAppLifeCycleInterface* handler); NativeAppLifeCycleInterface* GetLifeCycleHandler() const { return life_cycle_handler_; } bool SendEvent(pbnjson::JValue& payload); void SetAppId(const std::string& app_id) { app_id_ = app_id; } void SetPid(const std::string& pid) { pid_ = pid; } const std::string& AppId() const { return app_id_; } const std::string& Pid() const { return pid_; } int InterfaceVersion() const { return interface_version_; } bool IsRegistered() const { return is_registered_; } bool IsRegistrationExpired() const { return is_registration_expired_; } private: std::string app_id_; std::string pid_; int interface_version_; bool is_registered_; bool is_registration_expired_; LSMessage* lsmsg_; guint registration_check_timer_source_; double registration_check_start_time_; NativeAppLifeCycleInterface* life_cycle_handler_; }; class NativeAppLifeHandler: public AppLifeHandlerInterface { public: NativeAppLifeHandler(); virtual ~NativeAppLifeHandler(); virtual void launch(AppLaunchingItemPtr item); virtual void close(AppCloseItemPtr item, std::string& err_text); virtual void pause(const std::string& app_id, const pbnjson::JValue& params, std::string& err_text, bool send_life_event = true); virtual void clear_handling_item(const std::string& app_id); void RegisterApp(const std::string& app_id, LSMessage* lsmsg, std::string& err_text); bool ChangeRunningAppId(const std::string& current_id, const std::string& target_id, ErrorInfo& err_info); boost::signals2::signal<void (const std::string& app_id, const std::string& uid, const RuntimeStatus& life_status)> signal_app_life_status_changed; boost::signals2::signal<void (const std::string& app_id, const std::string& pid, const std::string& webprocid)> signal_running_app_added; boost::signals2::signal<void (const std::string& app_id)> signal_running_app_removed; boost::signals2::signal<void (const std::string& uid)> signal_launching_done; private: // declare friends for template methods pattern friend class NativeAppLifeCycleInterface; friend class NativeAppLifeCycleInterfaceVer1; friend class NativeAppLifeCycleInterfaceVer2; // functions void AddLaunchingItemIntoPendingQ(AppLaunchingItemPtr item); AppLaunchingItemPtr GetLaunchPendingItem(const std::string& app_id); void RemoveLaunchPendingItem(const std::string& app_id); KillingDataPtr GetKillingDataByAppId(const std::string& app_id); void RemoveKillingData(const std::string& app_id); bool FindPidsAndSendSystemSignal(const std::string& pid, int signame); bool SendSystemSignal(const PidVector& pids, int signame); void StartTimerToKillApp(const std::string& app_id, const std::string& pid, const PidVector& all_pids, guint timeout); void StopTimerToKillApp(const std::string& app_id); static gboolean KillAppOnTimeout(gpointer user_data); NativeClientInfoPtr MakeNewClientInfo(const std::string& app_id); NativeClientInfoPtr GetNativeClientInfo(const std::string& app_id, bool make_new = false); NativeClientInfoPtr GetNativeClientInfoByPid(const std::string& pid); NativeClientInfoPtr GetNativeClientInfoOrMakeNew(const std::string& app_id); void RemoveNativeClientInfo(const std::string& app_id); void PrintNativeClients(); static void ChildProcessWatcher(GPid pid, gint status, gpointer data); void HandleClosedPid(const std::string& pid, gint status); void HandlePendingQOnRegistered(const std::string& app_id); void HandlePendingQOnClosed(const std::string& app_id); void CancelLaunchPendingItemAndMakeItDone(const std::string& app_id); // variables std::list<KillingDataPtr> killing_list_; std::list<AppLaunchingItemPtr> launch_pending_queue_; std::vector<NativeClientInfoPtr> active_clients_; NativeAppLifeCycleInterfaceVer1 native_handler_v1_; NativeAppLifeCycleInterfaceVer2 native_handler_v2_; }; #endif
39.838843
149
0.771289
[ "vector" ]
daf8b3aa5c7d8642016b0bd54bee25c242c67de8
3,694
h
C
aimsdata/src/aimsdata/roi/fill_d.h
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
4
2019-07-09T05:34:10.000Z
2020-10-16T00:03:15.000Z
aimsdata/src/aimsdata/roi/fill_d.h
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
72
2018-10-31T14:52:50.000Z
2022-03-04T11:22:51.000Z
aimsdata/src/aimsdata/roi/fill_d.h
brainvisa/aims-free
5852c1164292cadefc97cecace022d14ab362dc4
[ "CECILL-B" ]
null
null
null
/* This software and supporting documentation are distributed by * Institut Federatif de Recherche 49 * CEA/NeuroSpin, Batiment 145, * 91191 Gif-sur-Yvette cedex * France * * This software is governed by the CeCILL-B license under * French law and abiding by the rules of distribution of free software. * You can use, modify and/or redistribute the software under the * terms of the CeCILL-B license as circulated by CEA, CNRS * and INRIA at the following URL "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ #include <aims/roi/fill.h> #include <aims/bucket/bucketMap.h> #include <set> namespace aims { template <typename T> void floodFill( carto::Volume<T> & vol, const Point3d & pos, T value, Connectivity::Type connectivity, T tolerence, bool verbose ) { typedef Point3d Pt; typedef std::list<Pt> Pset; std::vector<int> size = vol.getSize(), bsize = vol.getSize(); bsize[0] += 2; bsize[1] += 2; bsize[2] += 2; carto::VolumeRef<int16_t> bdone( bsize ); std::vector<int> bpos( 3, 1 ); carto::VolumeRef<int16_t> done( bdone, bpos, size ); bdone.fill( 1 ); done.fill( 0 ); T initVal = vol.at( pos ); T minVal = initVal - tolerence; T maxVal = initVal + tolerence; std::cout << "minVal: " << minVal << ", maxVal: " << maxVal << std::endl; Pset front1, front2; Pset *front = &front1, *next_front = &front2; next_front->push_back( pos ); Connectivity c( &vol( 0, 1 ) - &vol( 0 ), &vol( 0, 0, 1 ) - &vol( 0 ), connectivity ); int i, n = c.nbNeighbors(); done.at( pos ) = 1; Connectivity c2( &done( 0, 1 ) - &done( 0 ), &done( 0, 0, 1 ) - &done( 0 ), connectivity ); while( !next_front->empty() ) { if( verbose ) std::cout << "front size: " << next_front->size() << std::endl; // swap fronts Pset * t = front; front = next_front; next_front = t; next_front->clear(); Pset::const_iterator ip, ep = front->end(); for( ip=front->begin(); ip!=ep; ++ip ) { const Pt & p = *ip; T* pp = &vol.at( p ); *pp = value; int16_t *pd = &done.at( p ); for( i=0; i<n; ++i ) { int16_t *ppd = pd + c2.offset( i ); const T & val = *( pp + c.offset( i ) ); if( *ppd == 0 && val >= minVal && val <= maxVal ) { next_front->push_back( p + c.xyzOffset( i ) ); *ppd = 1; } } } } } }
34.523364
79
0.613698
[ "vector" ]
dafdabf557ebd60010f01eada09778049a329363
2,152
c
C
src/db/store/bvec.c
adventure-db/adventure
355f7b11f627cfc6b9030786c0bcd8cd5b279b94
[ "MIT" ]
10
2015-02-24T03:03:45.000Z
2021-11-23T17:20:09.000Z
src/db/store/bvec.c
adventure-db/adventure
355f7b11f627cfc6b9030786c0bcd8cd5b279b94
[ "MIT" ]
null
null
null
src/db/store/bvec.c
adventure-db/adventure
355f7b11f627cfc6b9030786c0bcd8cd5b279b94
[ "MIT" ]
2
2017-11-30T22:23:43.000Z
2021-07-24T03:22:33.000Z
#include "bvec.h" #include <src/util/dbg.h> #define BVEC_DEF_POWER_TWO 1 #define BVEC_DEF_PAGE_SIZE 64 #define BVEC_HEADER_SIZE 8 // Some limits for error checking #define BVEC_MIN_PAGE_SIZE 64 #define BVEC_MAX_PAGE_SIZE 65536 #define PG_HEADER(s,page) (read_ui64(s, page, 0)) #define PG_FLAGS(hdr) ((hdr >> 56) & 0xFFFF) #define PG_SIZE(hdr) ((hdr >> 32) & 0xFFFF) #define PG_NKEYS(hdr) ((hdr >> 16) & 0xFFFF) #define PG_USED(hdr) ((hdr >> 0) & 0xFFFF) #define PG_END(hdr) (PG_USED(hdr)) #define PG_FREE(hdr) (PG_SIZE(hdr) - PG_USED(hdr)) #define PG_START(hdr) (BVEC_HEADER_SIZE) // INLINE HELPERS /* static inline uint64_t read_ui64(struct store *s, page_p page, item_p i) { return store_read_ui64(s, page + i); } */ static inline void write_ui64(struct store *s, page_p page, item_p i, uint64_t n) { store_write_ui64(s, page + i, n); } /* static inline void copy(struct store *s, page_p dest, item_p di, page_p src, item_p si, item_p sz) { store_copy(s, dest + di, src + si, sz); } */ // HEADER HELPERS static inline void bvec_hdr_write(struct store *s, page_p page, unsigned char flags, uint16_t sz_page, uint16_t n_keys, uint16_t used, uint64_t next_ptr) { unsigned char unused = 16; bv_header hdr = ((uint64_t) flags << 56) | ((uint64_t) unused << 48) | ((uint64_t) sz_page << 32) | ((uint64_t) n_keys << 16) | ((uint64_t) used << 0); write_ui64(s, page, 0, hdr); } // ITERATION HELPERS // EXTERNAL API page_p bvec_create(struct store *s) { page_p page = store_alloc(s, BVEC_DEF_PAGE_SIZE); bvec_hdr_write(s, page, 0, BVEC_DEF_PAGE_SIZE, 0, BVEC_HEADER_SIZE, 0); return page; } // TODO: implement void bvec_destroy(struct store *s, page_p page) { } // Get an item from the vector struct bv_cur bvec_get(struct store *s, page_p page, uint64_t index) { return (struct bv_cur) {.page = 0, .index = 0}; } // Add an item to the vector page_p bvec_add(struct store *s, page_p page, uint64_t index, bv_val val) { check(s, "store is NULL"); check(page, "page is not valid"); error: return page; }
22.893617
81
0.662639
[ "vector" ]
9702fb6f91dd7821103dbf1c0d0c4f5b818318fc
2,398
h
C
ForgeRock-Authenticator/FRAFMDatabaseConnectionHelper.h
WrenSecurity/forgerock-authenticator-ios
669dd5969caa469c66b05804eb5e2ad6f123e2f8
[ "Apache-2.0" ]
null
null
null
ForgeRock-Authenticator/FRAFMDatabaseConnectionHelper.h
WrenSecurity/forgerock-authenticator-ios
669dd5969caa469c66b05804eb5e2ad6f123e2f8
[ "Apache-2.0" ]
null
null
null
ForgeRock-Authenticator/FRAFMDatabaseConnectionHelper.h
WrenSecurity/forgerock-authenticator-ios
669dd5969caa469c66b05804eb5e2ad6f123e2f8
[ "Apache-2.0" ]
null
null
null
/* * The contents of this file are subject to the terms of the Common Development and * Distribution License (the License). You may not use this file except in compliance with the * License. * * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the * specific language governing permission and limitations under the License. * * When distributing Covered Software, include this CDDL Header Notice in each file and include * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL * Header, with the fields enclosed by brackets [] replaced by your own identifying * information: "Portions copyright [year] [name of copyright owner]". * * Copyright 2016 ForgeRock AS. */ @class FMDatabase; @class FRADatabaseConfiguration; @class FRAFMDatabaseFactory; /*! * Responsible for generating a connection to the SQL Database. */ @interface FRAFMDatabaseConnectionHelper : NSObject /*! * Initialise the database with any required configuration. */ - (instancetype)initWithConfiguration:(FRADatabaseConfiguration *)configuration databaseFactory:(FRAFMDatabaseFactory *)factory; /*! * Establish a connection to the database and return this to the caller. * * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. * @return An initialised instance of the database if successfully initialised. Otherwise nil. */ - (FMDatabase *)getConnectionWithError:(NSError *__autoreleasing *)error; /*! * Close a connection to the database which was previously opened by this * class. * * @param database possibly nil database instance which was opened by this class. */ - (void)closeConnectionToDatabase:(FMDatabase *)database; /*! * Read an SQL schema file from the App. The requested schema must be present * in the App, otherwise this is an error. * * @param schema The schema file to read in, excluding the .sql extension. * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. * @return non-nil schema file contents as a string. * @throws FRADatabaseException If the file did not exist. */ + (NSString *)readSchema:(NSString *)schema withError:(NSError *__autoreleasing *)error; @end
41.344828
171
0.764387
[ "object" ]
74a2453f9df1890609ee6207ec327b5307ed64e8
3,816
h
C
components/nanokernel/esr/sw/fx_esr.h
cbuilder/fxrtos-lite
ada55a8693e29e1c04dd5aaba2b18ef90f9eafd7
[ "BSD-3-Clause" ]
16
2020-06-26T21:54:54.000Z
2022-03-05T12:19:06.000Z
components/nanokernel/esr/sw/fx_esr.h
cbuilder/fxrtos-lite
ada55a8693e29e1c04dd5aaba2b18ef90f9eafd7
[ "BSD-3-Clause" ]
null
null
null
components/nanokernel/esr/sw/fx_esr.h
cbuilder/fxrtos-lite
ada55a8693e29e1c04dd5aaba2b18ef90f9eafd7
[ "BSD-3-Clause" ]
6
2020-07-08T04:46:38.000Z
2022-03-07T06:33:16.000Z
#ifndef _FX_ESR_SW_HEADER_ #define _FX_ESR_SW_HEADER_ /** ****************************************************************************** * @file sw/fx_esr.h * @brief Interface header for event service routines. * ****************************************************************************** * Copyright (C) JSC EREMEX, 2008-2020. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include FX_INTERFACE(LANG_TYPES) #include FX_INTERFACE(HAL_INTR_FRAME) #include FX_INTERFACE(FX_RTP) #include FX_INTERFACE(FX_SCHED) #include FX_INTERFACE(TRACE_ESR) #include FX_INTERFACE(FX_SYNC) #include FX_INTERFACE(FX_ESR_TRAP) //! //! Datatype for ESR priority level (EPL). It is like SPL, but it is attribute //! of ESR, whereas SPL is attribute of processor. EPL may be considered as //! sub-levels of SPL_LOW level. //! typedef unsigned int epl_t; enum { FX_ESR_OK = FX_STATUS_OK, FX_ESR_INVALID_PTR = 1, FX_ESR_INVALID_EPL = 2, FX_ESR_INVALID_OBJ = 3, FX_ESR_INVALID_ENTRY = 4, FX_ESR_ERR_MAX }; //! //! ESR representation. //! typedef struct _fx_esr_t { epl_t epl; fx_rtp_t rtp; fx_sched_item_t sched_item; bool active; fx_esr_exception_target_t traps; hal_intr_frame_t* intr_context; void (*func)(struct _fx_esr_t*, uintptr_t, void*); void* arg; trace_esr_handle_t trace_handle; uintptr_t msg; fx_sync_waiter_t waiter; fx_sync_wait_block_t wb; } fx_esr_t; // // HAL uses this function as "kernel init", in case when "threads" are // implemented as other executable and schedulable entity they still have to // name init function as thread_ctor. // void fx_thread_ctor(void); int fx_esr_init( fx_esr_t* esr, epl_t epl, void (*func)(fx_esr_t*, uintptr_t, void*), void* arg ); int fx_esr_deinit(fx_esr_t* esr); int fx_esr_activate(fx_esr_t* esr, uintptr_t msg); void fx_esr_exit(void); #define fx_esr_get_pl(esr) (esr->epl) epl_t fx_esr_raise_pl(epl_t new_epl); void fx_esr_lower_pl(epl_t new_epl); int fx_esr_wait_msg(fx_sync_waitable_t* object, bool wait); FX_METADATA(({ interface: [FX_ESR, SW] })) #endif
36.692308
81
0.670597
[ "object" ]
74ab33670ee5ea9e3df67c0f18f1729f3445b9b3
3,332
h
C
src/Core/Transform.h
wmcnamara/crynn
357deb66040cf7df2b3dd6b09ed75b30983cf7dd
[ "MIT" ]
50
2020-10-14T14:22:34.000Z
2022-02-12T20:03:54.000Z
src/Core/Transform.h
wmcnamara/crynn
357deb66040cf7df2b3dd6b09ed75b30983cf7dd
[ "MIT" ]
9
2020-11-30T04:21:26.000Z
2021-06-21T13:39:56.000Z
src/Core/Transform.h
wmcnamara/crynn
357deb66040cf7df2b3dd6b09ed75b30983cf7dd
[ "MIT" ]
5
2021-05-06T22:05:46.000Z
2021-09-23T17:06:41.000Z
#pragma once #include "glm/glm.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> #include <iostream> #include <memory> #include <unordered_set> #include "Math/Math.h" #include <memory> namespace crynn { /// <summary> /// Matrix representation with easy functions to transform it. /// This class is mostly intended to be inherited from. /// Any transformations made, (translate, scale rotate) will be applied to the "transformMatrix" member. /// You can use this matrix however you please. Its generally used as a model or view matrix, and works very well with MeshRenderer. /// Inspired from the Unity transform class. /// </summary> class Transform { public: Transform(); virtual ~Transform(); Transform(const Transform& other) = delete; Transform& operator=(const Transform& other) = delete; Transform(Transform&& other) noexcept = delete; Transform& operator=(Transform&& other) noexcept = delete; void Translate(Vec3 translation); //Applies a translation to this object. void Scale(Vec3 scale); //Applies a scale to the object void Rotate(Vec3 rot); //Applies a rotation to the object. rot is the XYZ euler angle rotation. Angles should be in degrees void SetPosition(Vec3 position); //Sets the position of the object Vec3 GetPosition() const; //Returns a Vec3 containing the XYZ position of the object void SetScale(Vec3 scale); //Sets the scale of the object Vec3 GetScale() const; //Returns a Vec3 containing the XYZ scale of the object void SetRotation(Vec3 rot); //Sets the objects rotation. rot is the XYZ euler angle rotation. Angles should be in degrees const Quat& GetRotation() const; //Returns a quaternion representing the objects rotation. If you would like euler angles, use GetRotationEuler(). Vec3 GetRotationEuler() const; //Returns a Vec3 with the euler angle rotation state. Vec3 GetForwardVector() const; Vec3 GetRightVector() const; Vec3 GetUpVector() const; //Creates a transformation matrix from the position, rotation and scale of this transform. Mat4 GetMatrix() const; void SetParent(Transform* parent); Transform& GetParent(); void RemoveParent(); //Returns a reference to the set of children this transform has const std::unordered_set<Transform*>& GetChildren(); private: Vec3 m_position = Vec3(0, 0, 0); Quat m_rotation = Quat(Vec3(0.0f, 0.0f, 0.0f)); Vec3 m_scale = Vec3(1, 1, 1); Vec3 m_eulerRotation = Vec3(0, 0, 0); //Cache for the euler rotation of the object. Not used in any calculation. Degrees Transform* m_parent = nullptr; std::unordered_set<Transform*> m_children; //pointers to this objects children. //Recursively computes a matrix that applies transformations from this matrice's parents, instead of the world. //The matrix parameter passed to this function will have all the transformations from its parent transforms applied to it. Mat4& ComputeLocalMatrixRecursive(Mat4& matrix, const Transform* const transform) const; //Caching variables mutable Mat4 m_worldMatrixCache = Mat4(1.0f); //Cached model matrix with transformations relative to the world origin mutable std::atomic_bool m_recalculateMatrix = true; // Indicates model matrix needs to be recalculated. set to true after translating/rotating/scaling. }; }
42.717949
154
0.744298
[ "object", "model", "transform" ]
74ace356333b2629b7ebefafbac9322bcc469e20
17,861
c
C
nitan/adm/kernel/importer.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/adm/kernel/importer.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/adm/kernel/importer.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// importer.c // 用户檔案導入器 #include <ansi.h> inherit ITEM; inherit F_SAVE; #define SAVE_DIR "/data.3k/" #define SUFFIX_NAME "fr" #define SUFFIX_SIZE 26 // 日誌等級分為 3 級,如何界定一段消息應該記錄在 // 哪一級的日誌中? // LV 1: 無法複製文件、載入用户等錯誤信息 // LV 2: 對用户有損的刪除一類的操作信息 // LV 3: 複製或者修改這樣的無損操作信息 #define LOG_LEVEL 3 #define LOG(lv, msg) log_file(sprintf("transfer/LV%d", lv), msg); // 奇怪的是 'nosave' 關鍵字不許用? static string suffix = "abcdefghijklmnopqrstuvwxyz"; static string save_dir = SAVE_DIR; mapping save_dbase; int transfer_user(string arg); void global_destruct_player(object ob, int raw); void transfer_autoload(object user, string card_file); string *get_user_list(string dir); object global_find_player(string user); mapping assure_user_file(string user, int flag); void create() { // 載入原來的 dbased 數據 if (clonep() || ! this_player(1)) { destruct(this_object()); return; } seteuid(getuid()); restore(); set_name("用户檔案導入器", ({ "data importer", "importer", })); set_weight(1); if (clonep()) set_default_object(__FILE__); else { set("unit", "台"); set("long", "這是一台用户檔案導入器,請輸入 help " "importer 查看詳細使用説明。\n"); } setup(); move(this_player(1)); } void setup() { ::setup(); } mixed query_object_data(string index) { return save_dbase[index]; } mapping query_save_dbase() { return save_dbase; } string query_save_file() { return save_dir + "dbased"; } void init() { add_action("do_help", "help"); add_action("do_batch", "batch"); add_action("do_merge", "merge"); } int do_help(string arg) { switch (arg) { case "importer": write(@HELP 在這裏你可以使用以下這些和用户檔案導入器相關的命令: batch 批量導入用户數據。 HELP ); break; case "batch": write(@HELP_BATCH 指令格式 : batch 批量導入用户數據。 相關指令:import, merge HELP_BATCH ); break; case "merge": write(@HELP_BATCH 指令格式 : merge dbase 將另外站點的數據庫併入目前站點的數據庫。 相關指令:batch HELP_BATCH ); break; default: return notify_fail("你要查看什麼幫助?\n"); } return 1; } // 獲得一個不重複的用户名 mapping assure_user_file(string user, int flag) { #if 0 int times; mapping file = ([ ]); for (times = 0; times < SUFFIX_SIZE; times++) { file["login_to"] = sprintf("%slogin/%c/%s%c.o", DATA_DIR, user[0], user, suffix[times]); file["user_to"] = sprintf("%suser/%c/%s%c.o", DATA_DIR, user[0], user, suffix[times]); file["uid"] = sprintf("%s%c", user, suffix[times]); if (file_size(file["login_to"]) < 0 || file_size(file["user_to"]) < 0) return file; } #else mapping file = ([ ]); file["login_to"] = sprintf("%slogin/%c/%s%s.o", DATA_DIR, user[0], user, "_" + SUFFIX_NAME); file["user_to"] = sprintf("%suser/%c/%s%s.o", DATA_DIR, user[0], user, "_" + SUFFIX_NAME); file["uid"] = sprintf("%s%s", user, "_" + SUFFIX_NAME); if (flag || file_size(file["login_to"]) < 0 || file_size(file["user_to"]) < 0) return file; #endif return 0; } // 獲得指定目錄下所有的用户列表 string *get_user_list(string dir) { string *sub_dir_list; string sub_dir; string *user_list; string *temp_list; dir += "login/"; sub_dir_list = get_dir(dir); sub_dir_list = filter_array(sub_dir_list, (: file_size($(dir) + $1) == -2 :)); sub_dir_list = map_array(sub_dir_list, (: $(dir) + $1 + "/" :)); user_list = ({ }); foreach (sub_dir in sub_dir_list) { temp_list = get_dir(sub_dir); if (! arrayp(temp_list) || ! sizeof(temp_list)) continue; reset_eval_cost(); temp_list = filter_array(temp_list, (: sscanf($1, "%*s.bak") == 0 :)); temp_list = map_array(temp_list, (: $1[0..<3] :)); user_list += temp_list; } return user_list; } // 尋找或調入某一個玩家,本來可以使用 UPDATE_D 中的同名函數, // 但因為這裏直接析構了 login_ob,無法對 login_ob 做改名操 // 作。所以需要用到這個函數。 // 如果程序處理中需要更新那些不在線的玩家,則可以使用該函數 // 將這個玩家調入並且進行修改,請注意:修改完畢以後程序必須 // 保存玩家,並且使用 global_destruct_player 將玩家析構,如 // 果沒有調用這個函數,則賦予玩家的定時器會自動析構玩家。 object global_find_player(string user) { object ob; object login_ob; ob = find_player(user); if (! ob) { login_ob = new(LOGIN_OB); login_ob->set("id", user); ob = LOGIN_D->make_body(login_ob); if (! ob) { catch(destruct(login_ob)); return 0; } evaluate(bind((: seteuid(getuid()) :), ob)); if (! ob->restore()) { catch(destruct(login_ob)); catch(destruct(ob)); return 0; } ob->set_temp("temp_loaded", 1); ob->set_temp("link_ob", login_ob); ob->start_call_out(bind((: call_other, __FILE__, "global_destruct_player", ob, 0 :), ob), 0); login_ob->restore(); login_ob->set_temp("body_ob", ob); } return ob; } // 析構一個被 UPDATE_D 調入的玩家 void global_destruct_player(object ob, int raw) { object login_ob; if (objectp(ob) && ob->query_temp("temp_loaded")) { // 增加對 login_ob 的析構 if (objectp(login_ob = ob->query_temp("link_ob"))) { if (raw) login_ob->save(); destruct(login_ob); } if (raw) ob->save(); destruct(ob); } } // 有哪些東西不可以繼續允許 autoload 載入? // 玩家自造的物品,考慮到玩家的 ID 可能改變了, // 如果繼續載入勢必影響其他的玩家,所以必須刪 // 除 autoload。 現在看來,似乎只有這一種,考 // 慮到這一種並不需要把文件載入就可以查出,所 // 以這裏可以簡單的通過 sscanf & filter_array // 來處理用户的 autoload 列表, 過濾掉 /data/ // 目錄下的文件。 void transfer_autoload(object user, string card_file) { string *autoload; autoload = user->query_autoload_info(); if (! arrayp(autoload) || ! sizeof(autoload)) return; autoload = filter_array(autoload, (: (! sscanf($1, "/data/%*s")) :)); if (stringp(card_file)) autoload += ({ card_file }); user->set_autoload_info(autoload); } int do_merge(string arg) { mapping m1, m2; string mk; string key, new_key, id, iname; object ob; int ok; if (arg != "dbase") return notify_fail("你要併入什麼?\n"); foreach (key in keys(save_dbase)) { reset_eval_cost(); if (sscanf(key, DATA_DIR "item/ring/%s", id)) { // Ring information new_key = key + "_" + SUFFIX_NAME; } else if (sscanf(key, DATA_DIR "item/%*s/%s-%s", id, iname) == 3) { // Item information new_key = sprintf(DATA_DIR "item/%c/%s-%s", id[0], id + "_" + SUFFIX_NAME, iname); } else { write("Ignore key - " + key + "!\n"); continue; } if (mapp(save_dbase[key]) && mapp(m1 = save_dbase[key]["owner"])) { /* Convert data */ m2 = allocate_mapping(sizeof(m1)); foreach (mk in keys(m1)) { m2[mk + "_" + SUFFIX_NAME] = m1[mk]; } save_dbase[key]["owner"] = m2; } ok = DBASE_D->set_object_data(new_key, save_dbase[key]); if (! ok) { write(HIR "Failed to set object information: " + new_key + "\n" NOR); continue; } if (objectp(ob = find_object(new_key))) ob->restore(); } return 1; } int do_batch() { int i; string *user_list; string user; user_list = get_user_list(save_dir); write(WHT "開始遷移用户數據...\n\n" NOR); i = 0; foreach (user in user_list) { /* 開始轉換的日誌 for (i = 1; i < LOG_LEVEL + 1; i++) LOG(i, "Start transfering (" + user + ")'s data...\n"); */ reset_eval_cost(); if (transfer_user(user)) { i++; write(sprintf("%-15s: Succeed\n", user)); } else write(sprintf("%-15s: " WHT "Failed" NOR "\n", user)); } write(WHT "\n遷移用户數據完成,共 " + sizeof(user_list) + " 名用户,成功遷移 " + i + " 名用户。\n" NOR); return 1; } // 這兩個定義是為了簡化代碼 #define user_file(x) sprintf("%suser/%c/%s.o", save_dir, x[0], x) #define login_file(x) sprintf("%slogin/%c/%s.o", save_dir, x[0], x) // 轉換指定的用户 int transfer_user(string arg) { object user; object link; object card_ob; string login_from; string user_from; string uid; string card_file; string couple_id; string ring_file; string *item_list; string item_name; string item_file; string file_content; mapping couple_file; mapping file; mixed item_data; int is_ok; // 找到舊的用户文件 login_from = login_file(arg); user_from = user_file(arg); if (file_size(login_from) <= 0 || file_size(user_from) <= 0) { LOG(1, "File not found: (" + login_from + " & " + user_from + ").\n"); return 0; } // 複製用户文件到 DATA_DIR file = assure_user_file(arg, 0); if (! file) { LOG(1, "User conflict: (" + login_from + " & " + user_from + ").\n"); return 0; } if (! cp(login_from, file["login_to"]) || ! cp(user_from, file["user_to"])) { LOG(1, "Copy file to: (" + file["login_to"] + " | " + file["user_to"] + ") failed.\n"); return 0; } uid = file["uid"]; if (! objectp(user = global_find_player(uid))) { LOG(1, "Load user: (" + uid + ") failed.\n"); return 0; } if (uid != arg) { // 修改 LOGIN_OB 和 USER_OB 的 ID if (objectp(link = user->query_temp("link_ob"))) link->set("id", uid); user->set("id", uid); LOG(2, "User ID (" + arg + ") changed into: (" + uid + ").\n"); } // 添加姓名對應,中文姓名的雷同就算了吧。 NAME_D->map_name(user->name(), uid); // 轉換房屋為建房卡 // 注意玩家手裏的鑰匙要收走,但是考慮到所有的 // autoload 物品, 除了一些特殊情況外都要清除, // 所以這裏暫不考慮。 switch (user->query("private_room/type")) { case "盤龍居" : card_file = "/d/room/obj/ultracard"; break; case "彩虹居" : card_file = "/d/room/obj/super"; break; case "獨樂居" : card_file = "/d/room/obj/card"; break; default : card_file = 0; } if (stringp(card_file)) { user->delete("private_room"); LOG(2, "Deleted (" + arg + ")'s private room.\n"); LOG(3, "User (" + arg + ") get a free card.\n"); } // 刪除結義、同盟關係 if (user->query("brothers")) { user->delete("brothers"); LOG(2, "Deleted (" + arg + ")'s brother relation.\n"); } if (user->query("league")) { user->delete("league"); LOG(2, "Deleted (" + arg + ")'s league relation.\n"); } // 刪除幫派 user->delete("party"); // ...on 08/01 21:35. // 確認婚姻關係,考慮到配偶的 ID 有可能變化, // 所以這裏要取得一個配偶唯一可能的 ID, 確 // 保此用户的婚姻關係不出現問題,但問題在於, // 倘若在尋找這個配偶唯一可能的 ID 時,該配 // 偶的文件已經轉移到了 /data/ 下呢?就會弄 // 糊塗了,因此,對於已經轉移過的,要修改源 // 目錄內的文件名。 couple_id = user->query("couple/id"); if (stringp(couple_id)) { // 改變配偶名字 couple_file = assure_user_file(couple_id, 1); couple_id = couple_file["uid"]; user->set("couple/id", couple_id); LOG(3, "User (" + arg + ")'s couple/id set to " + couple_id + ".\n"); // 嗯,要自己保管好自己的結婚戒指 if (user->query("can_summon/wedding ring")) { ring_file = sprintf("%sitem/ring/%s.c", DATA_DIR, uid); cp(sprintf("%sitem/ring/%s.c", save_dir, arg), ring_file); user->set("can_summon/wedding ring", sprintf("%sitem/ring/%s.c", DATA_DIR, uid)); LOG(3, "User (" + arg + ")'s wedding ring copied to " + ring_file + ".\n"); } // 從原來的數據中獲得戒指的存盤信 // 息,導入到 DBASE_D 中。 ring_file = sprintf("%sitem/ring/%s", DATA_DIR, arg); item_data = query_object_data(ring_file); if (item_data) { item_data["user"] = sprintf("%s(%s)", user->name(), uid); is_ok = DBASE_D->set_object_data(sprintf("%sitem/ring/%s", DATA_DIR, uid), item_data); LOG((is_ok ? 3 : 1), "Wedding ring data of (" + arg + ") port to DBASE_D " + (is_ok ? "succeed" : "failed") + ".\n"); } } // 導入自造物品 // 獲得原來的自造物品列表 item_list = get_dir(sprintf("%sitem/%c/%s-*.c", save_dir, arg[0], arg)); if (arrayp(item_list) && sizeof(item_list)) { foreach (item_name in item_list) { // 要去掉後面的 .c 字樣 item_file = sprintf("%sitem/%c/%s", DATA_DIR, arg[0], item_name[0..<3]); item_data = query_object_data(item_file); // 獲得物品的具體名稱 sscanf(item_name, arg + "-%s.c", item_name); // 生成新的物品文件名 item_file = sprintf("%sitem/%c/%s-%s.c", DATA_DIR, uid[0], uid, item_name); // 複製文件 is_ok = cp(sprintf("%sitem/%c/%s-%s.c", save_dir, arg[0], arg, item_name), item_file); if (! is_ok) { LOG(1, "Failed copy Item " + item_name + " of (" + arg + ").\n"); } else { // 將文件中全部的原來的用户 ID // 字樣全部替換為新的 if (arg != uid) { file_content = read_file(item_file); file_content = replace_string(file_content, arg, uid); write_file(item_file, file_content, 1); } if (item_data) { // 修改 "user" 屬性以適應新的 ID item_data["user"] = sprintf("%s(%s)", user->name(), uid); // 將原來的物品存盤信息導入 DBASE_D is_ok = DBASE_D->set_object_data(item_file, item_data); } // 更新用户身上的物品列表 user->set("can_summon/" + item_name, item_file); LOG(3, "Item " + item_name + " of (" + arg + ") successfully " "tranfered.\n"); } } } // 轉換用户的 autoload 信息,去掉無法繼續 // 使用的,如果獲得了卡片,則增加卡片的載 // 入信息 transfer_autoload(user, card_file); // raw : 1,給 user 存一下盤 global_destruct_player(user, 1); // 修改文件名,表示此用户已經轉換 rename(login_file(arg), login_file(arg) + ".bak"); rename(user_file(arg), user_file(arg) + ".bak"); LOG(3, "User (" + arg + ") successfully tranfered.\n"); return 1; }
28.669342
99
0.426516
[ "object" ]
74ae7e5f8933dd184b0729f08c03cc58c9f50759
13,310
c
C
tutorial/simulator/action.c
CMU-TBD/tdl
ecc1047ac3715e1c19852512c9a4c7c0d4a67c2a
[ "BSD-3-Clause" ]
null
null
null
tutorial/simulator/action.c
CMU-TBD/tdl
ecc1047ac3715e1c19852512c9a4c7c0d4a67c2a
[ "BSD-3-Clause" ]
null
null
null
tutorial/simulator/action.c
CMU-TBD/tdl
ecc1047ac3715e1c19852512c9a4c7c0d4a67c2a
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * PROJECT: TDL Tutorial * * (c) Copyright 2001 Reid Simmons. All rights reserved. * (c) Copyright 1994 Richard Goodwin & Reid Simmons. All rights reserved. * * FILE: action.c * * ABSTRACT: * * This file provides a set for routines for simulating the action of the * robot in the environment. * * $Source: /afs/cs.cmu.edu/project/TCA/Master/tcaV8/tutorial/simulator/action.c,v $ * $Revision: 1.3 $ * $Date: 1995/04/07 05:09:39 $ * $Author: rich $ * * REVISION HISTORY: * * $Log: action.c,v $ *****************************************************************************/ #include <math.h> #include "common.h" #include "sim-xwindows.h" #include "files.h" #include "action.h" #include "updates.h" #include "sensors.h" #include "environment.h" #include "draw_env.h" /***************************************************************************** * Global constants *****************************************************************************/ /***************************************************************************** * Global variables *****************************************************************************/ double robot_x=0.0, robot_y=0.0, robot_o = 0.0; double robot_r = 0.0; int collision = 0; int all_goals_reached = 0; double robot_min_dist = 0.1; /* minimum dist for robot when collide */ double forward_noise_level = 0.0; double turning_noise_level = 0.0; int actual_object = 0; int actual_freespace = 0; double torsoDir = 0.0; double rotation_velocity = 0.0; double rotation_distance = 0.0; double translation_velocity = 0.0; double translation_distance = 0.0; static int intersect_lines(double *int_x, double *int_y, double x1, double y1, double dx1, double dy1, double x2, double y2, double dx2, double dy2, int orient) { /* dx1|dy1: only horizontal (orient=0) or vertical (orient=1) */ double lambda, temp; if (orient == 0){ /* horizontal */ if (FABS(dy2) > ALMOST_ZERO){ /* lines not parallel (otherwise no intersection) */ lambda = (y1 - y2) / dy2; if (lambda > 0.0){ *int_y = y1; *int_x = temp = x2 + (lambda * dx2); if (temp >= x1 && temp <= x1+dx1) return TRUE; } } } else /* vertical */ if (FABS(dx2) > ALMOST_ZERO){ /* not parallel */ lambda = (x1 - x2) / dx2; if (lambda > 0.0){ *int_x = x1; *int_y = temp = y2 + (lambda * dy2); if (temp >= y1 && temp <= y1+dy1) return TRUE; } } return FALSE; } int check_intersection(double *int_x, double *int_y, double beam_x, double beam_y, double dbeam_x, double dbeam_y, double x1, double y1, double x2, double y2) { if (beam_x < x1 || beam_x > x2 || beam_y < y1 || beam_y > y2) return FALSE; /* beam origin not in objext x1y1-x2y2 */ if ((dbeam_y < 0.0 && intersect_lines(int_x, int_y, x1, y1, x2-x1, 0.0, beam_x, beam_y, dbeam_x, dbeam_y, 0)) || (dbeam_x < 0.0 && intersect_lines(int_x, int_y, x1, y1, 0.0, y2-y1, beam_x, beam_y, dbeam_x, dbeam_y, 1)) || (dbeam_y > 0.0 && intersect_lines(int_x, int_y, x1, y2, x2-x1, 0.0, beam_x, beam_y, dbeam_x, dbeam_y, 0)) || (dbeam_x > 0.0 && intersect_lines(int_x, int_y, x2, y1, 0.0, y2-y1, beam_x, beam_y, dbeam_x, dbeam_y, 1))){ return TRUE; } return FALSE; } int check_obstacle(struct _object *objs_l, int n_obj_l, double *int_x, double *int_y, double beam_x, double beam_y, double dbeam_x, double dbeam_y, double x1, double y1, double x2, double y2, double offset) { int intersect = 0, i; double dist, min_dist=0.0; double closest_int_x=0.0, closest_int_y=0.0; double a, b, c, lambda, h1, h2, discr, diameter; double x1_minus_offset = x1 - offset, y1_minus_offset = y1 - offset, x2_plus_offset = x2 + offset, y2_plus_offset = y2 + offset; double temp1, temp2; for (i = 0; i < n_obj_l; i++){ if (objs_l[i].type == O_RECTANGLE && objs_l[i].status == 0 && /* rectangle */ ((objs_l[i].x1 >= x1_minus_offset && objs_l[i].x1 <= x2_plus_offset && objs_l[i].y1 >= y1_minus_offset && objs_l[i].y1 <= y2_plus_offset) || (objs_l[i].x2 >= x1_minus_offset && objs_l[i].x2 <= x2_plus_offset && objs_l[i].y1 >= y1_minus_offset && objs_l[i].y1 <= y2_plus_offset) || (objs_l[i].x1 >= x1_minus_offset && objs_l[i].x1 <= x2_plus_offset && objs_l[i].y2 >= y1_minus_offset && objs_l[i].y2 <= y2_plus_offset) || (objs_l[i].x2 >= x1_minus_offset && objs_l[i].x2 <= x2_plus_offset && objs_l[i].y2 >= y1_minus_offset && objs_l[i].y2 <= y2_plus_offset))){ if (dbeam_y > 0.0 && intersect_lines(int_x, int_y, objs_l[i].x1-offset, objs_l[i].y1-offset, objs_l[i].x2-objs_l[i].x1+(2.0*offset), 0.0, beam_x, beam_y, dbeam_x, dbeam_y, 0) && *int_x >= objs_l[i].x1-offset && *int_x <= objs_l[i].x2+offset){ temp1 = beam_x - *int_x; temp2 = beam_y - *int_y; dist = (temp1 * temp1) + (temp2 * temp2); if (intersect == FALSE || dist < min_dist){ min_dist = dist; intersect = TRUE; closest_int_x = *int_x; closest_int_y = *int_y; } } else if (dbeam_y < 0.0 && intersect_lines(int_x, int_y, objs_l[i].x1-offset, objs_l[i].y2+offset, objs_l[i].x2-objs_l[i].x1+(2.0*offset), 0.0, beam_x, beam_y, dbeam_x, dbeam_y, 0) && *int_x >= objs_l[i].x1-offset && *int_x <= objs_l[i].x2+offset) { temp1 = beam_x - *int_x; temp2 = beam_y - *int_y; dist = (temp1 * temp1) + (temp2 * temp2); if (intersect == FALSE || dist < min_dist) { min_dist = dist; intersect = TRUE; closest_int_x = *int_x; closest_int_y = *int_y; } } if (dbeam_x > 0.0 && intersect_lines(int_x, int_y, objs_l[i].x1-offset, objs_l[i].y1-offset, 0.0, objs_l[i].y2-objs_l[i].y1+(2.0*offset), beam_x, beam_y, dbeam_x, dbeam_y, 1) && *int_y >= objs_l[i].y1-offset && *int_y <= objs_l[i].y2+offset){ temp1 = beam_x - *int_x; temp2 = beam_y - *int_y; dist = (temp1 * temp1) + (temp2 * temp2); if (intersect == FALSE || dist < min_dist){ min_dist = dist; intersect = TRUE; closest_int_x = *int_x; closest_int_y = *int_y; } } else if (dbeam_x < 0.0 && intersect_lines(int_x, int_y, objs_l[i].x2+offset, objs_l[i].y1-offset, 0.0, objs_l[i].y2-objs_l[i].y1+(2.0*offset), beam_x, beam_y, dbeam_x, dbeam_y, 1) && *int_y >= objs_l[i].y1-offset && *int_y <= objs_l[i].y2+offset) { temp1 = beam_x - *int_x; temp2 = beam_y - *int_y; dist = (temp1 * temp1) + (temp2 * temp2); if (intersect == FALSE || dist < min_dist) { min_dist = dist; intersect = TRUE; closest_int_x = *int_x; closest_int_y = *int_y; } } } diameter = objs_l[i].diameter + offset; if (objs_l[i].type == O_ROUND && objs_l[i].status == 0 && /* rectangle */ objs_l[i].x1 >= x1-diameter && objs_l[i].x1 <= x2+diameter && objs_l[i].y1 >= y1-diameter && objs_l[i].y1 <= y2+diameter){ /* intersection circle with line */ a = (dbeam_x * dbeam_x) + (dbeam_y * dbeam_y); b = (beam_x*dbeam_x) + (beam_y*dbeam_y) - (dbeam_x*objs_l[i].x1) - (dbeam_y*objs_l[i].y1); h1 = beam_x - objs_l[i].x1; h2 = beam_y - objs_l[i].y1; c = (h1 * h1) + (h2 * h2) - (diameter * diameter); if (a != 0.0){ discr = ((b*b) / (a*a)) - (c/a); if (discr > 0.0){ discr = sqrt(discr); h1 = 0.0 - (b / a); lambda = h1 - discr; if (lambda < 0.0 && h1 + discr >= 0.0){ lambda = 0.0; fprintf(stderr, "\nWarning: object %f %f in obst #%d?",beam_x, beam_y,i); } if (lambda >= 0.0){ h1 = lambda * dbeam_x; h2 = lambda * dbeam_y; *int_x = beam_x + h1; *int_y = beam_y + h2; dist = (h1 * h1) + (h2 * h2); if (intersect == FALSE || dist < min_dist){ min_dist = dist; intersect = TRUE; closest_int_x = *int_x; closest_int_y = *int_y; } } } } } } if (intersect){ *int_x = closest_int_x; *int_y = closest_int_y; } return intersect; } void doChange(double deltaX, double deltaY, double deltaT ) { int i, space_i, in_new_space, j, test, obst_test; double dist=0.0, dx, dy, object_x, object_y, d3, d2; double old_x, old_y, old_o; double robot2_x=0.0, robot2_y=0.0, robot3_x=0.0, robot3_y=0.0; double fwdSq, angle=0.0; int tried_before[MAX_OBJ]; if (actual_freespace < 0) for (i = 0; i < n_space; i++){ if (robot_x >= space[i].x1 && robot_x <= space[i].x2 && robot_y >= space[i].y1 && robot_y <= space[i].y2) actual_freespace = i; } if (actual_freespace < 0){ fprintf(stderr, "\nWARNING: robot not in free space..."); } if (turning_noise_level != 0) { deltaT = distrNormal(deltaT, deltaT*turning_noise_level); } if (forward_noise_level != 0) { deltaX = distrNormal(deltaX, deltaX*forward_noise_level); deltaY = distrNormal(deltaY, deltaY*forward_noise_level); } fwdSq = (double)(SQR(deltaX) + SQR(deltaY)); if( deltaX == 0 && deltaY == 0 ) angle = robot_o; else angle = (double)PI/2-(double)atan2(deltaY,deltaX); old_o = robot_o; robot_o = angle; old_x = robot_x; old_y = robot_y; for (; robot_o >= TWO_PI; robot_o -= TWO_PI); for (; robot_o < 0.0 ; robot_o += TWO_PI); collision = 0; if (check_obstacle(objs, n_obj, &robot_x, &robot_y, old_x, old_y, sin(robot_o), cos(robot_o), space[actual_freespace].x1, space[actual_freespace].y1, space[actual_freespace].x2, space[actual_freespace].y2, robot_r) == 0){ robot_x = old_x + deltaX; robot_y = old_y + deltaY; } else { dist = (((robot_x - old_x) * (robot_x - old_x)) + ((robot_y - old_y) * (robot_y - old_y))); if (dist < fwdSq) { fprintf(stderr, "Collision: At distance %.2f\n", dist); collision = 1; } if (dist >= fwdSq){ robot_x = old_x + deltaX; robot_y = old_y + deltaY; } } if (robot_x < space[actual_freespace].x1 || robot_x > space[actual_freespace].x2 || robot_y < space[actual_freespace].y1 || robot_y > space[actual_freespace].y2){ /* robot left last freespace */ robot_x = object_x = old_x; robot_y = object_y = old_y; space_i = actual_freespace; for (i = 0; i < MAX_OBJ; i++) tried_before[i] = 0; tried_before[space_i] = 1; in_new_space = 1; do{ obst_test = check_obstacle(objs, n_obj, &robot2_x, &robot2_y, object_x, object_y, sin(robot_o), cos(robot_o), space[space_i].x1, space[space_i].y1, space[space_i].x2, space[space_i].y2, robot_r); test = check_intersection(&robot3_x, &robot3_y, object_x, object_y, sin(robot_o), cos(robot_o), space[space_i].x1, space[space_i].y1, space[space_i].x2, space[space_i].y2); if (obst_test == 1 || test == 1){ d2 = SQR(robot2_x - object_x) + SQR(robot2_y - object_y); d3 = SQR(robot3_x - object_x) + SQR(robot3_y - object_y); if (obst_test == 1 && (test == 0 || d2 < d3)){ robot_x = robot2_x; robot_y = robot2_y; } else { robot_x = robot3_x; robot_y = robot3_y; } dx = robot_x - old_x; dy = robot_y - old_y; dist = (dx * dx) + (dy * dy); if (dist > fwdSq){ robot_x = old_x + deltaX; robot_y = old_y + deltaY; } dx = robot_x - object_x; dy = robot_y - object_y; } in_new_space = 0; if (obst_test == 0 && dist <= fwdSq){ for (j = 0; j < n_space; j++){ if (tried_before[j] == 0 && in_new_space == 0 && robot_x >= space[j].x1 - ALMOST_ZERO && robot_x <= space[j].x2 + ALMOST_ZERO && robot_y >= space[j].y1 - ALMOST_ZERO && robot_y <= space[j].y2 + ALMOST_ZERO){ space_i = j; object_x = robot_x; object_y = robot_y; in_new_space = 1; tried_before[space_i] = 1; } } } } while (in_new_space != 0); if (dist < fwdSq) { fprintf(stderr, "Collision: At distance %.2f\n", dist); collision = 1; } for (i = 0; i < n_space; i++){ if (robot_x >= space[i].x1 && robot_x <= space[i].x2 && robot_y >= space[i].y1 && robot_y <= space[i].y2) actual_freespace = i; } if (robot_x < objs[actual_object].x1 || robot_x > objs[actual_object].x2 || robot_y < objs[actual_object].y1 || robot_y > objs[actual_object].y2){ actual_object = -1; for (i = 0; i < n_obj && actual_object == -1; i++) if (robot_x >= objs[i].x1 && robot_x <= objs[i].x2 && robot_y >= objs[i].y1 && robot_y <= objs[i].y2){ actual_object = i; break; } } } if (collision == 1){ robot_x -= robot_min_dist * sin(robot_o); robot_y -= robot_min_dist * cos(robot_o); } robot_o = old_o + deltaT; } /* This is equivalent to the act of lifting the robot and moving it * to a new location without the encoders registering the movement. */ void hyperJump(double new_x, double new_y, double new_o) { robot_x = new_x; robot_y = new_y; robot_o = new_o; /* this function needs a value */ /* greater than 0 to update the */ /* position, so this is how long */ /* a teleportation will take, 1 msec */ updatePosition(1); sensors(); refreshSimDisplay(TRUE); RedrawWholeMap(); }
30.597701
85
0.574981
[ "object" ]
74af744d92cda3fb7eb9e8af27b34978d920e927
1,137
h
C
src/cpp/QOpenGLShaderProgram/qopenglshaderprogram_wrap.h
sedwards2009/nodegui-plugin-opengl
e12669f2efbb07420f86ed8e10c85a9e408f4ff7
[ "MIT" ]
3
2021-10-16T03:40:08.000Z
2021-11-10T07:16:11.000Z
src/cpp/QOpenGLShaderProgram/qopenglshaderprogram_wrap.h
sedwards2009/nodegui-plugin-opengl
e12669f2efbb07420f86ed8e10c85a9e408f4ff7
[ "MIT" ]
null
null
null
src/cpp/QOpenGLShaderProgram/qopenglshaderprogram_wrap.h
sedwards2009/nodegui-plugin-opengl
e12669f2efbb07420f86ed8e10c85a9e408f4ff7
[ "MIT" ]
1
2022-02-16T01:34:24.000Z
2022-02-16T01:34:24.000Z
#pragma once #include <napi.h> #include <QOpenGLShaderProgram> #include <QPointer> #include <Extras/Export/export.h> #include <core/Component/component_macro.h> class DLL_EXPORT QOpenGLShaderProgramWrap : public Napi::ObjectWrap<QOpenGLShaderProgramWrap> { COMPONENT_WRAPPED_METHODS_DECLARATION private: QPointer<QOpenGLShaderProgram> instance; bool ownInstance; public: static Napi::Object init(Napi::Env env, Napi::Object exports); QOpenGLShaderProgramWrap(const Napi::CallbackInfo& info); ~QOpenGLShaderProgramWrap(); QOpenGLShaderProgram* getInternalInstance(); // class constructor static Napi::FunctionReference constructor; // wrapped methods Napi::Value addShader(const Napi::CallbackInfo& info); Napi::Value addShaderFromSourceCode(const Napi::CallbackInfo& info); Napi::Value bind(const Napi::CallbackInfo& info); Napi::Value delete_(const Napi::CallbackInfo& info); Napi::Value link(const Napi::CallbackInfo& info); Napi::Value log(const Napi::CallbackInfo& info); Napi::Value programId(const Napi::CallbackInfo& info); Napi::Value release(const Napi::CallbackInfo& info); };
29.921053
70
0.769569
[ "object" ]
74b1e3759e041432c394b913c5c82dd2f47d5917
8,855
h
C
Remoting/Views/vtkPolarAxesRepresentation.h
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
815
2015-01-03T02:14:04.000Z
2022-03-26T07:48:07.000Z
Remoting/Views/vtkPolarAxesRepresentation.h
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
9
2015-04-28T20:10:37.000Z
2021-08-20T18:19:01.000Z
Remoting/Views/vtkPolarAxesRepresentation.h
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
328
2015-01-22T23:11:46.000Z
2022-03-14T06:07:52.000Z
/*========================================================================= Program: ParaView Module: vtkPolarAxesRepresentation.h Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkPolarAxesRepresentation - representation for a polar-axes. // .SECTION Description // vtkPolarAxesRepresentation is a representation for the Polar-Axes that shows a // bounding box with labels around any input dataset. #ifndef vtkPolarAxesRepresentation_h #define vtkPolarAxesRepresentation_h #include "vtkRemotingViewsModule.h" //needed for exports #include "vtkNew.h" // needed for vtkNew. #include "vtkPVDataRepresentation.h" #include "vtkWeakPointer.h" // needed for vtkWeakPointer. class vtkPolarAxesActor; class vtkPolyData; class vtkPVRenderView; class vtkTextProperty; class VTKREMOTINGVIEWS_EXPORT vtkPolarAxesRepresentation : public vtkPVDataRepresentation { public: static vtkPolarAxesRepresentation* New(); vtkTypeMacro(vtkPolarAxesRepresentation, vtkPVDataRepresentation); void PrintSelf(ostream& os, vtkIndent indent) override; // Description: // Get/Set the Position to transform the data bounds. vtkSetVector3Macro(Position, double); vtkGetVector3Macro(Position, double); // Description: // Get/Set the Orientation to transform the data bounds. vtkSetVector3Macro(Orientation, double); vtkGetVector3Macro(Orientation, double); // Description: // Get/Set the Scale to transform the data bounds. vtkSetVector3Macro(Scale, double); vtkGetVector3Macro(Scale, double); // Description: // Get the bounds of the data. vtkGetVector6Macro(DataBounds, double); // Description: // Get/Set custom bounds to use. When corresponding CustomBoundsActive is // true, the data bounds will be ignored for that direction and CustomBounds // will be used instead. vtkSetVector6Macro(CustomBounds, double); vtkGetVector6Macro(CustomBounds, double); // Description: // Get/Set whether to use custom bounds for a particular dimension. vtkSetVector3Macro(EnableCustomBounds, int); vtkGetVector3Macro(EnableCustomBounds, int); // Description: // Set the use of a custom range. vtkSetMacro(EnableCustomRange, bool); vtkGetMacro(EnableCustomRange, bool); // Description: // Get/Set custom range to use. // the data bounds will be ignored for that direction and CustomRange // will be used instead. vtkSetVector2Macro(CustomRange, double); vtkGetVector2Macro(CustomRange, double); // Description: // Set the actor color. virtual void SetPolarAxisColor(double r, double g, double b); virtual void SetPolarArcsColor(double r, double g, double b); virtual void SetSecondaryPolarArcsColor(double r, double g, double b); virtual void SetSecondaryRadialAxesColor(double r, double g, double b); virtual void SetLastRadialAxisColor(double r, double g, double b); virtual void SetPolarAxisTitleTextProperty(vtkTextProperty* prop); virtual void SetPolarAxisLabelTextProperty(vtkTextProperty* prop); virtual void SetLastRadialAxisTextProperty(vtkTextProperty* prop); virtual void SetSecondaryRadialAxesTextProperty(vtkTextProperty* prop); // Description: // This needs to be called on all instances of vtkPolarAxesRepresentation when // the input is modified. void MarkModified() override { this->Superclass::MarkModified(); } // Description: // vtkAlgorithm::ProcessRequest() equivalent for rendering passes. This is // typically called by the vtkView to request meta-data from the // representations or ask them to perform certain tasks e.g. // PrepareForRendering. int ProcessViewRequest(vtkInformationRequestKey* request_type, vtkInformation* inInfo, vtkInformation* outInfo) override; // Description: // Set visibility of the representation. void SetVisibility(bool visible) override; // Description: // Set (forward) visibility of the parent (composite) representation. virtual void SetParentVisibility(bool visible); //*************************************************************************** // Forwarded to internal vtkPolarAxesActor virtual void SetLog(bool active); virtual void SetNumberOfRadialAxes(vtkIdType val); virtual void SetNumberOfPolarAxisTicks(int val); virtual void SetAutoSubdividePolarAxis(bool active); virtual void SetMinimumRadius(double radius); virtual void SetMinimumAngle(double angle); virtual void SetMaximumAngle(double angle); virtual void SetSmallestVisiblePolarAngle(double angle); virtual void SetTickLocation(int location); virtual void SetRadialUnits(bool use); virtual void SetScreenSize(double size); virtual void SetPolarAxisTitle(const char* title); virtual void SetPolarLabelFormat(const char* format); virtual void SetExponentLocation(int location); virtual void SetRadialAngleFormat(const char* format); virtual void SetEnableDistanceLOD(int enable); virtual void SetDistanceLODThreshold(double val); virtual void SetEnableViewAngleLOD(int enable); virtual void SetViewAngleLODThreshold(double val); virtual void SetPolarAxisVisibility(int visible); virtual void SetDrawRadialGridlines(int draw); virtual void SetDrawPolarArcsGridlines(int draw); virtual void SetPolarTitleVisibility(int visible); virtual void SetRadialAxisTitleLocation(int location); virtual void SetPolarAxisTitleLocation(int location); virtual void SetPolarLabelVisibility(int visible); virtual void SetArcTicksOriginToPolarAxis(int use); virtual void SetRadialAxesOriginToPolarAxis(int use); virtual void SetPolarTickVisibility(int visible); virtual void SetAxisTickVisibility(int visible); virtual void SetAxisMinorTickVisibility(int visible); virtual void SetArcTickVisibility(int visible); virtual void SetArcMinorTickVisibility(int visible); virtual void SetArcMajorTickSize(double size); virtual void SetPolarAxisMajorTickSize(double size); virtual void SetLastRadialAxisMajorTickSize(double size); virtual void SetPolarAxisTickRatioSize(double size); virtual void SetLastAxisTickRatioSize(double size); virtual void SetArcTickRatioSize(double size); virtual void SetPolarAxisMajorTickThickness(double thickness); virtual void SetLastRadialAxisMajorTickThickness(double thickness); virtual void SetArcMajorTickThickness(double thickness); virtual void SetPolarAxisTickRatioThickness(double thickness); virtual void SetLastAxisTickRatioThickness(double thickness); virtual void SetArcTickRatioThickness(double thickness); virtual void SetDeltaAngleMajor(double delta); virtual void SetDeltaAngleMinor(double delta); virtual void SetRadialAxesVisibility(int visible); virtual void SetRadialTitleVisibility(int visible); virtual void SetPolarArcsVisibility(int visible); virtual void SetUse2DMode(int use); virtual void SetRatio(double ratio); virtual double GetDeltaRangeMinor(); virtual double GetDeltaRangeMajor(); // Description: // Set the renderer to use. Default is to use the // vtkPVRenderView::DEFAULT_RENDERER. vtkSetMacro(RendererType, int); vtkGetMacro(RendererType, int); protected: vtkPolarAxesRepresentation(); ~vtkPolarAxesRepresentation() override; int FillInputPortInformation(int port, vtkInformation* info) override; int RequestData( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector*) override; virtual void InitializeDataBoundsFromData(vtkDataObject* data); virtual void UpdateBounds(); // Description: // Adds the representation to the view. This is called from // vtkView::AddRepresentation(). Subclasses should override this method. // Returns true if the addition succeeds. bool AddToView(vtkView* view) override; // Description: // Removes the representation to the view. This is called from // vtkView::RemoveRepresentation(). Subclasses should override this method. // Returns true if the removal succeeds. bool RemoveFromView(vtkView* view) override; vtkNew<vtkPolyData> OutlineGeometry; vtkWeakPointer<vtkPVRenderView> RenderView; vtkPolarAxesActor* PolarAxesActor; double Position[3]; double Scale[3]; double Orientation[3]; double CustomBounds[6]; int EnableCustomBounds[3]; double CustomRange[2]; bool EnableCustomRange; double DataBounds[6]; int RendererType; vtkTimeStamp DataBoundsTime; bool ParentVisibility; private: vtkPolarAxesRepresentation(const vtkPolarAxesRepresentation&) = delete; void operator=(const vtkPolarAxesRepresentation&) = delete; }; #endif
39.53125
89
0.768718
[ "transform" ]
74b6e060bdd67808e85abca38d73193748ec69ef
3,725
h
C
packedForest/src/fpSingleton/dataset/inputCSVData.h
sree0917/SPORF
73f97aa29affd818b8632a6ef4f23d67e682f9a4
[ "Apache-2.0" ]
33
2017-08-28T18:33:20.000Z
2018-12-29T02:46:08.000Z
packedForest/src/fpSingleton/dataset/inputCSVData.h
sree0917/SPORF
73f97aa29affd818b8632a6ef4f23d67e682f9a4
[ "Apache-2.0" ]
150
2019-02-06T16:53:04.000Z
2019-08-07T17:42:11.000Z
packedForest/src/fpSingleton/dataset/inputCSVData.h
sree0917/SPORF
73f97aa29affd818b8632a6ef4f23d67e682f9a4
[ "Apache-2.0" ]
16
2017-05-18T17:05:39.000Z
2018-12-04T22:44:42.000Z
#ifndef inputCSVData_h #define inputCSVData_h #include <vector> #include <iostream> #include "fpReadCSV.h" #include "fpDataBase.h" #include "inputData.h" #include <string> //#define HOLDSIZE 128 namespace fp { template <typename T, typename Q> class inputCSVData : public inputData<T,Q> { private: inputXData<T> X; inputYDataClassification<Q> Y; //std::vector<std::vector<T> > dataTempStore; public: inputCSVData(const std::string& forestCSVFileName, const int &columnWithY) { csvHandle csvH(forestCSVFileName); if(columnWithY >= csvH.returnNumColumns()){ throw std::runtime_error("column with class labels does not exist." ); return; } X.initializeXData(csvH.returnNumColumns()-1, csvH.returnNumRows()); Y.initializeYData(csvH.returnNumRows()); /* dataTempStore.resize(csvH.returnNumColumns()-1); for(auto& i : dataTempStore){ i.resize(HOLDSIZE); } int pRow = 0; for(; pRow < csvH.returnNumRows()-HOLDSIZE; pRow+=HOLDSIZE){ for(int i = 0; i<HOLDSIZE; i++){ for(int j=0; j<csvH.returnNumColumns(); j++){ if(j < columnWithY){ dataTempStore[j][i] = csvH.returnNextElement<T>(); }else if(j == columnWithY){ Y.setYElement(pRow+i, csvH.returnNextElement<Q>()); }else{ dataTempStore[j-1][i] = csvH.returnNextElement<T>(); } } } for(int j=0; j<csvH.returnNumColumns()-1; j++){ for(int k = 0; k < HOLDSIZE; ++k){ X.setXElement(j,k+pRow, dataTempStore[j][k]); } } } for(int i = pRow; i<csvH.returnNumRows(); i++){ for(int j=0; j<csvH.returnNumColumns(); j++){ if(j < columnWithY){ X.setXElement(j,i, csvH.returnNextElement<T>()); }else if(j == columnWithY){ Y.setYElement(i, csvH.returnNextElement<Q>()); }else{ X.setXElement(j-1,i, csvH.returnNextElement<T>()); } } } */ for(int i=0; i<csvH.returnNumRows(); i++){ for(int j=0; j<csvH.returnNumColumns(); j++){ if(j < columnWithY){ X.setXElement(j,i, csvH.returnNextElement<T>()); }else if(j == columnWithY){ Y.setYElement(i, csvH.returnNextElement<Q>()); }else{ X.setXElement(j-1,i, csvH.returnNextElement<T>()); } } } } ~inputCSVData(){ //TODO destroy X and Y } inline Q returnClassOfObservation(const int &observationNum){ return Y.returnYElement(observationNum); } inline T returnFeatureValue(const int &featureNum, const int &observationNum){ return X.returnElement(featureNum, observationNum); } inline void prefetchFeatureValue(const int &featureNum, const int &observationNum){ X.prefetchElement(featureNum, observationNum); } inline int returnNumFeatures(){ return X.returnNumFeatures(); } inline int returnNumObservations(){ return Y.returnNumObservations(); } inline int returnNumClasses(){ return Y.numClasses(); } inline void checkY(){ return Y.checkClassRepresentation(); } void printDataStats(){ std::cout << "there are " << this->returnNumFeatures() << " features.\n"; std::cout << "there are " << this->returnNumObservations() << " observations.\n"; } void printXValues(){ for(int i = 0; i < this->returnNumFeatures(); i++){ for(int j = 0; j < this->returnNumObservations(); j++){ std::cout << this->returnFeatureValue(i,j) << " "; } std::cout << "\n"; } } void printYValues(){ for(int j = 0; j < this->returnNumObservations(); j++){ std::cout << this->returnClassOfObservation(j) << " "; } std::cout << "\n"; } }; } //namespace fp #endif //inputCSVData_h
25.513699
86
0.612886
[ "vector" ]
74b880ad392acbcca617ad02e66c498b803d4c22
7,966
h
C
Tools/MedusaExport/max9/include/triobj.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
Tools/MedusaExport/max9/include/triobj.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
Tools/MedusaExport/max9/include/triobj.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
//**************************************************************************/ // Copyright (c) 1998-2006 Autodesk, Inc. // All rights reserved. // // These coded instructions, statements, and computer programs contain // unpublished proprietary information written by Autodesk, Inc., and are // protected by Federal copyright law. They may not be disclosed to third // parties or copied or duplicated in any form, in whole or in part, without // the prior written consent of Autodesk, Inc. //**************************************************************************/ // FILE: triobj.h // DESCRIPTION: Defines Triangle Mesh Object // AUTHOR: Dan Silva // HISTORY: created 9 September 1994 //**************************************************************************/ #ifndef __TRIOBJ__ #define __TRIOBJ__ #include "meshlib.h" #include "snap.h" #include "maxtess.h" #define TRI_MULTI_PROCESSING TRUE extern CoreExport Class_ID triObjectClassID; class TriObject: public GeomObject { protected: Interval geomValid; Interval topoValid; Interval texmapValid; Interval selectValid; Interval vcolorValid; Interval gfxdataValid; ChannelMask validBits; // for the remaining constant channels CoreExport void CopyValidity(TriObject *fromOb, ChannelMask channels); #if TRI_MULTI_PROCESSING static int refCount; static HANDLE defThread; static HANDLE defMutex; static HANDLE defStartEvent; static HANDLE defEndEvent; friend DWORD WINAPI defFunc(LPVOID ptr); #endif // inherited virtual methods for Reference-management CoreExport RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message ); public: Mesh mesh; TessApprox mDispApprox; bool mSubDivideDisplacement; bool mDisableDisplacement; bool mSplitMesh; CoreExport TriObject(); CoreExport ~TriObject(); // inherited virtual methods: //from animatable using GeomObject::GetInterface; CoreExport void* GetInterface(ULONG id); CoreExport void ReleaseInterface(ULONG id,void *i); // From BaseObject CoreExport int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt); CoreExport int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags); CoreExport void Snap(TimeValue t, INode* inode, SnapInfo *snap, IPoint2 *p, ViewExp *vpt); CoreExport CreateMouseCallBack* GetCreateMouseCallBack(); CoreExport RefTargetHandle Clone(RemapDir& remap = DefaultRemapDir()); // From Object CoreExport ObjectState Eval(TimeValue time); CoreExport Interval ObjectValidity(TimeValue t); CoreExport BOOL HasUVW(); CoreExport BOOL HasUVW (int mapChannel); // get and set the validity interval for the nth channel CoreExport Interval ChannelValidity(TimeValue t, int nchan); CoreExport void SetChannelValidity(int i, Interval v); CoreExport void InvalidateChannels(ChannelMask channels); // Convert-to-type validity CoreExport Interval ConvertValidity(TimeValue t); // Deformable object procs int IsDeformable() { return 1; } int NumPoints() { return mesh.getNumVerts(); } Point3 GetPoint(int i) { return mesh.getVert(i); } void SetPoint(int i, const Point3& p) { mesh.setVert(i,p); } CoreExport BOOL IsPointSelected (int i); CoreExport float PointSelection (int i); // Mappable object procs int IsMappable() { return 1; } int NumMapChannels () { return MAX_MESHMAPS; } int NumMapsUsed () { return mesh.getNumMaps(); } void ApplyUVWMap(int type, float utile, float vtile, float wtile, int uflip, int vflip, int wflip, int cap,const Matrix3 &tm,int channel=1) { mesh.ApplyUVWMap(type,utile,vtile,wtile,uflip,vflip,wflip,cap,tm,channel); } CoreExport BOOL PolygonCount(TimeValue t, int& numFaces, int& numVerts); void PointsWereChanged(){ mesh.InvalidateGeomCache(); } CoreExport void GetDeformBBox(TimeValue t, Box3& box, Matrix3 *tm=NULL,BOOL useSel=FALSE ); CoreExport void Deform(Deformer *defProc, int useSel); CoreExport int CanConvertToType(Class_ID obtype); CoreExport Object* ConvertToType(TimeValue t, Class_ID obtype); CoreExport void FreeChannels(ChannelMask chan); CoreExport Object *MakeShallowCopy(ChannelMask channels); CoreExport void ShallowCopy(Object* fromOb, ChannelMask channels); CoreExport void NewAndCopyChannels(ChannelMask channels); CoreExport DWORD GetSubselState(); CoreExport void SetSubSelState(DWORD s); CoreExport BOOL CheckObjectIntegrity(); // From GeomObject CoreExport int IntersectRay(TimeValue t, Ray& ray, float& at, Point3& norm); CoreExport ObjectHandle CreateTriObjRep(TimeValue t); // for rendering, also for deformation CoreExport void GetWorldBoundBox(TimeValue t, INode *inode, ViewExp* vpt, Box3& box ); CoreExport void GetLocalBoundBox(TimeValue t, INode *inode, ViewExp* vpt, Box3& box ); CoreExport Mesh* GetRenderMesh(TimeValue t, INode *inode, View &view, BOOL& needDelete); // for displacement mapping CoreExport BOOL CanDoDisplacementMapping(); CoreExport TessApprox& DisplacmentApprox() { return mDispApprox; } CoreExport bool& DoSubdivisionDisplacment() { return mSubDivideDisplacement; } CoreExport bool& SplitMeshForDisplacement() { return mSplitMesh; } CoreExport void SetDisplacmentApproxToPreset(int preset); CoreExport void DisableDisplacementMapping(BOOL disable); CoreExport void TopologyChanged(); Mesh& GetMesh() { return mesh; } // Animatable methods CoreExport void DeleteThis(); void FreeCaches() {mesh.InvalidateGeomCache(); } Class_ID ClassID() { return Class_ID(TRIOBJ_CLASS_ID,0); } void GetClassName(MSTR& s) { s = MSTR(_M("TriObject")); } void NotifyMe(Animatable *subAnim, int message) {} int IsKeyable() { return 0;} int Update(TimeValue t) { return 0; } //BOOL BypassTreeView() { return TRUE; } // This is the name that will appear in the history browser. MCHAR *GetObjectName() { return _M("Mesh"); } CoreExport void RescaleWorldUnits(float f); // IO CoreExport IOResult Save(ISave *isave); CoreExport IOResult Load(ILoad *iload); // TriObject-specific methods //! \brief Should reduce any derived display data to save memory, since the node wont be drawn until the user undhides it /*! This function should delete any derived data used to display the object such as gfx normals, direct mesh caches etc. This is typicallly called when the user hides the node or sets it as bounding box */ CoreExport void ReduceDisplayCaches(); }; CoreExport void SetDisplacmentPreset(int preset, TessApprox approx); // Regular TriObject CoreExport ClassDesc* GetTriObjDescriptor(); // A new decsriptor can be registered to replace the default // tri object descriptor. This new descriptor will then // be used to create tri objects. CoreExport void RegisterEditTriObjDesc(ClassDesc* desc); CoreExport ClassDesc* GetEditTriObjDesc(); // Returns default of none have been registered // Use this instead of new TriObject. It will use the registered descriptor // if one is registered, otherwise you'll get a default tri-object. CoreExport TriObject *CreateNewTriObject(); #include "XTCObject.h" const Class_ID kTriObjNormalXTCID = Class_ID(0x730a33d7, 0x27246c55); // The purpose of this class is to remove specified Mesh normals // after modifiers which would invalidate them. class TriObjectNormalXTC : public XTCObject { public: TriObjectNormalXTC () { } Class_ID ExtensionID () { return kTriObjNormalXTCID; } CoreExport XTCObject *Clone(); ChannelMask DependsOn () { return PART_TOPO|PART_GEOM; } ChannelMask ChannelsChanged () { return 0; } CoreExport void PreChanChangedNotify (TimeValue t, ModContext &mc, ObjectState *os, INode *node, Modifier *mod, bool bEndOfPipeline); CoreExport void PostChanChangedNotify (TimeValue t, ModContext &mc, ObjectState *os, INode *node, Modifier *mod, bool bEndOfPipeline); CoreExport void DeleteThis (); }; #endif
37.575472
124
0.734371
[ "mesh", "object" ]
74babbe02a67b2d61390dbf61150a13b1a6ff2db
1,230
h
C
src/gui/src/gui.h
aching/Clusterlib
da81a653e9630b61214dbf7c37c75196300cf606
[ "Apache-2.0" ]
2
2015-03-31T17:57:46.000Z
2019-06-18T17:29:46.000Z
src/gui/src/gui.h
aching/Clusterlib
da81a653e9630b61214dbf7c37c75196300cf606
[ "Apache-2.0" ]
null
null
null
src/gui/src/gui.h
aching/Clusterlib
da81a653e9630b61214dbf7c37c75196300cf606
[ "Apache-2.0" ]
1
2020-04-24T05:23:25.000Z
2020-04-24T05:23:25.000Z
/* * Copyright (c) 2010 Yahoo! Inc. All rights reserved. Licensed under * the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. * * $Id$ */ #ifndef _CL_GUI_H_ #define _CL_GUI_H_ /* * The main include file for users of the gui. */ #include <string> #include <vector> #include <list> #include <map> #include <algorithm> #include <iostream> #include <pthread.h> #include <errno.h> #include <sys/time.h> #include <stdlib.h> #include <stdio.h> #include <iomanip> #include "log.h" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> #include "clusterlib.h" #include "microhttpserver.h" #include "httpd.h" DEFINE_LOGGER(GUI_LOG, "gui") /* Forward declarations */ #endif /* !_CL_GUI_H_ */
25.625
70
0.730081
[ "vector" ]
74d56155a7acf1c11749356e17a700c27e9cf41d
822
h
C
odk/api/inc/odkapi_acquisition_task_xml.h
HpLightcorner/OXYGEN-SDK
4ede0ea07b513032605b32fc86539f081589e58c
[ "MIT" ]
4
2019-12-20T18:21:03.000Z
2020-09-08T05:16:53.000Z
odk/api/inc/odkapi_acquisition_task_xml.h
HpLightcorner/OXYGEN-SDK
4ede0ea07b513032605b32fc86539f081589e58c
[ "MIT" ]
13
2020-07-01T19:35:08.000Z
2022-03-18T13:58:06.000Z
odk/api/inc/odkapi_acquisition_task_xml.h
HpLightcorner/OXYGEN-SDK
4ede0ea07b513032605b32fc86539f081589e58c
[ "MIT" ]
3
2020-07-28T06:50:56.000Z
2022-02-24T10:32:52.000Z
// Copyright DEWETRON GmbH 2019 #pragma once #include "odkapi_timestamp_xml.h" #include "odkuni_defines.h" #include <boost/utility/string_view.hpp> #include <cstdint> #include <string> #include <vector> namespace odk { class AddAcquisitionTaskTelegram { public: AddAcquisitionTaskTelegram() noexcept; bool parse(const boost::string_view& xml_string); ODK_NODISCARD std::string generate() const; std::uint64_t m_id; std::vector<std::uint64_t> m_input_channels; std::vector<std::uint64_t> m_output_channels; }; class AcquisitionTaskProcessTelegram { public: bool parse(const boost::string_view& xml_string); ODK_NODISCARD std::string generate() const; odk::Timestamp m_start; odk::Timestamp m_end; }; }
21.076923
57
0.676399
[ "vector" ]
74d6b58ccfc857a98b551cc598f97f859a7c665d
11,957
h
C
Source/ZipLib/ZipArchiveEntry.h
komiyamma/wbenny-ziplib
e9f347506443ab4fdc7de6a59ddaf98bd714148f
[ "Zlib" ]
245
2018-06-08T16:07:44.000Z
2022-03-31T16:36:50.000Z
Source/ZipLib/ZipArchiveEntry.h
komiyamma/wbenny-ziplib
e9f347506443ab4fdc7de6a59ddaf98bd714148f
[ "Zlib" ]
5
2017-03-04T12:13:54.000Z
2017-03-26T21:55:08.000Z
Source/ZipLib/ZipArchiveEntry.h
komiyamma/wbenny-ziplib
e9f347506443ab4fdc7de6a59ddaf98bd714148f
[ "Zlib" ]
84
2018-05-22T06:00:07.000Z
2022-02-07T09:57:44.000Z
#pragma once #include "detail/ZipLocalFileHeader.h" #include "detail/ZipCentralDirectoryFileHeader.h" #include "methods/ICompressionMethod.h" #include "methods/StoreMethod.h" #include "methods/DeflateMethod.h" #include "methods/LzmaMethod.h" #include "streams/substream.h" #include "utils/enum_utils.h" #include <cstdint> #include <ctime> #include <string> #include <vector> #include <memory> class ZipArchive; /** * \brief Represents a compressed file within a zip archive. */ class ZipArchiveEntry : public std::enable_shared_from_this<ZipArchiveEntry> { friend class ZipFile; friend class ZipArchive; public: typedef std::shared_ptr<ZipArchiveEntry> Ptr; /** * \brief Values that represent the way the zip entry will be compressed. */ enum class CompressionMode { Immediate, Deferred }; /** * \brief Values that represent the MS-DOS file attributes. */ enum class Attributes : uint32_t { None = 0, ReadOnly = 1, Hidden = 2, System = 4, Directory = 16, Archive = 32, Device = 64, Normal = 128, Temporary = 256, SparseFile = 512, ReparsePoint = 1024, Compressed = 2048, }; MARK_AS_TYPED_ENUMFLAGS_FRIEND(Attributes); MARK_AS_TYPED_ENUMFLAGS_FRIEND(CompressionMode); /** * \brief Destructor. */ ~ZipArchiveEntry(); /** * \brief Gets full path of the entry. * * \return The full name with the path. */ const std::string& GetFullName() const; /** * \brief Sets full name with the path of the entry. * * \param fullName The full name with the path. */ void SetFullName(const std::string& fullName); /** * \brief Gets only the file name of the entry (without path). * * \return The file name. */ const std::string& GetName() const; /** * \brief Sets only a file name of the entry. * If the file is located within some folder, the path is kept. * * \param name The file name. */ void SetName(const std::string& name); /** * \brief Gets the comment of this zip entry. * * \return The comment. */ const std::string& GetComment() const; /** * \brief Sets a comment of this zip entry. * * \param comment The comment. */ void SetComment(const std::string& comment); /** * \brief Gets the time the file was last modified. * * \return The last write time. */ time_t GetLastWriteTime() const; /** * \brief Sets the time the file was last modified. * * \param modTime Time of the modifier. */ void SetLastWriteTime(time_t modTime); /** * \brief Gets the file attributes of this zip entry. * * \return The file attributes. */ Attributes GetAttributes() const; /** * \brief Gets the compression method. * * \return The compression method. */ uint16_t GetCompressionMethod() const; /** * \brief Sets the file attributes of this zip entry. * * \param value The file attributes. */ void SetAttributes(Attributes value); /** * \brief Query if this entry is password protected. * * \return true if password protected, false if not. */ bool IsPasswordProtected() const; /** * \brief Gets the password of the zip entry. If the password is empty string, the password is not set. * * \return The password. */ const std::string& GetPassword() const; /** * \brief Sets a password of the zip entry. If the password is empty string, the password is not set. * Use before GetDecompressionStream or SetCompressionStream. * * \param password The password. */ void SetPassword(const std::string& password); /** * \brief Gets CRC 32 of the file. * * \return The CRC 32. */ uint32_t GetCrc32() const; /** * \brief Gets the size of the uncompressed data. * * \return The size. */ size_t GetSize() const; /** * \brief Gets the size of compressed data. * * \return The compressed size. */ size_t GetCompressedSize() const; /** * \brief Determine if we can extract the entry. * It depends on which version was the zip archive created with. * * \return true if we can extract, false if not. */ bool CanExtract() const; /** * \brief Query if this entry is a directory. * * \return true if directory, false if not. */ bool IsDirectory() const; /** * \brief Query if this object is using data descriptor. * Data descriptor is small chunk of information written after the compressed data. * It's most useful when encrypting a zip entry. * When it is not using, the CRC32 value is required before * encryption of the file data begins. In this case there is no way * around it: must read the stream in its entirety to compute the * actual CRC32 before proceeding. * * \return true if using data descriptor, false if not. */ bool IsUsingDataDescriptor() const; /** * \brief Use data descriptor. * Data descriptor is small chunk of information written after the compressed data. * It's most useful when encrypting a zip entry. * When it is not using, the CRC32 value is required before * encryption of the file data begins. In this case there is no way * around it: must read the stream in its entirety to compute the * actual CRC32 before proceeding. * \param use (Optional) If true, use the data descriptor, false to not use. */ void UseDataDescriptor(bool use = true); /** * \brief Sets the input stream to fetch the data to compress from. * * \param stream The input stream to compress. * \param method (Optional) The method of compression. * \param mode (Optional) The mode of compression. * If deferred mode is chosen, the data are compressed when the zip archive is about to be written. * The stream instance must exist when the ZipArchive::WriteToStream method is called. * The advantage of deferred compression mode is the compressed data needs not to be loaded * into the memory, because they are streamed into the final output stream. * * If immediate mode is chosen, the data are compressed immediately into the memory buffer. * It is not recommended to use this method for large files. * The advantage of immediate mode is the input stream can be destroyed (i.e. by scope) * even before the ZipArchive::WriteToStream method is called. * * \return true if it succeeds, false if it fails. */ bool SetCompressionStream(std::istream& stream, ICompressionMethod::Ptr method = DeflateMethod::Create(), CompressionMode mode = CompressionMode::Deferred); /** * \brief Sets compression stream to be null and unsets the password. The entry would contain no data with zero size. */ void UnsetCompressionStream(); /** * \brief Gets raw stream of the compressed data. * * \return null if it fails, else the stream of raw data. */ std::istream* GetRawStream(); /** * \brief Gets decompression stream. * If the file is encrypted and correct password is not provided, it returns nullptr. * * \return null if it fails, else the decompression stream. */ std::istream* GetDecompressionStream(); /** * \brief Query if the GetRawStream method has been already called. * * \return true if the raw stream is opened, false if not. */ bool IsRawStreamOpened() const; /** * \brief Query if the GetDecompressionStream method has been already called. * * \return true if the decompression stream is opened, false if not. */ bool IsDecompressionStreamOpened() const; /** * \brief Closes the raw stream, opened by GetRawStream. */ void CloseRawStream(); /** * \brief Closes the decompression stream, opened by GetDecompressionStream. */ void CloseDecompressionStream(); /** * \brief Removes this entry from the ZipArchive. */ void Remove(); private: static const uint16_t VERSION_MADEBY_DEFAULT = 63; static const uint16_t VERSION_NEEDED_DEFAULT = 10; static const uint16_t VERSION_NEEDED_EXPLICIT_DIRECTORY = 20; static const uint16_t VERSION_NEEDED_ZIP64 = 45; enum class BitFlag : uint16_t { None = 0, Encrypted = 1, DataDescriptor = 8, UnicodeFileName = 0x800 }; MARK_AS_TYPED_ENUMFLAGS_FRIEND(BitFlag); ZipArchiveEntry(); ZipArchiveEntry(const ZipArchiveEntry&); ZipArchiveEntry& operator = (ZipArchiveEntry&); // static methods static ZipArchiveEntry::Ptr CreateNew(ZipArchive* zipArchive, const std::string& fullPath); static ZipArchiveEntry::Ptr CreateExisting(ZipArchive* zipArchive, detail::ZipCentralDirectoryFileHeader& cd); // methods void SetCompressionMethod(uint16_t value); BitFlag GetGeneralPurposeBitFlag() const; void SetGeneralPurposeBitFlag(BitFlag value, bool set = true); uint16_t GetVersionToExtract() const; void SetVersionToExtract(uint16_t value); uint16_t GetVersionMadeBy() const; void SetVersionMadeBy(uint16_t value); int32_t GetOffsetOfLocalHeader() const; void SetOffsetOfLocalHeader(int32_t value); bool HasCompressionStream() const; void FetchLocalFileHeader(); void CheckFilenameCorrection(); void FixVersionToExtractAtLeast(uint16_t value); void SyncLFH_with_CDFH(); void SyncCDFH_with_LFH(); std::ios::pos_type GetOffsetOfCompressedData(); std::ios::pos_type SeekToCompressedData(); void SerializeLocalFileHeader(std::ostream& stream); void SerializeCentralDirectoryFileHeader(std::ostream& stream); void UnloadCompressionData(); void InternalCompressStream(std::istream& inputStream, std::ostream& outputStream); // for encryption void FigureCrc32(); uint8_t GetLastByteOfEncryptionHeader(); ////////////////////////////////////////////////////////////////////////// ZipArchive* _archive; //< pointer to the owning zip archive std::shared_ptr<std::istream> _rawStream; //< stream of raw compressed data std::shared_ptr<std::istream> _compressionStream; //< stream of uncompressed data std::shared_ptr<std::istream> _encryptionStream; //< underlying encryption stream std::shared_ptr<std::istream> _archiveStream; //< substream of owning zip archive file // internal compression data std::shared_ptr<std::iostream> _immediateBuffer; //< stream used in the immediate mode, stores compressed data in memory std::istream* _inputStream; //< input stream ICompressionMethod::Ptr _compressionMethod; //< compression method CompressionMode _compressionMode; //< compression mode, either deferred or immediate std::string _name; // TODO: make as flags bool _originallyInArchive; bool _isNewOrChanged; bool _hasLocalFileHeader; detail::ZipLocalFileHeader _localFileHeader; detail::ZipCentralDirectoryFileHeader _centralDirectoryFileHeader; std::ios::pos_type _offsetOfCompressedData; std::ios::pos_type _offsetOfSerializedLocalFileHeader; std::string _password; };
30.502551
160
0.634356
[ "object", "vector" ]
74dbec5901f713c7fa2dba09d049846fcf905649
3,001
h
C
include/graphics/tcRadioButton.h
dhanin/friendly-bassoon
fafcfd3921805baddc1889dc0ee2fa367ad882f8
[ "BSD-3-Clause" ]
2
2021-11-17T10:59:38.000Z
2021-11-17T10:59:45.000Z
include/graphics/tcRadioButton.h
dhanin/nws
87a3f24a7887d84b9884635064b48d456b4184e2
[ "BSD-3-Clause" ]
null
null
null
include/graphics/tcRadioButton.h
dhanin/nws
87a3f24a7887d84b9884635064b48d456b4184e2
[ "BSD-3-Clause" ]
null
null
null
/** ** @file tcRadioButton.h */ /* ** Copyright (c) 2014, GCBLUE PROJECT ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from ** this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT ** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING ** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _TCRADIOBUTTON_H_ #define _TCRADIOBUTTON_H_ #if _MSC_VER > 1000 #pragma once #endif #include "tc3DWindow2.h" #include <string> class TiXmlNode; class tcButton; /** * Radio button class derived from tc3DWindow2. * XML configuration is required for this control */ class tcRadioButton : public tc3DWindow2 { public: void ActivateButton(long buttonCommand); virtual void Draw(); std::string GetCaption() const {return caption;} long GetCommand() const {return command;} void SetCaption(std::string s) {caption = s;} void SetCommand(long cmd) {command = cmd;} void SetSoundEffect(int effect) {soundEffect = effect;} /// XML configuration required for this control tcRadioButton(tc3DWindow2 *parent, TiXmlNode *config); virtual ~tcRadioButton(); protected: std::vector<tcButton*> buttons; ///< buttons within the radio button control std::string caption; ///< title caption for radio button long command; ///< command for radio button event bool isMouseOver; int soundEffect; float fontSize; static unsigned ref_count; virtual void OnButtonCommand(wxCommandEvent& event); virtual void OnEnterWindow(wxMouseEvent& event); virtual void OnLButtonDown(wxMouseEvent& event); virtual void OnLButtonUp(wxMouseEvent& event); virtual void OnLeaveWindow(wxMouseEvent& event); DECLARE_EVENT_TABLE() }; #endif
37.5125
146
0.751749
[ "vector" ]
74ebdab0c3abe0809ccff6a1f42d2994d58b8c70
3,185
h
C
src/swganh/object/tangible/tangible_binding.h
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
1
2015-03-25T16:02:17.000Z
2015-03-25T16:02:17.000Z
src/swganh/object/tangible/tangible_binding.h
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
src/swganh/object/tangible/tangible_binding.h
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #ifndef SWGANH_OBJECT_TANGIBLE_TANGIBLE_BINDING_H_ #define SWGANH_OBJECT_TANGIBLE_TANGIBLE_BINDING_H_ #include "swganh/object/object_binding.h" #include "swganh/object/tangible/tangible.h" #include <boost/python.hpp> using namespace boost::python; using namespace std; using namespace swganh::object::tangible; void exportTangible() { class_<Tangible, bases<swganh::object::Object>, std::shared_ptr<Tangible>, boost::noncopyable>("Tangible") .add_property("customization", &Tangible::GetCustomization, &Tangible::SetCustomization, "Gets and Sets the tangible customization") //.def("customization.__add__", &Tangible::AddCustomization, "Adds a string to the existing customization") .def("component_customization", &Tangible::GetComponentCustomization, "Gets the current component_customization") .def("add_component_customization", &Tangible::AddComponentCustomization, "Adds a string to the component_customization") .def("remove_component_customization", &Tangible::RemoveComponentCustomization, "Removes the specified component_customization") //.def("component_customization.__add__", &Tangible::AddComponentCustomization, "Adds a crc to the component customization list") //.def("component_customization.__sub__", &Tangible::RemoveComponentCustomization, "Removes crc from the component customization list") .def("clear_component_customization", &Tangible::ClearComponentCustomization, "Clears all crc's from the component customization list") .add_property("options_mask", &Tangible::GetOptionsMask, &Tangible::SetOptionsMask, "Gets and Sets the options mask") .def("toggle_option", &Tangible::ToggleOption, "Toggles the specified option") .add_property("incap_timer", &Tangible::GetIncapTimer, &Tangible::SetIncapTimer, "Gets and Sets the incapacitation timer of the tangible object") .add_property("condition", &Tangible::GetCondition, &Tangible::SetConditionDamage, "Gets and Sets the current condition of the tangible") .add_property("max_condition", &Tangible::GetMaxCondition, &Tangible::SetMaxCondition, "Gets and Sets the max condition of the tangible") .add_property("static", &Tangible::IsStatic, &Tangible::SetStatic, "Gets and Sets the static property") .def("add_defender", &Tangible::AddDefender, "Adds a defender to the list") .def("remove_defender", &Tangible::RemoveDefender, "Removes a defender from the list") .def("defended", &Tangible::IsDefending, "Checks if the object is being defended") .def("reset_defenders", &Tangible::ResetDefenders, "Resets the defenders to the specified tangible") .def("clear_defenders", &Tangible::ClearDefenders, "Clears all defenders from the tangible object") .def("activate_auto_attack", &Tangible::ActivateAutoAttack, "Activates auto attack for the tangible object") .def("clear_auto_attack", &Tangible::ClearAutoAttack, "Clears the auto attack flag") .def("is_auto_attacking", &Tangible::IsAutoAttacking, "returns true if currently auto attacking") ; } #endif // SWGANH_OBJECT_TANGIBLE_TANGIBLE_BINDING_H_
70.777778
147
0.779278
[ "object" ]
74ed98cd8c16000fcee1492fc8a4b421f256a481
1,775
h
C
src/gameManager/GameManager.h
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
src/gameManager/GameManager.h
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
src/gameManager/GameManager.h
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
/**@file Game Manager header*/ #ifndef GAME_MANAGER_H #define GAME_MANAGER_H #include <SFML/Graphics.hpp> #include <SFML/Main.hpp> #include <memory> #include <vector> #include <mutex> #include <thread> #include "Component.h" #include "Observer.h" #include "ThreadContainer.h" #include "../TileMap/TileMap.h" #include "../UI/UI.h" #include "../entities/entities.h" /** @class GameManager @brief manages the game*/ class GameManager : public Observer { public: /**@brief class constructor*/ GameManager(); /**@brief class destructor*/ ~GameManager(); /**@brief initializes the game*/ void init(); /**@brief main loop of the game*/ void mainloop(); /**@brief observer implementation*/ virtual void on_Notify(Component* subject, Event event); /**@brief add a component @param comp pointer to component to add*/ void add_Component(const std::shared_ptr<Component> comp); /**@brief test function*/ void testFunc(); /**@brief */ void setRoverBase(std::string mission); /**@brief */ void addAlienGroup(int alien_number, int alien_average_stats); /**@brief computes and sets an entity's path to a target position @param e pointer to the entity which path needs to be compute and set @param e_target position of the target*/ void compute_and_set_path(Entity* e, sf::Vector2i e_target); private: sf::RenderWindow window; std::vector<std::shared_ptr<Component>> components; std::shared_ptr<TileMap> tm; std::shared_ptr<UI_ProgressBar> pb; std::shared_ptr<UI_TextBox> tb; std::shared_ptr<UI_VisualPath> vp; std::shared_ptr<UI_Point> start; std::shared_ptr<UI_Point> finish; std::vector<std::thread> entities; std::vector<std::shared_ptr<AlienGroup>> ag; std::shared_ptr<RoverBase> rb; std::mutex* m; }; #endif
28.629032
71
0.715493
[ "vector" ]
74f288bf82059041376ad6e8347e94c3c92aee75
892
h
C
src/backend/bridge/ddl/raw_column_info.h
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
6
2017-04-28T00:38:52.000Z
2018-11-06T07:06:49.000Z
src/backend/bridge/ddl/raw_column_info.h
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
4
2017-07-08T00:41:56.000Z
2017-07-08T00:42:13.000Z
src/backend/bridge/ddl/raw_column_info.h
eric-haibin-lin/pelotondb
904d6bbd041a0498ee0e034d4f9f9f27086c3cab
[ "Apache-2.0" ]
1
2020-06-19T08:05:03.000Z
2020-06-19T08:05:03.000Z
#pragma once #include "backend/bridge/ddl/raw_constraint_info.h" #include "backend/catalog/column.h" namespace peloton { namespace bridge { class raw_column_info { public: raw_column_info(ValueType column_type, oid_t column_length, std::string column_name, bool is_inlined, std::vector<raw_constraint_info> raw_constraints) : column_type(column_type), column_length(column_length), column_name(column_name), is_inlined(is_inlined), raw_constraints(raw_constraints) {} catalog::Column CreateColumn(void) const; std::string GetColName() const { return column_name; } private: ValueType column_type; size_t column_length; std::string column_name; bool is_inlined; // Constraint information std::vector<raw_constraint_info> raw_constraints; }; } // namespace bridge } // namespace peloton
22.871795
67
0.715247
[ "vector" ]
74f5d1b8c8c04c67db5a4df719a3be6aebdee7a0
17,953
h
C
source_code/system_fpl/source_code/calculation/section_fpl/Fpl_Sec_Type_Dike.h
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_fpl/source_code/calculation/section_fpl/Fpl_Sec_Type_Dike.h
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_fpl/source_code/calculation/section_fpl/Fpl_Sec_Type_Dike.h
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
#pragma once /**\class Fpl_Sec_Type_Dike \author Daniel Bachmann et al. \author produced by the Institute of Hydraulic Engineering (IWW), RWTH Aachen University \version 0.0.1 \date 2009 */ #ifndef FPL_SEC_TYPE_DIKE_H #define FPL_SEC_TYPE_DIKE_H //system fpl #include "_Fpl_Section_Type.h" #include "Fpl_Cub_Dike_Waterside.h" #include "Fpl_Cub_Dike_Landside.h" #include "Fpl_Cub_Dike_Crest.h" #include "Fpl_Dike_Geo_Foreland.h" #include "Fpl_Dike_Geo_Hinterland.h" #include "Fpl_Mech_Slope_Stability_Dike.h" #include "Fpl_Mech_Wave_Generation.h" #include "Fpl_Mech_Waverunup_Dike.h" #include "Fpl_Mech_Overflow_Dike.h" #include "Fpl_Mech_Bursting_Din_Dike.h" #include "Fpl_Mech_Piping_Sell_Dike.h" #include "Fpl_Mech_Piping_Lane_Dike.h" #include "Fpl_Mech_Piping_Schmertmann_Dike.h" #include "Fpl_Mech_Landside_Erosion.h" #include "Fpl_Mech_Wave_Impact_Waterside_Dike.h" #include "Fpl_Mech_Waterside_Erosion.h" #include "Fpl_Mech_Waterside_Erosion_Start.h" #include "Fpl_Cub_Waterside_Materialzone.h" #include "Fpl_Seepage_Line_Point_List.h" #include "Fpl_Seepage_Calculator_Dike.h" ///Class for the section type of the flood-protection line as dike \ingroup fpl /** */ class Fpl_Sec_Type_Dike : public _Fpl_Section_Type { public: ///Default constructor Fpl_Sec_Type_Dike(void); ///Default destructor ~Fpl_Sec_Type_Dike(void); //members ///Pointer to the table for storing the results of the mechanism of the dike section static Tables *result_table; //method ///Set the input of the dune section (geometrie, variables, faulttree) per database void set_input(const int section_id, const bool frc_sim, QSqlDatabase *ptr_database); ///Read in the fpl-section type from file void read_section_type_per_file(QFile *ifile, int *line_counter, const bool frc_sim); ///Read the mechanisms of the fault-tree per file void read_mechanism_faulttree_perfile(QFile *ifile, int *line_counter); ///Check which mechanisms of the fault-tree are required per file void check_mechanism_faulttree_perfile(QFile *ifile, int *line_counter); ///Read the waterside geometry of the section per file void read_waterside_geometry(QFile *ifile, int *line_counter); ///Read the landside geometry of the section per file void read_landside_geometry(QFile *ifile, int *line_counter); ///Read the geometrical material zone(s) of the section per file void read_geo_matzones(QFile *ifile, int *line_counter); ///Read the material variable zone(s) of the section per file void read_var_matzones(QFile *ifile, int *line_counter); ///Read the waterside material variable zone(s) of the section per file void read_var_waterside_matzones(QFile *ifile, int *line_counter); ///Transfer the section type data to database, e.g. geometry, random variables etc. void transfer_sectiontype2database(const int section_id, QSqlDatabase *ptr_database); ///Calculate the fault tree with random distributed variables (true) or with deterministic variables (false) int make_faulttree(const bool random_calculation=false); ///Check the statistics of the random variables used in the section type void check_statistic(void); ///Output the statistics of the random variables used in the section type to display/console void output_statistic(void); ///Reset the statistic important values void reset_statistics(void); ///Output the section members to display/console void output_member(void); ///Output the reliability of the fault tree mechanisms for a deterministic calculation to display/console void output_reliability(string output_folder, const int sec_id, const string sec_name); ///Output the geometry to tecplot void output_geometry2tecplot(ofstream *output); ///Output the geometry to paraview void output_geometry2paraview(ofstream *output); ///Output the geometry to excel void output_geometry2excel(ofstream *output); ///Output result members of the mechanisms to database table void output_result2table(QSqlDatabase *ptr_database, _fpl_simulation_type simulation_type, _sys_system_id id, const int section_id, const int counter_mc_sim); ///Output the deterministic results to tecplot void output_determ_res2tecplot(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the deterministic results to Paraview void output_determ_res2paraview(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the deterministic results to Excel void output_determ_res2excel(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the MC results to tecplot void output_mc_res2tecplot(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the MC results to Paraview void output_mc_res2paraview(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the MC results to Excel void output_mc_res2excel(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the FRC results to tecplot void output_frc_res2tecplot(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the FRC results to Paraview void output_frc_res2paraview(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Output the FRC results to Excel void output_frc_res2excel(ofstream *output, QSqlDatabase *ptr_database, _sys_system_id id, const int section_id); ///Create the database table for the results of the mechanism of the dike section static void create_result_table(QSqlDatabase *ptr_database); ///Delete all data in the database table for the results of the mechanism of the dike section static void delete_data_in_result_table(QSqlDatabase *ptr_database); ///Delete a data set in the database table for the results of the mechanism of the dike section for a specific system state static void delete_data_in_result_table(QSqlDatabase *ptr_database, const _sys_system_id id); ///Delete a data set in the database table for the results of the mechanism of the dike section static void delete_data_in_result_table(QSqlDatabase *ptr_database, const int section_id, const _sys_system_id id, const _fpl_simulation_type sim_type); ///Set the database table for the results of the mechanism of the dike section : it sets the table name and the name of the columns and allocate them static void set_result_table(QSqlDatabase *ptr_database, const bool not_close=false); ///Select results of given fpl section in a database table static int select_results_in_database(QSqlQueryModel *results, QSqlDatabase *ptr_database, const _sys_system_id id, const int sec_id, const _fpl_simulation_type sim_type); ///Close and delete the database table for the results of the mechanism of the dike section static void close_result_table(void); ///Switch the applied-flag for the results of the mechanism of the dike section in the database table for a defined system state static void switch_applied_flag_result_table(QSqlDatabase *ptr_database, const _sys_system_id id, const bool flag); ///Switch the applied-flag for the results of the mechanism of the dike section in the database table for a defined system state and id static void switch_applied_flag_result_table(QSqlDatabase *ptr_database, const _sys_system_id id, const bool flag, const int sec_id); ///Check and set the section geometry out of the read in geometry members void check_set_geometry(void); private: //members ///Pointer to wave generation mechanism induced by wind for a dike section Fpl_Mech_Wave_Generation *wave_wind_event; ///Pointer to wave forced runup by wind for a dike section after Eurotop-manual (2007) Fpl_Mech_Wave_Runup *wave_runup_event; ///Pointer to an overflow event for a dike section after modified Poleni-formula Fpl_Mech_Overflow_Dike *overflow_event; ///Pointer to an bursting event for a dike section after DIN19712 Fpl_Mech_Bursting_Din_Dike *bursting_din_event; ///Pointer to an piping event for a dike section after Sellmeijer Fpl_Mech_Piping_Sell_Dike *piping_sell_event; ///Pointer to an piping event for a dike section after Lane Fpl_Mech_Piping_Lane_Dike *piping_lane_event; ///Pointer to an piping event for a dike section after Schmertmann Fpl_Mech_Piping_Schmertmann_Dike *piping_schmertmann_event; ///Pointer to an slope stability event for landside of a dike section after Krey Fpl_Mech_Slope_Stability_Dike *slope_stability_landside_event; ///Pointer to an slope stability event for waterside of a dike section after Krey Fpl_Mech_Slope_Stability_Dike *slope_stability_waterside_event; ///Pointer to an erosion event for landside of a dike section Fpl_Mech_Landside_Erosion *erosion_landside_event; ///Pointer to an erosion event for waterside of a dike section Fpl_Mech_Waterside_Erosion *erosion_waterside_event; ///Pointer to an start erosion event for waterside of a dike section Fpl_Mech_Waterside_Erosion_Start *erosion_waterside_start_event; ///Pointer to an wave pressure impact event for the waterside of a dike section Fpl_Mech_Wave_Impact_Waterside_Dike *wave_impact_event; ///Base point of the landside of the dike section Fpl_Section_Points base_land; ///Crest point of the landside of the dike section Fpl_Section_Points crest_land; ///The cubature of the waterside of the dike section Fpl_Cub_Dike_Waterside waterside_cubature; ///The cubature of the crest of the dike section Fpl_Cub_Dike_Crest crest_cubature; ///The cubature of the landside of the dike Fpl_Cub_Dike_Landside landside_cubature; ///The foreland geometrie of the dike Fpl_Dike_Geo_Foreland foreland; ///The hinterland geometrie of the dike Fpl_Dike_Geo_Hinterland hinterland; ///Number of geometrical material zone of the dike int number_material_zones; ///Geometrical material zones of the dike Fpl_Dike_Geo_Materialzone *material_zones; ///Number of material variable zone of the dike int number_material_variable_zones; ///Material variable zones of the dike Fpl_Dike_Var_Materialzone *material_variable_zones; ///Number of material waterside zone int number_mat_waterside_zones; ///Waterside material zone Fpl_Cub_Waterside_Materialzone *material_waterside_zone; ///Polygon of the outer boundary of the dike (cubature, foreland, hinterland) Geo_Simple_Polygon outer_polygon; ///Polysegment of the outer boundary of the dike (cubature, foreland, hinterland) Geo_Polysegment outer_polysegment; ///Seepage point list for the dike body ascending water Fpl_Seepage_Line_Point_List seepage_body_ascending; ///Seepage point list for the dike body descending water Fpl_Seepage_Line_Point_List seepage_body_descending; ///Calculator class for the seepage claculation Fpl_Seepage_Calculator_Dike seepage_calculator; ///Area of the section cuabture double area_cubature; ///Random variable of the water density Fpl_Random_Variables water_density; ///The current waterlevel for calculation double current_waterlevel; ///Index of the waterlevel at the impermeable layer begin int index_h_imperm_layer; //methods ///Allocate the mechanism for wave generation induced by wind void allocate_wind_wave_mechanism(void); ///Delete the mechanism for wave generation induced by wind void delete_wind_wave_mechanism(void); ///Allocate the mechanism for wave forced runup after Eurotop-manual (2007) void allocate_wave_runup_mechanism(void); ///Delete the mechanism for wave forced runup after Eurotop-manual (2007) void delete_wave_runup_mechanism(void); ///Allocate the mechanism for an overflow after modified Poleni-formula void allocate_overflow_mechanism(void); ///Delete the mechanism for an overflow after modified Poleni-formula void delete_overflow_mechanism(void); ///Allocate the mechanism for bursting after DIN19712 void allocate_bursting_din_mechanism(void); ///Delete the mechanism for bursting after DIN19712 void delete_bursting_din_mechanism(void); ///Allocate the mechanism for piping after Sellmeijer void allocate_piping_sell_mechanism(void); ///Delete the mechanism for piping after Sellmeijer void delete_piping_sell_mechanism(void); ///Allocate the mechanism for piping after Lane void allocate_piping_lane_mechanism(void); ///Delete the mechanism for piping after Lane void delete_piping_lane_mechanism(void); ///Allocate the mechanism for piping after Schmertmann void allocate_piping_schmertmann_mechanism(void); ///Delete the mechanism for piping after Schmertmann void delete_piping_schmertmann_mechanism(void); ///Allocate the mechanism for slope stability landside of the section after Krey void allocate_slope_stability_landside_mechanism(void); ///Delete the mechanism for slope stability landside of the section after Krey void delete_slope_stability_landside_mechanism(void); ///Allocate the mechanism for slope stability waterside of the section after Krey void allocate_slope_stability_waterside_mechanism(void); ///Delete the mechanism for slope stability waterside of the section after Krey void delete_slope_stability_waterside_mechanism(void); ///Allocate the mechanism for erosion landside of the section void allocate_erosion_landside_mechanism(void); ///Delete the mechanism for erosion landside of the section void delete_erosion_landside_mechanism(void); ///Allocate the mechanism for erosion waterside of the section void allocate_erosion_waterside_mechanism(void); ///Delete the mechanism for erosion waterside of the section void delete_erosion_waterside_mechanism(void); ///Allocate the mechanism for start the erosion waterside of the section void allocate_start_erosion_waterside_mechanism(void); ///Delete the mechanism for start the erosion waterside of the section void delete_start_erosion_waterside_mechanism(void); ///Allocate the mechanism of wave pressure impact on the waterside of the section void allocate_wave_impact_mechanism(void); ///Delete the mechanism of wave pressure impact on the waterside of the section void delete_wave_impact_mechanism(void); ///Allocate the geometrical material zones of the dike void allocate_material_zones(void); ///Delete the geometrical material zones of the dike void delete_material_zones(void); ///Allocate the material variable zone void allocate_material_variable_zone(void); ///Delete the material variable zone void delete_material_variable_zone(void); ///Allocate the waterside material variable zone void allocate_waterside_variable_zone(void); ///Delete the waterside material variable zone void delete_waterside_variable_zone(void); ///Set the general parameters of the section to the mechanisms void set_general(void); ///Set the random variables of this section and the relevant mechanisms from database table void set_variables(const bool frc_sim, QSqlDatabase *ptr_database, const int section_id); ///Set the geometry of the section and their surrounding via a database table void set_geometrie(QSqlDatabase *ptr_database, const int section_id); ///Set control parameters of the mechanisms void set_control_parameter_mechanism(QSqlDatabase *ptr_database, const int section_id, const bool frc_sim); ///Initialize the mechanisms void init_mechanism(const int section_id); ///Set the fault tree for this section type via a database table void init_fault_tree(QSqlDatabase *ptr_database); ///Decide and allocate the mechanism, which should by applied during calculation void decide_mechanism(const string mechanism_name, const bool application_flag, const bool applied_in_tree); ///Set the dike geometry via database and set it to the relevant mechanisms void read_cubature(QSqlDatabase *ptr_database, const int section_id); ///Set the dike material zones via database void read_matzones(QSqlDatabase *ptr_database, const int section_id); ///Set the dike material variable zones via database void read_mat_variable_zones(QSqlDatabase *ptr_database, const int section_id); ///Connect the material zones to the material variable zone void connect_material_zones(void); ///Set the dike material variable zones of the waterside via database void read_mat_variable_zones_waterside(QSqlDatabase *ptr_database, const int section_id); ///Connect the material zones to the material variable zone of the waterside void connect_material_zones_waterside(void); ///Create the geometrical outer boundary of the dike as polysegment void make_geometrical_outer_dike_polysegment(void); ///Create the geometrical outer boundary of the dike as polygon void make_geometrical_outer_dike_polygon(void); ///Calcualte the area of the cubature void calc_area_cubature(void); ///Check the initialized fault-tree void check_fault_tree(void); ///Check the gradient of a dike for their physical sense void check_dike_gradients(const double grad, const bool waterside); ///Reset the flags for the random generation void reset_random_flag(void); ///Calculate new waterlevels of the seepage line void calculate_waterlevel_seepage_line(const double water_level, Fpl_Seepage_Line_Point_List *ascending, Fpl_Seepage_Line_Point_List *descending); ///Output the seepage line to tecplot void output_seepage2tecplot(const string seepage_file); ///Output the seepage line to paraview void output_seepage2paraview(const string seepage_file); ///Output the seepage line to excel void output_seepage2excel(const string seepage_file); ///Get a pointer to a material variable zone Fpl_Dike_Var_Materialzone* get_ptr_specified_material_variable_zone(_fpl_zone_type specifier); ///Count the number of grass cover zones and artificial revetments of the waterside void count_waterside_zones(int *no_artif, int *no_grass); ///Set error(s) Error set_error(const int err_type); ///Set warning(s) Warning set_warning(const int warn_type); }; #endif
46.874674
175
0.808277
[ "geometry" ]
d345a195b51843088a35568b35ed2f46906e63e9
5,522
h
C
art/Framework/Principal/Worker.h
gaponenko/art
63bae591711903fdc611a8ecbd4bfa54347c711a
[ "BSD-3-Clause" ]
null
null
null
art/Framework/Principal/Worker.h
gaponenko/art
63bae591711903fdc611a8ecbd4bfa54347c711a
[ "BSD-3-Clause" ]
16
2021-11-05T14:29:41.000Z
2022-03-24T15:43:39.000Z
art/Framework/Principal/Worker.h
gaponenko/art
63bae591711903fdc611a8ecbd4bfa54347c711a
[ "BSD-3-Clause" ]
1
2022-01-19T20:13:53.000Z
2022-01-19T20:13:53.000Z
#ifndef art_Framework_Principal_Worker_h #define art_Framework_Principal_Worker_h // vim: set sw=2 expandtab : // ====================================================================== // Worker: this is a basic scheduling unit - an abstract base class to // something that is really a producer or filter. // // A worker will not actually call through to the module unless it is // in a Ready state. After a module is actually run, the state will // not be Ready. The Ready state can only be reestablished by doing a // reset(). // // Pre/post module signals are posted only in the Ready state. // // Execution statistics are kept here. // // If a module has thrown an exception during execution, that // exception will be rethrown if the worker is entered again and the // state is not Ready. In other words, execution results (status) are // cached and reused until the worker is reset(). // ====================================================================== #include "art/Framework/Principal/fwd.h" #include "art/Persistency/Provenance/ModuleDescription.h" #include "art/Utilities/ScheduleID.h" #include "art/Utilities/Transition.h" #include "hep_concurrency/WaitingTaskList.h" #include <atomic> #include <exception> #include <string> #include <vector> namespace hep::concurrency { class SerialTaskQueueChain; } namespace art { class ActivityRegistry; class ModuleContext; class FileBlock; class RunPrincipal; class SubRunPrincipal; class EventPrincipal; namespace detail { class SharedResources; } class Worker { friend class RunWorkerFunctor; public: enum State { Ready, Pass, Fail, Working, ExceptionThrown }; virtual ~Worker() = default; Worker(ModuleDescription const&, WorkerParams const&); void beginJob(detail::SharedResources const&); void endJob(); void respondToOpenInputFile(FileBlock const& fb); void respondToCloseInputFile(FileBlock const& fb); void respondToOpenOutputFiles(FileBlock const& fb); void respondToCloseOutputFiles(FileBlock const& fb); bool doWork(Transition, Principal&, ModuleContext const&); void doWork_event(hep::concurrency::WaitingTaskPtr workerInPathDoneTask, EventPrincipal&, ModuleContext const&); // This is used only to do trigger results insertion. void doWork_event(EventPrincipal&, ModuleContext const&); ScheduleID scheduleID() const { return scheduleID_; } ModuleDescription const& description() const; std::string const& label() const; // Used only by WorkerInPath. bool returnCode() const; hep::concurrency::SerialTaskQueueChain* serialTaskQueueChain() const; // Used by EventProcessor // Used by Schedule // Used by EndPathExecutor void reset(); // Used only by writeSummary std::size_t timesVisited() const; std::size_t timesRun() const; std::size_t timesPassed() const; std::size_t timesFailed() const; std::size_t timesExcept() const; void runWorker(EventPrincipal&, ModuleContext const&); protected: virtual std::string workerType() const = 0; virtual hep::concurrency::SerialTaskQueueChain* implSerialTaskQueueChain() const = 0; virtual void implBeginJob(detail::SharedResources const& resources) = 0; virtual void implEndJob() = 0; virtual bool implDoBegin(RunPrincipal& rp, ModuleContext const& mc) = 0; virtual bool implDoEnd(RunPrincipal& rp, ModuleContext const& mc) = 0; virtual bool implDoBegin(SubRunPrincipal& srp, ModuleContext const& mc) = 0; virtual bool implDoEnd(SubRunPrincipal& srp, ModuleContext const& mc) = 0; virtual bool implDoProcess(EventPrincipal&, ModuleContext const&) = 0; private: // API implementation classes must use to provide their API to us virtual void implRespondToOpenInputFile(FileBlock const& fb) = 0; virtual void implRespondToCloseInputFile(FileBlock const& fb) = 0; virtual void implRespondToOpenOutputFiles(FileBlock const& fb) = 0; virtual void implRespondToCloseOutputFiles(FileBlock const& fb) = 0; ScheduleID const scheduleID_; ModuleDescription const md_; ActionTable const& actions_; ActivityRegistry const& actReg_; std::atomic<int> state_{Ready}; // if state is 'exception' // Note: threading: There is no accessor for this data, the only // way it is ever used is from the doWork* functions. Right now // event processing only sets it, but run and subrun processing // reads it. It is not clear that event processing needs this // anymore, and if we go to multiple runs and subruns in flight, // they may not need it anymore as well. For now, leave this, is // not thread safe. std::exception_ptr cached_exception_{}; std::atomic<bool> workStarted_{false}; std::atomic<bool> returnCode_{false}; // Holds the waiting workerInPathDone tasks. Note: For shared // modules the workers are shared. For replicated modules each // schedule has its own private worker copies (the whole reason // schedules exist!). hep::concurrency::WaitingTaskList waitingTasks_; protected: std::atomic<std::size_t> counts_visited_{}; std::atomic<std::size_t> counts_run_{}; std::atomic<std::size_t> counts_passed_{}; std::atomic<std::size_t> counts_failed_{}; std::atomic<std::size_t> counts_thrown_{}; }; } // namespace art #endif /* art_Framework_Principal_Worker_h */ // Local Variables: // mode: c++ // End:
34.5125
80
0.698841
[ "vector" ]
d34dc0f06893f74961f8851ecf42d741858fd8e1
14,212
c
C
filesys/miniFilter/NameChanger/ncinit.c
Microsoft/Windows-driver-samples
407a607d50801cd4e49bd383996c63cfc232b9c0
[ "MS-PL" ]
3,084
2015-03-18T04:40:32.000Z
2019-05-06T17:14:33.000Z
filesys/miniFilter/NameChanger/ncinit.c
Microsoft/Windows-driver-samples
407a607d50801cd4e49bd383996c63cfc232b9c0
[ "MS-PL" ]
275
2015-03-19T18:44:41.000Z
2019-05-06T14:13:26.000Z
filesys/miniFilter/NameChanger/ncinit.c
Microsoft/Windows-driver-samples
407a607d50801cd4e49bd383996c63cfc232b9c0
[ "MS-PL" ]
3,091
2015-03-19T00:08:54.000Z
2019-05-06T16:42:01.000Z
#include "nc.h" _At_(OutputString->Buffer, _Post_notnull_) NTSTATUS NcLoadRegistryString ( _In_ HANDLE Key, _In_ PCWSTR valueName, _Out_ PUNICODE_STRING OutputString ); BOOLEAN NcIs8DOT3Compatible ( _In_ PUNICODE_STRING TestName, _In_opt_ PUNICODE_STRING LongName ); #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, NcInitializeMapping) #pragma alloc_text(INIT, NcLoadRegistryString) #pragma alloc_text(INIT, NcIs8DOT3Compatible) #endif // The #pragma is a notation to the static code analyzer that the Buffer // returned from the function will always be properly initialized. // The multiple allocations/frees of the buffers causes it to lose track. #pragma warning(push) #pragma warning(disable:6001) _At_(OutputString->Buffer, _Post_notnull_) NTSTATUS NcLoadRegistryString ( _In_ HANDLE Key, _In_ PCWSTR valueName, _Out_ PUNICODE_STRING OutputString ) { #pragma warning(pop) PKEY_VALUE_PARTIAL_INFORMATION TempMappingBuffer = NULL; ULONG TempMappingKeyLength = 0; UNICODE_STRING ValueString; PWCHAR OutputStringBuffer = NULL; NTSTATUS Status; PAGED_CODE(); // // Query the length of the registry value. // RtlInitUnicodeString( &ValueString, valueName ); NcLoadRegistryStringRetry: Status = ZwQueryValueKey( Key, &ValueString, KeyValuePartialInformation, NULL, 0, &TempMappingKeyLength ); // // If we could not successfully locate the value, return the // error to our caller. // if (Status != STATUS_BUFFER_TOO_SMALL && Status != STATUS_BUFFER_OVERFLOW) { goto NcLoadRegistryStringCleanup; } // // Allocate a buffer large enough to hold the string. // if (TempMappingBuffer != NULL) { ExFreePoolWithTag( TempMappingBuffer, NC_TAG ); } TempMappingBuffer = ExAllocatePoolZero( PagedPool, TempMappingKeyLength, NC_TAG ); if (TempMappingBuffer == NULL) { Status = STATUS_INSUFFICIENT_RESOURCES; goto NcLoadRegistryStringCleanup; } // // Now attempt to read the string. // Status = ZwQueryValueKey( Key, &ValueString, KeyValuePartialInformation, TempMappingBuffer, TempMappingKeyLength, &TempMappingKeyLength ); // // If the value is changing underneath us, the length we // collected above may be stale. Loop back, reallocate // and try again. // if (Status == STATUS_BUFFER_TOO_SMALL || Status == STATUS_BUFFER_OVERFLOW) { goto NcLoadRegistryStringRetry; } if (!NT_SUCCESS( Status )) { goto NcLoadRegistryStringCleanup; } // // If we're reading a string, it had better: // 1. Be a string. // 2. Fit in a UNICODE_STRING. // 3. Have some characters in it (we never need empty strings in this filter.) // if (TempMappingBuffer->Type != REG_SZ || TempMappingBuffer->DataLength >= MAXUSHORT || TempMappingBuffer->DataLength <= sizeof(WCHAR)) { Status = STATUS_INVALID_PARAMETER; goto NcLoadRegistryStringCleanup; } // // Allocate a buffer for the target string. Note that we // allocate one fewer WCHAR, as we have no need for the // NULL terminator in our UNICODE_STRING. // OutputStringBuffer = ExAllocatePoolZero( NonPagedPool, TempMappingBuffer->DataLength - sizeof(WCHAR), NC_TAG ); if (OutputStringBuffer == NULL) { Status = STATUS_INSUFFICIENT_RESOURCES; goto NcLoadRegistryStringCleanup; } // // We only modify the output string on success. On failure, it is // left with previous values. // Status = STATUS_SUCCESS; OutputString->MaximumLength = (USHORT)TempMappingBuffer->DataLength - sizeof(WCHAR); OutputString->Buffer = OutputStringBuffer; RtlCopyMemory( OutputStringBuffer, TempMappingBuffer->Data, OutputString->MaximumLength ); OutputString->Length = OutputString->MaximumLength; // // This buffer is in use and should not be cleaned up. // OutputStringBuffer = NULL; NcLoadRegistryStringCleanup: if (TempMappingBuffer != NULL) { ExFreePoolWithTag( TempMappingBuffer, NC_TAG ); } if (OutputStringBuffer != NULL) { ExFreePoolWithTag( OutputStringBuffer, NC_TAG ); } return Status; } BOOLEAN NcIs8DOT3Compatible ( _In_ PUNICODE_STRING TestName, _In_opt_ PUNICODE_STRING LongName ) { BOOLEAN SpacesPresent; USHORT Index; PAGED_CODE(); // // When the user supplies a shortname, we expect it to be a valid // shortname. This function will check the name's length. // if (!RtlIsNameLegalDOS8Dot3( TestName, NULL, &SpacesPresent )) { return FALSE; } // // Our shortnames should not have spaces. // if (SpacesPresent) { return FALSE; } // // In this sample, we enforce that the shortname must NOT contain // a tilde (~). // // If the shortname could contain a tilde, the filesystem would // be able to autogenerate a conflicting shortname in response to // an operation on a long name. We could only detect this // afterwards (in a post-operation callback), but we may not be // able to handle the condition correctly. Explicitly changing // a shortname requires NTFS and restore privilege. Rather than // attempt to obtain this functionality via creative mechanism, // this filter simply prevents a shortname which could create // this condition. // // Note that in a product it may be advantageous to create both // sides of the mapping on disk. Part of this sample is to // illustrate the emulation of an object which does not exist, // so we did not do this here. // // We enforce: // 1. The name must not have a tilde (for the above reasons); // 2. The name must not contain a path seperator; // 3. The name must be fully uppercase to be a valid DOS name // for (Index = 0; Index < TestName->Length/sizeof(WCHAR); Index++) { if (TestName->Buffer[Index] == L'~' || TestName->Buffer[Index] == L'\\' || TestName->Buffer[Index] != RtlUpcaseUnicodeChar( TestName->Buffer[Index] )) { return FALSE; } } // // We're done validating the short name. Now we must check the // long and short names for consistency. If we have no long name, // we're done. // if (!ARGUMENT_PRESENT( LongName )) { return TRUE; } // // Check if the long name is a valid shortname. We recurse into // ourselves for this. Note that since we're not specifying a // long name, the recursion is bounded. // if (NcIs8DOT3Compatible( LongName, NULL )) { // // If both our long and short paths are compliant, they had // better be the same. // if (!RtlEqualUnicodeString( TestName, LongName, FALSE )) { return FALSE; } } return TRUE; } NTSTATUS NcInitializeMapping( _In_ PUNICODE_STRING RegistryPath ) /*++ Routine Descrition: This routine initializes the mapping structure. It will try to populate it from the registry, and if that fails use a default string. Arguments: RegistryPath - The path key passed to the driver during DriverEntry. Return Value: None. --*/ { NTSTATUS Status; OBJECT_ATTRIBUTES Attributes; HANDLE DriverRegKey = NULL; UNICODE_STRING TempPath = EMPTY_UNICODE_STRING; USHORT Index; PAGED_CODE(); RtlZeroMemory( &NcGlobalData, sizeof( NcGlobalData )); // // Open the mapping registry key. // InitializeObjectAttributes( &Attributes, RegistryPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL ); Status = ZwOpenKey( &DriverRegKey, KEY_READ, &Attributes ); if (!NT_SUCCESS( Status )) { FLT_ASSERT( DriverRegKey == NULL ); goto NcInitializeMappingCleanup; } Status = NcLoadRegistryString( DriverRegKey, L"UserMapping", &TempPath ); if (!NT_SUCCESS( Status )) { goto NcInitializeMappingCleanup; } // // We check that the name does not contain two // contiguous slashes. This implies an empty // name component, which we make no attempt to // handle. // for (Index = 1; Index < TempPath.Length/sizeof(WCHAR); Index++) { if (TempPath.Buffer[Index] == L'\\' && TempPath.Buffer[Index - 1] == L'\\') { Status = STATUS_INVALID_PARAMETER; goto NcInitializeMappingCleanup; } } Status = NcParseFinalComponent( &TempPath, &NcGlobalData.UserMappingPath, &NcGlobalData.UserMappingFinalComponentLong ); if (!NT_SUCCESS( Status )) { goto NcInitializeMappingCleanup; } NcFreeUnicodeString( &TempPath ); Status = NcLoadRegistryString( DriverRegKey, L"UserMappingFinalComponentShort", &NcGlobalData.UserMappingFinalComponentShort ); if (!NT_SUCCESS( Status )) { goto NcInitializeMappingCleanup; } Status = NcLoadRegistryString( DriverRegKey, L"RealMapping", &TempPath ); if (!NT_SUCCESS( Status )) { goto NcInitializeMappingCleanup; } // // We check that the name does not contain two // contiguous slashes. This implies an empty // name component, which we make no attempt to // handle. // for (Index = 1; Index < TempPath.Length/sizeof(WCHAR); Index++) { if (TempPath.Buffer[Index] == L'\\' && TempPath.Buffer[Index - 1] == L'\\') { Status = STATUS_INVALID_PARAMETER; goto NcInitializeMappingCleanup; } } Status = NcParseFinalComponent( &TempPath, &NcGlobalData.RealMappingPath, &NcGlobalData.RealMappingFinalComponent ); if (!NT_SUCCESS( Status )) { goto NcInitializeMappingCleanup; } // // We expect out parent mappings to start with '\', and we expect // no final component to start with '\'. We have already checked // that the strings contain one WCHAR, but we require two for the // parent mappings, since the first one is '\'. // if (NcGlobalData.RealMappingPath.Length < (2 * sizeof(WCHAR)) || NcGlobalData.UserMappingPath.Length < (2 * sizeof(WCHAR)) || NcGlobalData.RealMappingPath.Buffer[0] != L'\\' || NcGlobalData.UserMappingPath.Buffer[0] != L'\\' || NcGlobalData.UserMappingFinalComponentShort.Buffer[0] == L'\\' || NcGlobalData.UserMappingFinalComponentLong.Buffer[0] == L'\\' || NcGlobalData.RealMappingFinalComponent.Buffer[0] == L'\\') { Status = STATUS_INVALID_PARAMETER; goto NcInitializeMappingCleanup; } if (!NcIs8DOT3Compatible( &NcGlobalData.UserMappingFinalComponentShort, &NcGlobalData.UserMappingFinalComponentLong )) { Status = STATUS_INVALID_PARAMETER; goto NcInitializeMappingCleanup; } // // TODO: This sample assumes that the real mapping final component // is short. This should not be a required assumption. Note that // since we only have one component for the real mapping (long and // short), we don't need to check the long name for compatibility // with the short name. // if (!NcIs8DOT3Compatible( &NcGlobalData.RealMappingFinalComponent, NULL )) { Status = STATUS_INVALID_PARAMETER; goto NcInitializeMappingCleanup; } NcInitializeMappingCleanup: if (!NT_SUCCESS( Status )) { if (NcGlobalData.UserMappingPath.Buffer != NULL) { NcFreeUnicodeString( &NcGlobalData.UserMappingPath ); } if (NcGlobalData.UserMappingFinalComponentShort.Buffer != NULL) { NcFreeUnicodeString( &NcGlobalData.UserMappingFinalComponentShort ); } if (NcGlobalData.UserMappingFinalComponentLong.Buffer != NULL) { NcFreeUnicodeString( &NcGlobalData.UserMappingFinalComponentLong ); } if (NcGlobalData.RealMappingPath.Buffer != NULL) { NcFreeUnicodeString( &NcGlobalData.RealMappingPath ); } if (NcGlobalData.RealMappingFinalComponent.Buffer != NULL) { NcFreeUnicodeString( &NcGlobalData.RealMappingFinalComponent ); } } if (TempPath.Buffer != NULL) { NcFreeUnicodeString( &TempPath ); } if (DriverRegKey != NULL) { NTSTATUS BogusStatus; BogusStatus = ZwClose( DriverRegKey ); FLT_ASSERT(NT_SUCCESS( BogusStatus )); } return Status; }
28.886179
95
0.582395
[ "object" ]
d34dc502a1ea15d4d7ac0d0329a01bee85d71d4c
38,608
h
C
Fastor/expressions/linalg_ops/unary_lu_op.h
mablanchard/Fastor
f5ca2f608bdfee34833d5008a93a3f82ce42ddef
[ "MIT" ]
424
2017-05-15T14:34:30.000Z
2022-03-29T08:58:22.000Z
Fastor/expressions/linalg_ops/unary_lu_op.h
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
150
2016-12-23T10:08:12.000Z
2022-01-16T03:53:45.000Z
Fastor/expressions/linalg_ops/unary_lu_op.h
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
43
2017-09-20T19:47:24.000Z
2022-02-22T21:12:49.000Z
#ifndef UNARY_LU_OP_H #define UNARY_LU_OP_H #include "Fastor/meta/meta.h" #include "Fastor/backend/inner.h" #include "Fastor/backend/lufact.h" #include "Fastor/simd_vector/SIMDVector.h" #include "Fastor/tensor/AbstractTensor.h" #include "Fastor/tensor/Aliasing.h" #include "Fastor/tensor/Tensor.h" #include "Fastor/tensor/Ranges.h" #include "Fastor/tensor/TensorTraits.h" #include "Fastor/expressions/expression_traits.h" #include "Fastor/expressions/linalg_ops/linalg_computation_types.h" #include "Fastor/expressions/linalg_ops/unary_piv_op.h" namespace Fastor { namespace internal { /* Compile time recursive loop with inner for forward substitution of b/B given the lower unitriangular matrix L. The following meta functions implements L * y = b for single or multiple right sides */ //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// template <size_t from, size_t to> struct forward_subs_impl { template<typename T, size_t M> static FASTOR_INLINE void do_single_rhs(const Tensor<T,M,M> &L, const Tensor<T,M> &b, Tensor<T,M> &y) { y(from) = b(from) - _inner<T,from>(&L.data()[from*M],y.data()); forward_subs_impl<from+1,to>::do_single_rhs(L, b, y); } template<typename T, size_t M> static FASTOR_INLINE void do_single_rhs_pivot(const Tensor<T,M,M> &L, const Tensor<T,M> &b, const Tensor<size_t,M> &p, Tensor<T,M> &y) { y(from) = b(p(from)) - _inner<T,from>(&L.data()[from*M],y.data()); forward_subs_impl<from+1,to>::do_single_rhs_pivot(L, b, p, y); } template<typename T, size_t M, size_t N> static FASTOR_INLINE void do_multi_rhs(const size_t j, const Tensor<T,M,M> &L, const Tensor<T,M,N> &B, Tensor<T,M> &y, Tensor<T,M,N> &X) { y(from) = B(from,j) - _inner<T,from>(&L.data()[from*M],y.data()); X(from,j) = y(from); forward_subs_impl<from+1,to>::do_multi_rhs(j, L, B, y, X); } template<typename T, size_t M, size_t N> static FASTOR_INLINE void do_multi_rhs_pivot(const size_t j, const Tensor<T,M,M> &L, const Tensor<T,M,N> &B, const Tensor<size_t,M> &p, Tensor<T,M> &y, Tensor<T,M,N> &X) { y(from) = B(p(from),j) - _inner<T,from>(&L.data()[from*M],y.data()); X(from,j) = y(from); forward_subs_impl<from+1,to>::do_multi_rhs_pivot(j, L, B, p, y, X); } }; template <size_t from> struct forward_subs_impl<from,from> { template<typename T, size_t M> static FASTOR_INLINE void do_single_rhs(const Tensor<T,M,M> &L, const Tensor<T,M> &b, Tensor<T,M> &y) { y(from) = b(from) - _inner<T,from>(&L.data()[from*M],y.data()); } template<typename T, size_t M> static FASTOR_INLINE void do_single_rhs_pivot(const Tensor<T,M,M> &L, const Tensor<T,M> &b, const Tensor<size_t,M> &p, Tensor<T,M> &y) { y(from) = b(p(from)) - _inner<T,from>(&L.data()[from*M],y.data()); } template<typename T, size_t M, size_t N> static FASTOR_INLINE void do_multi_rhs(const size_t j, const Tensor<T,M,M> &L, const Tensor<T,M,N> &B, Tensor<T,M> &y, Tensor<T,M,N> &X) { y(from) = B(from,j) - _inner<T,from>(&L.data()[from*M],y.data()); X(from,j) = y(from); } template<typename T, size_t M, size_t N> static FASTOR_INLINE void do_multi_rhs_pivot(const size_t j, const Tensor<T,M,M> &L, const Tensor<T,M,N> &B, const Tensor<size_t,M> &p, Tensor<T,M> &y, Tensor<T,M,N> &X) { y(from) = B(p(from),j) - _inner<T,from>(&L.data()[from*M],y.data()); X(from,j) = y(from); } }; template<typename T, size_t M> FASTOR_INLINE Tensor<T,M> forward_subs(const Tensor<T,M,M> &L, const Tensor<T,M> &b) { Tensor<T,M> y(0); forward_subs_impl<0,M-1>::do_single_rhs(L, b, y); #if 0 // The run-time loop version // Solve for L * y = b for (size_t i=0; i< M; ++i) { T value = 0; for (size_t k=0; k<i; ++k) { value += L(i,k)*y(k); } y(i) = b(i) - value; } #endif return y; } template<typename T, size_t M, size_t N> FASTOR_INLINE Tensor<T,M,N> forward_subs(const Tensor<T,M,M> &L, const Tensor<T,M,N> &B) { // We keep a separate output tensor X from y [y is columns of X] // to avoid strided access in X for the inner product Tensor<T,M,N> X; for (size_t j=0; j < N; ++j) { Tensor<T,M> y(0); forward_subs_impl<0,M-1>::do_multi_rhs(j, L, B, y, X); } #if 0 // The run-time loop version - X needs to be zeroed out for this version for (size_t j=0; j < N; ++j) { Tensor<T,M> y(0); // Solve for L * y = b for (size_t i=0; i< M; ++i) { T value = 0; for (size_t k=0; k<i; ++k) { value += L(i,k)*y(k); } y(i) = B(i,j) - value; X(i,j) = y(i); } } #endif return X; } template<typename T, size_t M> FASTOR_INLINE Tensor<T,M> forward_subs(const Tensor<T,M,M> &L, const Tensor<size_t,M> &p, const Tensor<T,M> &b) { Tensor<T,M> y(0); forward_subs_impl<0,M-1>::do_single_rhs_pivot(L, b, p, y); #if 0 // The run-time loop version // Solve for L * y = b for (size_t i=0; i< M; ++i) { T value = 0; for (size_t k=0; k<i; ++k) { value += L(i,k)*y(k); } y(i) = b(p(i)) - value; } #endif return y; } template<typename T, size_t M, size_t N> FASTOR_INLINE Tensor<T,M,N> forward_subs(const Tensor<T,M,M> &L, const Tensor<size_t,M> &p, const Tensor<T,M,N> &B) { // We keep a separate output tensor X from y [y is columns of X] // to avoid strided access in X for the inner product Tensor<T,M,N> X; for (size_t j=0; j < N; ++j) { Tensor<T,M> y(0); forward_subs_impl<0,M-1>::do_multi_rhs_pivot(j, L, B, p, y, X); } #if 0 // The run-time loop version - X needs to be zeroed out for this version for (size_t j=0; j < N; ++j) { Tensor<T,M> y(0); // Solve for L * y = b for (size_t i=0; i< M; ++i) { T value = 0; for (size_t k=0; k<i; ++k) { value += L(i,k)*y(k); } y(i) = B(p(i),j) - value; X(i,j) = y(i); } } #endif return X; } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// /* Compile time recursive loop with inner for backward substitution of y/Y given the upper triangular matrix U. The following meta functions implements U * x = y for single or multiple right sides */ //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// template <int from, int to> struct backward_subs_impl { template<typename T, size_t M> static FASTOR_INLINE void do_single_rhs(const Tensor<T,M,M> &U, const Tensor<T,M> &y, Tensor<T,M> &x) { constexpr int idx = (int)M - from; const T value = _inner<T,idx>(&U.data()[from*M+from],&x.data()[from]); x(from) = ( y(from) - value) / U(from, from); backward_subs_impl<from-1,to>::do_single_rhs(U, y, x); } template<typename T, size_t M, size_t N> static FASTOR_INLINE void do_multi_rhs(const size_t j, const Tensor<T,M,M> &U, const Tensor<T,M,N> &Y, Tensor<T,M> &x, Tensor<T,M,N> &X) { constexpr int idx = (int)M - from; const T value = _inner<T,idx>(&U.data()[from*M+from],&x.data()[from]); x(from) = ( Y(from,j) - value ) / U(from, from); X(from,j) = x(from); backward_subs_impl<from-1,to>::do_multi_rhs(j, U, Y, x, X); } }; template <> struct backward_subs_impl<0,0> { template<typename T, size_t M> static FASTOR_INLINE void do_single_rhs(const Tensor<T,M,M> &U, const Tensor<T,M> &y, Tensor<T,M> &x) { constexpr int idx = (int)M; const T value = _inner<T,idx>(&U.data()[0*M+0],&x.data()[0]); x(0) = ( y(0) - value) / U(0, 0); } template<typename T, size_t M, size_t N> static FASTOR_INLINE void do_multi_rhs(const size_t j, const Tensor<T,M,M> &U, const Tensor<T,M,N> &Y, Tensor<T,M> &x, Tensor<T,M,N> &X) { constexpr int idx = (int)M; const T value = _inner<T,idx>(&U.data()[0*M+0],&x.data()[0]); x(0) = ( Y(0,j) - value ) / U(0, 0); X(0,j) = x(0); } }; template<typename T, size_t M> FASTOR_INLINE Tensor<T,M> backward_subs(const Tensor<T,M,M> &U, const Tensor<T,M> &y) { // We keep a separate output tensor X from x [x is columns of X] // to avoid strided access in X for the inner product Tensor<T,M> x(0); backward_subs_impl<int(M)-1,0>::do_single_rhs(U, y, x); #if 0 // The run-time loop version // Solve for of U * x = y for (int i= int(M) - 1; i>=0; --i) { T value = 0; for (int k=i; k<int(M); ++k) { value += U(i,k)*x(k); } x(i) = (y(i) - value) / U(i, i); } #endif return x; } template<typename T, size_t M, size_t N> FASTOR_INLINE Tensor<T,M,N> backward_subs(const Tensor<T,M,M> &U, const Tensor<T,M,N> &Y) { // We keep a separate output tensor X from x [x is columns of X] // to avoid strided access in X for the inner product Tensor<T,M,N> X; for (size_t j=0; j < N; ++j) { Tensor<T,M> x(0); backward_subs_impl<int(M)-1,0>::do_multi_rhs(j, U, Y, x, X); } #if 0 // The run-time loop version - X needs to be zeroed out for this version Tensor<T,M,N> X(0); for (size_t j=0; j < 1; ++j) { // Solve for of U * x = y for (int i= int(M) - 1; i>=0; --i) { T value = 0; for (int k=i; k<int(M); ++k) { value += U(i,k)*X(k,j); } X(i,j) = (Y(i,j) - value) / U(i, i); } } #endif return X; } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// /* Simple LU factorisation without pivoting */ //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// template <typename T, size_t M, enable_if_t_<is_greater_v_<M,0> && is_less_equal_v_<M,8>,bool> = false> FASTOR_INLINE void lu_simple_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { _lufact<T,M>(A.data(),L.data(),U.data()); } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,8>,bool> = false> FASTOR_INLINE void lu_simple_dispatcher(const Tensor<T,M,M>& A1, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { L.fill(0); U.fill(0); for (size_t j = 0; j < M; ++j) { L(j, j) = 1; for (size_t i = 0; i <= j; ++i) { T value = A1(i, j); for (size_t k = 0; k < i; ++k) { value -= L(i, k) * U(k, j); } U(i, j) = value; } for (size_t i = j; i < M; ++i) { T value = A1(i, j); for (size_t k = 0; k < j; ++k) { value -= L(i, k) * U(k, j); } value /= U(j, j); L(i, j) = value; } } } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // Recursive non-modifying LU using matmul/outer product //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// /* This in essence implements the following loop but with static views as dynamic views cannot be dispatched to matmul or a tensor cannot be constructed to be sent to matmul for(size_t j=0; j<M-1; ++j) { L(seq(j+1,M),j) /= L(j,j); L(seq(j+1,M),seq(j+1,M)) -= L(seq(j+1,M),j) % L(j,seq(j+1,M)); } This is a non-modifying version that fills L and U directly and avoids the need for extracting L and U later The pre-requisite is that L should be Identity and U be a copy of A before the recursive routine starts */ template<size_t from, size_t to> struct recursive_lu_impl { template<typename T, size_t M, size_t N> static FASTOR_INLINE void Do(Tensor<T,M,N> &L, Tensor<T,M,N> &U) { L(fseq<from+1,M>(),fix<from>) = U(fseq<from+1,M>(),fix<from>) / U.data()[from*N+from]; U(fseq<from+1,M>(),fix<from>) = 0; U(fseq<from+1,M>(),fseq<from+1,M>()) -= matmul(L(fseq<from+1,M>(),fix<from>), U(fix<from>,fseq<from+1,M>())); recursive_lu_impl<from+1,to>::Do(L, U); } }; template<size_t from> struct recursive_lu_impl<from,from> { template<typename T, size_t M, size_t N> static FASTOR_INLINE void Do(Tensor<T,M,N> &L, Tensor<T,M,N> &U) { L(fseq<from+1,M>(),fix<from>) = U(fseq<from+1,M>(),fix<from>) / U.data()[from*N+from]; U(fseq<from+1,M>(),fix<from>) = 0; U(fseq<from+1,M>(),fseq<from+1,M>()) -= matmul(L(fseq<from+1,M>(),fix<from>), U(fix<from>,fseq<from+1,M>())); } }; template <typename T, size_t M, enable_if_t_<is_equal_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_lu_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { L(0,0) = 1; U(0,0) = A(0,0); } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_lu_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { // Requires M >=2 U = A; L.eye2(); recursive_lu_impl<0,M-2>::Do(L, U); } #if 0 // Recursive in-place LU using matmul/outer product //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// /* This in essence implements the following loop but with static views as dynamic views cannot be dispatched to matmul or a tensor cannot be constructed to be sent to matmul for(size_t j=0; j<M-1; ++j) { L(seq(j+1,M),j) /= L(j,j); L(seq(j+1,M),seq(j+1,M)) -= L(seq(j+1,M),j) % L(j,seq(j+1,M)); } This is a self-modifying [in-place] version - if instead of a copy of (LU in this case) we pass the matrix itself it will decompose it in to an LU. Extracting L and U after this recursive decomposition is done almost beats the purpose performance wise */ template<size_t from, size_t to> struct recursive_lu_impl_inplace { template<typename T, size_t M, size_t N> static FASTOR_INLINE void Do(Tensor<T,M,N> &LU) { LU(fseq<from+1,M>(),fix<from>) /= LU.data()[from*N+from]; LU(fseq<from+1,M>(),fseq<from+1,M>()) -= matmul(LU(fseq<from+1,M>(),fix<from>), LU(fix<from>,fseq<from+1,M>())); recursive_lu_impl_inplace<from+1,to>::Do(LU); } }; template<size_t from> struct recursive_lu_impl_inplace<from,from> { template<typename T, size_t M, size_t N> static FASTOR_INLINE void Do(Tensor<T,M,N> &LU) { LU(fseq<from+1,M>(),fix<from>) /= LU.data()[from*N+from]; LU(fseq<from+1,M>(),fseq<from+1,M>()) -= matmul(LU(fseq<from+1,M>(),fix<from>), LU(fix<from>,fseq<from+1,M>())); } }; template <typename T, size_t M, enable_if_t_<is_equal_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_inplace_lu_dispatcher(Tensor<T,M,M>& A) { return; } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_inplace_lu_dispatcher(Tensor<T,M,M>& A) { // Requires M >=2 recursive_lu_impl_inplace<0,M-2>::Do(A); } template <typename T, size_t M, enable_if_t_<is_equal_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_inplace_lu_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& LU) { LU(0,0) = A(0,0); } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_inplace_lu_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& LU) { // Requires M >=2 LU =A; recursive_lu_impl_inplace<0,M-2>::Do(LU); } template <typename T, size_t M, enable_if_t_<is_equal_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_inplace_lu_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { L(0,0) = 1; U(0,0) = A(0,0); } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,1>,bool> = false> FASTOR_INLINE void recursive_inplace_lu_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { // Requires M >=2 Tensor<T,M,M> LU(A); recursive_lu_impl_inplace<0,M-2>::Do(LU); // Extracting L and U after this recursive decomposition is done // almost beats the purpose performance wise for (size_t i=0; i<M; ++i) { L(i,i) = 1; } for (size_t i=0; i<M; ++i) { for (size_t j=0; j<i; ++j) { L(i,j) = LU(i,j); } } for (size_t i=0; i<M; ++i) { for (size_t j=i; j<M; ++j) { U(i,j) = LU(i,j); } } } #endif //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// /* Block LU factorisation without pivoting */ //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// template <typename T, size_t M, enable_if_t_<is_greater_v_<M,0> && is_less_equal_v_<M,8>,bool> = false> FASTOR_INLINE void lu_block_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { _lufact<T,M>(A.data(),L.data(),U.data()); } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,8> && is_less_equal_v_<M,32>,bool> = false> FASTOR_INLINE void lu_block_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { recursive_lu_dispatcher(A, L, U); } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,32> && is_less_equal_v_<M,64>,bool> = false> FASTOR_INLINE void lu_block_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { // We will compute LU decomposition block-wise assuming that A11 and A22 are invertible // // [A11 A12] [L11 0] [U11 U12] // [A21 A22] [L21 L22] [0 U22] // // This results in // // A11 = L11 * U11 // A12 = L11 * U12 // A21 = L21 * U11 // A22 = L21 * U12 - L22 * U22 // // Hence we need to do LU factorisation once for A11 and once for A22 // This is to avoid odd sizes for instance for size 35 we would // want to do 35 = 16 + 19 rather than 35 = 32 + 3 if the start size was 32 constexpr size_t N = (M / 8UL * 8UL) / 2UL; // start size Tensor<T,N ,N > A11 = A(fseq<0,N>(),fseq<0,N>()); Tensor<T,N ,M-N> A12 = A(fseq<0,N>(),fseq<N,M>()); Tensor<T,M-N, N> A21 = A(fseq<N,M>(),fseq<0,N>()); Tensor<T,M-N,M-N> A22 = A(fseq<N,M>(),fseq<N,M>()); Tensor<T,N,N> L11(0), U11(0); lu_block_dispatcher(A11, L11, U11); // Solve for U12 = {L11}^(-1)*A12 Tensor<T,N ,M-N> U12 = tmatmul<UpLoType::Lower,UpLoType::General>(tinverse<InvCompType::SimpleInv, UpLoType::UniLower>(L11),A12); // Solve for L21 = A21*{U11}^(-1) Tensor<T,M-N, N> L21 = tmatmul<UpLoType::General,UpLoType::Upper>(A21,tinverse<InvCompType::SimpleInv, UpLoType::Upper>(U11)); Tensor<T,M-N,M-N> S = A22 - matmul(L21,U12); Tensor<T,M-N,M-N> L22(0), U22(0); lu_block_dispatcher(S, L22, U22); L(fseq<0,N>(),fseq<0,N>()) = L11; // L(fseq<0,N>(),fseq<N,M>()) = 0; L(fseq<N,M>(),fseq<0,N>()) = L21; L(fseq<N,M>(),fseq<N,M>()) = L22; U(fseq<0,N>(),fseq<0,N>()) = U11; U(fseq<0,N>(),fseq<N,M>()) = U12; // U(fseq<N,M>(),fseq<0,N>()) = 0; U(fseq<N,M>(),fseq<N,M>()) = U22; } // Conditional dispatch namespace useless { template <typename T, size_t M, enable_if_t_<is_greater_v_<M,0> && is_less_equal_v_<M,64>,bool> = false> FASTOR_INLINE void lu_block_simple_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { lu_block_dispatcher(A, L, U); return; } template <typename T, size_t M, enable_if_t_<is_greater_v_<M,64>,bool> = false> FASTOR_INLINE void lu_block_simple_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { // lu_simple_dispatcher(A, L, U); recursive_lu_dispatcher(A, L, U); return; } } // useless /* For sizes greater than 64 we tile differently to avoid too many recursions */ template <typename T, size_t M, enable_if_t_<is_greater_v_<M,64>,bool> = false> FASTOR_INLINE void lu_block_dispatcher(const Tensor<T,M,M>& A, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { // We will compute LU decomposition block-wise assuming that A11 and A22 are invertible // // [A11 A12] [L11 0] [U11 U12] // [A21 A22] [L21 L22] [0 U22] // // This results in // // A11 = L11 * U11 // A12 = L11 * U12 // A21 = L21 * U11 // A22 = L21 * U12 - L22 * U22 // // Hence we need to do LU factorisation once for A11 and once for A22 // This is to avoid odd sizes for instance for size 65 we would // want to do 65 = 32 + 33 rather than 65 = 64 + 1 if the start size was 64 constexpr size_t N = (M / 16UL * 16UL) / 2UL; // start size Tensor<T,N ,N > A11 = A(fseq<0,N>(),fseq<0,N>()); Tensor<T,N ,M-N> A12 = A(fseq<0,N>(),fseq<N,M>()); Tensor<T,M-N, N> A21 = A(fseq<N,M>(),fseq<0,N>()); Tensor<T,M-N,M-N> A22 = A(fseq<N,M>(),fseq<N,M>()); Tensor<T,N,N> L11(0), U11(0); useless::lu_block_simple_dispatcher(A11, L11, U11); // Solve for U12 = {L11}^(-1)*A12 Tensor<T,N ,M-N> U12 = tmatmul<UpLoType::Lower,UpLoType::General>(tinverse<InvCompType::SimpleInv, UpLoType::UniLower>(L11),A12); // Ideally use forward_subs but its iterative nature makes it less efficient than tmatmul // Tensor<T,N ,M-N> U12 = forward_subs(L11,A12); // Solve for L21 = A21*{U11}^(-1) Tensor<T,M-N, N> L21 = tmatmul<UpLoType::General,UpLoType::Upper>(A21,tinverse<InvCompType::SimpleInv, UpLoType::Upper>(U11)); // Not quite performant as we can't avoid the matmul here // Tensor<T,N ,N > I; I.eye2(); // Tensor<T,M-N, N> L21 = matmul(A21, backward_subs(U11, I)); Tensor<T,M-N,M-N> S = A22 - matmul(L21,U12); Tensor<T,M-N,M-N> L22(0), U22(0); useless::lu_block_simple_dispatcher(S, L22, U22); L(fseq<0,N>(),fseq<0,N>()) = L11; // L(fseq<0,N>(),fseq<N,M>()) = 0; L(fseq<N,M>(),fseq<0,N>()) = L21; L(fseq<N,M>(),fseq<N,M>()) = L22; U(fseq<0,N>(),fseq<0,N>()) = U11; U(fseq<0,N>(),fseq<N,M>()) = U12; // U(fseq<N,M>(),fseq<0,N>()) = 0; U(fseq<N,M>(),fseq<N,M>()) = U22; } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// } // internal /* Block LU factorisation overloads */ //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // BlockLU - no pivot template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<is_tensor_v<Expr> && LUType == LUCompType::BlockLU,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { L.fill(0); U.fill(0); internal::lu_block_dispatcher(src.self(),L,U); } template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<!is_tensor_v<Expr> && LUType == LUCompType::BlockLU,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { L.fill(0); U.fill(0); typename Expr::result_type tmp(src.self()); internal::lu_block_dispatcher(tmp,L,U); } // BlockLU - vector pivot template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<is_tensor_v<Expr> && LUType == LUCompType::BlockLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<size_t,M>& P) { L.fill(0); U.fill(0); pivot_inplace(src.self(),P); auto A(apply_pivot(src.self(),P)); internal::lu_block_dispatcher(A,L,U); } template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<!is_tensor_v<Expr> && LUType == LUCompType::BlockLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<size_t,M>& P) { L.fill(0); U.fill(0); typename Expr::result_type A(src.self()); pivot_inplace(A,P); // Modify A as A is a temporary anyway apply_pivot_inplace(A,P); internal::lu_block_dispatcher(A,L,U); } // BlockLU - matrix pivot template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<is_tensor_v<Expr> && LUType == LUCompType::BlockLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<T,M,M>& P) { L.fill(0); U.fill(0); pivot_inplace(src.self(),P); auto A(apply_pivot(src.self(),P)); internal::lu_block_dispatcher(A,L,U); } template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<!is_tensor_v<Expr> && LUType == LUCompType::BlockLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<T,M,M>& P) { L.fill(0); U.fill(0); typename Expr::result_type A(src.self()); pivot_inplace(A,P); // Modify A as A is a temporary anyway apply_pivot_inplace(A,P); internal::lu_block_dispatcher(A,L,U); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// /* Simple LU factorisation overloads */ //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // SimpleLU - no pivot template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<is_tensor_v<Expr> && LUType == LUCompType::SimpleLU,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { internal::lu_simple_dispatcher(src.self(),L,U); } template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<!is_tensor_v<Expr> && LUType == LUCompType::SimpleLU,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U) { typename Expr::result_type tmp(src.self()); internal::lu_simple_dispatcher(tmp,L,U); } // SimpleLU - vector pivot template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<is_tensor_v<Expr> && LUType == LUCompType::SimpleLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<size_t,M>& P) { pivot_inplace(src.self(),P); auto A(apply_pivot(src.self(),P)); internal::lu_simple_dispatcher(A,L,U); } template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<!is_tensor_v<Expr> && LUType == LUCompType::SimpleLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<size_t,M>& P) { typename Expr::result_type A(src.self()); pivot_inplace(A,P); // Modify A as A is a temporary anyway apply_pivot_inplace(A,P); internal::lu_simple_dispatcher(A,L,U); } // SimpleLU - matrix pivot template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<is_tensor_v<Expr> && LUType == LUCompType::SimpleLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<T,M,M>& P) { pivot_inplace(src.self(),P); auto A(apply_pivot(src.self(),P)); internal::lu_simple_dispatcher(A,L,U); } template<LUCompType LUType = LUCompType::BlockLU, typename Expr, size_t DIM0, typename T, size_t M, enable_if_t_<!is_tensor_v<Expr> && LUType == LUCompType::SimpleLUPiv,bool> = false> FASTOR_INLINE void lu(const AbstractTensor<Expr,DIM0> &src, Tensor<T,M,M>& L, Tensor<T,M,M>& U, Tensor<T,M,M>& P) { typename Expr::result_type A(src.self()); pivot_inplace(A,P); // Modify A as A is a temporary anyway apply_pivot_inplace(A,P); internal::lu_simple_dispatcher(A,L,U); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // Inversion using LU //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// namespace internal { template<typename T, size_t M> FASTOR_INLINE Tensor<T,M,M> get_lu_inverse(const Tensor<T,M,M> &L, const Tensor<T,M,M> &U) { // We will solve for multiple RHS [B = I] // Loop over columns of B = I Tensor<T,M,M> I; I.eye2(); Tensor<T,M,M> Y = forward_subs(L, I); Tensor<T,M,M> X = backward_subs(U, Y); return X; } template<typename T, size_t M> FASTOR_INLINE Tensor<T,M,M> get_lu_inverse(Tensor<T,M,M> &L, const Tensor<T,M,M> &U, const Tensor<size_t,M> &p) { // We will solve for multiple RHS [B = I] // Loop over columns of B = I Tensor<T,M,M> I; I.eye2(); Tensor<T,M,M> Y = forward_subs(L, p, I); Tensor<T,M,M> X = backward_subs(U, Y); return X; } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// } // internal // SimpleLU template<InvCompType InvType = InvCompType::SimpleInv, typename T, size_t M, enable_if_t_<InvType == InvCompType::SimpleLU,bool> = false> FASTOR_INLINE Tensor<T,M,M> inverse(const Tensor<T,M,M> &A) { Tensor<T,M,M> L, U; lu<LUCompType::SimpleLU>(A, L, U); return internal::get_lu_inverse(L, U); } // BlockLU template<InvCompType InvType = InvCompType::SimpleInv, typename T, size_t M, enable_if_t_<InvType == InvCompType::BlockLU,bool> = false> FASTOR_INLINE Tensor<T,M,M> inverse(const Tensor<T,M,M> &A) { Tensor<T,M,M> L, U; lu<LUCompType::BlockLU>(A, L, U); return internal::get_lu_inverse(L, U); } // SimpleLUPiv template<InvCompType InvType = InvCompType::SimpleInv, typename T, size_t M, enable_if_t_<InvType == InvCompType::SimpleLUPiv,bool> = false> FASTOR_INLINE Tensor<T,M,M> inverse(const Tensor<T,M,M> &A) { Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::SimpleLUPiv>(A, L, U, p); return internal::get_lu_inverse(L, U, p); } // BlockLUPiv template<InvCompType InvType = InvCompType::SimpleInv, typename T, size_t M, enable_if_t_<InvType == InvCompType::BlockLUPiv,bool> = false> FASTOR_INLINE Tensor<T,M,M> inverse(const Tensor<T,M,M> &A) { Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::BlockLUPiv>(A, L, U, p); return internal::get_lu_inverse(L, U, p); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // Solving linear system of equations using LU //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// namespace internal { template<typename T, size_t M> FASTOR_INLINE Tensor<T,M> get_lu_solve(const Tensor<T,M,M> &L, const Tensor<T,M,M> &U, const Tensor<T,M> &b) { Tensor<T,M> y = forward_subs(L, b); Tensor<T,M> x = backward_subs(U, y); return x; } template<typename T, size_t M> FASTOR_INLINE Tensor<T,M> get_lu_solve(Tensor<T,M,M> &L, const Tensor<T,M,M> &U, const Tensor<size_t,M> &p, const Tensor<T,M> &b) { Tensor<T,M> y = forward_subs(L, p, b); Tensor<T,M> x = backward_subs(U, y); return x; } // Multiple RHS template<typename T, size_t M, size_t N> FASTOR_INLINE Tensor<T,M,N> get_lu_solve(const Tensor<T,M,M> &L, const Tensor<T,M,M> &U, const Tensor<T,M,N> &B) { Tensor<T,M,N> Y = forward_subs(L, B); Tensor<T,M,N> X = backward_subs(U, Y); return X; } template<typename T, size_t M, size_t N> FASTOR_INLINE Tensor<T,M,N> get_lu_solve(const Tensor<T,M,M> &L, const Tensor<T,M,M> &U, const Tensor<size_t,M> &p, const Tensor<T,M,N> &B) { Tensor<T,M,N> Y = forward_subs(L, p, B); Tensor<T,M,N> X = backward_subs(U, Y); return X; } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// } // internal // Single RHS // SimpleLU - no pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, enable_if_t_< SType == SolveCompType::SimpleLU, bool> = false> FASTOR_INLINE Tensor<T,M> solve(const Tensor<T,M,M> &A, const Tensor<T,M> &b) { Tensor<T,M,M> L, U; lu<LUCompType::SimpleLU>(A, L, U); return internal::get_lu_solve(L, U, b); } // SimpleLU - pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, enable_if_t_< SType == SolveCompType::SimpleLUPiv, bool> = false> FASTOR_INLINE Tensor<T,M> solve(const Tensor<T,M,M> &A, const Tensor<T,M> &b) { Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::SimpleLUPiv>(A, L, U, p); return internal::get_lu_solve(L, U, p, b); } // BlockLU - no pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, enable_if_t_< SType == SolveCompType::BlockLU, bool> = false> FASTOR_INLINE Tensor<T,M> solve(const Tensor<T,M,M> &A, const Tensor<T,M> &b) { Tensor<T,M,M> L, U; lu<LUCompType::BlockLU>(A, L, U); return internal::get_lu_solve(L, U, b); } // BlockLU - pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, enable_if_t_< SType == SolveCompType::BlockLUPiv, bool> = false> FASTOR_INLINE Tensor<T,M> solve(const Tensor<T,M,M> &A, const Tensor<T,M> &b) { Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::BlockLUPiv>(A, L, U, p); return internal::get_lu_solve(L, U, p, b); } // Multiple RHS // SimpleLU - no pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, size_t N, enable_if_t_< SType == SolveCompType::SimpleLU, bool> = false> FASTOR_INLINE Tensor<T,M,N> solve(const Tensor<T,M,M> &A, const Tensor<T,M,N> &B) { Tensor<T,M,M> L, U; lu<LUCompType::SimpleLU>(A, L, U); return internal::get_lu_solve(L, U, B); } // SimpleLU - pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, size_t N, enable_if_t_< SType == SolveCompType::SimpleLUPiv, bool> = false> FASTOR_INLINE Tensor<T,M,N> solve(const Tensor<T,M,M> &A, const Tensor<T,M,N> &B) { Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::SimpleLUPiv>(A, L, U, p); return internal::get_lu_solve(L, U, p, B); } // SimpleLU - no pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, size_t N, enable_if_t_< SType == SolveCompType::BlockLU, bool> = false> FASTOR_INLINE Tensor<T,M,N> solve(const Tensor<T,M,M> &A, const Tensor<T,M,N> &B) { Tensor<T,M,M> L, U; lu<LUCompType::BlockLU>(A, L, U); return internal::get_lu_solve(L, U, B); } // SimpleLU - pivot template<SolveCompType SType = SolveCompType::SimpleInv, typename T, size_t M, size_t N, enable_if_t_< SType == SolveCompType::BlockLUPiv, bool> = false> FASTOR_INLINE Tensor<T,M,N> solve(const Tensor<T,M,M> &A, const Tensor<T,M,N> &B) { Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::BlockLUPiv>(A, L, U, p); return internal::get_lu_solve(L, U, p, B); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // Computing determinant using LU //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// template<DetCompType DetType = DetCompType::Simple, typename T, size_t M, enable_if_t_<DetType == DetCompType::LU,bool> = false> FASTOR_INLINE T determinant(const Tensor<T,M,M> &A) { int nswaps = internal::count_swaps(A) % 2UL == 0 ? 1 : -1; Tensor<T,M,M> L, U; Tensor<size_t,M> p; lu<LUCompType::BlockLUPiv>(A, L, U, p); return product(diag(U)) * nswaps; } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// } // end of namespace Fastor #endif // UNARY_LU_OP_H
39.761071
142
0.541546
[ "vector" ]
d34f44cbfa7476d44f7312f5cff8bcb69e3454df
22,555
c
C
d/deku/mausoleum/inherits/puzzle_daemon.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/deku/mausoleum/inherits/puzzle_daemon.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/deku/mausoleum/inherits/puzzle_daemon.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
/*========================================= A puzzle daemon - assigns a puzzle type to tomb rooms when the assign_puzzles function is called. This determine the particular description of the tomb IE provides hint to the puzzle solution varies - so puzzles should remain the same for a window of 2 hours - will not change on reset but will change when the room is reloaded =========================================*/ #include <std.h> #include "area_stuff.h" #include "drawings.h" inherit DAEMON; //mapping PUZZLES (["word puzzle" : (["current solution": "", "current tomb" : 1-4, "room" : "hint"]), ]) mapping PUZZLES = ([]); int PUZZLE_DELAY; mapping DOPPLEGANGERS = ([]); void assign_puzzles(); void install_puzzles(object room); void actual_puzzle_assignment(); void assign_word_puzzle(); void assign_number_puzzle(); void assign_picture_puzzle(); void assign_sphere_puzzle(); mapping query_puzzles() { return PUZZLES; } string assign_random_letters(int hint); string get_puzzle_solution(string type); mixed is_puzzle_room(string myRoom, string type); string *get_puzzle_rooms(int tomb); string assign_random_colors(string hint, string myRoom); mapping default_items(); mixed get_sarcophagus_type(string myRoom); void assign_puzzles() { string *saved_arr; int delay; if(!PUZZLE_DELAY || !mapp(PUZZLES)) { PUZZLE_DELAY = time() + 7200; PUZZLES = ([]); actual_puzzle_assignment(); return; } else { if(time() > PUZZLE_DELAY || !mapp(PUZZLES)) { PUZZLES = ([]); PUZZLE_DELAY = time() + 7200; actual_puzzle_assignment(); return; } else return; } } void actual_puzzle_assignment() { string *puzzles = ({"word puzzle", "number puzzle", "sphere puzzle", "picture puzzle"}); string cur_puzzle; int *nums = ({1, 2, 3, 4}); int cur_tomb; while(sizeof(nums)) { cur_puzzle = puzzles[random(sizeof(puzzles))]; puzzles -= ({cur_puzzle}); cur_tomb = nums[random(sizeof(nums))]; nums -= ({cur_tomb}); PUZZLES += ([cur_puzzle : (["current solution" : "", "sarcophagus location" : MAUS+"tomb"+cur_tomb+"_5.c", "current tomb" : cur_tomb, "rooms" : ([]), ]), ]); continue; } assign_word_puzzle(); assign_sphere_puzzle(); assign_picture_puzzle(); assign_number_puzzle(); } mixed get_sarcophagus_type(string myRoom) { if(!stringp(myRoom)) return 0; if(!mapp(PUZZLES) || !sizeof(keys(PUZZLES))) assign_puzzles(); if(PUZZLES["word puzzle"]["sarcophagus location"] == myRoom) return "word puzzle"; else if(PUZZLES["number puzzle"]["sarcophagus location"] == myRoom) return "number puzzle"; else if(PUZZLES["sphere puzzle"]["sarcophagus location"] == myRoom) return "sphere puzzle"; else if(PUZZLES["picture puzzle"]["sarcophagus location"] == myRoom) return "picture puzzle"; return 0; } mixed is_puzzle_room(string myRoom, string type) { string *myRooms; if(!stringp(myRoom)) return 0; if(!mapp(PUZZLES) || !sizeof(keys(PUZZLES))) assign_puzzles(); if(!mapp(PUZZLES[type]["rooms"])) return 0; myRooms = keys(PUZZLES[type]["rooms"]); if(!pointerp(myRooms)) return 0; if(member_array(myRoom, myRooms) == -1) return 0; if(type == "sphere puzzle" || type == "picture puzzle") { return PUZZLES[type]["rooms"][myRoom]["hint"]; } return PUZZLES[type]["rooms"][myRoom]; } string *get_puzzle_rooms(int tomb) { string *rooms, mydir; mydir = MAUS+"tomb"+tomb+"_*.c"; rooms = get_dir(mydir); rooms -= ({"tomb"+tomb+"_5.c"}); return rooms; } string get_puzzle_solution(string type) { if(!mapp(PUZZLES)) assign_puzzles(); return PUZZLES[type]["current solution"]; } void assign_number_puzzle() { string *NUMS = ({"1", "2", "3", "4", "5", "6", "7", "8", "9"}); string *solution, num, *rooms; int tomb; solution = ({}); while(sizeof(NUMS)) { num = NUMS[random(sizeof(NUMS))]; solution += ({num}); NUMS -= ({num}); continue; } tomb = PUZZLES["number puzzle"]["current tomb"]; PUZZLES["number puzzle"]["current solution"] = implode(solution,""); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_1.c" : solution[0]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_2.c" : solution[1]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_3.c" : solution[2]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_4.c" : solution[3]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_6.c" : solution[5]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_7.c" : solution[6]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_8.c" : solution[7]]); PUZZLES["number puzzle"]["rooms"] += ([MAUS + "tomb"+tomb+"_9.c" : solution[8]]); return; } void assign_sphere_puzzle() { string *poss_colors = ({"red", "green", "cyan", "pink", "orange", "white"}); string *solution, hint, *rooms, room; int tomb, order; tomb = PUZZLES["sphere puzzle"]["current tomb"]; rooms = get_puzzle_rooms(tomb); solution = ({}); order = 1; while(sizeof(rooms)) { room = rooms[random(sizeof(rooms))]; hint = poss_colors[random(sizeof(poss_colors))]; solution += ({hint}); rooms -= ({room}); room = MAUS + room; PUZZLES["sphere puzzle"]["rooms"] += ([room : ([ "hint" : hint, "order" : order ]), ]); order++; continue; } PUZZLES["sphere puzzle"]["current solution"] = implode(solution, ""); return; } void assign_picture_puzzle() { string *picture_choices = ({"skeleton", "zombie", "ghoul", "ghost", "werewolf", "goblin", "hobgoblin", "gnoll"}); string *solution, hint, *rooms, room; int tomb, order; tomb = PUZZLES["picture puzzle"]["current tomb"]; rooms = get_puzzle_rooms(tomb); solution = ({}); order = 1; while(sizeof(rooms)) { room = rooms[random(sizeof(rooms))]; hint = picture_choices[random(sizeof(picture_choices))]; solution += ({hint}); rooms -= ({room}); room = MAUS + room; PUZZLES["picture puzzle"]["rooms"] += ([room : (["hint" : hint, "order" : order]), ]); order++; continue; } PUZZLES["picture puzzle"]["current solution"] = implode(solution, ""); return; } void assign_word_puzzle() { string *hints, *rooms, room, hint; string *WORD_CHOICES = ({"mountain","desolate","possible","conclude", "evolving","insanity","darkness","dramatic","solution","horrible", "unliving","unsteady","collapse","drowning","morphing","changing"}); string myWord = WORD_CHOICES[random(sizeof(WORD_CHOICES))]; int tomb, num, max; tomb = PUZZLES["word puzzle"]["current tomb"]; hints = explode(myWord, ""); PUZZLES["word puzzle"]["current solution"] = myWord; rooms = get_puzzle_rooms(tomb); if(!sizeof(rooms)) return; while(sizeof(hints)) { room = rooms[random(sizeof(rooms))]; rooms -= ({room}); num = random(sizeof(hints)); max = (sizeof(hints) - 1); hint = hints[num]; if(max == 0) hints -= ({hint}); else if(num == 0) hints = hints[1..max]; else hints = hints[0..(num-1)] + hints[(num+1)..max]; room = MAUS + room; PUZZLES["word puzzle"]["rooms"] += ([room : hint]); continue; } return; } string assign_random_numbers(string hint) { string *NUMS = ({"1", "2", "3", "4", "5", "6", "7", "8", "9"}); string *num_hint, num; int x, flag; x = 3 + random(4); num_hint = ({}); while(x > 0) { num = NUMS[random(sizeof(NUMS))]; if(num == hint && !flag) { num = "%^BOLD%^%^CYAN%^("+num+")%^RESET%^"; flag = 1; } else num = "%^BOLD%^%^GREEN%^"+num+"%^RESET%^"; num_hint += ({num}); x--; } if(!flag) { num_hint[random(sizeof(num_hint))] = "%^BOLD%^%^CYAN%^("+hint+")%^RESET%^"; } return implode(num_hint, " "); } string assign_random_letters(string hint) { string *LETS = ({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}); string let; string *let_hint; int x, flag; x = 4 + random(7); let_hint = ({}); while(x > 0) { let = LETS[random(sizeof(LETS))]; LETS -= ({let}); if(let == hint && !flag) { let = "%^BOLD%^%^CYAN%^("+capitalize(let)+")%^RESET%^"; flag = 1; } else let = "%^BOLD%^%^GREEN%^"+capitalize(let)+"%^RESET%^"; let_hint += ({let}); x--; } if(!flag) { let_hint[random(sizeof(let_hint))] = "%^BOLD%^%^CYAN%^("+capitalize(hint)+")%^RESET%^"; } return implode(let_hint, " "); } string assign_random_colors(string hint, string myRoom) { mapping myColors = (["red" : "%^RED%^", "green" : "%^GREEN%^", "cyan" : "%^CYAN%^", "pink" : "%^MAGENTA%^", "orange" : "%^ORANGE%^", "white" : "%^WHITE%^"]); string *poss_colors = ({"red", "green", "cyan", "pink", "orange", "white"}); string *let_hint, let; int order, x; let_hint = ({}); order = PUZZLES["sphere puzzle"]["rooms"][myRoom]["order"]; x = 1; while(x < 9) { if(x == order) { let = "%^BOLD%^%^BLACK%^(%^RESET%^%^BOLD%^"+myColors[hint]+"*%^BOLD%^%^BLACK%^)%^RESET%^"; } else { let = poss_colors[random(sizeof(poss_colors))]; let = "%^BOLD%^%^BLACK%^(%^RESET%^"+myColors[let]+"o%^BOLD%^%^BLACK%^)%^RESET%^"; } let_hint += ({let}); x++; continue; } return implode(let_hint, " "); } string assign_random_pictures(string hint, string myRoom) { string *picture_choices = ({"skeleton", "zombie", "ghoul", "ghost", "werewolf", "goblin", "hobgoblin", "gnoll"}); string *let_hint, let, pic; int order, x; let_hint = ({}); order = PUZZLES["picture puzzle"]["rooms"][myRoom]["order"]; x = 1; picture_choices -= ({hint}); while(x < 9) { if(x == order) { let = hint; } else { let = picture_choices[random(sizeof(picture_choices))]; picture_choices -= ({let}); } let_hint += ({let}); x++; continue; } return "a " +implode(let_hint[0..6], ", ") + " and a "+let_hint[7]; } mapping default_items() { mapping tmp; tmp = ([({"tomb", "structure", "mausoleum", "stone"}) : "%^BOLD%^%^WHITE%^This ancient "+ "tomb, like the rest of the mausoleum, was obviously once quite grand. However, "+ "that time has long since passed. It looks as if no one has visited it in ages and "+ "obviously whoever or whatever may have once cared for it has ceased.%^RESET%^", ({"torch holders", "holders", "dust", "cobwebs"}) : "%^BOLD%^%^YELLOW%^These are all empty now and "+ "covered with dust and cobwebs... "+ "another testament to the fact that all care for this place has long since "+ "ceased.%^RESET%^",]); return tmp; } mapping picture_items(string hint) { mapping picture_choices, tmp; string *pcs; int x; picture_choices = ([ "skeleton" : ([ "default" : SKEL, "hint" : SKEL_H, ]), "zombie" : ([ "default" : ZOM, "hint" : ZOM_H, ]), "ghoul" : ([ "default" : GHOUL, "hint" : GHOUL_H, ]), "ghost" : ([ "default": GHOST, "hint" : GHOST_H, ]), "werewolf" : ([ "default" : WERE, "hint" : WERE_H, ]), "goblin" : ([ "default" : GOB, "hint" : GOB_H, ]), "hobgoblin" : ([ "default" : HOB, "hint" : HOB_H, ]), "gnoll" : ([ "default" : GNOLL, "hint" : GNOLL_H, ]),]); //picture_choices = ([]); pcs = keys(picture_choices); tmp = ([]); for(x = 0;x < sizeof(pcs);x++) { if(hint == pcs[x]) tmp += ([({pcs[x], "drawing of "+pcs[x], pcs[x] + " drawing"}) : picture_choices[pcs[x]]["hint"],]); else tmp += ([({pcs[x], "drawing of "+pcs[x], pcs[x] + " drawing"}) : picture_choices[pcs[x]]["default"],]); } return tmp; } string query_puzzle_description(object room) { object sarc; mixed hint; mapping tmp; string myRoom, ret, let, sol; if(!objectp(room)) return "This wrong is broken. Tell Saide."; myRoom = base_name(room) + ".c"; ret = "%^BOLD%^%^BLACK%^You stand within an "+ "ancient tomb. It is composed from the same %^BOLD%^%^WHITE%^white "+ "stone%^BOLD%^%^BLACK%^ that the rest of the mausoleum has been "+ "constructed from. It is also instantly apparent that it too has long since "+ "been abandoned. There are %^BOLD%^%^WHITE%^cracks%^BOLD%^%^BLACK%^ visible on "+ "the walls, floor, and ceiling. The entire structure %^BOLD%^%^GREEN%^groans "+ "%^BOLD%^%^BLACK%^and %^BOLD%^%^GREEN%^creaks%^BOLD%^%^BLACK%^ around you, as it "+ "wages an unrelenting war against the weight of the %^RESET%^%^ORANGE%^dirt "+ "%^BOLD%^%^BLACK%^above. There are %^BOLD%^%^YELLOW%^torch holders%^BOLD%^%^BLACK%^ "+ "on the walls, though they are covered by %^RESET%^%^MAGENTA%^dust"+ "%^BOLD%^%^BLACK%^ and %^BOLD%^%^WHITE%^cobwebs%^BOLD%^%^BLACK%^. They have long "+ "been empty."; if(stringp(hint = is_puzzle_room(myRoom, "word puzzle"))) { ret += "%^BOLD%^%^BLACK%^ There are %^BOLD%^%^YELLOW%^letters%^BOLD%^%^BLACK%^"+ " scrawled all over the walls, visible "+ "only because of the dust in which they are written. Most of them have "+ "faded with time, however, a few are still legible.%^RESET%^"; if((string)room->query_property("mysolution") != get_puzzle_solution("word puzzle") || (string)room->query_property("mypuzzle") != "word puzzle") { tmp = default_items(); let = assign_random_letters(hint); tmp += ([({"letters", "walls"}) : "%^BOLD%^%^WHITE%^There are multitudes of "+ "letters scrawled all over the walls. They are visible only because of the "+ "dust in which they are written. Most of them have long since faded with the "+ "unrelenting passage of time. You are able to make out the following "+ "legibly:\n"+let+"%^RESET%^"]); tmp += ([({"cracks", "crack"}) : (:"crack_description":)]); room->remove_property("mypuzzle"); room->remove_property("mysolution"); room->set_property("mypuzzle", "word puzzle"); room->set_property("mysolution", get_puzzle_solution("word puzzle")); room->set_items(tmp); } return ret; } else if(stringp(hint = is_puzzle_room(myRoom, "number puzzle"))) { ret += "%^BOLD%^%^BLACK%^ There are %^RESET%^%^ORANGE%^numbers %^BOLD%^%^BLACK%^"+ "written in the thick dust which coats the walls here. They appear randomly all over "+ "the walls but most of them are so faded from the passage of time that they are "+ "now illegible.%^RESET%^"; if((string)room->query_property("mysolution") != get_puzzle_solution("number puzzle") || (string)room->query_property("mypuzzle") != "number puzzle") { tmp = default_items(); let = assign_random_numbers(hint); tmp += ([({"numbers", "walls"}) : "%^BOLD%^%^WHITE%^These numbers have been "+ "written in the thick dust which coats the walls here. They appear randomly all "+ "over the walls but most of them are so faded from the passage of time that "+ "they are now illegible. You can only manage to make out the following:\n"+ let+"%^RESET%^"]); tmp += ([({"cracks", "crack"}) : (:"crack_description":)]); room->remove_property("mypuzzle"); room->remove_property("mysolution"); room->set_property("mysolution", get_puzzle_solution("number puzzle")); room->set_property("mypuzzle", "number puzzle"); room->set_items(tmp); } return ret; } else if(stringp(hint = is_puzzle_room(myRoom, "sphere puzzle"))) { ret += "%^BOLD%^%^BLACK%^ There are strange %^RESET%^%^CYAN%^spheres%^BOLD%^%^BLACK%^ "+ "of various colors engraved into the walls. They constrast quite dramatically with "+ "the simple %^BOLD%^%^WHITE%^white stone%^BOLD%^%^BLACK%^ of the tomb. "+ "They have been engraved slightly above "+ "the %^BOLD%^%^YELLOW%^torch holders%^BOLD%^%^BLACK%^ and you see eight of them "+ "in total. You get the sense that at some point they held much more meaning than they "+ "do now, though you have no idea what purpose they might have originally served.%^RESET%^"; if((string)room->query_property("mysolution") != get_puzzle_solution("sphere puzzle") || (string)room->query_property("mypuzzle") != "sphere puzzle") { tmp = default_items(); tmp += ([({"cracks", "crack"}) : (:"crack_description":)]); let = assign_random_colors(hint, myRoom); tmp += ([({"spheres", "colored spheres"}) : "%^BOLD%^%^WHITE%^These strange spheres "+ "are of various colors, though they are all exactly the same size. You get the sense "+ "that some point they served a very important purpose but whatever their "+ "original intention was it is beyond you. The eight that remain look like the following:"+ "\n"+let+"%^RESET%^"]); room->remove_property("mypuzzle"); room->remove_property("mysolution"); room->set_property("mysolution", get_puzzle_solution("sphere puzzle")); room->set_property("mypuzzle", "sphere puzzle"); room->set_items(tmp); } return ret; } else if(stringp(hint = is_puzzle_room(myRoom, "picture puzzle"))) { ret += "%^BOLD%^%^BLACK%^ There are %^RESET%^%^ORANGE%^drawings%^BOLD%^%^BLACK%^ "+ "of different creatures covering large portions of the walls. You are unsure of what "+ "purpose they might serve or what their original meaning was, but they add an air of "+ "mystery to this tomb.%^RESET%^"; if((string)room->query_property("mysolution") != get_puzzle_solution("picture puzzle") || (string)room->query_property("mypuzzle") != "picture puzzle") { tmp = default_items(); tmp += ([({"cracks", "crack"}) : (:"crack_description":)]); let = assign_random_pictures(hint, myRoom); tmp += ([({"drawings", "drawing"}) : "%^RESET%^%^ORANGE%^These drawings "+ "cover large portions of the walls. You see drawings that "+ "resemble "+let+". You could look at "+ "each drawing individually if you wanted to do so."]); tmp += picture_items(hint); room->remove_property("mypuzzle"); room->remove_property("mysolution"); room->set_property("mysolution", get_puzzle_solution("picture puzzle")); room->set_property("mypuzzle", "picture puzzle"); room->set_items(tmp); } return ret; } else if(stringp(hint = get_sarcophagus_type(myRoom))) { ret += "%^BOLD%^%^BLACK%^ There is an elaborately constructed %^BOLD%^%^WHITE%^platform%^BOLD%^"+ "%^BLACK%^ that rises up in the center of the tomb here. There is a large ornate sarcophagus "+ "sitting on top of it.%^RESET%^"; tmp = default_items(); sol = get_puzzle_solution(hint); if((string)room->query_property("mysolution") != sol || (string)room->query_property("mypuzzle") != hint) { tmp += ([({"cracks", "crack"}) : (:"crack_description":)]); if(!objectp(sarc = present("sarcophagus", room))) { sarc = new(MOBJ"sarcophagus"); sarc->move(room); } sarc->set_my_puzzle(hint); sarc->set_my_solution(sol); room->set_items(tmp); room->remove_property("mypuzzle"); room->remove_property("mysolution"); room->set_property("mypuzzle", hint); room->set_property("mysolution", sol); } } return ret; } void clear_dopples() { object dop; int x; string *names; if(!mapp(DOPPLEGANGERS)) return; if(!sizeof(keys(DOPPLEGANGERS))) return; names = keys(DOPPLEGANGERS); for(x = 0;x < sizeof(names);x++) { if(!objectp(dop = DOPPLEGANGERS[names[x]])) continue; dop->remove(); continue; } return; } void clean_up() { clear_dopples(); return ::clean_up(); } void dopple_ganger(object who) { string *rooms, *names, name, room; object dop; if(!objectp(who)) return; if(!userp(who)) return; if(avatarp(who)) return; if(!mapp(DOPPLEGANGERS)) DOPPLEGANGERS = ([]); names = keys(DOPPLEGANGERS); name = who->query_true_name(); rooms = get_dir(MAUS); rooms -= ({"hidden5", "hidden28"}); if(!sizeof(names)) { dop = new(MMON"doppleganger"); dop->hunting(who); room = rooms[random(sizeof(rooms))]; room = MAUS + room; dop->move(room); DOPPLEGANGERS += ([ name : dop]); return; } if(member_array(name, names) != -1) { if(objectp(dop = DOPPLEGANGERS[name])) return; dop = new(MMON"doppleganger"); dop->hunting(who); room = rooms[random(sizeof(rooms))]; room = MAUS + room; dop->move(room); DOPPLEGANGERS[name] = dop; return; } else { dop = new(MMON"doppleganger"); dop->hunting(who); room = rooms[random(sizeof(rooms))]; room = MAUS + room; dop->move(room); DOPPLEGANGERS += ([ name : dop]); return; } return; } mapping dopples() { int x; string *names; if(!mapp(DOPPLEGANGERS)) DOPPLEGANGERS = ([]); names = keys(DOPPLEGANGERS); for(x = 0;x < sizeof(names);x++) { if(!objectp(DOPPLEGANGERS[names[x]])) { map_delete(DOPPLEGANGERS, names[x]); continue; } continue; } return DOPPLEGANGERS; }
37.717391
165
0.563467
[ "object" ]
d35182f8aeccd476b2fa1c8e3f22ce796df44256
3,744
c
C
kqueue/pid_watcher.c
raventid/coursera_learning
115a03f08d30d8ba49f02c9692c289cbfb242358
[ "MIT" ]
1
2019-11-28T09:26:00.000Z
2019-11-28T09:26:00.000Z
kqueue/pid_watcher.c
raventid/coursera_learning
115a03f08d30d8ba49f02c9692c289cbfb242358
[ "MIT" ]
null
null
null
kqueue/pid_watcher.c
raventid/coursera_learning
115a03f08d30d8ba49f02c9692c289cbfb242358
[ "MIT" ]
null
null
null
// Simple pid watcher, it's a next step in my kqueue learning #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #include <errno.h> #include <string.h> #include <inttypes.h> #include <limits.h> #include <errno.h> /* Helper function */ #define INVALID 1 #define TOOSMALL 2 #define TOOLARGE 3 long long strtonum(const char *numstr, long long minval, long long maxval, const char **errstrp) { long long ll = 0; char *ep; int error = 0; struct errval { const char *errstr; int err; } ev[4] = { { NULL, 0 }, { "invalid", EINVAL }, { "too small", ERANGE }, { "too large", ERANGE }, }; ev[0].err = errno; errno = 0; if (minval > maxval) error = INVALID; else { ll = strtoll(numstr, &ep, 10); if (numstr == ep || *ep != '\0') error = INVALID; else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval) error = TOOSMALL; else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval) error = TOOLARGE; } if (errstrp != NULL) *errstrp = ev[error].errstr; errno = ev[error].err; if (error) ll = 0; return (ll); } int main(int argc, char **argv) { int kq; struct kevent kev; // the kevent structure, container for messages from kernel queue pid_t pid; // object we are interested in /* pid = strtonum(argv[1], 0, 10000, NULL); // str -> number */ // looks like I failed to write strtonum, so it does not work. // second kevent does not work either, program just exits without any sign of // anything. I should really learn to debug with GDB, LLDB :) pid = 57348; kq = kqueue(); // this is the way to initialize kevent structure // EVFILT_PROC - our target is a process // EV_ADD - we would like to add it to queue // NOTE_EXIT - we are interested in EXIT event (I think it is the death of process?) EV_SET(&kev, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); /* int */ /* kevent(int kq, const struct kevent *changelist, int nchanges, */ /* struct kevent *eventlist, int nevents, */ /* const struct timespec *timeout); */ // changelist is monitored object kernel should add to it's monitoring list // eventlist is space for kernel to write events kevent(kq, &kev, 1, NULL, 0, NULL); // registering object for kqueue printf("pid is %i", pid); kevent(kq, NULL, 0, &kev, 0, NULL); // query object return 0; } /* Now that we understand a bit about how kqueue works, we are in a position */ /* to learn some more about its sharp edges. As anyone familiar with select or */ /* poll and tell you, you may repeatedly call those functions and receive more or */ /* less the same results every time. If a socket has data available for reading, */ /* poll will return it. If you don’t read from the socket and call poll again, it is */ /* still readable and poll will again return it. This is not the case with kqueue. */ /* The first call to kqueue will indicate the socket is ready for reading, but the */ /* second will not. Why not? Between the calls to kqueue, the socket’s state has */ /* not changed. kqueue only records changes in state, it never actually reads the */ /* current state. To do so would mean returning to poll levels of scalability. The */ /* precise defintion of what constitutes a state change depends on the object. In */ /* the case of sockets, "available to read" is marked whenever new data arrives. */ /* So your code may work fine in testing if the other end of the socket writes more */ /* data between your kqueue calls, but once released into the variety of real world */ /* network situations the code will appear to hang. Be careful! */
33.72973
87
0.662927
[ "object" ]
d3694ab4bc5682bbc2a55624b72f8355c8740e48
1,769
h
C
Sources/Elastos/LibCore/tests/runtime/Reflection/eco/CFooBar.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/tests/runtime/Reflection/eco/CFooBar.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/tests/runtime/Reflection/eco/CFooBar.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 __CFOOBAR_H__ #define __CFOOBAR_H__ #include "_Reflection_CFooBar.h" #include <elastos/core/Object.h> namespace Reflection { CarClass(CFooBar) , public Object , public IFooBar { public: CAR_INTERFACE_DECL() CAR_OBJECT_DECL() CFooBar(); CARAPI constructor(); CARAPI GetValue( /* [out] */ String* str); CARAPI SetValue( /* [in] */ const String& str); CARAPI GetValue( /* [out] */ Int32* value); CARAPI SetValue( /* [in] */ Int32 value); CARAPI GetValue( /* [out] */ Int64* value); CARAPI SetValue( /* [in] */ Int64 value); CARAPI SetValue( /* [in] */ Int32 value0, /* [in] */ const String& str, /* [in] */ Int64 value1); CARAPI GetValue( /* [out] */ Int32* value0, /* [out] */ String* str, /* [out] */ Int64* value1); private: Int32 mValue0; String mString; Int64 mValue1; }; } // Reflection #endif //__CFOOBAR_H__
23.276316
75
0.57264
[ "object" ]
d36cc2ff660a2dbbada627f8f3a1e94719785132
8,002
h
C
src/Emulators/nestopiaue/NestopiaInterface/CDebugInterfaceNes.h
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
34
2021-05-29T07:04:17.000Z
2022-03-10T20:16:03.000Z
src/Emulators/nestopiaue/NestopiaInterface/CDebugInterfaceNes.h
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-25T13:05:21.000Z
2022-01-19T17:35:17.000Z
src/Emulators/nestopiaue/NestopiaInterface/CDebugInterfaceNes.h
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-24T18:37:41.000Z
2022-02-06T23:06:02.000Z
#ifndef _CDebugInterfaceNes_H_ #define _CDebugInterfaceNes_H_ #include "SYS_Defs.h" #include "CDebugInterface.h" #include "CDebugDataAdapter.h" class CImageData; class CViewC64; #define NST_VERSION "1.50" #define C64DEBUGGER_NES_VERSION_STRING NST_VERSION class CAudioChannelNes; class CDebugInterfaceNes : public CDebugInterface { public: CDebugInterfaceNes(CViewC64 *viewC64); //, uint8 *memory); virtual ~CDebugInterfaceNes(); volatile bool isInitialised; virtual int GetEmulatorType(); virtual CSlrString *GetEmulatorVersionString(); virtual const char *GetPlatformNameString(); virtual bool IsPal(); virtual double GetCpuClockFrequency(); virtual float GetEmulationFPS(); virtual void RunEmulationThread(); CAudioChannelNes *audioChannel; CDebugDataAdapter *dataAdapter; CDebugDataAdapter *dataAdapterPpuNmt; CDebugSymbols *symbolsPpuNmt; void RestartEmulation(); // virtual void InitKeyMap(C64KeyMap *keyMap); virtual void RefreshScreenNoCallback(); virtual void DoFrame(); virtual int GetScreenSizeX(); virtual int GetScreenSizeY(); // keyboard & joystick mapper virtual bool KeyboardDown(uint32 mtKeyCode); virtual bool KeyboardUp(uint32 mtKeyCode); virtual void JoystickDown(int port, uint32 axis); virtual void JoystickUp(int port, uint32 axis); virtual void ProcessJoystickEventSynced(int port, u32 axis, u8 buttonState); // this is called by CSnapshotManager to replay events at current cycle virtual void ReplayInputEventsFromSnapshotsManager(CByteBuffer *inputEventsBuffer); // virtual void SetDebugMode(uint8 debugMode); virtual uint8 GetDebugMode(); // virtual void Reset(); virtual void HardReset(); // this is main emulation cpu cycle counter virtual u64 GetMainCpuCycleCounter(); virtual u64 GetPreviousCpuInstructionCycleCounter(); // resettable counters for debug purposes virtual void ResetMainCpuDebugCycleCounter(); virtual u64 GetMainCpuDebugCycleCounter(); virtual bool LoadExecutable(char *fullFilePath); virtual bool MountDisk(char *fullFilePath, int diskNo, bool readOnly); virtual bool InsertCartridge(char *fullFilePath); virtual bool AttachTape(char *fullFilePath, bool readOnly); // virtual bool LoadFullSnapshot(char *filePath); virtual void SaveFullSnapshot(char *filePath); virtual bool LoadChipsSnapshotSynced(CByteBuffer *byteBuffer); virtual bool SaveChipsSnapshotSynced(CByteBuffer *byteBuffer); virtual bool LoadDiskDataSnapshotSynced(CByteBuffer *byteBuffer); virtual bool SaveDiskDataSnapshotSynced(CByteBuffer *byteBuffer); virtual bool IsDriveDirtyForSnapshot(); virtual void ClearDriveDirtyForSnapshotFlag(); // state virtual int GetCpuPC(); virtual void GetWholeMemoryMap(uint8 *buffer); virtual void GetWholeMemoryMapFromRam(uint8 *buffer); // void GetCpuRegs(u16 *PC, u8 *A, u8 *X, u8 *Y, u8 *P, u8 *S, u8 *IRQ); void GetPpuClocks(u32 *hClock, u32 *vClock, u32 *cycle); void SetVideoSystem(u8 videoSystem); void SetMachineType(u8 machineType); virtual void SetByte(uint16 addr, uint8 val); virtual uint8 GetByte(uint16 addr); virtual void GetMemory(uint8 *buffer, int addrStart, int addrEnd); // // make jmp without resetting CPU depending on dataAdapter virtual void MakeJmpNoReset(CDataAdapter *dataAdapter, uint16 addr); // make jmp and reset CPU virtual void MakeJmpAndReset(uint16 addr); virtual CDataAdapter *GetDataAdapter(); // APU virtual void SetApuMuteChannels(int apuNumber, bool mute1, bool mute2, bool mute3, bool mute4, bool mute5, bool muteExt); virtual void SetApuReceiveChannelsData(int apuNumber, bool isReceiving); virtual unsigned char GetApuRegister(u16 addr); virtual unsigned char GetPpuRegister(u16 addr); void ResetClockCounters(); virtual void StepOneCycle(); // virtual uint8 GetByteFromRamC64(uint16 addr); // virtual void MakeJmpC64(uint16 addr); // virtual void MakeJmpNoResetC64(uint16 addr); // virtual void MakeJsrC64(uint16 addr); // // // virtual void MakeBasicRunC64(); // // /// // virtual void SetStackPointerC64(uint8 val); // virtual void SetRegisterAC64(uint8 val); // virtual void SetRegisterXC64(uint8 val); // virtual void SetRegisterYC64(uint8 val); // virtual void SetRegisterPC64(uint8 val); // // /// // virtual void SetStackPointer1541(uint8 val); // virtual void SetRegisterA1541(uint8 val); // virtual void SetRegisterX1541(uint8 val); // virtual void SetRegisterY1541(uint8 val); // virtual void SetRegisterP1541(uint8 val); // // virtual void SetByte1541(uint16 addr, uint8 val); // virtual void SetByteToRam1541(uint16 addr, uint8 val); // virtual uint8 GetByte1541(uint16 addr); // virtual uint8 GetByteFromRam1541(uint16 addr); // virtual void MakeJmp1541(uint16 addr); // virtual void MakeJmpNoReset1541(uint16 addr); // // // memory access for memory map // virtual void GetWholeMemoryMapC64(uint8 *buffer); // virtual void GetWholeMemoryMapFromRamC64(uint8 *buffer); // virtual void GetWholeMemoryMap1541(uint8 *buffer); // virtual void GetWholeMemoryMapFromRam1541(uint8 *buffer); // // virtual void GetMemoryC64(uint8 *buffer, int addrStart, int addrEnd); // virtual void GetMemoryFromRamC64(uint8 *buffer, int addrStart, int addrEnd); // virtual void GetMemoryDrive1541(uint8 *buffer, int addrStart, int addrEnd); // virtual void GetMemoryFromRamDrive1541(uint8 *buffer, int addrStart, int addrEnd); // // virtual void FillC64Ram(uint16 addr, uint16 size, uint8 value); // // virtual void GetVICColors(uint8 *cD021, uint8 *cD022, uint8 *cD023, uint8 *cD025, uint8 *cD026, uint8 *cD027, uint8 *cD800); // virtual void GetVICSpriteColors(uint8 *cD021, uint8 *cD025, uint8 *cD026, uint8 *spriteColors); // virtual void GetCBMColor(uint8 colorNum, uint8 *r, uint8 *g, uint8 *b); // virtual void GetFloatCBMColor(uint8 colorNum, float *r, float *g, float *b); // // virtual bool LoadFullSnapshot(CByteBuffer *snapshotBuffer); // virtual void SaveFullSnapshot(CByteBuffer *snapshotBuffer); // // virtual bool LoadFullSnapshot(char *filePath); // virtual void SaveFullSnapshot(char *filePath); // // virtual void SetDebugMode(uint8 debugMode); // virtual uint8 GetDebugMode(); // // virtual bool IsCpuJam(); // virtual void ForceRunAndUnJamCpu(); // // virtual void AttachCartridge(CSlrString *filePath); // virtual void DetachCartridge(); // virtual void CartridgeFreezeButtonPressed(); // virtual void GetC64CartridgeState(C64StateCartridge *cartridgeState); // // // // virtual void SetVicRegister(uint8 registerNum, uint8 value); // virtual u8 GetVicRegister(uint8 registerNum); // // virtual void SetVicRecordStateMode(uint8 recordMode); // // // render states // virtual void RenderStateVIC(vicii_cycle_state_t *viciiState, // float posX, float posY, float posZ, bool isVertical, bool showSprites, CSlrFont *fontBytes, float fontSize, // std::vector<CImageData *> *spritesImageData, std::vector<CSlrImage *> *spritesImages, bool renderDataWithColors); // void PrintVicInterrupts(uint8 flags, char *buf); // void UpdateVICSpritesImages(vicii_cycle_state_t *viciiState, // std::vector<CImageData *> *spritesImageData, // std::vector<CSlrImage *> *spritesImages, bool renderDataWithColors); // // virtual void RenderStateDrive1541(float posX, float posY, float posZ, CSlrFont *fontBytes, float fontSize, // bool renderVia1, bool renderVia2, bool renderDriveLed, bool isVertical); // virtual void RenderStateCIA(float px, float py, float posZ, CSlrFont *fontBytes, float fontSize, int ciaId); // virtual void RenderStateSID(uint16 sidBase, float posX, float posY, float posZ, CSlrFont *fontBytes, float fontSize); // void PrintSidWaveform(uint8 wave, char *buf); // // // // memory // uint8 *c64memory; // // virtual void SetPatchKernalFastBoot(bool isPatchKernal); // virtual void SetRunSIDWhenInWarp(bool isRunningSIDInWarp); // // // // virtual void SetRunSIDEmulation(bool isSIDEmulationOn); // virtual void SetAudioVolume(float volume); }; extern CDebugInterfaceNes *debugInterfaceNes; #endif
34.791304
127
0.768433
[ "render", "vector" ]
d374ccd239e8cf2c73a61ad8934dd026b7961a3f
3,628
h
C
openmit/entry/entry_ffm.h
openmit/openmit
01e3262d69d47fbe38bad1ba95c7d1ade110d01e
[ "Apache-2.0" ]
15
2017-06-28T08:39:51.000Z
2019-03-27T14:08:45.000Z
openmit/entry/entry_ffm.h
openmit/openmit
01e3262d69d47fbe38bad1ba95c7d1ade110d01e
[ "Apache-2.0" ]
null
null
null
openmit/entry/entry_ffm.h
openmit/openmit
01e3262d69d47fbe38bad1ba95c7d1ade110d01e
[ "Apache-2.0" ]
3
2017-07-30T08:50:45.000Z
2017-10-24T14:41:30.000Z
/*! * Copyright (c) 2017 by Contributors * \file entry_ffm.h * \brief ffm model store unit * \author ZhouYong */ #ifndef OPENMIT_ENTRY_ENTRY_FFM_H_ #define OPENMIT_ENTRY_ENTRY_FFM_H_ #include "openmit/entry/entry.h" namespace mit { /* * \brief field-awared factorization machine model store unit */ struct FFMEntry : Entry { /*! \brief length of latent vector */ size_t embedding_size; /*! \brief field id */ mit_uint fieldid; /*! \brief constructor */ FFMEntry(const mit::ModelParam& model_param, mit::EntryMeta* entry_meta, mit::math::Random* random, mit_uint field = 0l); /*! \brief destructor */ ~FFMEntry() {} /*! \brief string format entry info */ std::string String(mit::EntryMeta* entry_meta = NULL) override; /*! \brief save entry */ void Save(dmlc::Stream* fo, mit::EntryMeta* entry_meta = NULL) override; /*! \brief save entry */ void Load(dmlc::Stream* fi, mit::EntryMeta* entry_meta = NULL) override; }; // struct FFMEntry FFMEntry::FFMEntry(const mit::ModelParam& model_param, mit::EntryMeta* entry_meta, mit::math::Random* random, mit_uint field) { embedding_size = model_param.embedding_size; CHECK(embedding_size > 0) << "embedding_size error for fm/ffm model."; fieldid = field; length = 1; if (fieldid > 0) { std::vector<mit_uint>* rfields = entry_meta->CombineInfo(field); size_t rfield_cnt = 0; if (rfields) { rfield_cnt += rfields->size(); length += rfield_cnt * embedding_size; } } wv = new mit_float[length](); for (auto idx = 0u; idx < length; ++idx) { wv[idx] = random->random(); } } // FFMEntry std::string FFMEntry::String(mit::EntryMeta* entry_meta) { CHECK_NOTNULL(entry_meta); std::string info = std::to_string(*wv); if (length == 1) return info; auto* rfields = entry_meta->CombineInfo(fieldid); if (!rfields) return info; for (auto i = 0u; i < rfields->size(); ++i) { auto idx_begin = 1 + i * embedding_size; info += " " + std::to_string((*rfields)[i]); info += ":" + std::to_string(wv[idx_begin + 0]); for (auto k = 1u; k < embedding_size; ++k) { info += "," + std::to_string(wv[idx_begin + k]); } } return info; } // FFMEntry::String void FFMEntry::Save(dmlc::Stream* fo, mit::EntryMeta* entry_meta) { fo->Write((char *) &fieldid, sizeof(mit_uint)); fo->Write((char *) &embedding_size, sizeof(size_t)); fo->Write((char *) &wv[0], sizeof(mit_float)); auto* rfields = entry_meta->CombineInfo(fieldid); if (!rfields) return; for (auto i = 0u; i < rfields->size(); ++i) { auto offset_begin = 1 + i * embedding_size; mit_uint rfid = (*rfields)[i]; fo->Write((char *) &rfid, sizeof(mit_uint)); for (size_t k = 0; k < embedding_size; ++k) { mit_float v = wv[offset_begin + k]; fo->Write((char *) &v, sizeof(mit_float)); } } } // FFMEntry::Save void FFMEntry::Load(dmlc::Stream* fi, mit::EntryMeta* entry_meta) { fi->Read(&fieldid, sizeof(mit_uint)); fi->Read(&embedding_size, sizeof(size_t)); fi->Read(&wv[0], sizeof(mit_float)); auto* rfields = entry_meta->CombineInfo(fieldid); if (!rfields) return; size_t offset = 1; for (auto i = 0u; i < rfields->size(); ++i) { mit_uint rfid; fi->Read(&rfid, sizeof(mit_uint)); CHECK_EQ(rfid, (*rfields)[i]) << "related fielid not match"; for (size_t k = 0; k < embedding_size; ++k) { fi->Read(&wv[offset], sizeof(mit_float)); offset++; } } } // FFMEntry::Load } // namespace mit #endif // OPENMIT_ENTRY_ENTRY_FFM_H_
30.487395
74
0.622933
[ "vector", "model" ]
d3795adf53d4a2ec4021a3946197433d16976e88
3,149
h
C
src/tracer/path_tracer.h
JakMobius/zeta_path_tracer
f17ac4e882319c6dd7dff545f7f1e1bf9cb045e1
[ "MIT" ]
3
2021-09-13T14:41:22.000Z
2021-09-18T07:59:15.000Z
src/tracer/path_tracer.h
JakMobius/zeta_path_tracer
f17ac4e882319c6dd7dff545f7f1e1bf9cb045e1
[ "MIT" ]
2
2021-03-26T15:04:54.000Z
2021-09-13T13:20:59.000Z
src/tracer/path_tracer.h
JakMobius/zeta_path_tracer
f17ac4e882319c6dd7dff545f7f1e1bf9cb045e1
[ "MIT" ]
3
2021-03-23T22:42:43.000Z
2021-12-18T21:58:58.000Z
#ifndef PATH_TRACER #define PATH_TRACER #include <cstdio> #include <vector> #include "utils/vec3d.h" #include "utils/ray.h" #include "color/color.h" #include "utils/progress_bar.h" #include "hits/hittable.h" #include "hits/hittable_list.h" #include "hits/hit_record.h" #include "camera_light_scene/scene.h" #include "acceleration_structures/bvh.h" #include "render_task.h" #include <thread> #include <cstring> #include <unistd.h> // extern const double AMBIENT; // extern const Vec3d BACKGROUND; struct conf_Render { int SCREEN_WIDTH; int SCREEN_HEIGHT; int MAX_TRACE_DEPTH; int PIXEL_SAMPLING; double GAMMA_CORRECTION; Vec3d BACKGROUND_COLOR; conf_Render(const int screen_width, const int screen_height, const int max_tracing_depth, const int pixel_sampling, const double gamma_correction, const Vec3d background_color); }; struct conf_Verbosity { int VERBOSITY; conf_Verbosity(const int verbosity); }; struct conf_SystemInfo { int timestamp; int kernel_cnt; const char *rtask_filename; bool to_rewrire_rtask_file; conf_SystemInfo(const int timestamp_, const int kernel_cnt_, const char *rtask_filename_, const bool to_rewrire_rtask_file_=false); }; struct conf_PathTracer { conf_Render render; conf_Verbosity verbos; conf_SystemInfo sysinf; conf_PathTracer(const conf_Render &render_config, const conf_Verbosity &verbos_config, const conf_SystemInfo &sysinf_config); inline void update_from_command_line_args(int argc, char* argv[]) { extern char *optarg; while (true) { switch(getopt(argc, argv, "k:t:v:R")) { case '?': case 'h': default: printf("run ./pather -k #threads-count -t #render-task-file\n"); printf("use -t only if you understand what it does\n"); break; case -1: break; case 'k': sscanf(optarg, "%d", &sysinf.kernel_cnt); continue; case 't': sysinf.rtask_filename = strdup(optarg); continue; case 'R': sysinf.to_rewrire_rtask_file = true; continue; } break; } } }; // Intersection test_ray(Ray &ray, const vector<Hittable*> &objects, const Hittable *to_ignore); Vec3d trace_ray(Ray &ray, const Hittable *hittable, const conf_PathTracer &config, const int cur_trace_depth = 1); Vec3d trace_ray(Ray &ray, const Hittable *hittable, const conf_PathTracer &config, const int cur_trace_depth, Vec3d *normal_vec, double *depth); Vec3d accumulate_pixel_color(const Camera *camera, const int px_x, const int px_y, const Hittable *hittable, const conf_PathTracer &config, Vec3d *normal_vec = nullptr, double *depth = nullptr); void render_image (Scene *scene, const conf_PathTracer &config); void render_into_buffer (Scene *scene, const conf_PathTracer &config, Color *buffer); void render_into_buffer (Scene *scene, const conf_PathTracer &config, Color *buffer, Vec3d *normal_map, double *depth_map); void render_rtask (Scene *scene, const conf_PathTracer &config, const RenderTask rtask, Color *buffer, const int verbouse = 1); void render_from_rtask_file(Scene *scene, const conf_PathTracer &config); #endif // PATH_TRACER
26.462185
136
0.731026
[ "render", "vector" ]
d3897f72634cd3883cceadfaaafba3a4e53998d5
13,930
c
C
server.c
aydanurakca/Socket-Programming
c8586e73393ceef7a48ca275b1e943b39edee2b2
[ "MIT" ]
5
2021-02-26T18:36:52.000Z
2021-04-11T14:03:11.000Z
server.c
aydanurakca/Socket-Programming
c8586e73393ceef7a48ca275b1e943b39edee2b2
[ "MIT" ]
null
null
null
server.c
aydanurakca/Socket-Programming
c8586e73393ceef7a48ca275b1e943b39edee2b2
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> // for inet_addr #include <unistd.h> #include <pthread.h> #include "json.h" //json.h and json.c are the libraries that i use to parse JSON object. The makefile and these two documents are also uploaded to Sakai and Github. To execute the program I need them to be in the same folder. #include "json.c" //The library is founded from Github. #define MAX_GROUP 15 //MAX NUMBER OF GROUPS IS 15. #define GROUP_CAPACITY 15 //CAPACITY OF EACH GROUP IS 15. #define PORT_NO 3205 //PORT NO IS 3205. typedef struct UserStr //USER STRUCT { char phoneNumber[10]; char groupName[100]; int groupNumber; int socketNo; int index; } USER; typedef struct GroupStr //GROUP STRUCT { char name[100]; char password[100]; USER Users[GROUP_CAPACITY]; USER owner; int userCount; } GROUP; GROUP Groups[MAX_GROUP]; int groupCount = 0; void groupReset(int i) //This function resets the given group and its properties. { Groups[i].userCount = 0; strcpy(Groups[i].name, ""); strcpy(Groups[i].password, ""); for (int j = 0; j < MAX_GROUP; j++) { strcpy(Groups[i].Users[j].phoneNumber, ""); strcpy(Groups[i].Users[j].groupName, ""); Groups[i].Users[j].socketNo = -1; Groups[i].Users[j].index = -1; } } int createGroup(USER *user, char *GroupName) //This function creates the group. { if (groupCount < MAX_GROUP) { for (int i = 0; i < MAX_GROUP; i++) { if (Groups[i].userCount == 0) //An empty index from Groups array is found. All the properties of groups are filled. { Groups[i].userCount++; strcpy(user->groupName, GroupName); strcpy(Groups[i].name, GroupName); strcpy(Groups[i].owner.phoneNumber, user->phoneNumber); user->groupNumber = i; user->index = 0; Groups[i].Users[0] = *user; char message[100]; strcpy(message, "Please enter group password:"); send(user->socketNo, message, strlen(message), 0); recv(user->socketNo, Groups[i].password, 100, 0); char *msg = "Group is created.\n"; send(user->socketNo, msg, strlen(msg), 0); groupCount++; char gname[100]; //That block sends the groupname to clientside to use it later. sprintf(gname, "-gname***%s", GroupName); send(user->socketNo, gname, 100, 0); break; } } } } void sendMessageToGroup(USER *user, char* from, char* to, char *message) { if((strcmp(from, user->phoneNumber) == 0) && (strcmp(to, user->groupName) == 0)){ //Controls if the given properties fit to the ones that is stored. If the group names and phone numbers are same, it sends. char msg[200]; char msg2[200]; strcpy(msg, user->phoneNumber); strcat(msg, ": "); strcat(msg, message); strcpy(msg2, "You: "); strcat(msg2, message); for (int i = 0; i < MAX_GROUP; i++) { if (Groups[user->groupNumber].Users[i].socketNo != user->socketNo && Groups[user->groupNumber].Users[i].socketNo != -1) //For the other users in the group. { send(Groups[user->groupNumber].Users[i].socketNo, msg, strlen(msg), 0); } else if (Groups[user->groupNumber].Users[i].socketNo == user->socketNo) //For the sender to make them see their message. { send(Groups[user->groupNumber].Users[i].socketNo, msg2, strlen(msg2), 0); } } } } void joinGroup(USER *user, char *group) { int isGroupExist = -1; int entrance = -1; char groupn[100]; for (int i = 0; i < MAX_GROUP; i++) { if ((strcmp(Groups[i].name, group) == 0) || (strcmp(Groups[i].owner.phoneNumber, group) == 0)) //Users can join to the group with owner's phone number or the group name. { isGroupExist = 1; if (Groups[i].userCount < GROUP_CAPACITY) { char message[100]; char temp[100]; strcpy(message, "This group is private. Please enter the password:"); //Each group is private. Password is needed. send(user->socketNo, message, strlen(message), 0); recv(user->socketNo, temp, 100, 0); if (strcmp(Groups[i].password, temp) == 0) { entrance = 1; } else { strcpy(message, "Password is incorrect."); send(user->socketNo, message, strlen(message), 0); } if (entrance == 1) { for (int j = 0; j < GROUP_CAPACITY; j++) { if (Groups[i].Users[j].socketNo == -1) { user->groupNumber = i; user->index = j; strcpy(user->groupName, Groups[i].name); Groups[i].userCount++; Groups[i].Users[j] = *user; char message[100]; strcpy(message, "You the entered the group."); send(user->socketNo, message, strlen(message), 0); if(strcmp(Groups[i].name, group) == 0){ //Groupname is sent to the client to use it later. sprintf(groupn, "-gname***%s", group); send(user->socketNo, groupn, 100, 0); } else if(strcmp(Groups[i].owner.phoneNumber, group) == 0){ sprintf(groupn, "-gname***%s", Groups[i].name); send(user->socketNo, groupn, 100, 0); } memset(groupn,"",sizeof(groupn)); //To clear the array. break; } } } } else //if the group is full { char *msg = "This group is full.\n"; send(user->socketNo, msg, strlen(msg), 0); break; } } } if(isGroupExist == -1) //There is no group with this name. { char *msg = "No such a group with that name.\n"; send(user->socketNo, msg, strlen(msg), 0); } } void *connection(void *socket_desc) { int socket = *((int *)socket_desc); char usr[100]; char username[100]; USER user; user.socketNo = socket; user.groupNumber = -1; char message[200] = "Please enter your phone number :"; //Phone number of the user is taken. send(socket, message, strlen(message), 0); recv(socket, user.phoneNumber, 100, 0); strcpy(usr, user.phoneNumber); sprintf(username, "-username %s", usr); //Phone number is sent to the client to use it later. send(socket, username, 100, 0); while (socket != -1) //This iteration goes on until the socket is -1. { char msg[100] = ""; char temp[100] = ""; char *temp1; recv(socket, msg, 100, 0); puts(msg); strcpy(temp, msg); char *token = (char *)malloc(100 * sizeof(char)); char *phoneNumber = (char *)malloc(100 * sizeof(char)); char *groupName = (char *)malloc(100 * sizeof(char)); if (strcmp(msg, "-exit") == 0) { socket = -1; strcpy(message, "You exit the program.\n"); free(socket_desc); send(user.socketNo, message, strlen(message), 0); } token = strtok(temp, " "); if ((strcmp(token, "-gcreate") == 0 && strlen(msg) > 8)) { if (user.groupNumber == -1) //The user has no groups yet { temp1 = strstr(msg, " "); temp1 = temp1 + 1; strcpy(groupName, temp1); phoneNumber = strtok(temp1, "+"); if (strcmp(phoneNumber, user.phoneNumber) == 0) { groupName = strtok(NULL, "+"); createGroup(&user, groupName); } else { strcpy(message, "Please enter your phone number correctly!\n"); send(socket, message, strlen(message), 0); } } else { strcpy(message, "You have already joined to another group... You cannot create another group.\n"); send(socket, message, strlen(message), 0); } } else if ((strcmp(token, "-gcreate") == 0)) { strcpy(message, "Please enter a group name.\n"); send(socket, message, strlen(message), 0); } else if (strcmp(token, "-join") == 0) { if (strlen(msg) > 5) { if (user.groupNumber == -1) //This means the user is not in any group. { temp1 = strstr(msg, " "); temp1 = temp1 + 1; joinGroup(&user, temp1); } else { strcpy(message, "You have already joined the group.\n"); send(socket, message, strlen(message), 0); } } } else if (strcmp(token, "-send") == 0) { if (user.groupNumber > -1) { if (strlen(msg) > 5) //There is a message { temp1 = strstr(msg, " "); temp1 = temp1 + 1; char string[100]; JSONObject *jsonMessage = parseJSON(temp1); //This is a library function. sendMessageToGroup(&user, jsonMessage ->pairs[0].value ->stringValue, jsonMessage ->pairs[1].value ->stringValue, jsonMessage ->pairs[2].value ->stringValue); //from, to, and messages are parsed from the JSON. } else { strcpy(message, "Please enter your message:\n"); send(socket, message, strlen(message), 0); } } } else if (strcmp(token, "-exit") == 0) //This is the command -exit groupName, not the exit from the program. { if (strlen(msg) > 5) { token = strstr(msg, " "); token = token + 1; if (user.groupNumber == -1) //User doesnt have any group, so they cannot leave. { strcpy(message, "You haven't joined any group.\n"); send(socket, message, strlen(message), 0); } else if (strstr(user.groupName, token) != NULL) { Groups[user.groupNumber].userCount--; //This user is leaving, count is decreased. if (Groups[user.groupNumber].userCount != 0) { USER tempUser; Groups[user.groupNumber].Users[user.index] = tempUser; Groups[user.groupNumber].Users[user.index].socketNo = -1; } else //If nobody left in the group, group is deleted. { groupReset(user.groupNumber); groupCount--; } user.groupNumber = -1; user.index = -1; strcpy(user.groupName, ""); strcpy(message, "You quit the group\n"); send(socket, message, strlen(message), 0); char temp4[100]; sprintf(temp4, "-gname***no_group"); send(socket, temp4, 100, 0); } else { strcpy(message, "Wrong group name...\n"); send(socket, message, strlen(message), 0); } } else { strcpy(message, "Please enter group name....\n"); send(socket, message, strlen(message), 0); } } } return 0; } int main(int argc, char *argv[]) { for (int i = 0; i < MAX_GROUP; i++) { groupReset(i); } int socket_desc, new_socket, c, *new_sock; struct sockaddr_in server, client; char *message; socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc == -1) { puts("Could not create socket"); return 1; } server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(PORT_NO); if (bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) { puts("Binding failed"); return 1; } listen(socket_desc, 100); c = sizeof(struct sockaddr_in); while ((new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t *)&c))) { int socket_des = new_socket; puts("Connection accepted"); message = "Welcome to DEU Signal!\n"; write(new_socket, message, strlen(message)); pthread_t sniffer; new_sock = malloc(1); *new_sock = new_socket; if (pthread_create(&sniffer, NULL, connection, (void *)new_sock) < 0) { puts("Could not create thread"); return 1; } } return 0; }
36.465969
229
0.48392
[ "object" ]
d3903e8ec772d6fa3cced1d5834248512e36af75
465
h
C
src/Vehicle.h
julianste/car-path-planning
83ee536997a20b38f0b40364b6a30e765b9a65fb
[ "MIT" ]
4
2019-08-27T10:31:28.000Z
2022-02-18T06:16:16.000Z
src/Vehicle.h
julianste/car-path-planning
83ee536997a20b38f0b40364b6a30e765b9a65fb
[ "MIT" ]
null
null
null
src/Vehicle.h
julianste/car-path-planning
83ee536997a20b38f0b40364b6a30e765b9a65fb
[ "MIT" ]
null
null
null
#ifndef VEHICLE_H #define VEHICLE_H #include <map> #include <string> #include <vector> using std::map; using std::string; using std::vector; class Vehicle { public: // Constructors Vehicle(); Vehicle(int id, double x, double y, double vx, double vy, double s, double d); // Destructor virtual ~Vehicle(); void updateVehicle(double x, double y, double vx, double vy, double s, double d); int id; float x,y,vx,vy,s,d; }; #endif // VEHICLE_H
16.034483
83
0.677419
[ "vector" ]
d39a7561185434bd3a33450424a01cdcbb67517c
341
h
C
CommonUtils/Classes/Serilizer/CommonSerilizer.h
klusinyan/CommonUtils
c627f3a0ed49cd78f5a5ac7082bfa2b4bef69adc
[ "MIT" ]
1
2016-10-18T15:39:32.000Z
2016-10-18T15:39:32.000Z
CommonUtils/Classes/Serilizer/CommonSerilizer.h
klusinyan/CommonUtils
c627f3a0ed49cd78f5a5ac7082bfa2b4bef69adc
[ "MIT" ]
null
null
null
CommonUtils/Classes/Serilizer/CommonSerilizer.h
klusinyan/CommonUtils
c627f3a0ed49cd78f5a5ac7082bfa2b4bef69adc
[ "MIT" ]
null
null
null
// Created by Karen Lusinyan on 12/03/15. // Copyright (c) 2015 Karen Lusinyan. All rights reserved. @interface CommonSerilizer : NSObject + (id)loadObjectForKey:(NSString *)key; + (void)saveObject:(id)object forKey:(NSString *)key; + (void)removeObjectForKey:(id)key; + (NSDictionary *)dictionaryFromObject:(NSObject *)object; @end
22.733333
59
0.733138
[ "object" ]
d39e4459b2e32d95420326cccaee1fc5952e124c
45,286
c
C
sdk/core/humber/src/sys/mpls/sys_humber_mpls.c
CentecNetworks/Lantern
a32604a1df796a550bf6ffa5ded63020b875658e
[ "Apache-2.0" ]
55
2015-01-20T00:09:45.000Z
2021-08-19T05:40:27.000Z
sdk/core/humber/src/sys/mpls/sys_humber_mpls.c
hehehexdc/Lantern
a32604a1df796a550bf6ffa5ded63020b875658e
[ "Apache-2.0" ]
1
2017-04-22T18:17:57.000Z
2017-09-15T11:28:26.000Z
sdk/core/humber/src/sys/mpls/sys_humber_mpls.c
hehehexdc/Lantern
a32604a1df796a550bf6ffa5ded63020b875658e
[ "Apache-2.0" ]
36
2015-02-13T00:58:22.000Z
2021-08-19T08:08:07.000Z
/** @file sys_humber_mpls.c @date 2010-03-12 @version v2.0 The file contains all mpls related function */ /**************************************************************************** * * Header Files * ****************************************************************************/ #include "ctc_const.h" #include "ctc_error.h" #include "ctc_mpls.h" #include "ctc_vector.h" #include "drv_humber.h" #include "drv_io.h" #include "sys_humber_chip.h" #include "sys_humber_usrid.h" #include "sys_humber_mpls.h" #include "sys_humber_nexthop_api.h" #include "sys_humber_queue_api.h" #include "sys_humber_ftm.h" #include "sys_humber_usrid.h" #include "sys_humber_vlan.h" #include "sys_humber_nexthop.h" #include "ctc_stats.h" #include "sys_humber_stats.h" /**************************************************************************** * * Global and Declaration * *****************************************************************************/ sys_mpls_master_t *p_mpls_master = NULL; #define SYS_MPLS_CREAT_LOCK \ { \ kal_mutex_create(&p_mpls_master->mutex); \ if(NULL == p_mpls_master->mutex) \ { \ CTC_ERROR_RETURN(CTC_E_FAIL_CREATE_MUTEX); \ } \ } #define SYS_MPLS_LOCK \ kal_mutex_lock(p_mpls_master->mutex) #define SYS_MPLS_UNLOCK \ kal_mutex_unlock(p_mpls_master->mutex) #define CTC_ERROR_RETURN_MPLS_UNLOCK(op) \ { \ int32 rv = (op); \ if (rv < 0) \ { \ kal_mutex_unlock(p_mpls_master->mutex);\ return rv; \ } \ } #define CTC_RETURN_MPLS_UNLOCK(op) \ { \ kal_mutex_unlock(p_mpls_master->mutex);\ return(op); \ } static int32 _sys_humber_mpls_ilm_normal(sys_mpls_ilm_t* p_ilm_info, void* mpls) { ds_mpls_t *dsmpls = mpls; if(p_ilm_info->pop) { dsmpls->scontinue = TRUE; } dsmpls->offset_bytes = 1; dsmpls->equal_cost_path_num10 = p_ilm_info->ecpn & 0x3; dsmpls->equal_cost_path_num2 = p_ilm_info->ecpn >> 2 & 0x1; if(CTC_MPLS_TUNNEL_MODE_UNIFORM != p_ilm_info->model) { dsmpls->use_label_ttl = TRUE; } dsmpls->use_label_exp = TRUE; dsmpls->over_write_priority = TRUE; dsmpls->packet_type = PKT_TYPE_IPV4; return CTC_E_NONE; } static int32 _sys_humber_mpls_ilm_l3vpn(sys_mpls_ilm_t* p_ilm_info, void* mpls) { ds_mpls_t *dsmpls = mpls; dsmpls->offset_bytes = 1; dsmpls->is_vc_label = TRUE; dsmpls->sbit = TRUE; dsmpls->s_bit_check_en = TRUE; if(CTC_MPLS_TUNNEL_MODE_UNIFORM != p_ilm_info->model) { dsmpls->use_label_ttl = TRUE; } dsmpls->use_label_exp = TRUE; dsmpls->over_write_priority = TRUE; dsmpls->packet_type = PKT_TYPE_IPV4; return CTC_E_NONE; } static int32 _sys_humber_mpls_ilm_vpws(sys_mpls_ilm_t* p_ilm_info, void* mpls) { ds_mpls_t *dsmpls = mpls; sys_nh_info_com_t* p_nhinfo; uint8 iloop_flag = 0; dsmpls->is_vc_label = TRUE; dsmpls->sbit = TRUE; dsmpls->s_bit_check_en = TRUE; if(p_ilm_info->id_type == CTC_MPLS_ID_SERVICE) { CTC_ERROR_RETURN(sys_humber_nh_get_nhinfo_by_nhid(p_ilm_info->nh_id, &p_nhinfo)); if(p_nhinfo->hdr.nh_entry_type == SYS_HUMBER_NH_TYPE_ILOOP) { iloop_flag = 1; } /* vpls source port, should be invalid 0xfff */ dsmpls->ttl_threshhold = 0x7f; dsmpls->equal_cost_path_num2 = 0x1; dsmpls->equal_cost_path_num10 = 0x3; dsmpls->priority_path_en = 0x1; dsmpls->ttl_decrease_mode = 0x1; } if(iloop_flag == 1) { dsmpls->offset_bytes = 0; } else if (p_ilm_info->cwen) { dsmpls->offset_bytes = 2; } else { dsmpls->offset_bytes = 1; } dsmpls->use_label_ttl = TRUE; dsmpls->use_label_exp = TRUE; dsmpls->over_write_priority = TRUE; dsmpls->packet_type = PKT_TYPE_ETH; return CTC_E_NONE; } static int32 _sys_humber_mpls_ilm_vpls(sys_mpls_ilm_t* p_ilm_info, void* mpls) { ds_mpls_t* dsmpls = mpls; dsmpls->is_vc_label = TRUE; dsmpls->sbit = TRUE; dsmpls->s_bit_check_en = TRUE; if(p_ilm_info->pwid <= SYS_MPLS_VPLS_SRC_PORT_NUM) { /* vpls source port, namely pwid*/ dsmpls->ttl_threshhold = p_ilm_info->pwid & 0x7f; dsmpls->equal_cost_path_num2 = (p_ilm_info->pwid >> 7) & 0x1; dsmpls->equal_cost_path_num10 = (p_ilm_info->pwid >> 8) & 0x3; dsmpls->priority_path_en = (p_ilm_info->pwid >> 10) & 0x1; dsmpls->ttl_decrease_mode = (p_ilm_info->pwid >> 11) & 0x1; } dsmpls->offset_bytes = 0; dsmpls->use_label_ttl = TRUE; dsmpls->use_label_exp = TRUE; dsmpls->over_write_priority = TRUE; dsmpls->packet_type = PKT_TYPE_ETH; return CTC_E_NONE; } static int32 _sys_humber_mpls_write_ilm(sys_mpls_ilm_t* p_mpls_info, sys_nh_offset_array_t fwd_offset) { ds_mpls_t dsmpls; uint8 chip_num; uint8 i; uint32 cmd; kal_memset(&dsmpls, 0, sizeof(ds_mpls_t)); /* flow policer ptr */ if(p_mpls_info->id_type == CTC_MPLS_ID_APS_SELECT) { dsmpls.aps_select_valid = 1; dsmpls.flow_policer_ptr7to0 = p_mpls_info->aps_group_id & 0xff; dsmpls.flow_policer_ptr10to8 = (p_mpls_info->aps_group_id >> 8) & 0x7; dsmpls.flow_policer_ptr11 = (p_mpls_info->aps_group_id >> 11) & 0x1; dsmpls.flow_policer_ptr15to12 = (p_mpls_info->aps_group_id >> 12) & 0x3; dsmpls.flow_policer_ptr15to12 |= 0x4; if(p_mpls_info->aps_select_ppath) { dsmpls.flow_policer_ptr15to12 |= 0x8; } } else if (p_mpls_info->id_type == CTC_MPLS_ID_FLOW) { extern int32 sys_humber_qos_policer_index_get(uint8 lchip, uint32 plc_id, uint32* p_index); uint32 policer_ptr; CTC_ERROR_RETURN(sys_humber_qos_policer_index_get(0, p_mpls_info->flw_vrf_srv, &policer_ptr)); dsmpls.flow_policer_ptr7to0 = policer_ptr & 0xff; dsmpls.flow_policer_ptr10to8 = (policer_ptr >> 8) & 0x7; dsmpls.flow_policer_ptr11 = (policer_ptr >> 11) & 0x1; dsmpls.flow_policer_ptr15to12 = (policer_ptr >> 12) & 0xf; } else { dsmpls.flow_policer_ptr7to0 = p_mpls_info->flw_vrf_srv & 0xff; dsmpls.flow_policer_ptr10to8 = (p_mpls_info->flw_vrf_srv >> 8) & 0x7; dsmpls.flow_policer_ptr11 = (p_mpls_info->flw_vrf_srv >> 11) & 0x1; dsmpls.flow_policer_ptr15to12 = (p_mpls_info->flw_vrf_srv >> 12) & 0xf; } if (p_mpls_info->type != CTC_MPLS_LABEL_TYPE_NORMAL) { //vc label if (p_mpls_info->cwen) { dsmpls.ttl_check_mode = 1; /* control word exist */ } if (p_mpls_info->id_type == CTC_MPLS_ID_VRF || p_mpls_info->id_type == CTC_MPLS_ID_SERVICE || ((p_mpls_info->type == CTC_MPLS_LABEL_TYPE_VPLS || p_mpls_info->type == CTC_MPLS_LABEL_TYPE_VPWS) && p_mpls_info->pwid <= SYS_MPLS_VPLS_SRC_PORT_NUM)) { dsmpls.ttl_check_mode |= (1<<1); } } else { //normal dsmpls.ttl_check_mode = (1<<1); //only support global ttl check } dsmpls.oam_check = (p_mpls_info->oam_en) ? TRUE : FALSE; p_mpls_master->write_ilm[p_mpls_info->type](p_mpls_info, &dsmpls); chip_num = sys_humber_get_local_chip_num(); cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); for(i = 0; i < chip_num; i++) { dsmpls.ds_fwd_ptr = fwd_offset[i] & 0xfffff; CTC_ERROR_RETURN(drv_tbl_ioctl(i, p_mpls_info->key_offset, cmd, &dsmpls)); } return CTC_E_NONE; } static int32 _sys_humber_mpls_remove_ilm(sys_mpls_ilm_t* p_mpls_info) { ds_mpls_t dsmpls; uint8 chip_num; uint8 i; uint32 cmd; kal_memset(&dsmpls, 0, sizeof(ds_mpls_t)); dsmpls.flow_policer_ptr7to0 = 0xff; dsmpls.flow_policer_ptr10to8 = 0x7; dsmpls.flow_policer_ptr11 = 0x1; dsmpls.flow_policer_ptr15to12 = 0xf; dsmpls.ds_fwd_ptr = 0xfffff; chip_num = sys_humber_get_local_chip_num(); cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); for(i = 0; i < chip_num; i++) { drv_tbl_ioctl(i, p_mpls_info->key_offset, cmd, &dsmpls); } return CTC_E_NONE; } /** @brief function of lookup mpls ilm information @param[in] pp_mpls_info, information used for lookup mpls ilm entry @param[out] pp_mpls_info, information of mpls ilm entry finded @return CTC_E_XXX */ static int32 _sys_humber_mpls_db_lookup(sys_mpls_ilm_t** pp_mpls_info) { sys_mpls_ilm_t* p_mpls_info; uint32 offset = (*pp_mpls_info)->label; /* get mpls entry index */ if((*pp_mpls_info)->spaceid) { offset -= p_mpls_master->min_int_label; } p_mpls_info = ctc_vector_get(p_mpls_master->space[(*pp_mpls_info)->spaceid].p_vet, offset); *pp_mpls_info = p_mpls_info; return CTC_E_NONE; } /** @brief function of add mpls ilm information @param[in] p_mpls_info, information should be maintained for mpls @return CTC_E_XXX */ static int32 _sys_humber_mpls_db_add(sys_mpls_ilm_t* p_mpls_info) { uint32 offset = p_mpls_info->label; /* get mpls entry index */ if(p_mpls_info->spaceid) { offset -= p_mpls_master->min_int_label; } p_mpls_info->key_offset = p_mpls_master->space[p_mpls_info->spaceid].base + offset; CTC_ERROR_RETURN(ctc_vector_add(p_mpls_master->space[p_mpls_info->spaceid].p_vet, offset, p_mpls_info)); return CTC_E_NONE; } /** @brief function of remove mpls ilm information @param[in] p_ipuc_info, information maintained by mpls @return CTC_E_XXX */ static int32 _sys_humber_mpls_db_remove(sys_mpls_ilm_t* p_mpls_info) { uint32 offset = p_mpls_info->label; /* get mpls entry index */ if(p_mpls_info->spaceid) { offset -= p_mpls_master->min_int_label; } ctc_vector_del(p_mpls_master->space[p_mpls_info->spaceid].p_vet, offset); return CTC_E_NONE; } /** @brief function of add mpls ilm entry @param[in] p_mpls_ilm, parameters used to add mpls ilm entry @return CTC_E_XXX */ int32 sys_humber_mpls_add_ilm(ctc_mpls_ilm_t* p_mpls_ilm) { sys_mpls_ilm_t *p_ilm_data, ilm_data; int32 ret; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(p_mpls_ilm); SYS_MPLS_NHID_EXTERNAL_VALID_CHECK(p_mpls_ilm->nh_id); SYS_MPLS_ILM_SPACE_CHECK(p_mpls_ilm->spaceid); SYS_MPLS_ILM_LABEL_CHECK(p_mpls_ilm->spaceid, p_mpls_ilm->label); SYS_MPLS_ILM_DATA_CHECK(p_mpls_ilm); SYS_MPLS_ILM_DATA_MASK(p_mpls_ilm); if(p_mpls_ilm->id_type == CTC_MPLS_ID_SERVICE) { CTC_ERROR_RETURN(sys_humber_get_physical_service_id(p_mpls_ilm->flw_vrf_srv_aps.service_id, &p_mpls_ilm->flw_vrf_srv_aps.service_id)); p_mpls_ilm->flw_vrf_srv_aps.service_id |= 0xC000; } /* prepare data */ p_ilm_data = &ilm_data; SYS_MPLS_KEY_MAP(p_mpls_ilm, p_ilm_data); SYS_MPLS_LOCK; /* lookup for mpls entrise */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(p_ilm_data) /* ilm have exist */ { sys_nh_param_ecmp_api_t nh_param; /* VC label must not do ecmp */ if(p_ilm_data->type != CTC_MPLS_LABEL_TYPE_NORMAL) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_EXIST); } if(p_ilm_data->id_type != p_mpls_ilm->id_type) { CTC_ERROR_RETURN_MPLS_UNLOCK(CTC_E_UNEXPECT); } if(p_ilm_data->ecpn >= CTC_MAX_ECPN - 1) { /* ecmp number exceed */ CTC_RETURN_MPLS_UNLOCK(CTC_E_EXCEED_MAX_SIZE); } if(p_ilm_data->nh_id == p_mpls_ilm->nh_id) { /* this ilm have installed */ CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_EXIST); } kal_memset(&nh_param, 0, sizeof(sys_nh_param_ecmp_api_t)); nh_param.ref_nh_id = p_mpls_ilm->nh_id; if(p_ilm_data->ecpn == 0) { CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_ecmp_nh_create(&nh_param, &p_ilm_data->nh_id)); } else { nh_param.change_type = SYS_NH_CHANGE_TYPE_ECMP_ADD_ITEM; CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_ecmp_nh_update(p_ilm_data->nh_id, &nh_param)); } p_ilm_data->ecpn++; switch(p_mpls_ilm->id_type) { case CTC_MPLS_ID_FLOW: p_ilm_data->flw_vrf_srv = p_mpls_ilm->flw_vrf_srv_aps.flow_id; break; case CTC_MPLS_ID_VRF: p_ilm_data->flw_vrf_srv = p_mpls_ilm->flw_vrf_srv_aps.vrf_id; break; case CTC_MPLS_ID_SERVICE: p_ilm_data->flw_vrf_srv = p_mpls_ilm->flw_vrf_srv_aps.service_id; break; case CTC_MPLS_ID_APS_SELECT: p_ilm_data->aps_group_id = p_mpls_ilm->flw_vrf_srv_aps.aps_select_grp_id; p_ilm_data->aps_select_ppath = p_mpls_ilm->aps_select_protect_path; break; default: p_ilm_data->flw_vrf_srv = 0xffff; break; } /* write mpls ilm entry */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_write_ilm(p_ilm_data, nh_param.fwd_offset)); } else { sys_nh_offset_array_t fwd_offset; SYS_MPLS_UNLOCK; CTC_ERROR_RETURN(sys_humber_nh_get_dsfwd_offset(p_mpls_ilm->nh_id, fwd_offset)); p_ilm_data = mem_malloc(MEM_MPLS_MODULE, sizeof(sys_mpls_ilm_t)); if(NULL == p_ilm_data) { return CTC_E_NO_MEMORY; } SYS_MPLS_KEY_MAP(p_mpls_ilm, p_ilm_data); SYS_MPLS_DATA_MAP(p_mpls_ilm, p_ilm_data); p_ilm_data->ecpn = 0; switch(p_mpls_ilm->id_type) { case CTC_MPLS_ID_FLOW: p_ilm_data->flw_vrf_srv = p_mpls_ilm->flw_vrf_srv_aps.flow_id; break; case CTC_MPLS_ID_VRF: p_ilm_data->flw_vrf_srv = p_mpls_ilm->flw_vrf_srv_aps.vrf_id; break; case CTC_MPLS_ID_SERVICE: p_ilm_data->flw_vrf_srv = p_mpls_ilm->flw_vrf_srv_aps.service_id; break; case CTC_MPLS_ID_APS_SELECT: p_ilm_data->aps_group_id = p_mpls_ilm->flw_vrf_srv_aps.aps_select_grp_id; p_ilm_data->aps_select_ppath = p_mpls_ilm->aps_select_protect_path; break; default: p_ilm_data->flw_vrf_srv = 0xffff; break; } SYS_MPLS_LOCK; ret = _sys_humber_mpls_db_add(p_ilm_data); if(ret) { mem_free(p_ilm_data); CTC_ERROR_RETURN_MPLS_UNLOCK(ret); } /* write mpls ilm entry */ ret = _sys_humber_mpls_write_ilm(p_ilm_data, fwd_offset); if(ret) { _sys_humber_mpls_db_remove(p_ilm_data); mem_free(p_ilm_data); CTC_ERROR_RETURN_MPLS_UNLOCK(ret); } } SYS_MPLS_UNLOCK; return CTC_E_NONE; } int32 sys_humber_mpls_update_ilm(ctc_mpls_ilm_t* p_mpls_ilm) { sys_mpls_ilm_t *p_ilm_data, ilm_data; uint8 i; uint8 chip_num; uint32 cmd; uint32 use_label; uint32 oam_check; sys_nh_offset_array_t fwd_offset; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(p_mpls_ilm); SYS_MPLS_ILM_SPACE_CHECK(p_mpls_ilm->spaceid); SYS_MPLS_ILM_LABEL_CHECK(p_mpls_ilm->spaceid, p_mpls_ilm->label); if(p_mpls_ilm->model >= CTC_MPLS_MAX_TUNNEL_MODE) return CTC_E_INVALID_PARAM; /* prepare data */ p_ilm_data = &ilm_data; SYS_MPLS_KEY_MAP(p_mpls_ilm, p_ilm_data); SYS_MPLS_LOCK; /* lookup for mpls entrise */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(p_ilm_data) /* ilm have exist */ { chip_num = sys_humber_get_local_chip_num(); if(p_mpls_ilm->model != p_ilm_data->model) { if(CTC_MPLS_TUNNEL_MODE_UNIFORM != p_mpls_ilm->model) { use_label = TRUE; } else { use_label = FALSE; } cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DS_MPLS_USE_LABEL_TTL); for(i = 0; i < chip_num; i++) { CTC_ERROR_RETURN_MPLS_UNLOCK(drv_tbl_ioctl(i, p_ilm_data->key_offset, cmd, &use_label)); } cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DS_MPLS_USE_LABEL_EXP); for(i = 0; i < chip_num; i++) { CTC_ERROR_RETURN_MPLS_UNLOCK(drv_tbl_ioctl(i, p_ilm_data->key_offset, cmd, &use_label)); } p_ilm_data->model = p_mpls_ilm->model; } if (p_mpls_ilm->oam_en != p_ilm_data->oam_en) { oam_check = (p_mpls_ilm->oam_en) ? TRUE : FALSE; cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DS_MPLS_OAM_CHECK); for(i = 0; i < chip_num; i++) { CTC_ERROR_RETURN_MPLS_UNLOCK(drv_tbl_ioctl(i, p_ilm_data->key_offset, cmd, &oam_check)); p_ilm_data->oam_en = p_mpls_ilm->oam_en; } } if (p_mpls_ilm->nh_id != p_ilm_data->nh_id) { CTC_ERROR_RETURN(sys_humber_nh_get_dsfwd_offset(p_mpls_ilm->nh_id, fwd_offset)); cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DS_MPLS_DS_FWD_PTR); for(i = 0; i < chip_num; i++) { CTC_ERROR_RETURN(drv_tbl_ioctl(i, p_ilm_data->key_offset, cmd, &fwd_offset[i])); } p_ilm_data->nh_id = p_mpls_ilm->nh_id; } } SYS_MPLS_UNLOCK; return CTC_E_NONE; } /** @brief function of remove mpls ilm entry @param[in] p_ipuc_param, parameters used to remove mpls ilm entry @return CTC_E_XXX */ int32 sys_humber_mpls_del_ilm(ctc_mpls_ilm_t* p_mpls_ilm) { sys_mpls_ilm_t *p_ilm_data, ilm_data; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(p_mpls_ilm); SYS_MPLS_NHID_EXTERNAL_VALID_CHECK(p_mpls_ilm->nh_id); SYS_MPLS_ILM_SPACE_CHECK(p_mpls_ilm->spaceid); SYS_MPLS_ILM_LABEL_CHECK(p_mpls_ilm->spaceid, p_mpls_ilm->label); /* prepare data */ p_ilm_data = &ilm_data; SYS_MPLS_KEY_MAP(p_mpls_ilm, p_ilm_data); SYS_MPLS_LOCK; /* lookup for ipuc entrise */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(!p_ilm_data) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } if(p_ilm_data->ecpn == 0) { if(p_ilm_data->nh_id != p_mpls_ilm->nh_id) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } /* write mpls ilm entry */ _sys_humber_mpls_remove_ilm(p_ilm_data); _sys_humber_mpls_db_remove(p_ilm_data); mem_free(p_ilm_data); } else { sys_nh_param_ecmp_api_t nh_param; uint32 ecmp_nhid; kal_memset(&nh_param, 0, sizeof(sys_nh_param_ecmp_api_t)); nh_param.ref_nh_id = p_mpls_ilm->nh_id; nh_param.change_type = SYS_NH_CHANGE_TYPE_ECMP_REMOVE_ITEM; ecmp_nhid = p_ilm_data->nh_id; CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_ecmp_nh_update(ecmp_nhid, &nh_param)); p_ilm_data->ecpn--; if(p_ilm_data->ecpn == 0) { p_ilm_data->nh_id = nh_param.ref_nh_id; } /* write mpls ilm entry */ _sys_humber_mpls_write_ilm(p_ilm_data, nh_param.fwd_offset); if(p_ilm_data->ecpn == 0) { CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_ecmp_nh_delete(ecmp_nhid)); } } SYS_MPLS_UNLOCK; return CTC_E_NONE; } int32 sys_humber_mpls_get_ilm(uint32 nh_id[CTC_MAX_ECPN], ctc_mpls_ilm_t* p_mpls_ilm) { sys_mpls_ilm_t *p_ilm_data, ilm_data; uint8 i; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(nh_id); CTC_PTR_VALID_CHECK(p_mpls_ilm); SYS_MPLS_ILM_SPACE_CHECK(p_mpls_ilm->spaceid); SYS_MPLS_ILM_LABEL_CHECK(p_mpls_ilm->spaceid, p_mpls_ilm->label); /* prepare data */ p_ilm_data = &ilm_data; SYS_MPLS_KEY_MAP(p_mpls_ilm, p_ilm_data); SYS_MPLS_LOCK; /* lookup for ipuc entrise */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(!p_ilm_data) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } if(p_ilm_data->ecpn != 0) { sys_nh_info_ecmp_t* p_nhinfo; CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_nh_get_nhinfo_by_nhid(p_ilm_data->nh_id, (sys_nh_info_com_t**)&p_nhinfo)); if(SYS_HUMBER_NH_TYPE_ECMP != p_nhinfo->hdr.nh_entry_type) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } for(i = 0; i < p_nhinfo->valid_item_cnt; i++) { nh_id[i] = p_nhinfo->item_array[i].nh_id; } } else { nh_id[0] = p_ilm_data->nh_id; } p_mpls_ilm->pwid = p_ilm_data->pwid; p_mpls_ilm->id_type = p_ilm_data->id_type; p_mpls_ilm->type = p_ilm_data->type; p_mpls_ilm->model = p_ilm_data->model; p_mpls_ilm->cwen = p_ilm_data->cwen; p_mpls_ilm->pop = p_ilm_data->pop; p_mpls_ilm->nh_id = p_ilm_data->nh_id; p_mpls_ilm->id_type = p_ilm_data->id_type; switch(p_ilm_data->id_type) { case CTC_MPLS_ID_FLOW: p_mpls_ilm->flw_vrf_srv_aps.flow_id = p_ilm_data->flw_vrf_srv; break; case CTC_MPLS_ID_VRF: p_mpls_ilm->flw_vrf_srv_aps.vrf_id = p_ilm_data->flw_vrf_srv; break; case CTC_MPLS_ID_SERVICE: p_mpls_ilm->flw_vrf_srv_aps.service_id = p_ilm_data->flw_vrf_srv; break; case CTC_MPLS_ID_APS_SELECT: p_mpls_ilm->flw_vrf_srv_aps.aps_select_grp_id = p_ilm_data->aps_group_id; p_mpls_ilm->aps_select_protect_path = p_ilm_data->aps_select_ppath; break; default: break; } for(i = p_ilm_data->ecpn + 1; i < CTC_MAX_ECPN; i++) { nh_id[i] = CTC_INVLD_NH_ID; } SYS_MPLS_UNLOCK; return CTC_E_NONE; } int32 sys_humber_mpls_add_stats(ctc_mpls_stats_index_t* stats_index) { uint8 lchip, lchip_num; sys_nh_u16_array_t stats_ptr; uint32 cmd; int32 ret = CTC_E_NONE; ds_mpls_t dsmpls; sys_mpls_ilm_t *p_ilm_data, ilm_data; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(stats_index); SYS_MPLS_ILM_SPACE_CHECK(stats_index->spaceid); SYS_MPLS_ILM_LABEL_CHECK(stats_index->spaceid, stats_index->label); /* prepare data */ p_ilm_data = &ilm_data; p_ilm_data->label = stats_index->label; p_ilm_data->spaceid = stats_index->spaceid; SYS_MPLS_LOCK; /* lookup for mpls entrise */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(!p_ilm_data) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } if(CTC_MPLS_ID_STATS == p_ilm_data->id_type) { CTC_RETURN_MPLS_UNLOCK(CTC_E_MPLS_ENTRY_STATS_EXIST); } else if(CTC_MPLS_ID_NULL != p_ilm_data->id_type) { CTC_RETURN_MPLS_UNLOCK(CTC_E_MPLS_ENTRY_NOT_SUPPORT_STATS); } kal_memset(stats_ptr, 0xFF, sizeof(sys_nh_u16_array_t)); lchip_num = sys_humber_get_local_chip_num(); for(lchip = 0; lchip < lchip_num; lchip++) { /*alloc stats_ptr*/ ret = sys_humber_stats_create_statsptr(lchip, 1, &stats_ptr[lchip]); if(CTC_E_NONE != ret) { break; } p_ilm_data->stats_ptr[lchip] = stats_ptr[lchip]; } /*for rollback*/ if(CTC_E_NONE != ret) { for(lchip = 0; lchip < lchip_num; lchip++) { if(0xFFFF != stats_ptr[lchip]) { sys_humber_stats_delete_statsptr(lchip, 1, stats_ptr[lchip]); p_ilm_data->stats_ptr[lchip] = 0xFFFF; } } CTC_ERROR_RETURN_MPLS_UNLOCK(ret); } for(lchip = 0; lchip < lchip_num; lchip++) { cmd = DRV_IOR(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); CTC_ERROR_RETURN_MPLS_UNLOCK(drv_tbl_ioctl(lchip, p_ilm_data->key_offset, cmd, &dsmpls)); dsmpls.stats_ptr_mode = 1; dsmpls.flow_policer_ptr7to0 = stats_ptr[lchip] & 0xff; dsmpls.flow_policer_ptr10to8 = (stats_ptr[lchip] >> 8) & 0x7; dsmpls.flow_policer_ptr11 = (stats_ptr[lchip] >> 11) & 0x1; dsmpls.flow_policer_ptr15to12 = (stats_ptr[lchip] >> 12) & 0xf; cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); CTC_ERROR_RETURN_MPLS_UNLOCK(drv_tbl_ioctl(lchip, p_ilm_data->key_offset, cmd, &dsmpls)); } p_ilm_data->id_type = CTC_MPLS_ID_STATS; SYS_MPLS_UNLOCK; return CTC_E_NONE; } int32 sys_humber_mpls_del_stats(ctc_mpls_stats_index_t* stats_index) { uint8 lchip, lchip_num; uint16 stats_ptr; uint32 cmd; ds_mpls_t dsmpls; sys_mpls_ilm_t *p_ilm_data, ilm_data; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(stats_index); SYS_MPLS_ILM_SPACE_CHECK(stats_index->spaceid); SYS_MPLS_ILM_LABEL_CHECK(stats_index->spaceid, stats_index->label); /* prepare data */ p_ilm_data = &ilm_data; p_ilm_data->label = stats_index->label; p_ilm_data->spaceid = stats_index->spaceid; SYS_MPLS_LOCK; /* lookup for mpls entrise */ CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(!p_ilm_data) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } if(CTC_MPLS_ID_STATS != p_ilm_data->id_type) { CTC_RETURN_MPLS_UNLOCK(CTC_E_MPLS_ENTRY_STATS_NOT_EXIST); } lchip_num = sys_humber_get_local_chip_num(); for(lchip = 0; lchip < lchip_num; lchip++) { cmd = DRV_IOR(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); drv_tbl_ioctl(lchip, p_ilm_data->key_offset, cmd, &dsmpls); /*free stats_ptr*/ stats_ptr = (dsmpls.flow_policer_ptr7to0 & 0xff) | ((dsmpls.flow_policer_ptr10to8 & 0x7)<<8) | ((dsmpls.flow_policer_ptr11 & 0x1)<<11) | ((dsmpls.flow_policer_ptr15to12 &0xf)<<12); sys_humber_stats_delete_statsptr(lchip, 1, stats_ptr); dsmpls.stats_ptr_mode = 0; /*16'hFFFF indicates invalid*/ dsmpls.flow_policer_ptr7to0 = 0xff; dsmpls.flow_policer_ptr10to8 = 0x7; dsmpls.flow_policer_ptr11 = 0x1; dsmpls.flow_policer_ptr15to12 = 0xf; cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); drv_tbl_ioctl(lchip, p_ilm_data->key_offset, cmd, &dsmpls); p_ilm_data->stats_ptr[lchip] = 0xFFFF; } p_ilm_data->id_type = CTC_MPLS_ID_NULL; SYS_MPLS_UNLOCK; return CTC_E_NONE; } int32 sys_humber_mpls_get_stats(ctc_mpls_stats_index_t* stats_index, ctc_stats_basic_t* p_stats) { uint8 lchip, lchip_num; sys_mpls_ilm_t *p_ilm_data, ilm_data; ctc_stats_basic_t stats; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(stats_index); CTC_PTR_VALID_CHECK(p_stats); SYS_MPLS_ILM_SPACE_CHECK(stats_index->spaceid); SYS_MPLS_ILM_LABEL_CHECK(stats_index->spaceid, stats_index->label); kal_memset(p_stats, 0, sizeof(ctc_stats_basic_t)); p_ilm_data = &ilm_data; p_ilm_data->label = stats_index->label; p_ilm_data->spaceid = stats_index->spaceid; SYS_MPLS_LOCK; CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(!p_ilm_data) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } if(CTC_MPLS_ID_STATS != p_ilm_data->id_type) { CTC_RETURN_MPLS_UNLOCK(CTC_E_MPLS_ENTRY_NOT_SUPPORT_STATS); } lchip_num = sys_humber_get_local_chip_num(); for (lchip = 0; lchip < lchip_num; lchip++) { CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_stats_get_flow_stats(lchip, p_ilm_data->stats_ptr[lchip], &stats)); p_stats->byte_count += stats.byte_count; p_stats->packet_count += stats.packet_count; } SYS_MPLS_UNLOCK; return CTC_E_NONE; } int32 sys_humber_mpls_reset_stats(ctc_mpls_stats_index_t* stats_index) { uint8 lchip, lchip_num; sys_mpls_ilm_t *p_ilm_data, ilm_data; ctc_stats_basic_t stats; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(stats_index); SYS_MPLS_ILM_SPACE_CHECK(stats_index->spaceid); SYS_MPLS_ILM_LABEL_CHECK(stats_index->spaceid, stats_index->label); kal_memset(&stats, 0, sizeof(ctc_stats_basic_t)); p_ilm_data = &ilm_data; p_ilm_data->label = stats_index->label; p_ilm_data->spaceid = stats_index->spaceid; SYS_MPLS_LOCK; CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(!p_ilm_data) { CTC_RETURN_MPLS_UNLOCK(CTC_E_ENTRY_NOT_EXIST); } if(CTC_MPLS_ID_STATS != p_ilm_data->id_type) { CTC_RETURN_MPLS_UNLOCK(CTC_E_MPLS_ENTRY_NOT_SUPPORT_STATS); } lchip_num = sys_humber_get_local_chip_num(); for (lchip = 0; lchip < lchip_num; lchip++) { CTC_ERROR_RETURN_MPLS_UNLOCK(sys_humber_stats_reset_flow_stats(lchip, p_ilm_data->stats_ptr[lchip])); } SYS_MPLS_UNLOCK; return CTC_E_NONE; } static int32 _sys_humber_mpls_add_vpws_pw(sys_usrid_vlan_entry_t* p_userid_entry, ctc_mpls_l2vpn_pw_t* p_mpls_pw) { sys_vlan_info_t vlan_info; uint16 vlan_ptr; sys_nh_offset_array_t fwd_offset; uint8 chip_num; uint8 i; vlan_info.vlan_ptr_type = SYS_VLAN_PTR_TYPE_VPWS; CTC_ERROR_RETURN(sys_humber_vlan_get_vlan_ptr(&vlan_info, &vlan_ptr)); p_userid_entry->ds_entry_usrid.usr_vlan_ptr = vlan_ptr & 0x1fff; CTC_ERROR_RETURN(sys_humber_nh_get_dsfwd_offset(p_mpls_pw->u.pw_nh_id, fwd_offset)); p_userid_entry->ds_entry_usrid.fwd_ptr_valid = TRUE; chip_num = sys_humber_get_local_chip_num(); for (i = 0; i < chip_num; i++) { p_userid_entry->usrid_key_entry.lchip = i; p_userid_entry->ds_entry_usrid.binding_data_l.fwd_ptr = fwd_offset[i] & 0xffff; CTC_ERROR_RETURN(sys_humber_usrid_add_vlan_entry(p_userid_entry)); } return CTC_E_NONE; } static int32 _sys_humber_mpls_add_vpls_pw(sys_usrid_vlan_entry_t* p_userid_entry, ctc_mpls_l2vpn_pw_t* p_mpls_pw) { sys_vlan_info_t vlan_info; uint16 vlan_ptr; uint8 chip_num; uint8 i; vlan_info.vlan_ptr_type = p_mpls_pw->learn_disable?SYS_VLAN_PTR_TYPE_VPLS_LRN_DIS: SYS_VLAN_PTR_TYPE_VPLS_LRN_EN; CTC_ERROR_RETURN(sys_humber_vlan_get_vlan_ptr(&vlan_info, &vlan_ptr)); p_userid_entry->ds_entry_usrid.usr_vlan_ptr = vlan_ptr & 0x1fff; p_userid_entry->ds_entry_usrid.vrfid_valid = TRUE; p_userid_entry->ds_entry_usrid.binding_data_l.vrf_id = p_mpls_pw->u.vpls_info.fid; p_userid_entry->ds_entry_usrid.vpls_port_type = p_mpls_pw->u.vpls_info.vpls_port_type; if(p_mpls_pw->u.vpls_info.vpls_src_port <= SYS_MPLS_VPLS_SRC_PORT_NUM) { p_userid_entry->ds_entry_usrid.binding_data_h.vpls_src_port = p_mpls_pw->u.vpls_info.vpls_src_port & 0x1fff; p_userid_entry->ds_entry_usrid.binding_data_h.vpls_src_port_valid = TRUE; } chip_num = sys_humber_get_local_chip_num(); for (i = 0; i < chip_num; i++) { p_userid_entry->usrid_key_entry.lchip = i; CTC_ERROR_RETURN(sys_humber_usrid_add_vlan_entry(p_userid_entry)); } return CTC_E_NONE; } /** @brief function of add l2vpn pw entry @param[in] p_mpls_pw, parameters used to add l2vpn pw entry @return CTC_E_XXX */ int32 sys_humber_mpls_add_l2vpn_pw(ctc_mpls_l2vpn_pw_t* p_mpls_pw) { sys_usrid_vlan_entry_t userid_entry; SYS_MPLS_INIT_CHECK; CTC_PTR_VALID_CHECK(p_mpls_pw); SYS_MPLS_ILM_LABEL_CHECK(0, p_mpls_pw->label); SYS_MPLS_L2VPN_DATA_CHECK(p_mpls_pw); kal_memset(&userid_entry, 0, sizeof(sys_usrid_vlan_entry_t)); userid_entry.valid.vc_valid = TRUE; userid_entry.usrid_key_entry.customer_id = p_mpls_pw->label << 12; userid_entry.ds_entry_usrid.binding_data_h.srv_aclqos_en = p_mpls_pw->service_aclqos_enable; CTC_ERROR_RETURN(p_mpls_master->write_pw[p_mpls_pw->l2vpntype](&userid_entry, p_mpls_pw)); return CTC_E_NONE; } /** @brief function of remove l2vpn pw entry @param[in] label, vc label of the l2vpn pw entry @return CTC_E_XXX */ int32 sys_humber_mpls_del_l2vpn_pw(ctc_mpls_l2vpn_pw_t* p_mpls_pw) { sys_usrid_vlan_entry_t userid_entry; uint8 chip_num; uint8 i; SYS_MPLS_INIT_CHECK; SYS_MPLS_ILM_LABEL_CHECK(0, p_mpls_pw->label); kal_memset(&userid_entry, 0, sizeof(sys_usrid_vlan_entry_t)); userid_entry.valid.vc_valid = TRUE; userid_entry.usrid_key_entry.customer_id = p_mpls_pw->label << 12; chip_num = sys_humber_get_local_chip_num(); for (i = 0; i < chip_num; i++) { userid_entry.usrid_key_entry.lchip = i; CTC_ERROR_RETURN(sys_humber_usrid_delete_vlan_entry(&userid_entry)); } return CTC_E_NONE; } int32 sys_humber_mpls_reset_in_sqn(uint8 index) { sequencenumbertable_t ds_seq_num; uint8 chip_num; uint8 i; uint32 cmd; ds_seq_num.sequence_number = 1; cmd = DRV_IOW(IOC_TABLE, SEQUENCENUMBERTABLE, DRV_ENTRY_FLAG); chip_num = sys_humber_get_local_chip_num(); for (i = 0; i < chip_num; i++) { CTC_ERROR_RETURN(drv_tbl_ioctl(i, index, cmd, &ds_seq_num)); } return CTC_E_NONE; } int32 sys_humber_mpls_reset_out_sqn(uint8 index) { ds_l3_edit_sequence_num_t ds_edit_mpls_seq; uint8 chip_num; uint8 i; uint32 cmdr, cmdw; uint8 sub_index = index >> 2; uint8 offset = index & 0x3; cmdr = DRV_IOR(IOC_TABLE, DS_L3_EDIT_SEQUENCE_NUM, DRV_ENTRY_FLAG); cmdw = DRV_IOW(IOC_TABLE, DS_L3_EDIT_SEQUENCE_NUM, DRV_ENTRY_FLAG); chip_num = sys_humber_get_local_chip_num(); for (i = 0; i < chip_num; i++) { CTC_ERROR_RETURN(drv_tbl_ioctl(i, sub_index, cmdr, &ds_edit_mpls_seq)); switch(offset) { case 0: ds_edit_mpls_seq.seq_num31_to0 = 1; break; case 1: ds_edit_mpls_seq.seq_num63_to32 = 1; break; case 2: ds_edit_mpls_seq.seq_num95_to64 = 1; break; case 3: ds_edit_mpls_seq.seq_num127_to96 = 1; break; default: break; } CTC_ERROR_RETURN(drv_tbl_ioctl(i, sub_index, cmdw, &ds_edit_mpls_seq)); } return CTC_E_NONE; } int32 sys_humber_mpls_init_entries(void) { ds_mpls_t dsmpls; uint8 chip_num; uint32 i, j, k; uint32 cmd; kal_memset(&dsmpls, 0, sizeof(ds_mpls_t)); dsmpls.flow_policer_ptr7to0 = 0xff; dsmpls.flow_policer_ptr10to8 = 0x7; dsmpls.flow_policer_ptr11 = 0x1; dsmpls.flow_policer_ptr15to12 = 0xf; dsmpls.ds_fwd_ptr = 0xfffff; chip_num = sys_humber_get_local_chip_num(); cmd = DRV_IOW(IOC_TABLE, DS_MPLS, DRV_ENTRY_FLAG); /* ilm entries */ for(i = 0; i < CTC_MPLS_SPACE_NUMBER; i++) { if(p_mpls_master->space[i].enable) { for(j = 0; j < p_mpls_master->space[i].size; j++) { for(k = 0; k < chip_num; k++) { CTC_ERROR_RETURN(drv_tbl_ioctl(k, p_mpls_master->space[i].base + j, cmd, &dsmpls)); } } } } return CTC_E_NONE; } int32 sys_humber_mpls_init(ctc_mpls_init_t* p_mpls_info) { ds_mpls_ctl_t mpls_ctl; ipe_lookup_result_ctl_t rslt_ctl; uint32 cmdr, cmdw; int i, lchip, chip_num; uint32 base; uint8 block_num; /* check the parameter */ CTC_PTR_VALID_CHECK(p_mpls_info); for(i = 0; i < CTC_MPLS_SPACE_NUMBER; i++) { if(p_mpls_info->space_info[i].enable && p_mpls_info->space_info[i].sizetype > 15) { return CTC_E_INVALID_PARAM; } } p_mpls_master = mem_malloc(MEM_MPLS_MODULE, sizeof(sys_mpls_master_t)); if(NULL == p_mpls_master) { return CTC_E_NO_MEMORY; } chip_num = sys_humber_get_local_chip_num(); /* global space */ if(p_mpls_info->space_info[0].sizetype > 3) { block_num = 1 << (p_mpls_info->space_info[0].sizetype - 3); } else { block_num = 1; } cmdr = DRV_IOR(IOC_REG, IPE_LOOKUP_RESULT_CTL, DRV_ENTRY_FLAG); cmdw = DRV_IOW(IOC_REG, IPE_LOOKUP_RESULT_CTL, DRV_ENTRY_FLAG); CTC_ERROR_RETURN(drv_reg_ioctl(0, 0, cmdr, &rslt_ctl)); p_mpls_master->space[0].base = rslt_ctl.label_base_global << 8; p_mpls_master->space[0].size = SYS_MPLS_TBL_BLOCK_SIZE * (1 << p_mpls_info->space_info[0].sizetype); p_mpls_master->space[0].p_vet = ctc_vector_init(block_num, SYS_MPLS_TBL_BLOCK_SIZE * 8); if(NULL == p_mpls_master->space[0].p_vet) { return CTC_E_NO_MEMORY; } rslt_ctl.label_space_size_type_global = p_mpls_info->space_info[0].sizetype; for(lchip = 0; lchip < chip_num; lchip++) { CTC_ERROR_RETURN(drv_reg_ioctl(lchip, 0, cmdw, &rslt_ctl)); } base = rslt_ctl.label_base_global + (1 << p_mpls_info->space_info[0].sizetype); kal_memset(&mpls_ctl, 0, sizeof(ds_mpls_ctl_t)); mpls_ctl.num_of_label = CTC_MPLS_LABEL_NUM_PROCESS; cmdw = DRV_IOW(IOC_TABLE, DS_MPLS_CTL, DRV_ENTRY_FLAG); for (lchip = 0; lchip < chip_num; lchip++) { CTC_ERROR_RETURN(drv_tbl_ioctl(lchip, 0, cmdw, &mpls_ctl)); } p_mpls_master->space[0].enable = p_mpls_info->space_info[0].enable; /* interface space */ for(i = 1; i < CTC_MPLS_SPACE_NUMBER; i++) { if(p_mpls_info->space_info[i].enable) { if(p_mpls_info->space_info[i].sizetype > 3) { block_num = 1 << (p_mpls_info->space_info[i].sizetype - 3); } else { block_num = 1; } p_mpls_master->space[i].p_vet = ctc_vector_init(block_num, SYS_MPLS_TBL_BLOCK_SIZE * 8); if(NULL == p_mpls_master->space[i].p_vet) { return CTC_E_NO_MEMORY; } p_mpls_master->space[i].base = base << 8; p_mpls_master->space[i].size = SYS_MPLS_TBL_BLOCK_SIZE * (1 << p_mpls_info->space_info[i].sizetype); p_mpls_master->space[i].enable = TRUE; mpls_ctl.interface_label_valid = TRUE; mpls_ctl.label_base = base; mpls_ctl.label_space_sizetype = p_mpls_info->space_info[i].sizetype; base += (1 << p_mpls_info->space_info[i].sizetype); } else { p_mpls_master->space[i].enable = FALSE; mpls_ctl.interface_label_valid = FALSE; mpls_ctl.label_base = 0; mpls_ctl.label_space_sizetype = 0; } for(lchip = 0; lchip < chip_num; lchip++) { CTC_ERROR_RETURN(drv_tbl_ioctl(lchip, i, cmdw, &mpls_ctl)); } } /* min interface label, the label littler than it must be a global label */ p_mpls_master->min_int_label = rslt_ctl.min_interface_label << 8; /* call back function */ p_mpls_master->write_ilm[CTC_MPLS_LABEL_TYPE_NORMAL] = _sys_humber_mpls_ilm_normal; p_mpls_master->write_ilm[CTC_MPLS_LABEL_TYPE_L3VPN] = _sys_humber_mpls_ilm_l3vpn; p_mpls_master->write_ilm[CTC_MPLS_LABEL_TYPE_VPWS] = _sys_humber_mpls_ilm_vpws; p_mpls_master->write_ilm[CTC_MPLS_LABEL_TYPE_VPLS] = _sys_humber_mpls_ilm_vpls; p_mpls_master->write_pw[CTC_MPLS_L2VPN_VPWS] = _sys_humber_mpls_add_vpws_pw; p_mpls_master->write_pw[CTC_MPLS_L2VPN_VPLS] = _sys_humber_mpls_add_vpls_pw; CTC_ERROR_RETURN(sys_humer_nh_get_max_external_nhid( &p_mpls_master->max_external_nhid )); SYS_MPLS_CREAT_LOCK; sys_humber_mpls_init_entries(); return CTC_E_NONE; } int32 sys_humber_mpls_space_show(void) { uint32 i; SYS_MPLS_INIT_CHECK; SYS_MPLS_DBG_DUMP("The minimum interface space label is %d\n\r", p_mpls_master->min_int_label); SYS_MPLS_DBG_DUMP("Space Size\n\r"); for(i = 0; i < CTC_MPLS_SPACE_NUMBER; i++) { if(p_mpls_master->space[i].enable) { SYS_MPLS_DBG_DUMP("%-8d %d\n\r", i, p_mpls_master->space[i].size); } } return CTC_E_NONE; } static int32 _sys_humber_show_ilm_info(sys_mpls_ilm_t* p_ilm_data, void* data) { if(!p_ilm_data) { return CTC_E_NONE; } SYS_MPLS_DBG_DUMP("%-7d %-10d", p_ilm_data->spaceid, p_ilm_data->label); switch(p_ilm_data->type) { case CTC_MPLS_LABEL_TYPE_NORMAL: /**< This label is a normal label */ SYS_MPLS_DBG_DUMP("%-7s %-6d %-8d %-9d", "-", p_ilm_data->ecpn, p_ilm_data->key_offset, p_ilm_data->nh_id); break; case CTC_MPLS_LABEL_TYPE_L3VPN: /**< This label is a l3vpn VC label */ SYS_MPLS_DBG_DUMP("%-7s %-6d %-8d %-9d", "L3VPN", p_ilm_data->ecpn, p_ilm_data->key_offset, p_ilm_data->nh_id); break; case CTC_MPLS_LABEL_TYPE_VPWS: /**< This label is a vpws VC label */ SYS_MPLS_DBG_DUMP("%-7s %-6d %-8d %-9d", "VPWS", p_ilm_data->ecpn, p_ilm_data->key_offset, p_ilm_data->nh_id); break; case CTC_MPLS_LABEL_TYPE_VPLS: /**< This label is a vpls VC label */ SYS_MPLS_DBG_DUMP("%-7s %-6d %-8d %-9d", "VPLS", p_ilm_data->ecpn, p_ilm_data->key_offset, p_ilm_data->nh_id); break; default: break; } if(p_ilm_data->type == CTC_MPLS_LABEL_TYPE_VPLS) { SYS_MPLS_DBG_DUMP("%-7d", p_ilm_data->pwid); } else { SYS_MPLS_DBG_DUMP("- "); } if(p_ilm_data->type == CTC_MPLS_LABEL_TYPE_L3VPN) { SYS_MPLS_DBG_DUMP("%-8d", p_ilm_data->flw_vrf_srv); } else { SYS_MPLS_DBG_DUMP("- "); } if(p_ilm_data->type == CTC_MPLS_LABEL_TYPE_NORMAL || p_ilm_data->type == CTC_MPLS_LABEL_TYPE_L3VPN) { if(p_ilm_data->model == CTC_MPLS_TUNNEL_MODE_UNIFORM) { SYS_MPLS_DBG_DUMP("U "); } else if(p_ilm_data->model == CTC_MPLS_TUNNEL_MODE_SHORT_PIPE) { SYS_MPLS_DBG_DUMP("S "); } else { SYS_MPLS_DBG_DUMP("P "); } SYS_MPLS_DBG_DUMP("-"); } else { SYS_MPLS_DBG_DUMP("P "); if(p_ilm_data->cwen) { SYS_MPLS_DBG_DUMP("U"); } else { SYS_MPLS_DBG_DUMP("-"); } } SYS_MPLS_DBG_DUMP("\n\r"); return CTC_E_NONE; } int32 sys_humber_mpls_ilm_show(void) { int i; SYS_MPLS_INIT_CHECK; SYS_MPLS_DBG_DUMP("Mode : U-Uniform S-Short pipe P-Pipe\n\r"); SYS_MPLS_DBG_DUMP("Space Label Type Ecpn Offset NH ID PW VRF Mode CW\n\r"); for(i = 0; i < CTC_MPLS_SPACE_NUMBER; i++) { if(p_mpls_master->space[i].enable) { ctc_vector_traverse(p_mpls_master->space[i].p_vet, (vector_traversal_fn)_sys_humber_show_ilm_info, NULL); } } return CTC_E_NONE; } uint32 g_ilm_count= 0; static int32 _sys_humber_get_ilm_count(sys_mpls_ilm_t* p_ilm_data, void* data) { if (p_ilm_data != NULL) { g_ilm_count++; } return CTC_E_NONE; } int32 sys_humber_mpls_ilm_count(void) { int i; uint32 count = 0; SYS_MPLS_INIT_CHECK; for(i = 0; i < CTC_MPLS_SPACE_NUMBER; i++) { if (p_mpls_master->space[i].enable) { g_ilm_count = 0; ctc_vector_traverse(p_mpls_master->space[i].p_vet, (vector_traversal_fn)_sys_humber_get_ilm_count, &count); SYS_MPLS_DBG_DUMP("Mpls space %d ,ilm count:%-10d\n\r", i, g_ilm_count); } } return CTC_E_NONE; } int32 sys_humber_mpls_sqn_show(uint8 index) { sequencenumbertable_t ds_seq_num; ds_l3_edit_sequence_num_t ds_edit_mpls_seq; uint32 out_seq = 0; uint8 sub_index = index >> 2; uint8 offset = index & 0x3; uint32 cmd; cmd = DRV_IOR(IOC_TABLE, SEQUENCENUMBERTABLE, DRV_ENTRY_FLAG); CTC_ERROR_RETURN(drv_tbl_ioctl(0, index, cmd, &ds_seq_num)); cmd = DRV_IOR(IOC_TABLE, DS_L3_EDIT_SEQUENCE_NUM, DRV_ENTRY_FLAG); CTC_ERROR_RETURN(drv_tbl_ioctl(0, sub_index, cmd, &ds_edit_mpls_seq)); switch(offset) { case 0: out_seq = ds_edit_mpls_seq.seq_num31_to0; break; case 1: out_seq = ds_edit_mpls_seq.seq_num63_to32; break; case 2: out_seq = ds_edit_mpls_seq.seq_num95_to64; break; case 3: out_seq = ds_edit_mpls_seq.seq_num127_to96; break; default: break; } SYS_MPLS_DBG_DUMP("Incoming sequence number %d\n\r", ds_seq_num.sequence_number); SYS_MPLS_DBG_DUMP("Outgoing sequence number %d\n\r", out_seq); return CTC_E_NONE; } int32 sys_humber_mpls_check_label_used(uint16 spaceid, uint32 label, bool *used) { sys_mpls_ilm_t *p_ilm_data, ilm_data; *used = FALSE; SYS_MPLS_INIT_CHECK; SYS_MPLS_ILM_SPACE_CHECK(spaceid); SYS_MPLS_ILM_LABEL_CHECK(spaceid, label); p_ilm_data = &ilm_data; p_ilm_data->label = label; p_ilm_data->spaceid = spaceid; SYS_MPLS_LOCK; CTC_ERROR_RETURN_MPLS_UNLOCK(_sys_humber_mpls_db_lookup(&p_ilm_data)); if(p_ilm_data) { *used = TRUE; } SYS_MPLS_UNLOCK; return CTC_E_NONE; }
28.30375
164
0.647794
[ "model" ]
d3a0ab618ff852f22ae9da4fe581bca0b1d4e1df
1,190
h
C
handoff_response/src/gen/EffectiveArea.h
fermi-lat/irfs
cebe27fc6a974ac4448f15d7944b21e419c585e9
[ "BSD-3-Clause" ]
null
null
null
handoff_response/src/gen/EffectiveArea.h
fermi-lat/irfs
cebe27fc6a974ac4448f15d7944b21e419c585e9
[ "BSD-3-Clause" ]
4
2020-02-21T20:16:38.000Z
2022-03-22T17:39:03.000Z
handoff_response/src/gen/EffectiveArea.h
fermi-lat/irfs
cebe27fc6a974ac4448f15d7944b21e419c585e9
[ "BSD-3-Clause" ]
1
2020-07-07T18:30:05.000Z
2020-07-07T18:30:05.000Z
/** @file EffectiveArea.h @brief create and manage a plot of the effective area $Header$ */ #ifndef IRF_EffectiveArea_h #define IRF_EffectiveArea_h #include <vector> #include <iostream> #include <string> class IrfAnalysis; class TH2F; /** @class EffectiveArea * @brief manage the effective area plot */ class EffectiveArea { public: EffectiveArea( IrfAnalysis& irf, std::ostream& log=std::cout); ~EffectiveArea(); void fill(double energy, double costheta, bool front, int count=0); void summarize(); void draw(const std::string &ps_filename) ; void writeFitParameters(std::string outputFile, std::string treename); void fillParameterTables(); private: class Bins { public: Bins(); const std::vector<double>& energy_bins()const{return m_energy_bin_edges;} const std::vector<double>& angle_bins()const{return m_angle_bin_edges;} private: std::vector<double> m_energy_bin_edges; std::vector<double> m_angle_bin_edges; }m_bins; IrfAnalysis& m_irf; std::ostream * m_log; std::ostream& out() {return *m_log;} TH2F* m_hist; ///< the 2-d histogram that we manage }; #endif
22.037037
81
0.683193
[ "vector" ]
dd6bb9803eef2b4b4449483c6ff952516d42adb6
973
h
C
src/core/chunk.h
maxrt101/fflang
6f54a7c865df61602a3bc65b205806e33420febf
[ "MIT" ]
null
null
null
src/core/chunk.h
maxrt101/fflang
6f54a7c865df61602a3bc65b205806e33420febf
[ "MIT" ]
null
null
null
src/core/chunk.h
maxrt101/fflang
6f54a7c865df61602a3bc65b205806e33420febf
[ "MIT" ]
null
null
null
#ifndef FF_CORE_CHUNK_H_ #define FF_CORE_CHUNK_H_ #include <vector> #include "common.h" #include "core/value.h" enum OpCode : uint8_t { OP_CONSTANT, OP_CONSTANT_LONG, OP_NULL, OP_TRUE, OP_FALSE, OP_POP, OP_DEFINE_GLOBAL, OP_DEFINE_GLOBAL_LONG, OP_GET_GLOBAL, OP_GET_GLOBAL_LONG, OP_SET_GLOBAL, OP_SET_GLOBAL_LONG, OP_GET_LOCAL, OP_SET_LOCAL, OP_MAKECONST, OP_NOT, OP_NEGATE, OP_EQUAL, OP_GREATER, OP_LESS, OP_ADD, OP_SUBTRACT, OP_MULTIPLY, OP_DIVIDE, OP_JUMP, OP_JUMP_IF_FALSE, OP_LOOP, OP_PRINT, OP_CALL, OP_RETURN, }; class Chunk { private: struct LineInfo { size_t start_offset; int line; }; public: std::vector<uint8_t> code; std::vector<Value> constants; std::vector<LineInfo> lines; public: Chunk(); void AppendCode(uint8_t byte, int line = -1); int AddConstant(Value value); void WriteConstant(Value value, int line = -1); int GetLine(int offset) const; }; #endif
14.742424
49
0.704008
[ "vector" ]
dd6d9d63db39421fbbae9946cb79cfa45c510764
9,899
c
C
src/firmware_aups.c
sqf-ice/Mesh_Bee
7b5f3287c5100af9a54e83cad29060bee06fdd5d
[ "MIT" ]
53
2015-02-09T20:43:08.000Z
2022-03-01T06:59:38.000Z
src/firmware_aups.c
sqf-ice/Mesh_Bee
7b5f3287c5100af9a54e83cad29060bee06fdd5d
[ "MIT" ]
10
2015-03-28T07:24:26.000Z
2019-02-14T13:11:29.000Z
src/firmware_aups.c
Seeed-Studio/Mesh_Bee
7b5f3287c5100af9a54e83cad29060bee06fdd5d
[ "MIT" ]
41
2015-01-13T02:17:16.000Z
2021-11-09T14:48:38.000Z
/* * firmware_ups.c * - User Programming Space - * Firmware for SeeedStudio Mesh Bee(Zigbee) module * * Copyright (c) NXP B.V. 2012. * Spread by SeeedStudio * Author : Oliver Wang * Create Time: 2014/4 * Change Log : * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /****************************************************************************/ /*** Include files ***/ /****************************************************************************/ #include "firmware_aups.h" #include "firmware_uart.h" #include "suli.h" #include "ups_arduino_sketch.h" #include "firmware_hal.h" /****************************************************************************/ /*** Macro Definitions ***/ /****************************************************************************/ #ifndef TRACE_UPS #define TRACE_UPS FALSE #endif /****************************************************************************/ /*** Type Definitions ***/ /****************************************************************************/ /****************************************************************************/ /*** Local Function Prototypes ***/ /****************************************************************************/ extern bool searchAtStarter(uint8 *buffer, int len); /****************************************************************************/ /*** Exported Variables ***/ /****************************************************************************/ /* If node works on Master Mode,create two aups_ringbuf[UART,AirPort] */ struct ringbuffer rb_uart_aups; struct ringbuffer rb_air_aups; uint8 aups_uart_mempool[AUPS_UART_RB_LEN] = {0}; uint8 aups_air_mempool[AUPS_AIR_RB_LEN] = {0}; /****************************************************************************/ /*** Local Variables ***/ /****************************************************************************/ PRIVATE uint32 _loopInterval = 0; /****************************************************************************/ /*** External Variables ***/ /****************************************************************************/ /****************************************************************************/ /*** Exported Functions ***/ /****************************************************************************/ extern uint32 SPM_u32PushData(void *data, int len); /**************************************************************************** * * NAME: UPS_vInitRingbuffer * * DESCRIPTION: * init ringbuffer of user programming space * * PARAMETERS: Name RW Usage * * RETURNS: * void * ****************************************************************************/ void UPS_vInitRingbuffer() { /* aups ringbuffer is required in Master mode */ init_ringbuffer(&rb_uart_aups, aups_uart_mempool, AUPS_UART_RB_LEN); init_ringbuffer(&rb_air_aups, aups_air_mempool, AUPS_AIR_RB_LEN); } /**************************************************************************** * * NAME: ups_init * * DESCRIPTION: * init user programming space * * PARAMETERS: Name RW Usage * * RETURNS: * void * ****************************************************************************/ PUBLIC void ups_init(void) { /* Init ringbuffer */ UPS_vInitRingbuffer(); /* init suli */ suli_init(); /* init arduino sketch with arduino-style setup function */ arduino_setup(); /* Activate Arduino-ful MCU */ OS_eStartSWTimer(Arduino_LoopTimer, APP_TIME_MS(500), NULL); } /**************************************************************************** * * NAME: setNodeState * * DESCRIPTION: * set the state of node * * PARAMETERS: Name RW Usage * state W state of node * 0:DATA_MODE * 1:AT_MODE * 2:MCU_MODE * RETURNS: * void * ****************************************************************************/ void setNodeState(uint32 state) { g_sDevice.eMode = state; PDM_vSaveRecord(&g_sDevicePDDesc); } /**************************************************************************** * * NAME: vDelayMsec * * DESCRIPTION: * Delay n ms * * PARAMETERS: Name RW Usage * u32Period R ms * * RETURNS: * void * ****************************************************************************/ void vDelayMsec(uint32 u32Period) { uint32 i, k; const uint32 u32MsecCount = 1800; volatile uint32 j; //declare as volatile so compiler doesn't optimize increment away for (k = 0; k < u32Period; k++) for (i = 0; i < u32MsecCount; i++) j++; } /**************************************************************************** * * NAME: aupsReadable * * DESCRIPTION: * Delay n ms * * PARAMETERS: Name RW Usage * u32Period R ms * * RETURNS: * void * ****************************************************************************/ PUBLIC uint32 aupsAirPortReadable(void) { uint32 dataCnt = 0; OS_eEnterCriticalSection(mutexAirPort); dataCnt = ringbuffer_data_size(&rb_air_aups); OS_eExitCriticalSection(mutexAirPort); return dataCnt; } /**************************************************************************** * * NAME: aupsAirPortRead * * DESCRIPTION: * Read len bytes of data to dst * * PARAMETERS: Name RW Usage * dst W Pointer to destination of the buffer * len R number of the bytes you want to read * RETURNS: * uint8: real number of bytes you read * ****************************************************************************/ PUBLIC uint8 aupsAirPortRead(void *dst, int len) { uint32 dataCnt = 0, readCnt = 0; OS_eEnterCriticalSection(mutexAirPort); dataCnt = ringbuffer_data_size(&rb_air_aups); if (dataCnt >= len) readCnt = len; else readCnt = dataCnt; ringbuffer_pop(&rb_air_aups, dst, dataCnt); OS_eExitCriticalSection(mutexAirPort); return readCnt; } /**************************************************************************** * * NAME: aupsSendApiFrm * * DESCRIPTION: * send a api frame into the stream processor * * PARAMETERS: Name RW Usage * dst W Pointer to destination of the buffer * len R number of the bytes you want to read * RETURNS: * uint8: real number of bytes you read * ****************************************************************************/ PUBLIC uint8 aupsSendApiFrm(void *data, int len) { uint32 avlb_cnt = SPM_u32PushData(data, len); if (avlb_cnt >= THRESHOLD_READ) { OS_eActivateTask(APP_taskHandleUartRx); //Activate SPM immediately } else { vResetATimer(APP_tmrHandleUartRx, APP_TIME_MS(5)); //Activate SPM 5ms later } } /**************************************************************************** * * NAME: Arduino_Loop * * DESCRIPTION: * task for arduino loop * ****************************************************************************/ OS_TASK(Arduino_Loop) { /* Mutex, only in MCU mode,this loop will be called or data in ringbuffer may become mess */ if(E_MODE_MCU == g_sDevice.eMode) { /* Back-Ground to search AT delimiter */ uint8 tmp[AUPS_UART_RB_LEN]; uint32 avlb_cnt = suli_uart_readable(NULL, NULL); uint32 min_cnt = MIN(AUPS_UART_RB_LEN, avlb_cnt); /* Read,not pop,make sure we don't pollute user data in AUPS ringbuffer */ vHAL_UartRead(tmp, min_cnt); if (searchAtStarter(tmp, min_cnt)) { /* Set AT mode */ setNodeState(E_MODE_AT); suli_uart_printf(NULL, NULL, "Enter AT Mode.\r\n"); /* Clear ringbuffer of AUPS */ OS_eEnterCriticalSection(mutexRxRb); clear_ringbuffer(&rb_uart_aups); OS_eExitCriticalSection(mutexRxRb); } else { arduino_loop(); } /* * If a sleep event has already been scheduled in arduino_loop, * don't set a new arduino_loop */ if(true == bGetSleepStatus()) return; /* re-activate Arduino_Loop */ if(g_sDevice.config.upsXtalPeriod > 0) { OS_eStartSWTimer(Arduino_LoopTimer, APP_TIME_MS(g_sDevice.config.upsXtalPeriod), NULL); } else { OS_eActivateTask(Arduino_Loop); //this task is the lowest priority } } } /****************************************************************************/ /*** END OF FILE ***/ /****************************************************************************/
31.425397
105
0.436812
[ "mesh" ]
dd6d9e96868e98f1b00d61b52054a69d5fa0210a
11,903
h
C
src/c/mph/tuple_helpers.h
haesleinhuepf/hydra-image-processor
df15ba718ab4ed369a0b34434eab45f62e7c5377
[ "BSD-3-Clause" ]
8
2019-05-30T12:38:44.000Z
2020-02-10T20:01:45.000Z
src/c/mph/tuple_helpers.h
ericwait/hydra-signal-processor
76cbbac389045e7b3f26344cabec5befe5dcaf69
[ "BSD-3-Clause" ]
3
2018-09-27T12:40:54.000Z
2019-10-31T20:58:49.000Z
src/c/mph/tuple_helpers.h
ericwait/hydra-signal-processor
76cbbac389045e7b3f26344cabec5befe5dcaf69
[ "BSD-3-Clause" ]
4
2018-09-08T08:47:11.000Z
2020-01-19T11:57:26.000Z
#pragma once #include <tuple> #include "integer_sequence.h" namespace mph { // C++14 compatibility (make enable_if_t) template <bool Test, typename Type = void> using enable_if_t = typename std::enable_if<Test,Type>::type; ///////////////////////// // tuple_info - // Produces info about tuples that is useful in constexpr functions ///////////////////////// template <typename Tuple> struct tuple_info {}; template <typename... Types> struct tuple_info<std::tuple<Types...>> { static constexpr const int size = sizeof... (Types); using seq = mph::make_index_sequence<size>; using type = std::tuple<Types...>; }; template <typename Tuple> using tuple_info_t = typename tuple_info<Tuple>::type; // Internals for tuple-predicate filtering namespace internal { template <template<typename> class Pred, typename Tuple, typename Seq> struct filter_tuple_seq_impl {}; template <template<typename> class Pred, typename... Ts, std::size_t... Is> struct filter_tuple_seq_impl<Pred, std::tuple<Ts...>, index_sequence<Is...>> { template <typename T, std::size_t I> using filtered_seq = typename internal::conditional_seq<Pred<T>::value>::template type<std::size_t,I>; using type = typename mph::cat_integer_sequence<std::size_t, filtered_seq<Ts,Is>...>::type; }; // Used for index_seqence filtering template <size_t I, typename Head, typename... Tail> struct select_type_impl : public select_type_impl<I-1, Tail...> {}; template <typename Head, typename... Tail> struct select_type_impl<0, Head, Tail...> { using type = Head; }; // Get types of a tuple filtered on a index_sequence template <typename Seq, typename Tuple> struct select_tuple_types{}; template <std::size_t... Is, typename... Types> struct select_tuple_types<index_sequence<Is...>, std::tuple<Types...>> { using type = std::tuple<typename select_type_impl<Is, Types...>::type...>; }; template <typename... Types> struct select_tuple_types<index_sequence<>, std::tuple<Types...>> { using type = std::tuple<>; }; template <std::size_t N, typename Tuple> struct select_tuple_type {}; template <std::size_t N, typename... Types> struct select_tuple_type<N, std::tuple<Types...>> { using type = typename select_type_impl<N, Types...>::type; }; }; // Internal implementation for tie_tuple namespace internal { // TODO: Play with std::forward for this? template <std::size_t... Is, typename... Types> inline constexpr std::tuple<Types&...> tie_tuple_impl(index_sequence<Is...>, std::tuple<Types...>& tuple) { return std::tuple<Types&...>(std::get<Is>(tuple)...); } template <std::size_t... Is, typename... Types> inline constexpr std::tuple<Types&&...> tie_tuple_impl(index_sequence<Is...>, std::tuple<Types...>&& tuple) { return std::tuple<Types&&...>(std::get<Is>(tuple)...); } }; ///////////////////////// // filter_tuple_seq - // Generates an index sequence that can be used to select tuple subsets // based on a predicate (true/false) transform applied to each tuple element type ///////////////////////// template <template<typename> class Pred, typename Tuple> struct filter_tuple_seq {}; template <template<typename> class Pred, typename... Types> struct filter_tuple_seq<Pred, std::tuple<Types...>> { using type = typename internal::filter_tuple_seq_impl<Pred, std::tuple<Types...>, make_index_sequence<sizeof... (Types)>>::type; }; ///////////////////////// // filter_tuple_subseq - // Generates an index sequence that can be used to select tuple subsets // based on a predicate (true/false) transform applied to each tuple element type // // This version takes an input sub-seqeuence which is applied to tuple as a pre-filter // NOTE: Used for compositing filters (equivalent to and-ing predicates) ///////////////////////// template <template<typename> class Pred, typename Tuple, typename Subseq> struct filter_tuple_subseq {}; template <template<typename> class Pred, typename... Types, size_t... Is> struct filter_tuple_subseq<Pred, std::tuple<Types...>, index_sequence<Is...>> { using filtered_tuple = typename internal::select_tuple_types<index_sequence<Is...>, std::tuple<Types...>>::type; using type = typename internal::filter_tuple_seq_impl<Pred, filtered_tuple, index_sequence<Is...>>::type; }; ///////////////////////// // tie_tuple - // Takes a tuple instance and outputs a tuple of references to the tied variables // NOTE: the use of std::tie means this is really only useful if you have primary // data stored in a tuple ///////////////////////// template <typename... Types> inline constexpr std::tuple<Types&...> tie_tuple(std::tuple<Types...>& tuple) { return internal::tie_tuple_impl(make_index_sequence<sizeof...(Types)>(), tuple); } template <typename... Types> inline constexpr std::tuple<Types&&...> tie_tuple(std::tuple<Types...>&& tuple) { return internal::tie_tuple_impl(make_index_sequence<sizeof...(Types)>(), tuple); } ///////////////////////// // tuple_subset_t - // Returns the subset of tuple-types selected from the index sequence ///////////////////////// template <typename Seq, typename Tuple> using tuple_subset_t = typename internal::select_tuple_types<Seq, Tuple>::type; ///////////////////////// // tuple_subset_t - // Returns the type of the Nth value in tuple // TODO: Should use std::tuple_element instead? ///////////////////////// template <std::size_t N, typename Tuple> using tuple_select_t = typename internal::select_tuple_type<N, Tuple>::type; // Internals for tuple subset selection namespace internal { template <std::size_t... Is, typename... Types, typename = enable_if_t<!std::is_same<std::tuple<Types...>, std::tuple<>>::value>> inline constexpr tuple_subset_t<index_sequence<Is...>, std::tuple<Types&...>> tuple_subset_impl(index_sequence<Is...>, std::tuple<Types&...> tuple) { return tuple_subset_t<index_sequence<Is...>, std::tuple<Types&...>>(std::get<Is>(tuple)...); } template <std::size_t... Is, typename... Types> inline constexpr tuple_subset_t<index_sequence<Is...>, std::tuple<Types...>> tuple_subset_impl(index_sequence<Is...>, const std::tuple<Types...>& tuple) { return tuple_subset_t<index_sequence<Is...>, std::tuple<Types...>>(std::get<Is>(tuple)...); } } ///////////////////////// // tuple_subset - // Returns a new tuple that is the subset of elements (references if lvalue) listed in the // index sequence // NOTE: This SHOULD fail at compile-time if passed a make_tuple (doesn't on msvc) // NOTE: MSVC chooses std::tuple<Types&...> for non-reference arrays and matches std::tuple<>. // The gross enable_if_t forces it to use the correct overload definition ///////////////////////// // TODO: Make const versions of the reference subset functions template <std::size_t... Is, typename... Types, typename = enable_if_t<!std::is_same<std::tuple<Types...>,std::tuple<>>::value>> inline constexpr tuple_subset_t<index_sequence<Is...>, std::tuple<Types&...>> tuple_subset(index_sequence<Is...>, std::tuple<Types&...> tuple) { return internal::tuple_subset_impl(index_sequence<Is...>{}, tuple); } // Support template <std::size_t... Is, typename... Types> inline constexpr tuple_subset_t<index_sequence<Is...>, std::tuple<Types&...>> tuple_subset(index_sequence<Is...>, std::tuple<Types...>& tuple) { return internal::tuple_subset_impl(index_sequence<Is...>{}, tie_tuple(tuple)); } template <std::size_t... Is, typename... Types> inline constexpr tuple_subset_t<index_sequence<Is...>, std::tuple<Types...>> tuple_subset(index_sequence<Is...>, std::tuple<Types...>&& tuple) { return internal::tuple_subset_impl(index_sequence<Is...>{}, tie_tuple(tuple)); } ///////////////////////// // tuple_type_tfm - // Applies a type-transform structure (Tfm<E>::type) to each element-type E of a tuple // returns a tuple-type of transformed types ///////////////////////// template <template<typename> class Tfm, typename Tuple> struct tuple_type_tfm {}; template <template<typename> class Tfm, typename... Args> struct tuple_type_tfm<Tfm, std::tuple<Args...>> { using type = std::tuple<typename Tfm<Args>::type...>; }; template <template<typename> class TfmH, template<typename> class... TfmTail> struct compose_type_tfm { template <typename Tuple> struct tfm { using type = typename TfmH< typename compose_type_tfm<TfmTail...>::template tfm<Tuple>::type >::type; }; }; template <template<typename> class TfmH> struct compose_type_tfm<TfmH> { template <typename Tuple> struct tfm { using type = typename TfmH<Tuple>::type; }; }; namespace internal { template <typename Tuple> using composed_deref = compose_type_tfm<std::add_lvalue_reference, std::remove_pointer, std::remove_reference>::template tfm<Tuple>; }; template <typename Tuple> using tuple_ptr_t = typename tuple_type_tfm<std::add_pointer, Tuple>::type; template <typename Tuple> using tuple_deref_t = typename tuple_type_tfm<internal::composed_deref, Tuple>::type; // Internals for tuple_ptr/deref namespace internal { template <std::size_t... Is, typename... Types> inline constexpr tuple_ptr_t<std::tuple<Types...>> tuple_addr_of_impl(index_sequence<Is...>, std::tuple<Types&...> vars) { return tuple_ptr_t<std::tuple<Types...>>((&std::get<Is>(vars))...); } template <std::size_t...Is, typename... Types> inline constexpr tuple_deref_t<std::tuple<Types...>> tuple_deref_impl(index_sequence<Is...>, std::tuple<Types...> vars) { return tuple_deref_t<std::tuple<Types...>>((*std::get<Is>(vars))...); } }; ///////////////////////// // tuple_addr_of - // Return a tuple of pointers to input tuple elements (e.g. &var for each element) // TODO: Compatibility: Removed constexpr because gcc 5.4.0 flips out ///////////////////////// template <typename... Types> inline tuple_ptr_t<std::tuple<Types...>> tuple_addr_of(std::tuple<Types&...> tuple) { return internal::tuple_addr_of_impl(make_index_sequence<sizeof... (Types)>(), tuple); } template <typename... Types> inline tuple_ptr_t<std::tuple<Types...>> tuple_addr_of(std::tuple<Types...>& tuple) { return internal::tuple_addr_of_impl(make_index_sequence<sizeof... (Types)>(), tie_tuple(tuple)); } ///////////////////////// // tuple_deref - // Return a tuple of references to values from a tuple of pointers // TODO: Compatibility: Removed constexpr because gcc 5.4.0 flips out ///////////////////////// template <typename... Types> inline tuple_deref_t<std::tuple<Types...>> tuple_deref(std::tuple<Types...> tuple) { return internal::tuple_deref_impl(make_index_sequence<sizeof... (Types)>(), tuple); } // Internals for creating a replicated-value tuple namespace internal { template <std::size_t... Is, typename... Types, typename T> inline void tuple_fill_impl(index_sequence<Is...>, std::tuple<Types&...> tuple, T val) { (void)std::initializer_list<int> { ((std::get<Is>(tuple) = val), void(), 0)... }; } }; ///////////////////////// // tuple_fill_value // Fill the tuple with a specific value (mostly useful for nulling pointers) ///////////////////////// template <typename... Types, typename T> inline void tuple_fill_value(std::tuple<Types&...> tuple, T val) { internal::tuple_fill_impl(make_index_sequence<sizeof... (Types)>{}, tuple, val); } template <typename... Types, typename T> inline void tuple_fill_value(std::tuple<Types...>& tuple, T val) { internal::tuple_fill_impl(make_index_sequence<sizeof... (Types)>{}, tie_tuple(tuple), val); } // TODO: Move these to a different mph header template <bool B> using bool_constant = std::integral_constant<bool, B>; template<class B> struct negation: bool_constant<!bool(B::value)> { }; };
33.815341
154
0.667059
[ "transform" ]
dd8660f60473ac0d5c03f1ef5b509a86e1689510
7,045
h
C
grr/client/minicomm/file_contents.h
mikecb/grr
52fdd977729af2a09a147301c55b8b7f1eccfa67
[ "Apache-2.0" ]
5
2017-03-17T08:25:09.000Z
2022-02-22T05:28:14.000Z
grr/client/minicomm/file_contents.h
mikecb/grr
52fdd977729af2a09a147301c55b8b7f1eccfa67
[ "Apache-2.0" ]
null
null
null
grr/client/minicomm/file_contents.h
mikecb/grr
52fdd977729af2a09a147301c55b8b7f1eccfa67
[ "Apache-2.0" ]
3
2018-12-07T07:04:37.000Z
2022-02-22T05:28:16.000Z
#ifndef GRR_CLIENT_MINICOMM_FILE_CONTENTS_H_ #define GRR_CLIENT_MINICOMM_FILE_CONTENTS_H_ #include <iterator> #include <memory> #include "grr/client/minicomm/file_operations.h" namespace grr { class FileContentsIterator; // Provides read only random access to the contends of fd. The observed size // is fixed during the constructor. If the file is truncated after construction, // the missing bytes will be seen as having zero value. class FileContents { public: explicit FileContents(OpenedPath* fd) : error_(""), fd_(fd), blocks_(fd_->size() / kBlockSize + ((fd_->size() % kBlockSize) ? 1 : 0)), recent_block_index_(0) {} // These iterators, and their derivatives are use *this for backing and are // unsafe once *this is deleted. FileContentsIterator begin(); FileContentsIterator end(); private: // Used to read the file: std::string error_; OpenedPath* const fd_; // A power of 2. Expressions like n/kBlockSize and n%kBlockSize will be // optimized into bit shifts and masks. static constexpr size_t kBlockSize = 64 * 1024; struct Block { char data[kBlockSize]; }; // Find or load a block. Will return nullptr if index is >= blocks_.size(). std::shared_ptr<Block> GetBlock(int index); // A directory of blocks. Pre-allocated to store a (possibly empty) reference // to every block. std::vector<std::weak_ptr<Block>> blocks_; // If we have an iterator to a block, it will stay loaded. In addition we // always keep the last 4 blocks that we've loaded. This is to minimize the // chance of thrashing if an iterator moves back and forth repeatedly across a // block boundary. static constexpr int kNumRecentBlocks = 4; unsigned int recent_block_index_; std::shared_ptr<Block> recent_blocks_[kNumRecentBlocks]; friend class FileContentsIterator; }; // Random access iterator over the contents of a file. This is meant an // alternative to a pointer to a memmapped file with the following two // advantages: // 1) Does not crash if the file is truncated after creation. // 2) Can read large files on 32 bit systems. class FileContentsIterator : public std::iterator<std::random_access_iterator_tag, char, int64> { private: public: FileContentsIterator(difference_type offset, FileContents* contents) : contents_(contents) { GOOGLE_DCHECK(offset <= contents->fd_->size()); block_offset_ = offset % kBlockSize; block_index_ = offset / kBlockSize; data_ = contents->GetBlock(block_index_); } FileContentsIterator() : contents_(nullptr) {} inline difference_type FileOffset() const { return block_offset_ + block_index_ * FileContents::kBlockSize; } FileContentsIterator(const FileContentsIterator&) = default; FileContentsIterator(FileContentsIterator&&) = default; FileContentsIterator& operator=(const FileContentsIterator&) = default; FileContentsIterator& operator=(FileContentsIterator&&) = default; FileContentsIterator& operator++() { if (block_offset_ < kBlockSize - 1) { block_offset_ += 1; return *this; } block_offset_ = 0; block_index_ += 1; data_ = contents_->GetBlock(block_index_); return *this; } FileContentsIterator operator++(int) { FileContentsIterator r = *this; ++(*this); return r; } FileContentsIterator& operator+=(difference_type n) { if (n == 0) { return *this; } difference_type n_offset = block_offset_ + n; if (IsValidBlockOffset(n_offset)) { block_offset_ = n_offset; return *this; } const difference_type current_offset = FileOffset(); GOOGLE_DCHECK(n > 0 || -n <= current_offset); const difference_type new_offset = current_offset + n; *this = FileContentsIterator(new_offset, contents_); return *this; } FileContentsIterator& operator-=(difference_type n) { return * this += -n; } FileContentsIterator operator+(difference_type n) const { FileContentsIterator r(*this); r += n; return r; } friend FileContentsIterator operator+(difference_type n, const FileContentsIterator& rhs) { return rhs + n; } FileContentsIterator operator-(difference_type n) { FileContentsIterator r(*this); r += -n; return r; } difference_type operator-(const FileContentsIterator& rhs) { return FileOffset() - rhs.FileOffset(); } FileContentsIterator& operator--() { if (block_offset_ > 0) { block_offset_ -= 1; return *this; } GOOGLE_DCHECK(block_index_ > 0); block_offset_ = kBlockSize - 1; block_index_ -= 1; data_ = contents_->GetBlock(block_index_); return *this; } FileContentsIterator operator--(int) { FileContentsIterator r = *this; --(*this); return r; } char operator*() const { GOOGLE_DCHECK(IsValidBlockOffset(block_offset_)); GOOGLE_DCHECK(data_ != nullptr); return data_->data[block_offset_]; } char operator[](difference_type n) const { const difference_type n_offset = block_offset_ + n; if (IsValidBlockOffset(n_offset)) { return data_->data[n_offset]; } return *FileContentsIterator(FileOffset() + n, contents_); } bool operator==(const FileContentsIterator& rhs) const { GOOGLE_DCHECK(contents_ == rhs.contents_); return block_offset_ == rhs.block_offset_ && block_index_ == rhs.block_index_; } bool operator!=(const FileContentsIterator& rhs) const { GOOGLE_DCHECK(contents_ == rhs.contents_); return block_offset_ != rhs.block_offset_ || block_index_ != rhs.block_index_; } bool operator<(const FileContentsIterator& rhs) const { GOOGLE_DCHECK(contents_ == rhs.contents_); return block_index_ < rhs.block_index_ || (block_index_ == rhs.block_index_ && block_offset_ < rhs.block_offset_); } bool operator>(const FileContentsIterator& rhs) const { return rhs < *this; } bool operator<=(const FileContentsIterator& rhs) const { return block_index_ < rhs.block_index_ || (block_index_ == rhs.block_index_ && block_offset_ <= rhs.block_offset_); } bool operator>=(const FileContentsIterator& rhs) const { return rhs <= *this; } const char* operator->() const { GOOGLE_DCHECK(IsValidBlockOffset(block_offset_)); GOOGLE_DCHECK(data_ != nullptr); return &data_->data[block_offset_]; } private: static constexpr size_t kBlockSize = FileContents::kBlockSize; typedef FileContents::Block Block; static inline bool IsValidBlockOffset(difference_type offset) { return offset >= 0 && offset < kBlockSize; } int block_offset_; int block_index_; std::shared_ptr<Block> data_; FileContents* contents_; }; inline FileContentsIterator FileContents::begin() { return FileContentsIterator(0, this); } inline FileContentsIterator FileContents::end() { return FileContentsIterator(fd_->size(), this); } } // namespace grr #endif // GRR_CLIENT_MINICOMM_FILE_CONTENTS_H_
29.978723
80
0.695955
[ "vector" ]
dd8888945402d622375d1d044fee1a755aa11bc1
12,814
c
C
crankvisual/crankrenderplacedata.c
WSID/crank-system
7c94f829050815392259c227e38b34f97886f7fc
[ "MIT" ]
null
null
null
crankvisual/crankrenderplacedata.c
WSID/crank-system
7c94f829050815392259c227e38b34f97886f7fc
[ "MIT" ]
null
null
null
crankvisual/crankrenderplacedata.c
WSID/crank-system
7c94f829050815392259c227e38b34f97886f7fc
[ "MIT" ]
null
null
null
/* Copyright (C) 2015, WSID */ /* 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. */ #define _CRANKVISUAL_INSIDE #include <glib.h> #include <glib-object.h> #include "crankbase.h" #include "crankshape.h" #include "crankcore.h" #include "crankvisible.h" #include "crankprojection.h" #include "crankrenderplacedata.h" //////// Private Functions ///////////////////////////////////////////////////// //////// List of virtual functions ///////////////////////////////////////////// void crank_render_place_data_constructed (GObject *object); void crank_render_place_data_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec); void crank_render_place_data_dispose (GObject *object); void crank_render_place_data_finalize (GObject *object); gboolean crank_render_place_data_adding (CrankCompositable *compositable, CrankComposite *composite, GError **error); gboolean crank_render_place_data_removing (CrankCompositable *compositable, CrankComposite *composite, GError **error); //////// Private function for callback ///////////////////////////////////////// CrankVecFloat3 *crank_render_place_data_get_pos (gpointer data, gpointer userdata); gfloat crank_render_place_data_get_rad (gpointer data, gpointer userdata); void crank_render_place_data_free_pair (gpointer data); //////// Private type definition /////////////////////////////////////////////// struct _CrankRenderPlaceData { CrankCompositable1N parent; GHashTable **entity_counts; CrankOctreeSet **entity_sets; guint nentity_sets; }; G_DEFINE_TYPE (CrankRenderPlaceData, crank_render_place_data, CRANK_TYPE_COMPOSITABLE) //////// GTypeInstance ///////////////////////////////////////////////////////// void crank_render_place_data_init (CrankRenderPlaceData *pdata) { } void crank_render_place_data_class_init (CrankRenderPlaceDataClass *c) { GObjectClass *c_gobject = G_OBJECT_CLASS (c); CrankCompositableClass *c_compositable = CRANK_COMPOSITABLE_CLASS (c); c_gobject->constructed = crank_render_place_data_constructed; c_gobject->set_property = crank_render_place_data_set_property; c_gobject->dispose = crank_render_place_data_dispose; c_gobject->finalize = crank_render_place_data_finalize; c_compositable->adding = crank_render_place_data_adding; c_compositable->removing = crank_render_place_data_removing; pspecs_priv[PROP_PRIV_VISIBLE_TYPES] = g_param_spec_uint ("visible-types", "Visible types", "Visible types", 0, 16, 2, G_PARAM_PRIVATE | G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS ); g_object_class_install_properties (c_gobject, PROP_PRIV_COUNTS, pspecs_priv); crank_compositable_class_add_requisition (c_compositable, CRANK_TYPE_PLACE3); } //////// GObject /////////////////////////////////////////////////////////////// void crank_render_place_data_constructed (GObject *object) { CrankRenderPlaceData *pdata = (CrankRenderPlaceData*) object; CrankPlace3 *place = g_object_get_data (object, "place"); guint visible_types = GPOINTER_TO_UINT (g_object_get_data (object, "visible-types")); gpointer visible_offset = g_object_get_data (object, "visible-offset"); pdata->nentity_sets = visible_types; pdata->entity_sets = g_new (CrankOctreeSet*, pdata->nentity_sets); } void crank_render_place_data_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { switch (prop_id) { case PROP_PRIV_VISIBLE_TYPES: g_object_set_data (object, "visible-types", GINT_TO_POINTER (g_value_get_uint (value))); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); } } void crank_render_place_data_dispose (GObject *object) { GObjectClass *pc = crank_render_place_data_parent_class; CrankRenderPlaceData *pdata = (CrankRenderPlaceData*) object; guint i; for (i = 0; i < pdata->nentity_sets; i++) crank_octree_set_remove_all (pdata->entity_sets[i]); pc->dispose (object); } void crank_render_place_data_finalize (GObject *object) { GObjectClass *pc = crank_render_place_data_parent_class; CrankRenderPlaceData *pdata = (CrankRenderPlaceData*) object; guint i; for (i = 0; i < pdata->nentity_sets; i++) crank_octree_set_unref (pdata->entity_sets[i]); g_free (pdata->entity_sets); pc->finalize (object); } //////// CrankCompositable ///////////////////////////////////////////////////// gboolean crank_render_place_data_adding (CrankCompositable *compositable, CrankComposite *composite, GError **error) { CrankCompositableClass *pc = crank_render_place_data_parent_class; CrankRenderPlaceData *pdata; CrankPlace3 *place; guint i; if (! pc->adding (compositable, composite, error)) return FALSE; pdata = (CrankRenderPlaceData*) compositable; place = (CrankPlace3*)composite; pdata->entity_counts = g_new (GHashTable*, pdata->nentity_sets); pdata->entity_sets = g_new (CrankOctreeSet*, pdata->nentity_sets); for (i = 0; i < pdata->nentity_sets; i++) { pdata->entity_counts[i] = g_hash_table_new (g_direct_hash, g_direct_equal); pdata->entity_sets[i] = crank_octree_set_new_full (& place->boundary, crank_render_place_data_get_pos, NULL, NULL, crank_render_place_data_get_rad, NULL, NULL, crank_render_place_data_free_pair, crank_pair_object_hash, crank_pair_object_equal); } return TRUE; } gboolean crank_render_place_data_removing (CrankCompositable *compositable, CrankComposite *composite, GError **error) { CrankCompositableClass *pc = crank_render_place_data_parent_class; CrankRenderPlaceData *pdata; CrankPlace3 *place; guint i; pdata = (CrankRenderPlaceData*) compositable; place = (CrankPlace3*)composite; if (! pc->removing (compositable, composite, error)) return FALSE; for (i = 0; i < pdata->nentity_sets; i++) { g_hash_table_unref (pdata->entity_counts[i]); crank_octree_set_remove_all (pdata->entity_sets[i]); } g_free (pdata->entity_sets); pdata->entity_sets = NULL; return TRUE; } //////// Private type callbacks //////////////////////////////////////////////// CrankVecFloat3* crank_render_place_data_get_pos (gpointer data, gpointer userdata) { CrankPairPointer *pair = (CrankPairPointer*) data; CrankEntity3 *entity = (CrankEntity3*)pair->a; return & entity->position.mtrans; } gfloat crank_render_place_data_get_rad (gpointer data, gpointer userdata) { CrankPairPointer *pair = (CrankPairPointer*) data; CrankEntity3 *entity = (CrankEntity3*)pair->a; CrankVisible *visible = (CrankVisible*)pair->b; return entity->position.mscl * crank_visible_get_visible_radius (visible); } void crank_render_place_data_free_pair (gpointer data) { g_slice_free (CrankPairPointer, data); } //////// Internal Functions //////////////////////////////////////////////////// G_GNUC_INTERNAL void crank_render_place_data_add_entity (CrankRenderPlaceData *pdata, CrankEntity *entity, CrankVisible *visible, const guint tindex) { CrankOctreeSet *entity_set = pdata->entity_sets[tindex]; CrankPairObject *pair = g_slice_new (CrankPairObject); pair->a = (GObject*) entity; pair->b = (GObject*) visible; crank_octree_set_add (entity_set, pair); } G_GNUC_INTERNAL void crank_render_place_data_remove_entity (CrankRenderPlaceData *pdata, CrankEntity *entity, CrankVisible *visible, const guint tindex) { CrankOctreeSet *entity_set = pdata->entity_sets[tindex]; CrankPairObject pair = {(GObject*)entity, (GObject*)visible}; crank_octree_set_remove (entity_set, &pair); } //////// Public Functions ////////////////////////////////////////////////////// /** * crank_render_place_data_get_culled_list: * @pdata: A Place Data. * @culls: (array length=nculls): Array of planes to cull. * @nculls: Number of planes to cull. * @tindex: Type index. * * Adds items to @entities, which is frustum culled. * * Returns: (transfer container) (element-type CrankPairObject): List of entities * which is culled. */ GList* crank_render_place_data_get_culled_list (CrankRenderPlaceData *pdata, const CrankPlane3 *culls, const guint nculls, const guint tindex) { return crank_octree_set_get_culled_list (pdata->entity_sets[tindex], culls, nculls); } /** * crank_render_place_data_get_culled_array: * @pdata: A Place Data. * @entities: (transfer none) (element-type CrankPairObject): Array of entities. * @culls: (array length=nculls): Array of planes to cull. * @nculls: Number of planes to cull. * @tindex: Type index. * * Adds items to @entities, which is culled. * * Returns: (transfer none) (element-type CrankPairObject): @entities, with added entities. */ GPtrArray* crank_render_place_data_get_culled_array (CrankRenderPlaceData *pdata, GPtrArray *entities, const CrankPlane3 *culls, const guint nculls, const guint tindex) { return crank_octree_set_add_culled_array (pdata->entity_sets[tindex], entities, culls, nculls); } /** * crank_render_place_data_foreach_culled: * @pdata: A Place Data. * @culls: (array length=nculls): Array of planes to cull. * @nculls: Number of planes to cull. * @tindex: Type index. * @func: (scope call): A Function to call for each pair of (CrankEntity3, * CrankVisible). * @userdata: (closure func): Userdata for @func. * * Call @func for each pair in place. */ void crank_render_place_data_foreach_culled (CrankRenderPlaceData *pdata, const CrankPlane3 *culls, const guint nculls, const guint tindex, GFunc func, gpointer userdata) { return crank_octree_set_cull_foreach (pdata->entity_sets[tindex], culls, nculls, func, userdata); }
28.412417
91
0.600203
[ "object" ]
dd8bd893c54351da170399baa70c2752118601e8
4,104
h
C
modules/perception/inference/tensorrt/plugins/rcnn_proposal_plugin.h
jzjonah/apollo
bc534789dc0548bf2d27f8d72fe255d5c5e4f951
[ "Apache-2.0" ]
22,688
2017-07-04T23:17:19.000Z
2022-03-31T18:56:48.000Z
modules/perception/inference/tensorrt/plugins/rcnn_proposal_plugin.h
WJY-Mark/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
[ "Apache-2.0" ]
4,804
2017-07-04T22:30:12.000Z
2022-03-31T12:58:21.000Z
modules/perception/inference/tensorrt/plugins/rcnn_proposal_plugin.h
WJY-Mark/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
[ "Apache-2.0" ]
9,985
2017-07-04T22:01:17.000Z
2022-03-31T14:18:16.000Z
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <vector> #include "modules/perception/inference/tensorrt/rt_common.h" namespace apollo { namespace perception { namespace inference { // TODO(chenjiahao): complete member functions class RCNNProposalPlugin : public nvinfer1::IPlugin { public: RCNNProposalPlugin( const BBoxRegParameter &bbox_reg_param, const DetectionOutputSSDParameter &detection_output_ssd_param, nvinfer1::Dims *in_dims) { num_rois_ = in_dims[2].d[0]; for (int i = 0; i < 4; ++i) { bbox_mean_[i] = bbox_reg_param.bbox_mean(i); bbox_std_[i] = bbox_reg_param.bbox_std(i); } min_size_mode_ = static_cast<int>(detection_output_ssd_param.min_size_mode()); min_size_h_ = detection_output_ssd_param.min_size_h(); min_size_w_ = detection_output_ssd_param.min_size_w(); num_class_ = detection_output_ssd_param.num_class(); refine_out_of_map_bbox_ = detection_output_ssd_param.refine_out_of_map_bbox(); regress_agnostic_ = detection_output_ssd_param.regress_agnostic(); rpn_proposal_output_score_ = detection_output_ssd_param.rpn_proposal_output_score(); threshold_objectness_ = detection_output_ssd_param.threshold_objectness(); for (int i = 0; i < num_class_; ++i) { thresholds_.push_back(detection_output_ssd_param.threshold(i)); } NMSSSDParameter nms_param = detection_output_ssd_param.nms_param(); max_candidate_n_ = nms_param.max_candidate_n(0); overlap_ratio_ = nms_param.overlap_ratio(0); top_n_ = nms_param.top_n(0); out_channel_ = rpn_proposal_output_score_ ? 9 : 5; } virtual ~RCNNProposalPlugin() {} virtual int initialize() { return 0; } virtual void terminate() {} int getNbOutputs() const override { return 1; } nvinfer1::Dims getOutputDimensions(int index, const nvinfer1::Dims *inputs, int nbInputDims) override { // TODO(chenjiahao): complete input dims assertion // TODO(chenjiahao): batch size is hard coded to 1 here return nvinfer1::Dims4(top_n_ * 1, out_channel_, 1, 1); } void configure(const nvinfer1::Dims *inputDims, int nbInputs, const nvinfer1::Dims *outputDims, int nbOutputs, int maxBatchSize) override {} size_t getWorkspaceSize(int maxBatchSize) const override { return 0; } virtual int enqueue(int batchSize, const void *const *inputs, void **outputs, void *workspace, cudaStream_t stream); size_t getSerializationSize() override { return 0; } void serialize(void *buffer) override { char *d = reinterpret_cast<char *>(buffer), *a = d; size_t size = getSerializationSize(); CHECK_EQ(d, a + size); } private: const int thread_size_ = 512; bool refine_out_of_map_bbox_ = true; // TODO(chenjiahao): implement class-agnostic regression option bool regress_agnostic_ = false; bool rpn_proposal_output_score_ = true; float bbox_mean_[4]; float bbox_std_[4]; float min_size_h_; float min_size_w_; float threshold_objectness_; float overlap_ratio_; int num_class_; int num_rois_; int max_candidate_n_; int min_size_mode_; int top_n_; int out_channel_; int acc_box_num_; std::vector<float> thresholds_{}; }; } // namespace inference } // namespace perception } // namespace apollo
33.365854
79
0.691033
[ "vector" ]
dd8ef8fa93fa9a7cba92e1b501d1228da128e3e7
14,262
h
C
include/hge.h
gitindro/hge
713d6e8ae45d522e2c32732613b8444a05ef8353
[ "Zlib" ]
203
2015-01-20T11:07:24.000Z
2022-03-31T08:38:05.000Z
include/hge.h
gitindro/hge
713d6e8ae45d522e2c32732613b8444a05ef8353
[ "Zlib" ]
6
2017-02-17T10:59:21.000Z
2021-05-17T04:29:18.000Z
include/hge.h
gitindro/hge
713d6e8ae45d522e2c32732613b8444a05ef8353
[ "Zlib" ]
75
2015-03-09T01:36:46.000Z
2022-03-31T08:38:07.000Z
/*----------------------------------------------------------------------------- * Haaf's Game Engine 1.9 * Copyright (C) 2003-2007, Relish Games * Maintained 2012-2021 by dmytro.lytovchenko@gmail.com (github @kvakvs) * Github -- https://github.com/kvakvs/hge | Discord -- https://discord.gg/TdjamHt * * Old website: http://hge.relishgames.com; Old forum: http://relishgames.com/forum *-----------------------------------------------------------------------------*/ #pragma once #include <windows.h> #define HGE_VERSION 0x190 #include <impl/hgedefs.h> #include <impl/hgehandle.h> #include <impl/hgekeys.h> #include <impl/hgecolor.h> /* ** HGE System state constants */ enum hgeBoolState : int32_t { HGE_WINDOWED = 1, // bool run in window? (default: false) HGE_ZBUFFER = 2, // bool use z-buffer? (default: false) HGE_TEXTUREFILTER = 3, // bool texture filtering? (default: true) HGE_USESOUND = 4, // bool use BASS for sound? (default: true) HGE_DONTSUSPEND = 5, // bool focus lost:suspend? (default: false) HGE_HIDEMOUSE = 6, // bool hide system cursor? (default: true) HGE_SHOWSPLASH = 7, // bool hide system cursor? (default: true) }; enum hgeFuncState : int32_t { HGE_FRAMEFUNC = 8, // bool*() frame function (default: NULL) (you MUST set this) HGE_RENDERFUNC = 9, // bool*() render function (default: NULL) HGE_FOCUSLOSTFUNC = 10, // bool*() focus lost function (default: NULL) HGE_FOCUSGAINFUNC = 11, // bool*() focus gain function (default: NULL) HGE_GFXRESTOREFUNC = 12, // bool*() exit function (default: NULL) HGE_EXITFUNC = 13, // bool*() exit function (default: NULL) }; enum hgeHwndState : int32_t { HGE_HWND = 15, // int window handle: read only HGE_HWNDPARENT = 16, // int parent win handle (default: 0) }; enum hgeIntState : int32_t { HGE_SCREENWIDTH = 17, // int screen width (default: 800) HGE_SCREENHEIGHT = 18, // int screen height (default: 600) HGE_SCREENBPP = 19, // int screen bitdepth (default: 32) (desktop bpp in windowed mode) HGE_SAMPLERATE = 20, // int sample rate (default: 44100) HGE_FXVOLUME = 21, // int global fx volume (default: 100) HGE_MUSVOLUME = 22, // int global music volume (default: 100) HGE_STREAMVOLUME = 23, // int global music volume (default: 100) HGE_FPS = 24, // int fixed fps (default: HGEFPS_UNLIMITED) HGE_POWERSTATUS = 25, // int battery life percent + status }; enum hgeStringState : int32_t { HGE_ICON = 26, // char* icon resource (default: NULL) HGE_TITLE = 27, // char* window title (default: "HGE") HGE_INIFILE = 28, // char* ini file (default: NULL) (meaning no file) HGE_LOGFILE = 29, // char* log file (default: NULL) (meaning no file) }; // // Callback protoype used by HGE // typedef bool (*hgeCallback)(); // // HGE_FPS system state special constants // enum { HGEFPS_UNLIMITED = 0, HGEFPS_VSYNC = -1, }; // // HGE_POWERSTATUS system state special constants // enum { HGEPWR_AC = -1, HGEPWR_UNSUPPORTED = -2, }; // // HGE Primitive type constants // enum { HGEPRIM_LINES = 2, HGEPRIM_TRIPLES = 3, HGEPRIM_QUADS = 4, }; // // HGE Vertex structure // struct hgeVertex { float x, y; // screen position float z; // Z-buffer depth 0..1 uint32_t col; // color float tx, ty; // texture coordinates }; // // HGE Triple structure, represents a textured triangle // struct hgeTriple { hgeVertex v[3]; HTEXTURE tex; hgeBlendMode blend; }; // // HGE Quad structure // struct hgeQuad { hgeVertex v[4]; HTEXTURE tex; hgeBlendMode blend; }; // // HGE Interface class // Using PImpl pattern HGE class hides internal implementation detail from the user program. // The actual implementation is in hge_impl.h and not exported from the DLL. // class HGE { public: virtual ~HGE() = default; virtual void HGE_CALL Release() = 0; virtual bool HGE_CALL System_Initiate() = 0; virtual void HGE_CALL System_Shutdown() = 0; virtual bool HGE_CALL System_Start() = 0; virtual const char *HGE_CALL System_GetErrorMessage() const = 0; // NOLINTNEXTLINE virtual void HGE_CALL System_Log(const char *format, ...) = 0; virtual bool HGE_CALL System_Launch(const char *url) = 0; virtual void HGE_CALL System_Snapshot(const char *filename = nullptr) = 0; private: virtual void HGE_CALL System_SetStateBool(hgeBoolState state, bool value) = 0; virtual void HGE_CALL System_SetStateFunc(hgeFuncState state, hgeCallback value) = 0; virtual void HGE_CALL System_SetStateHwnd(hgeHwndState state, HWND value) = 0; virtual void HGE_CALL System_SetStateInt(hgeIntState state, int value) = 0; virtual void HGE_CALL System_SetStateString(hgeStringState state, const char *value) = 0; virtual bool HGE_CALL System_GetStateBool(hgeBoolState state) = 0; virtual hgeCallback HGE_CALL System_GetStateFunc(hgeFuncState state) = 0; virtual HWND HGE_CALL System_GetStateHwnd(hgeHwndState state) = 0; virtual int HGE_CALL System_GetStateInt(hgeIntState state) = 0; virtual const char *HGE_CALL System_GetStateString(hgeStringState state) = 0; public: void System_SetState(const hgeBoolState state, const bool value) { System_SetStateBool(state, value); } void System_SetState(const hgeFuncState state, const hgeCallback value) { System_SetStateFunc(state, value); } void System_SetState(const hgeHwndState state, HWND value) { System_SetStateHwnd(state, value); } void System_SetState(const hgeIntState state, const int value) { System_SetStateInt(state, value); } void System_SetState(const hgeStringState state, const char *value) { System_SetStateString(state, value); } bool System_GetState(const hgeBoolState state) { return System_GetStateBool(state); } hgeCallback System_GetState(const hgeFuncState state) { return System_GetStateFunc(state); } HWND System_GetState(const hgeHwndState state) { return System_GetStateHwnd(state); } int System_GetState(const hgeIntState state) { return System_GetStateInt(state); } const char *System_GetState(const hgeStringState state) { return System_GetStateString(state); } virtual void *HGE_CALL Resource_Load(const char *filename, uint32_t *size = nullptr) = 0; virtual void HGE_CALL Resource_Free(void *res) = 0; virtual bool HGE_CALL Resource_AttachPack(const char *filename, const char *password = nullptr) = 0; virtual void HGE_CALL Resource_RemovePack(const char *filename) = 0; virtual void HGE_CALL Resource_RemoveAllPacks() = 0; virtual const char *HGE_CALL Resource_MakePath(const char *filename = nullptr) = 0; virtual const char *HGE_CALL Resource_EnumFiles(const char *wildcard = nullptr) = 0; virtual const char *HGE_CALL Resource_EnumFolders(const char *wildcard = nullptr) = 0; virtual void HGE_CALL Ini_SetInt(const char *section, const char *name, int value) = 0; virtual int HGE_CALL Ini_GetInt(const char *section, const char *name, int def_val) = 0; virtual void HGE_CALL Ini_SetFloat(const char *section, const char *name, float value) = 0; virtual float HGE_CALL Ini_GetFloat(const char *section, const char *name, float def_val) = 0; virtual void HGE_CALL Ini_SetString(const char *section, const char *name, const char *value) = 0; virtual const char *HGE_CALL Ini_GetString(const char *section, const char *name, const char *def_val) = 0; virtual void HGE_CALL Random_Seed(int seed = 0) = 0; virtual int HGE_CALL Random_Int(int min, int max) = 0; virtual float HGE_CALL Random_Float(float min, float max) = 0; virtual float HGE_CALL Timer_GetTime() = 0; virtual float HGE_CALL Timer_GetDelta() = 0; virtual int HGE_CALL Timer_GetFPS() = 0; virtual HEFFECT HGE_CALL Effect_Load(const char *filename, uint32_t size = 0) = 0; virtual void HGE_CALL Effect_Free(HEFFECT eff) = 0; virtual HCHANNEL HGE_CALL Effect_Play(HEFFECT eff) = 0; virtual HCHANNEL HGE_CALL Effect_PlayEx(HEFFECT eff, int volume = 100, int pan = 0, float pitch = 1.0f, bool loop = false) = 0; virtual HMUSIC HGE_CALL Music_Load(const char *filename, uint32_t size = 0) = 0; virtual void HGE_CALL Music_Free(HMUSIC mus) = 0; virtual HCHANNEL HGE_CALL Music_Play(HMUSIC mus, bool loop, int volume = 100, int order = -1, int row = -1) = 0; virtual void HGE_CALL Music_SetAmplification(HMUSIC music, int ampl) = 0; virtual int HGE_CALL Music_GetAmplification(HMUSIC music) = 0; virtual int HGE_CALL Music_GetLength(HMUSIC music) = 0; virtual void HGE_CALL Music_SetPos(HMUSIC music, int order, int row) = 0; virtual bool HGE_CALL Music_GetPos(HMUSIC music, int *order, int *row) = 0; virtual void HGE_CALL Music_SetInstrVolume(HMUSIC music, int instr, int volume) = 0; virtual int HGE_CALL Music_GetInstrVolume(HMUSIC music, int instr) = 0; virtual void HGE_CALL Music_SetChannelVolume(HMUSIC music, int channel, int volume) = 0; virtual int HGE_CALL Music_GetChannelVolume(HMUSIC music, int channel) = 0; virtual HSTREAM HGE_CALL Stream_Load(const char *filename, uint32_t size = 0) = 0; virtual void HGE_CALL Stream_Free(HSTREAM stream) = 0; virtual HCHANNEL HGE_CALL Stream_Play(HSTREAM stream, bool loop, int volume = 100) = 0; virtual void HGE_CALL Channel_SetPanning(HCHANNEL chn, int pan) = 0; virtual void HGE_CALL Channel_SetVolume(HCHANNEL chn, int volume) = 0; virtual void HGE_CALL Channel_SetPitch(HCHANNEL chn, float pitch) = 0; virtual void HGE_CALL Channel_Pause(HCHANNEL chn) = 0; virtual void HGE_CALL Channel_Resume(HCHANNEL chn) = 0; virtual void HGE_CALL Channel_Stop(HCHANNEL chn) = 0; virtual void HGE_CALL Channel_PauseAll() = 0; virtual void HGE_CALL Channel_ResumeAll() = 0; virtual void HGE_CALL Channel_StopAll() = 0; virtual bool HGE_CALL Channel_IsPlaying(HCHANNEL chn) = 0; virtual float HGE_CALL Channel_GetLength(HCHANNEL chn) = 0; virtual float HGE_CALL Channel_GetPos(HCHANNEL chn) = 0; virtual void HGE_CALL Channel_SetPos(HCHANNEL chn, float fSeconds) = 0; virtual void HGE_CALL Channel_SlideTo(HCHANNEL channel, float time, int volume, int pan = -101, float pitch = -1) = 0; virtual bool HGE_CALL Channel_IsSliding(HCHANNEL channel) = 0; virtual void HGE_CALL Input_GetMousePos(float *x, float *y) = 0; virtual void HGE_CALL Input_SetMousePos(float x, float y) = 0; virtual int HGE_CALL Input_GetMouseWheel() = 0; virtual bool HGE_CALL Input_IsMouseOver() = 0; virtual bool HGE_CALL Input_KeyDown(int key) = 0; virtual bool HGE_CALL Input_KeyUp(int key) = 0; virtual bool HGE_CALL Input_GetKeyState(int key) = 0; virtual const char *HGE_CALL Input_GetKeyName(int key) = 0; virtual int HGE_CALL Input_GetKey() = 0; virtual int HGE_CALL Input_GetChar() = 0; virtual bool HGE_CALL Input_GetEvent(hgeInputEvent *event) = 0; virtual bool HGE_CALL Gfx_BeginScene(HTARGET target = 0) = 0; virtual void HGE_CALL Gfx_EndScene() = 0; virtual void HGE_CALL Gfx_Clear(hgeColor32 color) = 0; virtual void HGE_CALL Gfx_RenderLine(float x1, float y1, float x2, float y2, hgeColor32 color, float z = 0.5f) = 0; virtual void HGE_CALL Gfx_RenderTriple(const hgeTriple *triple) = 0; virtual void HGE_CALL Gfx_RenderQuad(const hgeQuad *quad) = 0; virtual hgeVertex *HGE_CALL Gfx_StartBatch(int prim_type, HTEXTURE tex, hgeBlendMode blend, int *max_prim) = 0; virtual void HGE_CALL Gfx_FinishBatch(int nprim) = 0; virtual void HGE_CALL Gfx_SetClipping(int x = 0, int y = 0, int w = 0, int h = 0) = 0; virtual void HGE_CALL Gfx_SetTransform(float x = 0, float y = 0, float dx = 0, float dy = 0, float rot = 0, float hscale = 0, float vscale = 0) = 0; virtual HSHADER HGE_CALL Shader_Create(const char *filename) = 0; virtual void HGE_CALL Shader_Free(HSHADER shader) = 0; virtual void HGE_CALL Gfx_SetShader(HSHADER shader) = 0; virtual HTARGET HGE_CALL Target_Create(int width, int height, bool zbuffer) = 0; virtual void HGE_CALL Target_Free(HTARGET target) = 0; virtual HTEXTURE HGE_CALL Target_GetTexture(HTARGET target) = 0; virtual HTEXTURE HGE_CALL Texture_Create(int width, int height) = 0; virtual HTEXTURE HGE_CALL Texture_Load(const char *filename, uint32_t size = 0, bool bMipmap = false) = 0; virtual void HGE_CALL Texture_Free(HTEXTURE tex) = 0; virtual int HGE_CALL Texture_GetWidth(HTEXTURE tex, bool bOriginal = false) = 0; virtual int HGE_CALL Texture_GetHeight(HTEXTURE tex, bool bOriginal = false) = 0; virtual uint32_t *HGE_CALL Texture_Lock(HTEXTURE tex, bool bReadOnly = true, int left = 0, int top = 0, int width = 0, int height = 0) = 0; virtual void HGE_CALL Texture_Unlock(HTEXTURE tex) = 0; }; extern "C" { HGE_EXPORT HGE *HGE_CALL hgeCreate(int ver); } // Used to mark mutable/out parameters, declares intent to write to that variable #define hgeMUTABLE /* mutable */ #define hgeOUT /* mutable, used to return data into a pointer */
31.345055
98
0.65068
[ "render" ]
dd92d61a06a021ccc00749b9c992601e49568eaf
3,014
h
C
third_party/maya/lib/usdMaya/MayaTransformWriter.h
marsupial/USD
98d49911893d59be5a9904a29e15959affd530ec
[ "BSD-3-Clause" ]
9
2021-03-31T21:23:48.000Z
2022-03-05T09:29:27.000Z
third_party/maya/lib/usdMaya/MayaTransformWriter.h
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
null
null
null
third_party/maya/lib/usdMaya/MayaTransformWriter.h
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
2
2016-12-13T00:53:40.000Z
2020-05-04T07:32:53.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #ifndef _usdExport_MayaTransformWriter_h_ #define _usdExport_MayaTransformWriter_h_ #include "usdMaya/MayaPrimWriter.h" #include "pxr/usd/usdGeom/xform.h" #include "pxr/usd/usdGeom/xformOp.h" #include <maya/MFnTransform.h> #include <maya/MPlugArray.h> class UsdGeomXformable; class UsdTimeCode; enum XFormOpType { TRANSLATE, ROTATE, SCALE, SHEAR }; enum AnimChannelSampleType { NO_XFORM, STATIC, ANIMATED }; // This may not be the best name here as it isn't necessarily animated. struct AnimChannel { MPlug plug[3]; AnimChannelSampleType sampleType[3]; // defValue should always be in "usd" space. that is, if it's a rotation // it should be a degree not radians. GfVec3d defValue; XFormOpType opType; UsdGeomXformOp::Type usdOpType; UsdGeomXformOp::Precision precision; std::string opName; bool isInverse; }; // Writes an MFnTransform class MayaTransformWriter : public MayaPrimWriter { public: MayaTransformWriter(MDagPath & iDag, UsdStageRefPtr stage, const JobExportArgs & iArgs); virtual ~MayaTransformWriter() {}; virtual void pushTransformStack( const MFnTransform& iTrans, const UsdGeomXformable& usdXForm, bool writeAnim); virtual UsdPrim write(const UsdTimeCode &usdTime); virtual bool isShapeAnimated() const { return mIsShapeAnimated; }; const MDagPath& getTransformDagPath() { return mXformDagPath; }; protected: bool writeTransformAttrs( const UsdTimeCode& usdTime, UsdGeomXformable& primSchema); private: bool mWriteTransformAttrs; MDagPath mXformDagPath; bool mIsShapeAnimated; std::vector<AnimChannel> mAnimChanList; size_t mJointOrientOpIndex[3]; size_t mRotateOpIndex[3]; size_t mRotateAxisOpIndex[3]; }; typedef shared_ptr < MayaTransformWriter > MayaTransformWriterPtr; #endif // _usdExport_MayaTransformWriter_h_
32.06383
92
0.734904
[ "vector" ]
dd9541516f03eccc0135d0e25c3fd4a9b0ecf00a
430
h
C
LeetCode/m_17.h
lei97/LeetCode
c12690899ff1a2deabb333cb68465b582ebad8e0
[ "MIT" ]
3
2019-08-27T09:35:56.000Z
2021-04-22T06:22:24.000Z
LeetCode/m_17.h
lei97/LeetCode
c12690899ff1a2deabb333cb68465b582ebad8e0
[ "MIT" ]
null
null
null
LeetCode/m_17.h
lei97/LeetCode
c12690899ff1a2deabb333cb68465b582ebad8e0
[ "MIT" ]
null
null
null
#pragma once #include "config.h" /* ������17. ��ӡ��1������nλ�� ˵��: �������� n����˳���ӡ���� 1 ������ n λʮ���������������� 3�� ���ӡ�� 1��2��3 һֱ������ 3 λ�� 999�� */ class Solution { public: vector<int> printNumbers(int n) { vector<int> data; auto max = pow(10, n); for (int i = 1; i < max; i++) { data.push_back(i); } return data; } };
19.545455
65
0.35814
[ "vector" ]
dd996587ec234e157d1c7c23bba1a3351523e7cc
3,826
c
C
d/underdark/mines/mon/gnobasic.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/underdark/mines/mon/gnobasic.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/underdark/mines/mon/gnobasic.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
//Octothorpe (9/6/08) //Underdark Mining Caverns, Svirfneblin Master Inherit #include <std.h> #include "../defs.h" inherit MONSTER; void create(){ object ob; object ob1; ::create(); set_id(({"gnome","deep gnome","svirfneblin"})); set_name("svirfneblin"); set_short("%^RESET%^d%^BOLD%^%^BLACK%^ee%^RESET%^p gnomish miner"); set_long("%^ORANGE%^This lightly armored gnome participates in "+ "the mining operation. He is wielding a solid mining pick, and is "+ "clothed in a light, leather jack. This gnome has %^BOLD%^%^BLACK%^"+ "gray %^RESET%^%^ORANGE%^pulled over a compact, wiry frame. The "+ "miner moves about with the skill and confidence of a veteran "+ "warrior, suggesting that the miners, and the guards that patrol "+ "the area, are one and the same.%^RESET%^"); set_race("gnome"); set_body_type("human"); set_gender("male"); set_alignment(4); set_size(1); set_class("fighter"); add_search_path("/cmds/fighter"); set_hd(25,random(4)+1); set_guild_level("fighter",25); set_mlevel("fighter",25); set_max_hp(random(50)+225); set_hp(query_max_hp()); set_stats("strength",18); set_stats("dexterity",18); set_stats("constitution",12); set_stats("intelligence",10); set_stats("wisdom",11); set_stats("charisma",8); set_property("full attacks",1); set_property("swarm",1); set_new_exp(17,"normal"); set_max_level(20); set_overall_ac(-5); set_speed(70); set_moving(1); set_mob_magic_resistance("average"); set_wielding_limbs(({"left hand","right hand"})); ob1 = new("/d/underdark/obj/sboots"); ob1->move(TO); ob1->set_property("monsterweapon",1); command("wear boots"); ob = new("/d/shadow/virtual/mon/gpick"); ob->move(TO); ob->set_property("monsterweapon",1); command("wield pick"); add_money("silver",random(100)+20); set("aggressive",3); set_func_chance(35); set_funcs(({"rushit","flashit","flashit","flashit"})); add_attack_bonus(random(8)); set_monster_feats(({ "powerattack", "shatter", "sunder", "rush" })); } void flashit(object targ){ if(!objectp(targ)) return; if(!objectp(TO)) return; TO->force_me("flash "+targ->query_name()); } void rushit(object targ){ if(!objectp(targ)) return; if(!objectp(TO)) return; TO->force_me("rush "+targ->query_name()); } //Adapted from Grazzt's goblins, query_invis suggestion from Nienne void init(){ string mrace=TP->query_race(); ::init(); if(TP->query_invis()) return; if(mrace == "kobold" || mrace == "drow" || mrace == "goblin" || mrace == "ogre" || mrace == "hook horror" || mrace == "orc" || mrace == "hobgoblin" || mrace == "bugbear" || mrace == "gnoll" || mrace == "ogre" || mrace == "half-ogre" || mrace == "ogre-mage" || mrace == "half-drow" || TP->query_property("kobhelp")){ command ("kill "+TPQN); } if(present("bldscl",TP)){ command ("kill "+TPQN); } /* if(mrace == "kobold"){ //put on hold as this cound potentially stack up indefinitely... N, 3/11 add_attack_bonus(query_attack_bonus()+1); }*/ } //Thanks to Nienne for the following code void die(object ob){ int i, flag; object myob, myob2, myob3, *mytarg; mytarg=TO->query_attackers(); flag = 0; if(sizeof(mytarg)){ for(i=0; i< sizeof(mytarg); i++) if(userp(mytarg[i])) flag = 1; } if(!flag){ myob=present("leather jack"); if(myob){ myob->move("/d/shadowgate/void"); myob->remove(); } myob2=present("boots"); if(myob2){ myob2->move("/d/shadowgate/void"); myob2->remove(); } myob3=present("scaled shirt"); if(myob3){ myob3->move("/d/shadowgate/void"); myob3->remove(); } } ::die(); }
29.890625
319
0.609775
[ "object", "solid" ]
dd9f293d50c40e1b6fbb3a297223c3e70c02141f
3,165
h
C
src/GameLogic/Systems/RenderSystem.h
gameraccoon/hide-and-seek
c6ddc6419e041f0d63f6d4497dd5b95aaa54ef25
[ "MIT" ]
3
2021-02-19T09:14:29.000Z
2022-03-08T08:35:45.000Z
src/GameLogic/Systems/RenderSystem.h
gameraccoon/hide-and-seek
c6ddc6419e041f0d63f6d4497dd5b95aaa54ef25
[ "MIT" ]
1
2019-11-23T09:13:25.000Z
2020-04-18T20:12:04.000Z
src/GameLogic/Systems/RenderSystem.h
gameraccoon/hide-and-seek
c6ddc6419e041f0d63f6d4497dd5b95aaa54ef25
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vector> #include <raccoon-ecs/system.h> #include <raccoon-ecs/async_operations.h> #include <raccoon-ecs/thread_pool.h> #include "GameData/Components/SpriteRenderComponent.generated.h" #include "GameData/Components/TransformComponent.generated.h" #include "GameData/Components/LightComponent.generated.h" #include "GameData/Components/LightBlockingGeometryComponent.generated.h" #include "GameData/Components/RenderModeComponent.generated.h" #include "GameData/Components/WorldCachedDataComponent.generated.h" #include "GameData/Components/BackgroundTextureComponent.generated.h" #include "GameData/Components/RenderAccessorComponent.generated.h" #include "HAL/Base/ResourceManager.h" #include "GameLogic/SharedManagers/WorldHolder.h" #include "GameLogic/SharedManagers/TimeData.h" struct RenderData; /** * System that handles rendering of world objects */ class RenderSystem : public RaccoonEcs::System { public: RenderSystem( RaccoonEcs::ComponentFilter<const WorldCachedDataComponent>&& worldCachedDataFilter, RaccoonEcs::ComponentFilter<const RenderModeComponent>&& renderModeFilter, RaccoonEcs::ComponentFilter<BackgroundTextureComponent>&& backgroundTextureFilter, RaccoonEcs::ComponentFilter<const LightBlockingGeometryComponent>&& lightBlockingGeometryFilter, RaccoonEcs::ComponentFilter<const SpriteRenderComponent, const TransformComponent>&& spriteRenderFilter, RaccoonEcs::ComponentFilter<LightComponent, const TransformComponent>&& lightFilter, RaccoonEcs::ComponentFilter<RenderAccessorComponent>&& renderAccessorFilter, WorldHolder& worldHolder, const TimeData& timeData, HAL::ResourceManager& resourceManager, RaccoonEcs::ThreadPool& threadPool) noexcept; ~RenderSystem() override = default; void update() override; static std::string GetSystemId() { return "RenderSystem"; } private: static void DrawVisibilityPolygon(RenderData& renderData, ResourceHandle lightSpriteHandle, const std::vector<Vector2D>& polygon, const Vector2D& fovSize, const Vector2D& drawShift); void drawBackground(RenderData& renderData, World& world, Vector2D drawShift, Vector2D windowSize); void drawLights(RenderData& renderData, class SpatialEntityManager& managerGroup, std::vector<class WorldCell*>& cells, Vector2D playerSightPosition, Vector2D drawShift, Vector2D maxFov, Vector2D screenHalfSize); private: RaccoonEcs::ComponentFilter<const WorldCachedDataComponent> mWorldCachedDataFilter; RaccoonEcs::ComponentFilter<const RenderModeComponent> mRenderModeFilter; RaccoonEcs::ComponentFilter<BackgroundTextureComponent> mBackgroundTextureFilter; RaccoonEcs::ComponentFilter<const LightBlockingGeometryComponent> mLightBlockingGeometryFilter; RaccoonEcs::ComponentFilter<const SpriteRenderComponent, const TransformComponent> mSpriteRenderFilter; RaccoonEcs::ComponentFilter<LightComponent, const TransformComponent> mLightFilter; RaccoonEcs::ComponentFilter<RenderAccessorComponent> mRenderAccessorFilter; WorldHolder& mWorldHolder; const TimeData& mTime; HAL::ResourceManager& mResourceManager; RaccoonEcs::ThreadPool& mThreadPool; ResourceHandle mLightSpriteHandle; };
45.869565
213
0.836335
[ "vector" ]
ddac4ec1819355aea0e956a1993b37351a1fe2ea
3,202
h
C
DearPyGui/src/core/AppItems/nodes/mvNodeEditor.h
NamWoo/DearPyGui
da4a3c7a0dbb3d5dfd8b0a7991521890ddd3e513
[ "MIT" ]
null
null
null
DearPyGui/src/core/AppItems/nodes/mvNodeEditor.h
NamWoo/DearPyGui
da4a3c7a0dbb3d5dfd8b0a7991521890ddd3e513
[ "MIT" ]
null
null
null
DearPyGui/src/core/AppItems/nodes/mvNodeEditor.h
NamWoo/DearPyGui
da4a3c7a0dbb3d5dfd8b0a7991521890ddd3e513
[ "MIT" ]
null
null
null
#pragma once #include "mvAppItem.h" #include "mvItemRegistry.h" #include <stdint.h> #include <imnodes.h> namespace Marvel { MV_REGISTER_WIDGET(mvNodeEditor, MV_ITEM_DESC_CONTAINER, StorageValueTypes::None, 1); class mvNodeEditor : public mvAppItem { public: static void InsertParser(std::map<std::string, mvPythonParser>* parsers); MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvNodeEditor, add_node_editor) MV_CREATE_EXTRA_COMMAND(get_selected_nodes); MV_CREATE_EXTRA_COMMAND(get_selected_links); MV_CREATE_EXTRA_COMMAND(clear_selected_nodes); MV_CREATE_EXTRA_COMMAND(clear_selected_links); MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_BoxSelector, imnodes::ColorStyle::ColorStyle_BoxSelector, 0L); MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_BoxSelectorOutline, imnodes::ColorStyle::ColorStyle_BoxSelectorOutline, 0L); MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_GridBackground, imnodes::ColorStyle::ColorStyle_GridBackground, 0L); MV_CREATE_CONSTANT(mvThemeCol_NodeEditor_GridLine, imnodes::ColorStyle::ColorStyle_GridLine, 0L); MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_GridSpacing, imnodes::StyleVar::StyleVar_GridSpacing, 0L); MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_LinkThickness, imnodes::StyleVar::StyleVar_LinkThickness, 0L); MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_LinkLineSegmentsPerLength, imnodes::StyleVar::StyleVar_LinkLineSegmentsPerLength, 0L); MV_CREATE_CONSTANT(mvThemeStyle_NodeEditor_LinkHoverDistance, imnodes::StyleVar::StyleVar_LinkHoverDistance, 0L); MV_START_EXTRA_COMMANDS MV_ADD_EXTRA_COMMAND(get_selected_nodes); MV_ADD_EXTRA_COMMAND(get_selected_links); MV_ADD_EXTRA_COMMAND(clear_selected_nodes); MV_ADD_EXTRA_COMMAND(clear_selected_links); MV_END_EXTRA_COMMANDS MV_START_GENERAL_CONSTANTS MV_END_GENERAL_CONSTANTS MV_START_COLOR_CONSTANTS MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_BoxSelector, mvImGuiCol_BoxSelector), MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_BoxSelectorOutline, mvImGuiCol_BoxSelectorOutline), MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_GridBackground, mvImGuiCol_GridBackground), MV_CREATE_CONSTANT_PAIR(mvThemeCol_NodeEditor_GridLine, mvImGuiCol_GridLine), MV_END_COLOR_CONSTANTS MV_START_STYLE_CONSTANTS MV_ADD_CONSTANT_F(mvThemeStyle_NodeEditor_GridSpacing, 20, 20), MV_ADD_CONSTANT_F(mvThemeStyle_NodeEditor_LinkThickness, 1, 12), MV_ADD_CONSTANT_F(mvThemeStyle_NodeEditor_LinkLineSegmentsPerLength, 1, 1), MV_ADD_CONSTANT_F(mvThemeStyle_NodeEditor_LinkHoverDistance, 3, 12), MV_END_STYLE_CONSTANTS public: mvNodeEditor(const std::string& name); void handleSpecificKeywordArgs(PyObject* dict) override; bool canChildBeAdded(mvAppItemType type) override; std::vector<std::string> getSelectedNodes() const; const std::vector<int>& getSelectedLinks() const { return m_selectedLinks; } void clearNodes() { m_clearNodes = true; } void clearLinks() { m_clearLinks = true; } void draw(ImDrawList* drawlist, float x, float y) override; private: std::vector<int> m_selectedNodes; std::vector<int> m_selectedLinks; bool m_clearNodes = false; bool m_clearLinks = false; PyObject* m_delinkCallback = nullptr; }; }
37.670588
131
0.831355
[ "vector" ]
ddad2dec8bf3d3c27cf8cb001fbedb5faad19293
1,246
h
C
include/cybergarage/x3d/MFVec3d.h
cybergarage/CyberX3D4CC
edcb6d34aa0b64f166feff35731bc56533b4c819
[ "BSD-3-Clause" ]
4
2015-12-06T08:09:39.000Z
2019-12-03T08:28:16.000Z
include/cybergarage/x3d/MFVec3d.h
cybergarage/CyberX3D4CC
edcb6d34aa0b64f166feff35731bc56533b4c819
[ "BSD-3-Clause" ]
2
2015-06-02T20:57:53.000Z
2016-10-21T05:21:09.000Z
include/cybergarage/x3d/MFVec3d.h
cybergarage/CyberX3D4CC
edcb6d34aa0b64f166feff35731bc56533b4c819
[ "BSD-3-Clause" ]
6
2015-06-02T04:38:50.000Z
2020-01-20T14:39:57.000Z
/****************************************************************** * * CyberX3D for C++ * * Copyright (C) Satoshi Konno 1996-2007 * * File: MFVec3d.h * ******************************************************************/ #ifndef _CX3D_MFVEC3D_H_ #define _CX3D_MFVEC3D_H_ #include <cybergarage/x3d/MField.h> #include <cybergarage/x3d/SFVec3d.h> namespace CyberX3D { class MFVec3d : public MField { public: MFVec3d(); void addValue(double x, double y, double z); void addValue(double value[]); void addValue(SFVec3d *vector); void addValue(const char *value); void insertValue(int index, double x, double y, double z); void insertValue(int index, double value[]); void insertValue(int index, SFVec3d *vector); void get1Value(int index, double value[]) const; void set1Value(int index, double value[]); void set1Value(int index, double x, double y, double z); void setValue(MField *mfield); void setValue(MFVec3d *vectors); void setValue(int size, double vectors[][3]); int getValueCount() const { return 3; } //////////////////////////////////////////////// // Output //////////////////////////////////////////////// void outputContext(std::ostream& printStream, const char *indentString) const; }; } #endif
21.482759
79
0.583467
[ "vector" ]
ddb01cee80f249bb917fede44393a6e23cebd280
6,026
h
C
Jx3Full/PhysX/include/NxD6Joint.h
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
2
2021-07-31T15:35:01.000Z
2022-02-28T05:54:54.000Z
sdk/physx/2.8.3/SDKs/Physics/include/NxD6Joint.h
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
sdk/physx/2.8.3/SDKs/Physics/include/NxD6Joint.h
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
#ifndef NX_PHYSICS_NXD6Joint #define NX_PHYSICS_NXD6Joint /*----------------------------------------------------------------------------*\ | | Public Interface to NVIDIA PhysX Technology | | www.nvidia.com | \*----------------------------------------------------------------------------*/ /** \addtogroup physics @{ */ #include "Nxp.h" #include "NxJoint.h" class NxD6JointDesc; /** \brief A D6 joint is a general constraint between two actors. It allows the user to individually define the linear and rotational degrees of freedom. It also allows the user to configure the joint with limits and driven degrees of freedom as they wish. For example to create a fixed joint we would need to do: \code ... d6Desc.twistMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.swing1Motion = NX_D6JOINT_MOTION_LOCKED; d6Desc.swing2Motion = NX_D6JOINT_MOTION_LOCKED; d6Desc.xMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.yMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.zMotion = NX_D6JOINT_MOTION_LOCKED; ... \endcode Or a Revolute joint: \code ... d6Desc.twistMotion = NX_D6JOINT_MOTION_FREE; d6Desc.swing1Motion = NX_D6JOINT_MOTION_LOCKED; d6Desc.swing2Motion = NX_D6JOINT_MOTION_LOCKED; d6Desc.xMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.yMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.zMotion = NX_D6JOINT_MOTION_LOCKED; ... \endcode And a spherical joint: \code ... d6Desc.twistMotion = NX_D6JOINT_MOTION_FREE; d6Desc.swing1Motion = NX_D6JOINT_MOTION_FREE; d6Desc.swing2Motion = NX_D6JOINT_MOTION_FREE; d6Desc.xMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.yMotion = NX_D6JOINT_MOTION_LOCKED; d6Desc.zMotion = NX_D6JOINT_MOTION_LOCKED; ... \endcode <h3>Creation</h3> Example: \include NxD6Joint_Create.cpp <h3>Visualizations:</h3> \li #NX_VISUALIZE_JOINT_LOCAL_AXES \li #NX_VISUALIZE_JOINT_WORLD_AXES \li #NX_VISUALIZE_JOINT_LIMITS <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes @see NxD6JointDesc NxJoint NxScene.createJoint() */ class NxD6Joint: public NxJoint { public: /** \brief Use this for changing a significant number of joint parameters at once. Use the set() methods for changing only a single property at once. Please note that you can not change the actor pointers using this function, if you do so the joint will be marked as broken and will stop working. Calling the loadFromDesc() method on a broken joint will result in an error message. <b>Sleeping:</b> This call wakes the actor if it is sleeping. \param[in] desc The descriptor used to set the state of the object. <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes \li WII : Yes @see saveToDesc NxD6JointDesc */ virtual void loadFromDesc(const NxD6JointDesc& desc) = 0; /** \brief Writes all of the object's attributes to the desc struct \param[out] desc The descriptor used to retrieve the state of the object. <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes \li WII : Yes @see loadFromDesc NxD6JointDesc */ virtual void saveToDesc(NxD6JointDesc& desc) = 0; /** \brief Set the drive position goal position when it is being driven. The goal position is specified relative to the joint frame corresponding to actor[0]. <b>Sleeping:</b> This call wakes the actor(s) if they are sleeping. \param position The goal position if NX_D6JOINT_DRIVE_POSITION is set for xDrive,yDrive or zDrive. <b>Range:</b> position vector <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes \li WII : Yes @see setDriveOrientation() NxD6JointDesc.drivePosition @see NxD6JointDesc */ virtual void setDrivePosition(const NxVec3 &position) = 0; /** \brief Set the drive goal orientation when it is being driven. The goal orientation is specified relative to the joint frame corresponding to actor[0]. <b>Sleeping:</b> This call wakes the actor(s) if they are sleeping. \param orientation The goal orientation if NX_D6JOINT_DRIVE_POSITION is set for swingDrive or twistDrive. <b>Range:</b> unit quaternion <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes \li WII : Yes @see setDrivePosition NxD6JointDesc.driveOrientation */ virtual void setDriveOrientation(const NxQuat &orientation) = 0; /** \brief Set the drive goal linear velocity when it is being driven. The drive linear velocity is specified relative to the actor[0] joint frame. <b>Sleeping:</b> This call wakes the actor(s) if they are sleeping. \param linVel The goal velocity if NX_D6JOINT_DRIVE_VELOCITY is set for xDrive,yDrive or zDrive. See #NxD6JointDesc. <b>Range:</b> velocity vector <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes \li WII : Yes @see setDriveAngularVelocity NxD6JointDesc.driveLinearVelocity */ virtual void setDriveLinearVelocity(const NxVec3 &linVel) = 0; /** \brief Set the drive angular velocity goal when it is being driven. The drive angular velocity is specified relative to the drive orientation target in the case of a slerp drive. The drive angular velocity is specified in the actor[0] joint frame in all other cases. <b>Sleeping:</b> This call wakes the actor(s) if they are sleeping. \param angVel The goal angular velocity if NX_D6JOINT_DRIVE_VELOCITY is set for swingDrive or twistDrive. <b>Range:</b> angular velocity vector <b>Platform:</b> \li PC SW: Yes \li GPU : Yes [SW] \li PS3 : Yes \li XB360: Yes \li WII : Yes @see setDriveLinearVelocity() NxD6JointDesc.driveAngularVelocity */ virtual void setDriveAngularVelocity(const NxVec3 &angVel) = 0; }; /** @} */ #endif //NVIDIACOPYRIGHTBEGIN /////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010 NVIDIA Corporation // All rights reserved. www.nvidia.com /////////////////////////////////////////////////////////////////////////// //NVIDIACOPYRIGHTEND
26.429825
147
0.694988
[ "object", "vector" ]
ddb0230faf75e2fbeada8286900fd4356c5e7ed6
681
c
C
src/BLASxON/lvl2/src/v__m_mult_v.c
meinkea/RottenCore
310a1cad96558e6e6accc1f67baf141fb921048c
[ "Unlicense" ]
null
null
null
src/BLASxON/lvl2/src/v__m_mult_v.c
meinkea/RottenCore
310a1cad96558e6e6accc1f67baf141fb921048c
[ "Unlicense" ]
null
null
null
src/BLASxON/lvl2/src/v__m_mult_v.c
meinkea/RottenCore
310a1cad96558e6e6accc1f67baf141fb921048c
[ "Unlicense" ]
null
null
null
/* /file v__m_mult_v.c * */ #include "../inc/v__m_mult_v.h" #include "../../gnd/datatypes/inc/matrix.h" #include "../../gnd/datatypes/inc/vector.h" #include "../../gnd/lvlZ/inc/array_dot.h" void v__m_mult_v( struct vector * restrict vRes, const struct matrix * restrict mOprA, const struct vector * restrict vOprB ) { const unsigned int Re = vRes->l; const unsigned int AcBe = mOprA->c; float * restrict vR = vRes->v; float * restrict mA = *(mOprA->m); const float * restrict vB = vOprB->v; for(unsigned int I=0; I<Re; ++I) { array_dot( vR, mA, vB, 0, AcBe ); vR += 1; mA += AcBe; } return; }
15.133333
43
0.577093
[ "vector" ]
ddb0670786f253505b8527ee88b1e5a2538c3b43
68,184
c
C
src/handle_snmp.c
5up3rc/Toposcan
ea36f46dffe9a468068b85e68b9dea707139f4b9
[ "Apache-2.0" ]
2
2021-07-04T17:51:50.000Z
2021-09-27T07:02:51.000Z
src/handle_snmp.c
5up3rc/Toposcan
ea36f46dffe9a468068b85e68b9dea707139f4b9
[ "Apache-2.0" ]
null
null
null
src/handle_snmp.c
5up3rc/Toposcan
ea36f46dffe9a468068b85e68b9dea707139f4b9
[ "Apache-2.0" ]
3
2021-04-26T05:41:56.000Z
2021-05-20T05:46:05.000Z
#include <net-snmp/net-snmp-config.h> #if HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #include <sys/types.h> #if HAVE_NETINET_IN_H # include <netinet/in.h> #endif #if TIME_WITH_SYS_TIME # ifdef WIN32 # include <sys/timeb.h> # else # include <sys/time.h> # endif # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include <stdio.h> #if HAVE_WINSOCK_H #include <winsock.h> #endif #if HAVE_NETDB_H #include <netdb.h> #endif #if HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include <net-snmp/net-snmp-includes.h> #include <ctype.h> #include "handle_snmp.h" #include "common.h" extern topo_config my_config_info; extern void _DEBUG_FILE(char *fmt, ...); #define NETSNMP_DS_APP_DONT_FIX_PDUS 0 #define NETSNMP_DS_WALK_INCLUDE_REQUESTED 1 #define NETSNMP_DS_WALK_PRINT_STATISTICS 2 #define NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC 3 #define NETSNMP_DS_WALK_TIME_RESULTS 4 #define NETSNMP_DS_WALK_DONT_GET_REQUESTED 5 oid objid_mib[] = { 1, 3, 6, 1, 2, 1 }; int numprinted = 0; /*mibs*/ int sprint_realloc_badtype_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char str[] = "Variable has bad type"; return snmp_strcat(buf, buf_len, out_len, allow_realloc, str); } int sprint_realloc_integer_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *enum_string = NULL; if ((var->type != ASN_INTEGER) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be INTEGER): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } for (; enums; enums = enums->next) { if (enums->value == *var->val.integer) { enum_string = enums->label; break; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "")) { //(const u_char *) "INTEGER: ")) { return 0; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { if (hint) { if (!(sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'd', hint, units))) { return 0; } } else { char str[16]; sprintf(str, "%ld", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } } else { char str[16]; sprintf(str, "(%ld)", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } int sprint_realloc_octet_string_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t saved_out_len = *out_len; const char *saved_hint = hint; int hex = 0, x = 0; u_char *cp; int output_format, len_needed; if ((var->type != ASN_OCTET_STR) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { const char str[] = "Wrong Type (should be OCTET STRING): "; if (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (hint) { int repeat, width = 1; long value; char code = 'd', separ = 0, term = 0, ch, intbuf[16]; u_char *ecp; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "")) { //if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "STRING: ")) { return 0; } } cp = var->val.string; ecp = cp + var->val_len; while (cp < ecp) { repeat = 1; if (*hint) { if (*hint == '*') { repeat = *cp++; hint++; } width = 0; while ('0' <= *hint && *hint <= '9') width = (width * 10) + (*hint++ - '0'); code = *hint++; if ((ch = *hint) && ch != '*' && (ch < '0' || ch > '9') && (width != 0 || (ch != 'x' && ch != 'd' && ch != 'o'))) separ = *hint++; else separ = 0; if ((ch = *hint) && ch != '*' && (ch < '0' || ch > '9') && (width != 0 || (ch != 'x' && ch != 'd' && ch != 'o'))) term = *hint++; else term = 0; if (width == 0) /* Handle malformed hint strings */ width = 1; } while (repeat && cp < ecp) { value = 0; if (code != 'a' && code != 't') { for (x = 0; x < width; x++) { value = value * 256 + *cp++; } } switch (code) { case 'x': if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT) && value < 16) { sprintf(intbuf, "0%lx", value); } else { sprintf(intbuf, "%lx", value); } if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 'd': sprintf(intbuf, "%ld", value); if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 'o': sprintf(intbuf, "%lo", value); if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 't': /* new in rfc 3411 */ case 'a': /* A string hint gives the max size - we may not need this much */ len_needed = SNMP_MIN( width, ecp-cp ); while ((*out_len + len_needed + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } for (x = 0; x < width && cp < ecp; x++) { *(*buf + *out_len) = *cp++; (*out_len)++; } *(*buf + *out_len) = '\0'; break; default: *out_len = saved_out_len; if (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "(Bad hint ignored: ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, saved_hint) && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ") ")) { return sprint_realloc_octet_string_my(buf, buf_len, out_len, allow_realloc, var, enums, NULL, NULL); } else { return 0; } } if (cp < ecp && separ) { while ((*out_len + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = separ; (*out_len)++; *(*buf + *out_len) = '\0'; } repeat--; } if (term && cp < ecp) { while ((*out_len + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = term; (*out_len)++; *(*buf + *out_len) = '\0'; } } if (units) { return (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + *out_len) = '\0'; return 1; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_STRING_OUTPUT_GUESS; } switch (output_format) { case NETSNMP_STRING_OUTPUT_GUESS: hex = 0; for (cp = var->val.string, x = 0; x < (int) var->val_len; x++, cp++) { if (!isprint(*cp) && !isspace(*cp)) { hex = 1; } } break; case NETSNMP_STRING_OUTPUT_ASCII: hex = 0; break; case NETSNMP_STRING_OUTPUT_HEX: hex = 1; break; } if (var->val_len == 0) { return snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\""); } if (hex) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "")) { //if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } else { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "Hex-STRING: ")) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "")) { //if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } } else { if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "")) { //"STRING: ")) { return 0; } } if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } if (!sprint_realloc_asciistring (buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "")) { //if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } int sprint_realloc_bitstring_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { int len, bit; u_char *cp; char *enum_string; if ((var->type != ASN_BIT_STR && var->type != ASN_OCTET_STR) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be BITS): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "\""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } else { u_char str[] = ""; //u_char str[] = "BITS: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.bitstring, var->val_len)) { return 0; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "\""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } else { cp = var->val.bitstring; for (len = 0; len < (int) var->val_len; len++) { for (bit = 0; bit < 8; bit++) { if (*cp & (0x80 >> bit)) { enum_string = NULL; for (; enums; enums = enums->next) { if (enums->value == (len * 8) + bit) { enum_string = enums->label; break; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { char str[16]; sprintf(str, "%d ", (len * 8) + bit); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } else { char str[16]; sprintf(str, "(%d) ", (len * 8) + bit); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } } cp++; } } return 1; } int sprint_realloc_counter64_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char a64buf[I64CHARSZ + 1]; if ((var->type != ASN_COUNTER64 #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES && var->type != ASN_OPAQUE_COUNTER64 && var->type != ASN_OPAQUE_I64 && var->type != ASN_OPAQUE_U64 #endif ) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { if (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "Wrong Type (should be Counter64): ")) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES if (var->type != ASN_COUNTER64) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "Opaque: ")) { return 0; } } #endif #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES switch (var->type) { case ASN_OPAQUE_U64: if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "UInt64: ")) { return 0; } break; case ASN_OPAQUE_I64: if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "Int64: ")) { return 0; } break; case ASN_COUNTER64: case ASN_OPAQUE_COUNTER64: #endif if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "Counter64: ")) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES if (var->type == ASN_OPAQUE_I64) { printI64(a64buf, var->val.counter64); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, a64buf)) { return 0; } } else { #endif printU64(a64buf, var->val.counter64); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, a64buf)) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } int sprint_realloc_float_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if ((var->type != ASN_OPAQUE_FLOAT) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { if (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "Wrong Type (should be Float): ")) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "Opaque: Float: ")) { return 0; } } /* * How much space needed for max. length float? 128 is overkill. */ while ((*out_len + 128 + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } sprintf((char *) (*buf + *out_len), "%f", *var->val.floatVal); *out_len += strlen((char *) (*buf + *out_len)); if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } int sprint_realloc_double_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if ((var->type != ASN_OPAQUE_DOUBLE) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { if (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Wrong Type (should be Double): ")) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "")) { //(buf, buf_len, out_len, allow_realloc, "Opaque: Float: ")) { return 0; } } /* * How much space needed for max. length double? 128 is overkill. */ while ((*out_len + 128 + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } sprintf((char *) (*buf + *out_len), "%f", *var->val.doubleVal); *out_len += strlen((char *) (*buf + *out_len)); if (units) { return (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } int sprint_realloc_opaque_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if ((var->type != ASN_OPAQUE #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES && var->type != ASN_OPAQUE_COUNTER64 && var->type != ASN_OPAQUE_U64 && var->type != ASN_OPAQUE_I64 && var->type != ASN_OPAQUE_FLOAT && var->type != ASN_OPAQUE_DOUBLE #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ ) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { if (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "Wrong Type (should be Opaque): ")) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES switch (var->type) { case ASN_OPAQUE_COUNTER64: case ASN_OPAQUE_U64: case ASN_OPAQUE_I64: return sprint_realloc_counter64_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE_FLOAT: return sprint_realloc_float_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE_DOUBLE: return sprint_realloc_double_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE: #endif if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = ""; //u_char str[] = "OPAQUE: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an object identifier into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_object_identifier_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { int buf_overflow = 0; if ((var->type != ASN_OBJECT_ID) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be OBJECT IDENTIFIER): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = ""; //u_char str[] = "OID: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, (oid *) (var->val.objid), var->val_len / sizeof(oid)); if (buf_overflow) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * @internal * Converts timeticks to hours, minutes, seconds string. * * @param timeticks The timeticks to convert. * @param buf Buffer to write to, has to be at * least 40 Bytes large. * * @return The buffer. */ static char * uptimeString(u_long timeticks, char *buf, size_t buflen) { int centisecs, seconds, minutes, hours, days; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS)) { snprintf(buf, buflen, "%lu", timeticks); return buf; } centisecs = timeticks % 100; timeticks /= 100; days = timeticks / (60 * 60 * 24); timeticks %= (60 * 60 * 24); hours = timeticks / (60 * 60); timeticks %= (60 * 60); minutes = timeticks / 60; seconds = timeticks % 60; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) snprintf(buf, buflen, "%d:%d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); else { if (days == 0) { snprintf(buf, buflen, "%d:%02d:%02d.%02d", hours, minutes, seconds, centisecs); } else if (days == 1) { snprintf(buf, buflen, "%d day, %d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); } else { snprintf(buf, buflen, "%d days, %d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); } } return buf; } int sprint_realloc_timeticks_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char timebuf[40]; if ((var->type != ASN_TIMETICKS) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be Timeticks): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS)) { char str[16]; sprintf(str, "%lu", *(u_long *) var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } return 1; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { char str[32]; sprintf(str, "(%lu) ", *(u_long *) var->val.integer); //sprintf(str, "Timeticks: (%lu) ", *(u_long *) var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } uptimeString(*(u_long *) (var->val.integer), timebuf, sizeof(timebuf)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) timebuf)) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } int sprint_realloc_gauge_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char tmp[32]; if ((var->type != ASN_GAUGE) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be Gauge32 or Unsigned32): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = ""; //u_char str[] = "Gauge32: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (hint) { if (!sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'u', hint, units)) { return 0; } } else { sprintf(tmp, "%lu", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) tmp)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } int sprint_realloc_counter_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char tmp[32]; if ((var->type != ASN_COUNTER) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be Counter32): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = ""; //u_char str[] = "Counter32: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } sprintf(tmp, "%lu", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) tmp)) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } int sprint_realloc_ipaddress_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char *ip = var->val.string; if ((var->type != ASN_IPADDRESS) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be IpAddress): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { /*u_char str[] = "IpAddress: ";*/ u_char str[] = ""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } while ((*out_len + 17) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } if (ip) sprintf((char *) (*buf + *out_len), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); *out_len += strlen((char *) (*buf + *out_len)); return 1; } int sprint_realloc_null_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if ((var->type != ASN_NULL) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be NULL): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } else { u_char str[] = ""; //u_char str[] = "NULL"; return snmp_strcat(buf, buf_len, out_len, allow_realloc, str); } } int sprint_realloc_uinteger_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *enum_string = NULL; if ((var->type != ASN_UINTEGER) && (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT))) { u_char str[] = "Wrong Type (should be UInteger32): "; if (snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } else { return 0; } } for (; enums; enums = enums->next) { if (enums->value == *var->val.integer) { enum_string = enums->label; break; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { if (hint) { if (!(sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'u', hint, units))) { return 0; } } else { char str[16]; sprintf(str, "%lu", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } } else { char str[16]; sprintf(str, "(%lu)", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Universal print routine, prints a variable into a buffer according to the variable * type. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_by_type_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { DEBUGMSGTL(("output", "sprint_by_type, type %d\n", var->type)); switch (var->type) { case ASN_INTEGER: return sprint_realloc_integer_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OCTET_STR: return sprint_realloc_octet_string_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_BIT_STR: return sprint_realloc_bitstring_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OPAQUE: return sprint_realloc_opaque_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OBJECT_ID: return sprint_realloc_object_identifier_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_TIMETICKS: return sprint_realloc_timeticks_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_GAUGE: return sprint_realloc_gauge_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_COUNTER: return sprint_realloc_counter_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_IPADDRESS: return sprint_realloc_ipaddress_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_NULL: return sprint_realloc_null_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_UINTEGER: return sprint_realloc_uinteger_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_COUNTER64: #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES case ASN_OPAQUE_U64: case ASN_OPAQUE_I64: case ASN_OPAQUE_COUNTER64: #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ return sprint_realloc_counter64_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES case ASN_OPAQUE_FLOAT: return sprint_realloc_float_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OPAQUE_DOUBLE: return sprint_realloc_double_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ default: DEBUGMSGTL(("sprint_by_type", "bad type: %d\n", var->type)); return sprint_realloc_badtype_my(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); } } int sprint_realloc_variable_my(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable, int flag_return) { if(flag_return) { int buf_overflow = 0; netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, objid, objidlen); if (buf_overflow) { return 0; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE)) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " = ")) { return 0; } } else { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ")) { return 0; } } else { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " = ")) { return 0; } } // end if-else NETSNMP_DS_LIB_QUICK_PRINT } // end if-else NETSNMP_DS_LIB_QUICKE_PRINT } else { *out_len = 0; } } /* if (variable->type == SNMP_NOSUCHOBJECT) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Object available on this agent at this OID"); } else if (variable->type == SNMP_NOSUCHINSTANCE) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Instance currently exists at this OID"); } else if (variable->type == SNMP_ENDOFMIBVIEW) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No more variables left in this MIB View (It is past the end of the MIB tree)"); } else */ { /* * Handle rare case where tree is empty. */ return sprint_realloc_by_type_my(buf, buf_len, out_len, allow_realloc, variable, 0, 0, 0); } } /** * Prints a variable to a file descriptor. * * @param f The file descriptor to print to. * @param objid The object id. * @param objidlen The length of teh object id. * @param variable The variable to print. */ /*void fprint_variable_my(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable)*/ void fprint_variable_my(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable, snmp_arg *argv, snmp_walk_callback cb, int flag_return) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { return; } else { if (sprint_realloc_variable_my(&buf, &buf_len, &out_len, 1, objid, objidlen, variable, flag_return)) { if(NULL != cb) cb(argv, (char *)buf); } else { } } SNMP_FREE(buf); } void fprint_variable_myget(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable, char *out_para, int flag_return) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { return; } else { if (sprint_realloc_variable_my(&buf, &buf_len, &out_len, 1, objid, objidlen, variable, flag_return)) { if(NULL != out_para) strncpy(out_para, (char *)buf, 256); } else { } } SNMP_FREE(buf); } /*mibs*/ void snmp_get_and_print(netsnmp_session * ss, oid * theoid, size_t theoid_len) { netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; int status; pdu = snmp_pdu_create(SNMP_MSG_GET); snmp_add_null_var(pdu, theoid, theoid_len); status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { for (vars = response->variables; vars; vars = vars->next_variable) { numprinted++; print_variable(vars->name, vars->name_length, vars); } } if (response) { snmp_free_pdu(response); } } int snmp_walk(snmp_arg *argv, snmp_walk_callback cb, int flag_return) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; oid name[MAX_OID_LEN]; size_t name_length; oid root[MAX_OID_LEN]; size_t rootlen; int count; int running; int status; int check; int exitval = 0; struct timeval tv1, tv2; char tmp_peername[64] = {0}; long tmp_snmp_version = my_config_info.snmp_version; numprinted = 0; sprintf(tmp_peername, "%s:%d", argv->peer_name, my_config_info.scan_port); netsnmp_ds_register_config(ASN_BOOLEAN, "snmpwalk", "dontCheckOrdering", NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); version1_retry: snmp_sess_init(&session); /* * -C c :do not check returned OIDs are increasing */ if(flag_return) netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); /* * read in MIB database and initialize the snmp library */ init_snmp("snmpapp"); /* * set the arguments */ session.version= tmp_snmp_version; session.peername = strdup(tmp_peername); session.community = (u_char *)strdup(argv->community); session.community_len = strlen((char *)session.community); session.retries = my_config_info.retries; session.timeout = my_config_info.snmptimeout * 1000000L; /* * get the initial object and subtree */ rootlen = MAX_OID_LEN; if (snmp_parse_oid(argv->oid, root, &rootlen) == NULL) { snmp_perror(argv->oid); if(session.peername){ free(session.peername); session.peername = NULL; } if(session.community){ free(session.community); session.community = NULL; } return -1; } SOCK_STARTUP; /* * open an SNMP session */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ if(session.peername){ free(session.peername); session.peername = NULL; } if(session.community){ free(session.community); session.community = NULL; } snmp_sess_perror("mysnmpwalk", &session); SOCK_CLEANUP; return -1; } /* * get first object to start walk */ memmove(name, root, rootlen * sizeof(oid)); name_length = rootlen; running = 1; check = !netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_CHECK_LEXICOGRAPHIC); if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_INCLUDE_REQUESTED)) { snmp_get_and_print(ss, root, rootlen); } if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_TIME_RESULTS)) gettimeofday(&tv1, NULL); while (running) { /* * create PDU for GETNEXT request and add object name to request */ pdu = snmp_pdu_create(SNMP_MSG_GETNEXT); snmp_add_null_var(pdu, name, name_length); /* * do the request */ status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { /* * check resulting variables */ for (vars = response->variables; vars; vars = vars->next_variable) { if ((vars->name_length < rootlen) || (memcmp(root, vars->name, rootlen * sizeof(oid)) != 0)) { /* * not part of this subtree */ running = 0; continue; } numprinted++; fprint_variable_my(vars->name, vars->name_length, vars, argv, cb, flag_return); if ((vars->type != SNMP_ENDOFMIBVIEW) && (vars->type != SNMP_NOSUCHOBJECT) && (vars->type != SNMP_NOSUCHINSTANCE)) { /* * not an exception value */ if (0 && check && snmp_oid_compare(name, name_length, vars->name, vars->name_length) >= 0) { _DEBUG_FILE("-----MYSNMP-----Error: OID not increasing: %s %d >= %s %d\n", name, name_length, vars->name, vars->name_length); /*fprint_objid(stderr, name, name_length); fprintf(stderr, " >= "); fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n");*/ running = 0; exitval = 1; } memmove((char *) name, (char *) vars->name, vars->name_length * sizeof(oid)); name_length = vars->name_length; } else /* * an exception value, so stop */ running = 0; } } else { /* * error in response, print it */ running = 0; if (response->errstat == SNMP_ERR_NOSUCHNAME) { _DEBUG_FILE("-----MYSNMP-----End of MIB\n"); } else { _DEBUG_FILE("-----MYSNMP-----Error in packet.\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { _DEBUG_FILE("-----MYSNMP-----Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) _DEBUG_FILE("%s %d\n", vars->name, vars->name_length); } exitval = 2; } } } else if (status == STAT_TIMEOUT) { _DEBUG_FILE("-----MYSNMP-----Timeout: No Response from %s\n", session.peername); running = 0; exitval = 4; } else /* status == STAT_ERROR */ { snmp_sess_perror("mysnmp", ss); running = 0; exitval = 1; } if (response) snmp_free_pdu(response); } if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_TIME_RESULTS)) gettimeofday(&tv2, NULL); if (numprinted == 0 && status == STAT_SUCCESS) { /* * no printed successful results, which may mean we were * pointed at an only existing instance. Attempt a GET, just * for get measure. */ if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_DONT_GET_REQUESTED)) { snmp_get_and_print(ss, root, rootlen); exitval = 3; } } /*free the strdup.*/ if(session.peername){ free(session.peername); session.peername = NULL; } if(session.community){ free(session.community); session.community = NULL; } snmp_close(ss); if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_PRINT_STATISTICS)) { _DEBUG_FILE("-----MYSNMP-----Variables found: %d\n", numprinted); } if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_WALK_TIME_RESULTS)) { _DEBUG_FILE("-----MYSNMP-----Total traversal time = %f seconds\n", (double) (tv2.tv_usec - tv1.tv_usec)/1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); } SOCK_CLEANUP; if(exitval==4 && tmp_snmp_version==SNMP_VERSION_2c) { tmp_snmp_version = SNMP_VERSION_1; exitval = 0; _DEBUG_FILE("[%s] %s using snmp version 1 to try again.\n", __func__, argv->peer_name); goto version1_retry; } return exitval; } int snmp_get(snmp_arg *argv, char *out_para, int flag_return) { netsnmp_session session, *ss; netsnmp_pdu *pdu; netsnmp_pdu *response; netsnmp_variable_list *vars; int count; int current_name = 1; oid name[MAX_OID_LEN]; size_t name_length; int status; int failures = 0; int exitval = 0; char tmp_peername[64] = {0}; long tmp_snmp_version = my_config_info.snmp_version; sprintf(tmp_peername, "%s:%d", argv->peer_name, my_config_info.scan_port); version1_retry: snmp_sess_init(&session); /* * read in MIB database and initialize the snmp library */ init_snmp("snmpapp"); /* * set the arguments */ session.version = tmp_snmp_version; session.peername = strdup(tmp_peername); session.community = (u_char *)strdup(argv->community); session.community_len = strlen((char *)session.community); session.retries = my_config_info.retries; session.timeout = my_config_info.snmptimeout * 1000000L; SOCK_STARTUP; /* * Open an SNMP session. */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("mysnmpget", &session); SOCK_CLEANUP; if(session.peername){ free(session.peername); session.peername = NULL; } if(session.community){ free(session.community); session.community = NULL; } return -1; } /* * Create PDU for GET request and add object names to request. */ pdu = snmp_pdu_create(SNMP_MSG_GET); for (count = 0; count < current_name; count++) { name_length = MAX_OID_LEN; if (!snmp_parse_oid(argv->oid, name, &name_length)) { snmp_perror(argv->oid); failures++; } else snmp_add_null_var(pdu, name, name_length); } if (failures) { snmp_close(ss); SOCK_CLEANUP; if(session.peername){ free(session.peername); session.peername = NULL; } if(session.community){ free(session.community); session.community = NULL; } return -1; } /* * Perform the request. * * If the Get Request fails, note the OID that caused the error, * "fix" the PDU (removing the error-prone OID) and retry. */ retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { for (vars = response->variables; vars; vars = vars->next_variable) { if (vars->type == SNMP_NOSUCHOBJECT || vars->type == SNMP_NOSUCHINSTANCE || vars->type == SNMP_ENDOFMIBVIEW) { exitval = 3; break; } fprint_variable_myget(vars->name, vars->name_length, vars, out_para, flag_return); } } else { _DEBUG_FILE("-----MYSNMP-----Error in packet\nReason: %s\n", snmp_errstring(response->errstat)); if (response->errindex != 0) { _DEBUG_FILE("-----MYSNMP-----Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++) /*EMPTY*/; if (vars) { _DEBUG_FILE("%s %d", vars->name, vars->name_length); } _DEBUG_FILE("\n"); } exitval = 2; /* * retry if the errored variable was successfully removed */ if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_APP_DONT_FIX_PDUS)) { pdu = snmp_fix_pdu(response, SNMP_MSG_GET); snmp_free_pdu(response); response = NULL; if (pdu != NULL) { goto retry; } } } /* endif -- SNMP_ERR_NOERROR */ } else if (status == STAT_TIMEOUT) { _DEBUG_FILE("-----MYSNMP-----Timeout: No Response from %s.\n", session.peername); exitval = 4; } else /* status == STAT_ERROR */ { snmp_sess_perror("mysnmpget", ss); exitval = 1; } /* endif -- STAT_SUCCESS */ /*free the strdup.*/ if(session.peername){ free(session.peername); session.peername = NULL; } if(session.community){ free(session.community); session.community = NULL; } if (response) snmp_free_pdu(response); snmp_close(ss); SOCK_CLEANUP; if(exitval==4 && tmp_snmp_version==SNMP_VERSION_2c) { tmp_snmp_version = SNMP_VERSION_1; exitval = 0; _DEBUG_FILE("[%s] %s using snmp version 1 to try again.\n", __func__, argv->peer_name); goto version1_retry; } argv->version = tmp_snmp_version; return exitval; }
31.981238
131
0.47388
[ "object" ]
20c7d39d2b3da4da8a8308ebee92b3b15a8abf90
19,404
h
C
src/LibSvm/libsvm.clr.h
vrvis/aardvark.semantictextonforests
5f5060d7fc25683808c632bda0620b8e69f4d1c1
[ "MIT" ]
4
2015-05-17T22:02:29.000Z
2016-12-21T14:23:11.000Z
src/LibSvm/libsvm.clr.h
vrvis/aardvark.semantictextonforests
5f5060d7fc25683808c632bda0620b8e69f4d1c1
[ "MIT" ]
3
2015-10-12T19:16:27.000Z
2017-04-20T00:30:55.000Z
src/LibSvm/libsvm.clr.h
aardvark-community/aardvark.semantictextonforests
5f5060d7fc25683808c632bda0620b8e69f4d1c1
[ "MIT" ]
2
2015-05-17T22:02:36.000Z
2015-12-21T12:15:37.000Z
#pragma once #include <stdio.h> #include <stdlib.h> #include <msclr/marshal.h> #include "svm.h" using namespace System; using namespace System::Collections; using namespace System::Collections::Generic; using namespace System::Globalization; using namespace System::IO; using namespace System::Runtime::InteropServices; using namespace msclr::interop; #define COPY_MANAGED_ARRAY_TO_NATIVE(type,n,NAME_NAT,NAME_MAN) { auto count = (n); native.NAME_NAT = new type[n]; pin_ptr<type> p = &model.NAME_MAN[0]; memcpy(native.NAME_NAT, p, (n) * sizeof(type)); } namespace LibSvm { public enum class SvmType { C_SVC = ::C_SVC, NU_SVC = ::NU_SVC, ONE_CLASS = ::ONE_CLASS, EPSILON_SVR = ::EPSILON_SVR, NU_SVR = ::NU_SVR }; public enum class KernelType { LINEAR = ::LINEAR, POLY = ::POLY, RBF = ::RBF, SIGMOID = ::SIGMOID, PRECOMPUTED = ::PRECOMPUTED }; public value struct Node { int Index; double Value; Node(int index, double value) : Index(index), Value(value) { } internal: Node(const svm_node& node) : Index(node.index), Value(node.value) { } }; public value struct Problem { array<array<Node>^>^ x; array<double>^ y; /// <summary> /// Number of training data entries. /// </summary> property int Count { int get() { return y->Length; } } Problem(array<array<Node>^>^ trainingVectors, array<double>^ targetValues) : x(trainingVectors), y(targetValues) { if (x->Length != y->Length) { throw gcnew ArgumentOutOfRangeException("Their need to be as many target values as training vectors."); } } internal: Problem(const svm_problem& problem) { auto l = problem.l; x = gcnew array<array<Node>^>(l); for (auto i = 0; i < l; i++) { auto row = problem.x[i]; auto count = 0; while (row[count].index != -1) count++; auto r = gcnew array<Node>(count); pin_ptr<Node> pr = &r[0]; memcpy(pr, row, count * sizeof(svm_node)); x[i] = r; } y = gcnew array<double>(l); pin_ptr<double> py = &y[0]; memcpy(py, problem.y, l * sizeof(double)); } }; public value struct Parameter { /// <summary></summary> SvmType SvmType; /// <summary></summary> KernelType KernelType; /// <summary>for poly</summary> int Degree; /// <summary>for poly/rbf/sigmoid</summary> double Gamma; /// <summary>for poly/sigmoid</summary> double Coef0; /* these are for training only */ /// <summary>in MB</summary> double CacheSize; /// <summary>stopping criteria</summary> double Eps; /// <summary>for C_SVC, EPSILON_SVR and NU_SVR</summary> double C; /// <summary></summary> array<int>^ WeightLabel; /// <summary></summary> array<double>^ Weight; /// <summary>for NU_SVC, ONE_CLASS, and NU_SVR</summary> double Nu; /// <summary>for EPSILON_SVR</summary> double p; /// <summary>use the shrinking heuristics</summary> int Shrinking; /// <summary>do probability estimates</summary> int Probability; internal: Parameter(const svm_parameter& native) { SvmType = (LibSvm::SvmType)native.svm_type; KernelType = (LibSvm::KernelType)native.kernel_type; Degree = native.degree; Gamma = native.gamma; Coef0 = native.coef0; CacheSize = native.cache_size; Eps = native.eps; C = native.C; WeightLabel = gcnew array<int>(native.nr_weight); Weight = gcnew array<double>(native.nr_weight); Nu = native.nu; p = native.p; Shrinking = native.shrinking; Probability = native.probability; for (auto i = 0; i < native.nr_weight; i++) WeightLabel[i] = native.weight_label[i]; for (auto i = 0; i < native.nr_weight; i++) Weight[i] = native.weight[i]; } }; public value struct Model { /// <summary>parameter</summary> Parameter Param; /// <summary>number of classes, = 2 in regression/one class svm</summary> int NrClass; /// <summary>total #SV</summary> int l; /// <summary>SVs (SV[l])</summary> array<array<Node>^>^ SV; /// <summary>coefficients for SVs in decision functions (sv_coef[k-1][l])</summary> array<array<double>^>^ SvCoef; /// <summary>constants in decision functions (rho[k*(k-1)/2])</summary> array<double>^ Rho; /// <summary>pairwise probability information</summary> array<double>^ ProbA; /// <summary></summary> array<double>^ ProbB; /// <summary>sv_indices[0,...,nSV-1] are values in [1,...,num_training_data] to indicate SVs in the training set</summary> array<int>^ SvIndices; /* for classification only */ /// <summary>label of each class (label[k])</summary> array<int>^ Label; /// <summary> /// number of SVs for each class (nSV[k]) /// nSV[0] + nSV[1] + ... + nSV[k-1] = l /// XXX /// </summary> array<int>^ nSV; /// <summary> /// 1 if svm_model is created by svm_load_model /// 0 if svm_model is created by svm_train /// </summary> int FreeSv; /// <summary> /// Gets SVM type of this model. /// </summary> property SvmType Type { SvmType get() { return Param.SvmType; } } internal: Model(const svm_model* native) { auto k = native->nr_class; // param Param = Parameter(native->param); // nr_class NrClass = k; // l l = native->l; // nSV nSV = gcnew array<int>(k); Marshal::Copy((IntPtr)native->nSV, nSV, 0, k); // label Label = gcnew array<int>(k); Marshal::Copy((IntPtr)native->label, Label, 0, k); // free_sv FreeSv = native->free_sv; // sv_indices SvIndices = gcnew array<int>(l); Marshal::Copy((IntPtr)native->sv_indices, SvIndices, 0, l); // SV SV = gcnew array<array<Node>^>(l); for (auto i = 0; i < l; i++) { auto count = 0; svm_node* p = native->SV[i]; while ((p++)->index != -1) ++count; auto row = gcnew array<Node>(count); pin_ptr<Node> pRow = &row[0]; memcpy(pRow, native->SV[i], count * sizeof(svm_node)); SV[i] = row; } // sv_coeff SvCoef = gcnew array<array<double>^>(k-1); for (auto i = 0; i < k - 1; i++) { SvCoef[i] = gcnew array<double>(l); Marshal::Copy((IntPtr)native->sv_coef[i], SvCoef[i], 0, l); } // rho auto count = k*(k - 1) / 2; Rho = gcnew array<double>(count); Marshal::Copy((IntPtr)native->rho, Rho, 0, count); // probA/probB if (Param.Probability != 0) { ProbA = gcnew array<double>(count); Marshal::Copy((IntPtr)native->probA, ProbA, 0, count); ProbB = gcnew array<double>(count); Marshal::Copy((IntPtr)native->probB, ProbB, 0, count); } } }; public ref class Svm abstract sealed { public: /// <summary> /// This function reads an SVM model from given filename. /// </summary> static Problem ReadProblem(String^ filename) { auto ys = gcnew List<double>(); auto xss = gcnew List<array<Node>^>(); auto lines = File::ReadLines(filename); for each (auto line in lines) { auto ts = line->Split(gcnew array<Char> { ' ' }, StringSplitOptions::RemoveEmptyEntries); auto y = Double::Parse(ts[0], CultureInfo::InvariantCulture); auto xs = gcnew array<Node>(ts->Length - 1); for (auto i = 1; i < ts->Length; i++) { auto ns = ts[i]->Split(':'); auto index = Int32::Parse(ns[0]); auto value = Double::Parse(ns[1], CultureInfo::InvariantCulture); auto n = Node(index, value); xs[i - 1] = n; } ys->Add(y); xss->Add(xs); } return Problem(xss->ToArray(), ys->ToArray()); } /// <summary> /// This function constructs and returns an SVM model according /// to the given training data and parameters. /// </summary> static Model Train(Problem problem, Parameter parameter) { svm_problem arg_problem; svm_parameter arg_parameter; try { // (1) convert managed Problem to svm_problem arg_problem = Convert(problem); // (2) convert managed Parameter to svm_parameter arg_parameter = Convert(parameter); // (3) call actual function auto r = svm_train(&arg_problem, &arg_parameter); // debug code //svm_save_model("C:/Data/test_r1.txt", r); //svm_save_model("C:/Data/test_r2.txt", &Convert(Model(r))); // (4) convert result svm_model to managed Model auto result = Model(r); FreeNativeModel(r, false); return result; } finally { FreeProblem(&arg_problem); svm_destroy_param(&arg_parameter); } } /// <summary> /// This function conducts cross validation. Data are separated to /// NrFold folds. Under given parameters, sequentially each fold is /// validated using the model from training the remaining. Predicted /// labels (of all prob's instances) in the validation process are /// stored in the array called target. /// The format of problem is same as that for Train(). /// </summary> static array<double>^ CrossValidation(Problem problem, Parameter parameter, int nrFold) { svm_problem arg_problem; svm_parameter arg_parameter; double* target = NULL; try { arg_problem = Convert(problem); arg_parameter = Convert(parameter); auto l = problem.Count; auto target = new double[l]; svm_cross_validation(&arg_problem, &arg_parameter, nrFold, target); auto result = gcnew array<double>(l); for (auto i = 0; i < l; i++) result[i] = target[i]; return result; } finally { FreeProblem(&arg_problem); if (target != NULL) free(target); } } /// <summary> /// This function does classification or regression on a test vector x /// given a model. /// For a classification model, the predicted class for x is returned. /// For a regression model, the function value of x calculated using /// the model is returned.For an one - class model, +1 or -1 is /// returned. /// </summary> static double Predict(Model model, array<Node>^ x) { svm_node* nativeNodes = NULL; svm_model nativeModel; try { nativeNodes = Convert(x); nativeModel = Convert(model); return svm_predict(&nativeModel, nativeNodes); } finally { if (nativeNodes) delete[] nativeNodes; FreeNativeModel(&nativeModel, true); } } /// <summary> /// This function gives decision values on a test vector x given a /// model, and returns the predicted label (classification) or /// the function value (regression). /// For a classification model with NrClass classes, this function /// gives NrClass*(NrClass - 1)/2 decision values in the array /// decValues. The order is label[0] vs.label[1], ..., /// label[0] vs.label[NrClass - 1], label[1] vs.label[2], ..., /// label[NrClass - 2] vs.label[NrClass - 1]. The returned value is /// the predicted class for x. Note that when NrClass=1, this /// function does not give any decision value. /// For a regression model, decValues[0] and the returned value are /// both the function value of x calculated using the model. For a /// one-class model, decValues[0] is the decision value of x, while /// the returned value is +1/-1. /// </summary> static double PredictValues(Model model, array<Node>^ x, array<double>^ decValues) { svm_node* nativeNodes = NULL; svm_model nativeModel; try { nativeNodes = Convert(x); nativeModel = Convert(model); pin_ptr<double> pDecValues = &decValues[0]; return svm_predict_values(&nativeModel, nativeNodes, pDecValues); } finally { if (nativeNodes) delete[] nativeNodes; FreeNativeModel(&nativeModel, true); } } /// <summary> /// This function does classification or regression on a test vector x /// given a model with probability information. /// For a classification model with probability information, this /// function gives NrClass probability estimates in the array /// probEstimates. The class with the highest probability is /// returned. For regression/one-class SVM, the array probEstimates /// is unchanged and the returned value is the same as that of /// Predict. /// </summary> static double PredictProbability(Model model, array<Node>^ x, array<double>^ probEstimates) { svm_node* nativeNodes = NULL; svm_model nativeModel; try { nativeNodes = Convert(x); nativeModel = Convert(model); pin_ptr<double> pProbEstimates = &probEstimates[0]; return svm_predict_probability(&nativeModel, nativeNodes, pProbEstimates); } finally { if (nativeNodes) delete[] nativeNodes; FreeNativeModel(&nativeModel, true); } } /// <summary> /// This function saves a model to a file. /// </summary> static void SaveModel(String^ fileName, Model model) { auto context = gcnew marshal_context(); const char* nativeFileName = context->marshal_as<const char*>(fileName); auto native_model = Convert(model); auto err = svm_save_model(nativeFileName, &native_model); if (err != 0) throw gcnew Exception("SaveModel failed with error code " + err + "."); } /// <summary> /// This function loads a model from file. /// </summary> static Model LoadModel(String^ fileName) { auto context = gcnew marshal_context(); const char* nativeFileName = context->marshal_as<const char*>(fileName); auto native_model = svm_load_model(nativeFileName); if (native_model == NULL) throw gcnew Exception("LoadModel failed to load model from " + fileName + "."); return Model(native_model); } /// <summary> /// This function checks whether the parameters are within the feasible /// range of the problem. This function should be called before /// Svm.Train() and Svm.CrossValidation(). It returns null if the /// parameters are feasible, otherwise an error message is returned. /// </summary> static String^ CheckParameter(Problem problem, Parameter parameter) { svm_problem arg_problem; svm_parameter arg_parameter; try { arg_problem = Convert(problem); arg_parameter = Convert(parameter); auto r = svm_check_parameter(&arg_problem, &arg_parameter); return gcnew String(r); } finally { FreeProblem(&arg_problem); } } /// <summary> /// This function checks whether the model contains required information /// to do probability estimates. If so, it returns true. Otherwise, false /// is returned. This function should be called before calling /// GetSvrProbability and PredictProbability. /// </summary> static bool CheckProbabilityModel(Model model) { svm_model nativeModel; try { nativeModel = Convert(model); auto r = svm_check_probability_model(&nativeModel); return r == 1; } finally { FreeNativeModel(&nativeModel, true); } } /// <summary> /// Disables libsvm's output to stdout. /// </summary> static void DisablePrint(); private: static svm_problem Convert(Problem problem) { svm_problem result; auto l = result.l = problem.y->Length; pin_ptr<double> yPinned = &problem.y[0]; result.y = new double[l]; memcpy(result.y, yPinned, l * sizeof(double)); result.x = new svm_node*[l]; for (int i = 0; i < l; i++) result.x[i] = Convert(problem.x[i]); return result; } static svm_node Convert(const Node node) { svm_node x; x.index = node.Index; x.value = node.Value; return x; } static svm_node* Convert(array<Node>^ x) { auto count = x->Length; auto p = new svm_node[count + 1]; pin_ptr<Node> pinned = &x[0]; memcpy(p, pinned, count * sizeof(svm_node)); p[count].index = -1; p[count].value = 0.0; // add delimiter return p; } static svm_parameter Convert(Parameter parameter) { svm_parameter result; result.svm_type = (int)parameter.SvmType; result.kernel_type = (int)parameter.KernelType; result.degree = parameter.Degree; result.gamma = parameter.Gamma; result.coef0 = parameter.Coef0; result.cache_size = parameter.CacheSize; result.eps = parameter.Eps; result.C = parameter.C; result.nr_weight = parameter.Weight ? parameter.Weight->Length : 0; if (parameter.WeightLabel && parameter.WeightLabel->Length) { auto count = parameter.WeightLabel->Length; result.weight_label = new int[count]; pin_ptr<int> pinnedWeightLabel = &parameter.WeightLabel[0]; memcpy(result.weight_label, pinnedWeightLabel, count * sizeof(int)); result.weight = new double[count]; pin_ptr<double> pinnedWeight = &parameter.Weight[0]; memcpy(result.weight, pinnedWeight, count * sizeof(double)); } else { result.weight_label = NULL; result.weight = NULL; } result.nu = parameter.Nu; result.p = parameter.p; result.shrinking = parameter.Shrinking; result.probability = parameter.Probability; return result; } static svm_model Convert(Model model) { auto k = model.NrClass; auto l = model.l; svm_model native; // param native.param = Convert(model.Param); // nr_class native.nr_class = model.NrClass; // l native.l = l; // nSV COPY_MANAGED_ARRAY_TO_NATIVE(int, k, nSV, nSV) // label COPY_MANAGED_ARRAY_TO_NATIVE(int, k, label, Label) // free_sv native.free_sv = model.FreeSv; // sv_indices COPY_MANAGED_ARRAY_TO_NATIVE(int, l, sv_indices, SvIndices) // SV native.SV = new svm_node*[l]; for (auto i = 0; i < l; i++) { auto r = model.SV[i]; pin_ptr<Node> p = &r[0]; native.SV[i] = new svm_node[r->Length + 1]; memcpy(native.SV[i], p, r->Length * sizeof(svm_node)); native.SV[i][r->Length] = { -1, 0 }; } // sv_coeff native.sv_coef = new double*[k - 1]; for (auto i = 0; i < k - 1; i++) { COPY_MANAGED_ARRAY_TO_NATIVE(double, l, sv_coef[i], SvCoef[i]) } // rho COPY_MANAGED_ARRAY_TO_NATIVE(double, k*(k - 1) / 2, rho, Rho) if (model.Param.Probability != 0) { // probA COPY_MANAGED_ARRAY_TO_NATIVE(double, k*(k - 1) / 2, probA, ProbA) // probB COPY_MANAGED_ARRAY_TO_NATIVE(double, k*(k - 1) / 2, probB, ProbB) } else { native.probA = native.probB = NULL; } return native; } static void FreeProblem(svm_problem* problem) { if (problem->y) { delete[] problem->y; problem->y = NULL; } if (problem->x) { for (int i = 0; i < problem->l; i++) { delete[] problem->x[i]; problem->x[i] = NULL; } delete[] problem->x; problem->x = NULL; } } static void FreeNativeModel(svm_model* native, bool deleteInnerSVs) { #define Clean(param) { if (native->param) delete[] native->param; native->param = NULL; } Clean(param.weight); Clean(param.weight_label); Clean(nSV); Clean(label); Clean(sv_indices); if (native->SV) { if (deleteInnerSVs) { for (auto i = 0; i < native->l; i++) { delete[] native->SV[i]; native->SV[i] = NULL; } } delete[] native->SV; native->SV = NULL; } if (native->sv_coef) { for (auto i = 0; i < native->nr_class - 1; i++) delete[] native->sv_coef[i]; delete[] native->sv_coef; } Clean(rho); Clean(probA); Clean(probB); } }; }
25.734748
201
0.628942
[ "vector", "model" ]
20cc8df7e8945db14b2813e92ad30bcb732aa03c
1,720
h
C
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/biocytin/zstackprojector.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/biocytin/zstackprojector.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/biocytin/zstackprojector.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#ifndef ZSTACKPROJECTOR_H #define ZSTACKPROJECTOR_H #include <vector> #include <string> #include "zprogressable.h" #include "tz_fmatrix.h" #include "tz_image_lib_defs.h" class ZStack; namespace Biocytin { class ZStackProjector : public ZProgressable { public: ZStackProjector(); ZStack* project(const ZStack *stack, bool includingDepth = false); inline void setAdjustingContrast(bool adj) { m_adjustingConstrast = adj; } inline void setSmoothingDepth(bool stat) { m_smoothingDepth = stat; } inline void setSpeedLevel(int level) { m_speedLevel = level; } inline void setUsingExisted(bool stat) { m_usingExisted = stat; } inline const std::vector<int>& getDepthArray() { return m_depthArray; } static std::string getDefaultResultFilePath(const std::string &basePath); private: inline double colorToValue(double g, double sr, double sg, double reg, double redScale, double redOffset, double greenScale, double greenOffset) { sr = sr * redScale + redOffset; sg = sg * greenScale + greenOffset; double ratio = (sg + reg) / (sr + reg); return g * ratio * ratio; } inline double colorToValue(double g, double sr, double sg, double reg) { double ratio = (sg + reg) / (sr + reg); return g * ratio * ratio; } double colorToValueH(double sr, double sg, double sb, double reg); private: FMatrix* smoothStackNull(Stack *stack); FMatrix* smoothStack(Stack *stack); FMatrix* smoothStackGaussian(Stack *stack); private: bool m_adjustingConstrast; bool m_smoothingDepth; int m_speedLevel; bool m_usingExisted; std::vector<int> m_depthArray; }; } #endif // ZSTACKPROJECTOR_H
24.571429
75
0.693605
[ "vector" ]
20d3c6b0e752757f9782865804d3e5774234e9b5
26,461
c
C
kernel/power/sgemm_small_kernel_nt_power10.c
jgillis/OpenBLAS
ee15f53c9ef7148b05e1b2ff80003df1685f0f10
[ "BSD-3-Clause" ]
4,392
2015-01-02T18:15:45.000Z
2022-03-29T12:14:38.000Z
kernel/power/sgemm_small_kernel_nt_power10.c
jgillis/OpenBLAS
ee15f53c9ef7148b05e1b2ff80003df1685f0f10
[ "BSD-3-Clause" ]
2,067
2015-01-01T03:50:01.000Z
2022-03-31T18:59:43.000Z
kernel/power/sgemm_small_kernel_nt_power10.c
jgillis/OpenBLAS
ee15f53c9ef7148b05e1b2ff80003df1685f0f10
[ "BSD-3-Clause" ]
1,564
2015-01-01T01:32:27.000Z
2022-03-30T07:12:54.000Z
/*************************************************************************** Copyright (c) 2021, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include "common.h" #include <altivec.h> typedef __vector unsigned char vec_t; #if !defined(B0) #define SAVE_4x4_ACC(ACC, N, M) \ __builtin_mma_disassemble_acc((void *)result, ACC); \ rc0 = vec_xl(0, C+(N+0)*ldc+M); \ rc0 = vec_mul(rc0, vbeta); \ result[0] = vec_madd(result[0], valpha, rc0); \ vec_xst(result[0], 0, C+(N+0)*ldc+M); \ rc0 = vec_xl(0, C+(N+1)*ldc+M); \ rc0 = vec_mul(rc0, vbeta); \ result[1] = vec_madd(result[1], valpha, rc0); \ vec_xst(result[1], 0, C+(N+1)*ldc+M); \ rc0 = vec_xl(0, C+(N+2)*ldc+M); \ rc0 = vec_mul(rc0, vbeta); \ result[2] = vec_madd(result[2], valpha, rc0); \ vec_xst(result[2], 0, C+(N+2)*ldc+M); \ rc0 = vec_xl(0, C+(N+3)*ldc+M); \ rc0 = vec_mul(rc0, vbeta); \ result[3] = vec_madd(result[3], valpha, rc0); \ vec_xst(result[3], 0, C+(N+3)*ldc+M); #define SAVE_4x2_ACC(ACC, N, M) \ __builtin_mma_disassemble_acc((void *)result, ACC); \ rc0 = vec_xl_len(C+(N+0)*ldc+M, 8); \ rc0 = vec_mul(rc0, vbeta); \ result[0] = vec_madd(result[0], valpha, rc0); \ vec_xst_len(result[0], C+(N+0)*ldc+M, 8); \ rc0 = vec_xl_len(C+(N+1)*ldc+M, 8); \ rc0 = vec_mul(rc0, vbeta); \ result[1] = vec_madd(result[1], valpha, rc0); \ vec_xst_len(result[1], C+(N+1)*ldc+M, 8); \ rc0 = vec_xl_len(C+(N+2)*ldc+M, 8); \ rc0 = vec_mul(rc0, vbeta); \ result[2] = vec_madd(result[2], valpha, rc0); \ vec_xst_len(result[2], C+(N+2)*ldc+M, 8); \ rc0 = vec_xl_len(C+(N+3)*ldc+M, 8); \ rc0 = vec_mul(rc0, vbeta); \ result[3] = vec_madd(result[3], valpha, rc0); \ vec_xst_len(result[3], C+(N+3)*ldc+M, 8); #define SAVE_2x4_ACC(ACC, N, M) \ __builtin_mma_disassemble_acc((void *)result, ACC); \ rc0 = vec_xl(0, C+(N+0)*ldc+M); \ rc0 = vec_mul(rc0, vbeta); \ result[0] = vec_madd(result[0], valpha, rc0); \ vec_xst(result[0], 0, C+(N+0)*ldc+M); \ rc0 = vec_xl(0, C+(N+1)*ldc+M); \ rc0 = vec_mul(rc0, vbeta); \ result[1] = vec_madd(result[1], valpha, rc0); \ vec_xst(result[1], 0, C+(N+1)*ldc+M); #define SAVE_1x4_VSR(result, N, M) \ rc0 = vec_xl(0, C+((N)*ldc)+M); \ rc0 = vec_mul(rc0, vbeta); \ result = vec_madd(result, valpha, rc0); \ vec_xst(result, 0, C+((N)*ldc)+M); #define SAVE_2x2_VSR(result, N, M) \ rc0 = vec_xl_len(C+(N*ldc)+M, 8); \ rc0 = vec_insert(C[(N+1)*ldc+M+0], rc0, 2); \ rc0 = vec_insert(C[(N+1)*ldc+M+1], rc0, 3); \ rc0 = vec_mul(rc0, vbeta); \ result = vec_madd(result, valpha, rc0); \ vec_xst_len(result, C+(N*ldc)+M, 8); \ C[(N+1)*ldc+M+0] = result[2]; \ C[(N+1)*ldc+M+1] = result[3]; #define SAVE_1x2_VSR(result, N, M) \ rc0 = vec_xl_len(C+(N*ldc)+M, 8); \ rc0 = vec_mul(rc0, vbeta); \ result = vec_madd(result, valpha, rc0); \ vec_xst_len(result, C+(N*ldc)+M, 8); #define SAVE_4x1_VSR(result, N, M) \ result = vec_mul(result, valpha); \ C[(N+0)*ldc+M] = (C[(N+0)*ldc+M] * beta) + result[0]; \ C[(N+1)*ldc+M] = (C[(N+1)*ldc+M] * beta) + result[1]; \ C[(N+2)*ldc+M] = (C[(N+2)*ldc+M] * beta) + result[2]; \ C[(N+3)*ldc+M] = (C[(N+3)*ldc+M] * beta) + result[3]; #define SAVE_2x1_VSR(result, N, M) \ result = vec_mul(result, valpha); \ C[(N+0)*ldc+M] = (C[(N+0)*ldc+M] * beta) + result[0]; \ C[(N+1)*ldc+M] = (C[(N+1)*ldc+M] * beta) + result[1]; #else #define SAVE_4x4_ACC(ACC, N, M) \ __builtin_mma_disassemble_acc((void *)result, ACC); \ result[0] = vec_mul(result[0], valpha); \ vec_xst(result[0], 0, C+(N+0)*ldc+M); \ result[1] = vec_mul(result[1], valpha); \ vec_xst(result[1], 0, C+(N+1)*ldc+M); \ result[2] = vec_mul(result[2], valpha); \ vec_xst(result[2], 0, C+(N+2)*ldc+M); \ result[3] = vec_mul(result[3], valpha); \ vec_xst(result[3], 0, C+(N+3)*ldc+M); #define SAVE_4x2_ACC(ACC, N, M) \ __builtin_mma_disassemble_acc((void *)result, ACC); \ result[0] = vec_mul(result[0], valpha); \ vec_xst_len(result[0], C+(N+0)*ldc+M, 8); \ result[1] = vec_mul(result[1], valpha); \ vec_xst_len(result[1], C+(N+1)*ldc+M, 8); \ result[2] = vec_mul(result[2], valpha); \ vec_xst_len(result[2], C+(N+2)*ldc+M, 8); \ result[3] = vec_mul(result[3], valpha); \ vec_xst_len(result[3], C+(N+3)*ldc+M, 8); #define SAVE_2x4_ACC(ACC, N, M) \ __builtin_mma_disassemble_acc((void *)result, ACC); \ result[0] = vec_mul(result[0], valpha); \ vec_xst(result[0], 0, C+(N+0)*ldc+M); \ result[1] = vec_mul(result[1], valpha); \ vec_xst(result[1], 0, C+(N+1)*ldc+M); #define SAVE_1x4_VSR(result, N, M) \ result = vec_mul(result, valpha); \ vec_xst(result, 0, C+((N)*ldc)+M); #define SAVE_2x2_VSR(result, N, M) \ result = vec_mul(result, valpha); \ vec_xst_len(result, C+(N*ldc)+M, 8); \ C[(N+1)*ldc+M+0] = result[2]; \ C[(N+1)*ldc+M+1] = result[3]; #define SAVE_1x2_VSR(result, N, M) \ result = vec_mul(result, valpha); \ vec_xst_len(result, C+(N*ldc)+M, 8); #define SAVE_4x1_VSR(result, N, M) \ result = vec_mul(result, valpha); \ C[(N+0)*ldc+M] = result[0]; \ C[(N+1)*ldc+M] = result[1]; \ C[(N+2)*ldc+M] = result[2]; \ C[(N+3)*ldc+M] = result[3]; #define SAVE_2x1_VSR(result, N, M) \ result = vec_mul(result, valpha); \ C[(N+0)*ldc+M] = result[0]; \ C[(N+1)*ldc+M] = result[1]; #endif #define INIT_8ACCS() \ __builtin_mma_xxsetaccz(&acc0); \ __builtin_mma_xxsetaccz(&acc1); \ __builtin_mma_xxsetaccz(&acc2); \ __builtin_mma_xxsetaccz(&acc3); \ __builtin_mma_xxsetaccz(&acc4); \ __builtin_mma_xxsetaccz(&acc5); \ __builtin_mma_xxsetaccz(&acc6); \ __builtin_mma_xxsetaccz(&acc7); #define INIT_4ACCS() \ __builtin_mma_xxsetaccz(&acc0); \ __builtin_mma_xxsetaccz(&acc1); \ __builtin_mma_xxsetaccz(&acc2); \ __builtin_mma_xxsetaccz(&acc3); #define INIT_2ACCS() \ __builtin_mma_xxsetaccz(&acc0); \ __builtin_mma_xxsetaccz(&acc1); #define INIT_1ACC() __builtin_mma_xxsetaccz(&acc0); #define LOAD_A_1x16(K, M) \ ra0 = vec_xl(0, A+(K*lda)+M+0); \ ra1 = vec_xl(0, A+(K*lda)+M+4); \ ra2 = vec_xl(0, A+(K*lda)+M+8); \ ra3 = vec_xl(0, A+(K*lda)+M+12); #define LOAD_A_1x8(K, M) \ ra0 = vec_xl(0, A+(K*lda)+M+0); \ ra1 = vec_xl(0, A+(K*lda)+M+4); #define LOAD_A_1x4(K, M) ra0 = vec_xl(0, A+(K*lda)+M); #define LOAD_A_2x2(K, M) \ ra0 = vec_splats(A[K*lda+M+0]); \ ra0 = vec_insert(A[K*lda+M+1], ra0, 1); \ ra0 = vec_insert(A[K*lda+M+1], ra0, 3); #define LOAD_A_1x2(K, M) ra0 = vec_xl_len(A+(K*lda)+M, 8); #define LOAD_A_1x1(K, M) ra0 = vec_splats(A[K*lda+M+0]); #define LOAD_B_1x16(K, N) \ rb0 = vec_xl(0, B+(K*ldb)+N+0); \ rb1 = vec_xl(0, B+(K*ldb)+N+4); \ rb2 = vec_xl(0, B+(K*ldb)+N+8); \ rb3 = vec_xl(0, B+(K*ldb)+N+12); #define LOAD_B_1x8(K, N) \ rb0 = vec_xl(0, B+(K*ldb)+N+0); \ rb1 = vec_xl(0, B+(K*ldb)+N+4); #define LOAD_B_1x4(K, N) rb0 = vec_xl(0, B+(K*ldb)+N); #define LOAD_B_2x2(K, N) \ rb0 = vec_splats(B[K*ldb+N]); \ rb0 = vec_insert(B[K*ldb+N+1], rb0, 2); \ rb0 = vec_insert(B[K*ldb+N+1], rb0, 3); #define LOAD_B_1x2(K, N) rb0 = vec_xl_len(B+(K*ldb)+N, 8); #define LOAD_B_1x1(K, N) rb0 = vec_splats(B[K*ldb+N]); #define KERNEL_MMA_8ACC(b0, b1, b2, b3, b4, b5, b6, b7, \ a0, a1, a2, a3, a4, a5, a6, a7) \ __builtin_mma_xvf32gerpp(&acc0, (vec_t)b0, (vec_t)a0); \ __builtin_mma_xvf32gerpp(&acc1, (vec_t)b1, (vec_t)a1); \ __builtin_mma_xvf32gerpp(&acc2, (vec_t)b2, (vec_t)a2); \ __builtin_mma_xvf32gerpp(&acc3, (vec_t)b3, (vec_t)a3); \ __builtin_mma_xvf32gerpp(&acc4, (vec_t)b4, (vec_t)a4); \ __builtin_mma_xvf32gerpp(&acc5, (vec_t)b5, (vec_t)a5); \ __builtin_mma_xvf32gerpp(&acc6, (vec_t)b6, (vec_t)a6); \ __builtin_mma_xvf32gerpp(&acc7, (vec_t)b7, (vec_t)a7); #define KERNEL_MMA_4ACC(b0, b1, b2, b3, a0, a1, a2, a3) \ __builtin_mma_xvf32gerpp(&acc0, (vec_t)b0, (vec_t)a0); \ __builtin_mma_xvf32gerpp(&acc1, (vec_t)b1, (vec_t)a1); \ __builtin_mma_xvf32gerpp(&acc2, (vec_t)b2, (vec_t)a2); \ __builtin_mma_xvf32gerpp(&acc3, (vec_t)b3, (vec_t)a3); #define KERNEL_MMA_2ACC(b0, b1, a0, a1) \ __builtin_mma_xvf32gerpp(&acc0, (vec_t)b0, (vec_t)a0); \ __builtin_mma_xvf32gerpp(&acc1, (vec_t)b1, (vec_t)a1); #define KERNEL_MMA_1ACC(b0, a0) \ __builtin_mma_xvf32gerpp(&acc0, (vec_t)b0, (vec_t)a0); #define KERNEL_VMADD_4VSR(a0, a1, a2, a3, b0, b1, b2, b3) \ result = vec_madd(a0, b0, result); \ result1 = vec_madd(a1, b1, result1); \ result2 = vec_madd(a2, b2, result2); \ result3 = vec_madd(a3, b3, result3); #define KERNEL_VMADD_2VSR(a0, a1, b0, b1) \ result = vec_madd(a0, b0, result); \ result1 = vec_madd(a1, b1, result1); #define KERNEL_VMADD_1VSR(a0, b0) \ result = vec_madd(a0, b0, result); #define PACK_A(ra0, ra1, ra2, ra3, offset) \ vec_xst(ra0, 0, packA+(k*16)+0+offset); \ vec_xst(ra1, 0, packA+(k*16)+4+offset); \ vec_xst(ra2, 0, packA+(k*16)+8+offset); \ vec_xst(ra3, 0, packA+(k*16)+12+offset); #define LOAD_PACKED_A(ra0, ra1, ra2, ra3, offset) \ ra0 = vec_xl(0, packA+(k*16)+0+offset); \ ra1 = vec_xl(0, packA+(k*16)+4+offset); \ ra2 = vec_xl(0, packA+(k*16)+8+offset); \ ra3 = vec_xl(0, packA+(k*16)+12+offset); #ifdef B0 int CNAME(BLASLONG M, BLASLONG N, BLASLONG K, IFLOAT * A, BLASLONG lda, FLOAT alpha, IFLOAT * B, BLASLONG ldb, FLOAT * C, BLASLONG ldc) #else int CNAME(BLASLONG M, BLASLONG N, BLASLONG K, IFLOAT * A, BLASLONG lda, FLOAT alpha, IFLOAT * B, BLASLONG ldb, FLOAT beta, FLOAT * C, BLASLONG ldc) #endif { BLASLONG m, n, k; BLASLONG m16 = M & ~15; BLASLONG m8 = M & ~7; BLASLONG m4 = M & ~3; BLASLONG m2 = M & ~1; BLASLONG n16 = N & ~15; BLASLONG n8 = N & ~7; BLASLONG n4 = N & ~3; BLASLONG n2 = N & ~1; vector float valpha = vec_splats(alpha); #if !defined(B0) vector float vbeta = vec_splats(beta); #endif #if defined(__GNUC__) && !defined(__clang__) int has_packing = (M >= 40 && N >= 40 && K >= 40) ? 1 : 0; #else int has_packing = 0; #endif float *packA; if (has_packing) packA = (float *)malloc(K*16*sizeof(float)); for (m = 0; m < m16; m += 16) { for (n = 0; n < n8; n += 8) { __vector_quad acc0, acc1, acc2, acc3, acc4, acc5, acc6, acc7; INIT_8ACCS(); register vector float ra0, ra1, ra2, ra3; register vector float rb0, rb1; if (has_packing) { if (n == 0) { for (k = 0; k < K; k++) { LOAD_A_1x16(k, m); LOAD_B_1x8(k, n); KERNEL_MMA_8ACC(rb0, rb1, rb0, rb1, rb0, rb1, rb0, rb1, ra0, ra0, ra1, ra1, ra2, ra2, ra3, ra3); PACK_A(ra0, ra1, ra2, ra3, 0); } } else { for (k = 0; k < K; k++) { LOAD_PACKED_A(ra0, ra1, ra2, ra3, 0); LOAD_B_1x8(k, n); KERNEL_MMA_8ACC(rb0, rb1, rb0, rb1, rb0, rb1, rb0, rb1, ra0, ra0, ra1, ra1, ra2, ra2, ra3, ra3); } } } else { for (k = 0; k < K; k++) { LOAD_A_1x16(k, m); LOAD_B_1x8(k, n); KERNEL_MMA_8ACC(rb0, rb1, rb0, rb1, rb0, rb1, rb0, rb1, ra0, ra0, ra1, ra1, ra2, ra2, ra3, ra3); } } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc2, n+0, m+4); SAVE_4x4_ACC(&acc4, n+0, m+8); SAVE_4x4_ACC(&acc6, n+0, m+12); SAVE_4x4_ACC(&acc1, n+4, m+0); SAVE_4x4_ACC(&acc3, n+4, m+4); SAVE_4x4_ACC(&acc5, n+4, m+8); SAVE_4x4_ACC(&acc7, n+4, m+12); } for (; n < n4; n += 4) { __vector_quad acc0, acc1, acc2, acc3; INIT_4ACCS(); register vector float ra0, ra1, ra2, ra3; register vector float rb0; if (!has_packing) { for (k = 0; k < K; k++) { LOAD_A_1x16(k, m); LOAD_B_1x4(k, n); KERNEL_MMA_4ACC(rb0, rb0, rb0, rb0, ra0, ra1, ra2, ra3); } } else { for (k = 0; k < K; k++) { LOAD_PACKED_A(ra0, ra1, ra2, ra3, 0); LOAD_B_1x4(k, n); KERNEL_MMA_4ACC(rb0, rb0, rb0, rb0, ra0, ra1, ra2, ra3); } } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc1, n+0, m+4); SAVE_4x4_ACC(&acc2, n+0, m+8); SAVE_4x4_ACC(&acc3, n+0, m+12); } for (; n < n2; n += 2) { __vector_quad acc0, acc1, acc2, acc3; INIT_4ACCS(); register vector float ra0, ra1, ra2, ra3; register vector float rb0; if (!has_packing) { for (k = 0; k < K; k++) { LOAD_A_1x16(k, m); LOAD_B_1x2(k, n); KERNEL_MMA_4ACC(rb0, rb0, rb0, rb0, ra0, ra1, ra2, ra3); } } else { for (k = 0; k < K; k++) { LOAD_PACKED_A(ra0, ra1, ra2, ra3, 0); LOAD_B_1x2(k, n); KERNEL_MMA_4ACC(rb0, rb0, rb0, rb0, ra0, ra1, ra2, ra3); } } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_2x4_ACC(&acc0, n, m+0); SAVE_2x4_ACC(&acc1, n, m+4); SAVE_2x4_ACC(&acc2, n, m+8); SAVE_2x4_ACC(&acc3, n, m+12); } for (; n < N; n++) { vector float result = ((vector float){0., 0., 0., 0.}); vector float result1 = ((vector float){0., 0., 0., 0.}); vector float result2 = ((vector float){0., 0., 0., 0.}); vector float result3 = ((vector float){0., 0., 0., 0.}); register vector float ra0, ra1, ra2, ra3; register vector float rb0; if (!has_packing) { for (k = 0; k < K; k++) { LOAD_A_1x16(k, m); LOAD_B_1x1(k, n); KERNEL_VMADD_4VSR(ra0, ra1, ra2, ra3, rb0, rb0, rb0, rb0); } } else { for (k = 0; k < K; k++) { LOAD_PACKED_A(ra0, ra1, ra2, ra3, 0); LOAD_B_1x1(k, n); KERNEL_VMADD_4VSR(ra0, ra1, ra2, ra3, rb0, rb0, rb0, rb0); } } #if !defined(B0) register vector float rc0; #endif SAVE_1x4_VSR(result, n, m); SAVE_1x4_VSR(result1, n, m+4); SAVE_1x4_VSR(result2, n, m+8); SAVE_1x4_VSR(result3, n, m+12); } } for (; m < m8; m += 8) { for (n = 0; n < n16; n += 16) { __vector_quad acc0, acc1, acc2, acc3, acc4, acc5, acc6, acc7; INIT_8ACCS(); register vector float ra0, ra1; register vector float rb0, rb1, rb2, rb3; for (k = 0; k < K; k++) { LOAD_A_1x8(k, m); LOAD_B_1x16(k, n); KERNEL_MMA_8ACC(rb0, rb1, rb2, rb3, rb0, rb1, rb2, rb3, ra0, ra0, ra0, ra0, ra1, ra1, ra1, ra1); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc4, n+0, m+4); SAVE_4x4_ACC(&acc1, n+4, m+0); SAVE_4x4_ACC(&acc5, n+4, m+4); SAVE_4x4_ACC(&acc2, n+8, m+0); SAVE_4x4_ACC(&acc6, n+8, m+4); SAVE_4x4_ACC(&acc3, n+12, m+0); SAVE_4x4_ACC(&acc7, n+12, m+4); } for (; n < n8; n += 8) { __vector_quad acc0, acc1, acc2, acc3; INIT_4ACCS(); register vector float ra0, ra1; register vector float rb0, rb1; for (k = 0; k < K; k++) { LOAD_A_1x8(k, m); LOAD_B_1x8(k, n); KERNEL_MMA_4ACC(rb0, rb1, rb0, rb1, ra0, ra0, ra1, ra1); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc2, n+0, m+4); SAVE_4x4_ACC(&acc1, n+4, m+0); SAVE_4x4_ACC(&acc3, n+4, m+4); } for (; n < n4; n += 4) { __vector_quad acc0, acc1; INIT_2ACCS(); register vector float ra0, ra1; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x8(k, m); LOAD_B_1x4(k, n); KERNEL_MMA_2ACC(rb0, rb0, ra0, ra1); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc1, n+0, m+4); } for (; n < n2; n += 2) { __vector_quad acc0, acc1; INIT_2ACCS(); register vector float ra0, ra1; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x8(k, m); LOAD_B_1x2(k, n); KERNEL_MMA_2ACC(rb0, rb0, ra0, ra1); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_2x4_ACC(&acc0, n, m+0); SAVE_2x4_ACC(&acc1, n, m+4); } for (; n < N; n++) { vector float result = ((vector float){0.,0.,0.,0.}); vector float result1 = ((vector float){0.,0.,0.,0.}); register vector float ra0, ra1; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x8(k, m); LOAD_B_1x1(k, n); KERNEL_VMADD_2VSR(ra0, ra1, rb0, rb0); } #if !defined(B0) register vector float rc0; #endif SAVE_1x4_VSR(result, n, m); SAVE_1x4_VSR(result1, n, m+4); } } for (; m < m4; m += 4) { for (n = 0; n < n16; n += 16) { __vector_quad acc0, acc1, acc2, acc3; INIT_4ACCS(); register vector float ra0; register vector float rb0, rb1, rb2, rb3; for (k = 0; k < K; k++) { LOAD_A_1x4(k, m); LOAD_B_1x16(k, n); KERNEL_MMA_4ACC(rb0, rb1, rb2, rb3, ra0, ra0, ra0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc1, n+4, m+0); SAVE_4x4_ACC(&acc2, n+8, m+0); SAVE_4x4_ACC(&acc3, n+12, m+0); } for (; n < n8; n += 8) { __vector_quad acc0, acc1; INIT_2ACCS(); register vector float ra0; register vector float rb0, rb1; for (k = 0; k < K; k++) { LOAD_A_1x4(k, m); LOAD_B_1x8(k, n); KERNEL_MMA_2ACC(rb0, rb1, ra0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); SAVE_4x4_ACC(&acc1, n+4, m+0); } for (; n < n4; n += 4) { __vector_quad acc0; INIT_1ACC(); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x4(k, m); LOAD_B_1x4(k, n); KERNEL_MMA_1ACC(rb0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x4_ACC(&acc0, n+0, m+0); } for (; n < n2; n += 2) { __vector_quad acc0; INIT_1ACC(); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x4(k, m); LOAD_B_1x2(k, n); KERNEL_MMA_1ACC(rb0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_2x4_ACC(&acc0, n, m); } for (; n < N; n++) { vector float result = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x4(k, m); LOAD_B_1x1(k, n); KERNEL_VMADD_1VSR(ra0, rb0); } #if !defined(B0) register vector float rc0; #endif SAVE_1x4_VSR(result, n, m); } } for (; m < m2; m += 2) { for (n = 0; n < n16; n += 16) { __vector_quad acc0, acc1, acc2, acc3; INIT_4ACCS(); register vector float ra0; register vector float rb0, rb1, rb2, rb3; for (k = 0; k < K; k++) { LOAD_A_1x2(k, m); LOAD_B_1x16(k, n); KERNEL_MMA_4ACC(rb0, rb1, rb2, rb3, ra0, ra0, ra0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x2_ACC(&acc0, n+0, m+0); SAVE_4x2_ACC(&acc1, n+4, m+0); SAVE_4x2_ACC(&acc2, n+8, m+0); SAVE_4x2_ACC(&acc3, n+12, m+0); } for (; n < n8; n += 8) { __vector_quad acc0, acc1; INIT_2ACCS(); register vector float ra0; register vector float rb0, rb1; for (k = 0; k < K; k++) { LOAD_A_1x2(k, m); LOAD_B_1x8(k, n); KERNEL_MMA_2ACC(rb0, rb1, ra0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x2_ACC(&acc0, n+0, m+0); SAVE_4x2_ACC(&acc1, n+4, m+0); } for (; n < n4; n += 4) { __vector_quad acc0; INIT_1ACC(); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x2(k, m); LOAD_B_1x4(k, n); KERNEL_MMA_1ACC(rb0, ra0); } #if !defined(B0) register vector float rc0; #endif vector float result[4]; SAVE_4x2_ACC(&acc0, n+0, m+0); } for (; n < n2; n += 2) { vector float result = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_2x2(k, m); LOAD_B_2x2(k, n); KERNEL_VMADD_1VSR(ra0, rb0); } #if !defined(B0) register vector float rc0; #endif SAVE_2x2_VSR(result, n, m); } for (; n < N; n++) { vector float result = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x2(k, m); LOAD_B_1x1(k, n); KERNEL_VMADD_1VSR(ra0, rb0); } #if !defined(B0) register vector float rc0; #endif SAVE_1x2_VSR(result, n, m); } } for (; m < M; m++) { for (n = 0; n < n16; n += 16) { vector float result = ((vector float){0.,0.,0.,0.}); vector float result1 = ((vector float){0.,0.,0.,0.}); vector float result2 = ((vector float){0.,0.,0.,0.}); vector float result3 = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0, rb1, rb2, rb3; for (k = 0; k < K; k++) { LOAD_A_1x1(k, m); LOAD_B_1x16(k, n); KERNEL_VMADD_4VSR(ra0, ra0, ra0, ra0, rb0, rb1, rb2, rb3); } SAVE_4x1_VSR(result, n+0, m); SAVE_4x1_VSR(result1, n+4, m); SAVE_4x1_VSR(result2, n+8, m); SAVE_4x1_VSR(result3, n+12, m); } for (; n < n8; n += 8) { vector float result = ((vector float){0.,0.,0.,0.}); vector float result1 = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0, rb1; for (k = 0; k < K; k++) { LOAD_A_1x1(k, m); LOAD_B_1x8(k, n); KERNEL_VMADD_2VSR(ra0, ra0, rb0, rb1); } SAVE_4x1_VSR(result, n+0, m); SAVE_4x1_VSR(result1, n+4, m); } for (; n < n4; n += 4) { vector float result = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x1(k, m); LOAD_B_1x4(k, n); KERNEL_VMADD_1VSR(ra0, rb0); } SAVE_4x1_VSR(result, n+0, m); } for (; n < n2; n += 2) { vector float result = ((vector float){0.,0.,0.,0.}); register vector float ra0; register vector float rb0; for (k = 0; k < K; k++) { LOAD_A_1x1(k, m); LOAD_B_1x2(k, n); KERNEL_VMADD_1VSR(ra0, rb0); } SAVE_2x1_VSR(result, n+0, m); } for (; n < N; n++) { FLOAT result = 0.0f; for (k = 0; k < K; k++) { result += A[k*lda+m] * B[k*ldb+n]; } result = result * alpha; #if !defined(B0) C[n*ldc+m] = (C[n*ldc+m] * beta) + result; #else C[n*ldc+m] = result; #endif } } if (has_packing) free (packA); return 0; }
29.798423
147
0.532935
[ "vector" ]
20e2dfeebd8efde1fe3d05f801b4495de3afce2c
5,473
c
C
thirdparty/vitasdk/taihen/src/substitute/lib/transform-dis.c
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
1
2020-09-21T01:15:45.000Z
2020-09-21T01:15:45.000Z
taiHEN/substitute/lib/transform-dis.c
cedricwaltercson/h-encore
7a60866cce31270b7e9bac78fad4a8cc39f2a854
[ "MIT" ]
null
null
null
taiHEN/substitute/lib/transform-dis.c
cedricwaltercson/h-encore
7a60866cce31270b7e9bac78fad4a8cc39f2a854
[ "MIT" ]
null
null
null
#include "substitute-internal.h" #ifdef TARGET_DIS_SUPPORTED #define DIS_MAY_MODIFY 1 #include "substitute.h" #include "dis.h" #include "transform-dis.h" #include <stdbool.h> #include <stdint.h> #define P(x) transform_dis_##x struct transform_dis_ctx { /* outputs */ int err; struct dis_ctx_base base; uint_tptr pc_trampoline; uint_tptr pc_patch_start; /* this is only tentative - it will be updated to include parts of * instructions poking out, and instructions forced to be transformed by IT */ uint_tptr pc_patch_end; /* for IT - eww */ bool force_keep_transforming; bool ban_calls; /* i.e. trying to be thread safe */ bool ban_jumps; /* allow transforming rel branches at beginning */ void **rewritten_ptr_ptr; void *write_newop_here; struct arch_dis_ctx arch; }; #define tdis_ctx struct transform_dis_ctx * /* largely similar to jump_dis */ static NOINLINE UNUSED void transform_dis_indirect_call(struct transform_dis_ctx *ctx) { /* see error description */ if (ctx->ban_calls && ctx->base.pc + ctx->base.op_size < ctx->pc_patch_end) ctx->err = SUBSTITUTE_ERR_FUNC_CALLS_AT_START; } static NOINLINE UNUSED void transform_dis_ret(struct transform_dis_ctx *ctx) { /* ret is okay if it's at the end of the required patch (past the original * patch size is good too) */ if (ctx->base.pc + ctx->base.op_size < ctx->pc_patch_end) ctx->err = SUBSTITUTE_ERR_FUNC_TOO_SHORT; } static UNUSED void transform_dis_unidentified(UNUSED struct transform_dis_ctx *ctx) { #ifdef TRANSFORM_DIS_VERBOSE printf("transform_dis (0x%llx): unidentified\n", (unsigned long long) ctx->base.pc); #endif /* this isn't exhaustive, so unidentified is fine */ } static NOINLINE UNUSED void transform_dis_bad(struct transform_dis_ctx *ctx) { ctx->err = SUBSTITUTE_ERR_FUNC_BAD_INSN_AT_START; } static INLINE UNUSED void transform_dis_thumb_it(UNUSED struct transform_dis_ctx *ctx) { /* ignore, since it was turned into B */ } static void transform_dis_branch_top(struct transform_dis_ctx *ctx, uintptr_t dpc, int cc) { if (dpc >= ctx->pc_patch_start && dpc < ctx->pc_patch_end) { /* don't support this for now */ ctx->err = SUBSTITUTE_ERR_FUNC_BAD_INSN_AT_START; return; } if (cc & CC_CALL) { transform_dis_indirect_call(ctx); } else if (ctx->ban_jumps) { transform_dis_ret(ctx); } } static void transform_dis_dis(struct transform_dis_ctx *ctx); static void transform_dis_pre_dis(struct transform_dis_ctx *ctx); static void transform_dis_post_dis(struct transform_dis_ctx *ctx); int transform_dis_main(const void *restrict code_ptr, void **restrict rewritten_ptr_ptr, uint_tptr pc_patch_start, uint_tptr *pc_patch_end_p, uint_tptr pc_trampoline, struct arch_dis_ctx *arch_ctx_p, int *offset_by_pcdiff, int options) { struct transform_dis_ctx ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pc_patch_start = pc_patch_start; ctx.pc_patch_end = *pc_patch_end_p; ctx.base.pc = pc_patch_start; ctx.arch = *arch_ctx_p; ctx.ban_calls = options & TRANSFORM_DIS_BAN_CALLS; ctx.ban_jumps = options & TRANSFORM_DIS_REL_JUMPS; /* data is written to rewritten both by this function directly and, in case * additional scaffolding is needed, by arch-specific transform_dis_* */ ctx.rewritten_ptr_ptr = rewritten_ptr_ptr; void *rewritten_start = *rewritten_ptr_ptr; int written_pcdiff = 0; offset_by_pcdiff[written_pcdiff++] = 0; while (ctx.base.pc < ctx.pc_patch_end && !ctx.force_keep_transforming) { ctx.base.modify = false; ctx.err = 0; ctx.base.ptr = code_ptr + (ctx.base.pc - pc_patch_start); ctx.pc_trampoline = pc_trampoline + (*rewritten_ptr_ptr - rewritten_start); const void *start = ctx.base.ptr; transform_dis_pre_dis(&ctx); void *rewritten_ptr = *rewritten_ptr_ptr; ctx.write_newop_here = rewritten_ptr; transform_dis_dis(&ctx); #ifdef TRANSFORM_DIS_VERBOSE printf("transform_dis (0x%llx): >> op_size=%d newop_size=%d\n", (unsigned long long) ctx.base.pc, ctx.base.op_size, ctx.base.newop_size); #endif if (ctx.err) return ctx.err; if (ctx.write_newop_here != NULL) { if (ctx.base.modify) memcpy(ctx.write_newop_here, ctx.base.newop, ctx.base.newop_size); else memcpy(ctx.write_newop_here, start, ctx.base.op_size); if (*rewritten_ptr_ptr == rewritten_ptr) *rewritten_ptr_ptr += ctx.base.op_size; } ctx.base.pc += ctx.base.op_size; transform_dis_post_dis(&ctx); int pcdiff = ctx.base.pc - ctx.pc_patch_start; while (written_pcdiff < pcdiff) offset_by_pcdiff[written_pcdiff++] = -1; offset_by_pcdiff[written_pcdiff++] = (int) (*rewritten_ptr_ptr - rewritten_start); } *pc_patch_end_p = ctx.base.pc; *arch_ctx_p = ctx.arch; return SUBSTITUTE_OK; } #include stringify(TARGET_DIR/arch-transform-dis.inc.h) #include stringify(TARGET_DIR/dis-main.inc.h) #endif /* TARGET_DIS_SUPPORTED */
33.371951
82
0.661246
[ "transform" ]
20e77b1239f53b0de8e8142dc645dbe6473195a5
2,033
h
C
mafsa/tarray.h
selavy/studies
e17b91ffab193e46fec00cf2b8070dbf1f2c39e3
[ "MIT" ]
null
null
null
mafsa/tarray.h
selavy/studies
e17b91ffab193e46fec00cf2b8070dbf1f2c39e3
[ "MIT" ]
null
null
null
mafsa/tarray.h
selavy/studies
e17b91ffab193e46fec00cf2b8070dbf1f2c39e3
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <cstddef> #include <string> #include <vector> #include <optional> #include <iosfwd> struct Tarray { using u32 = uint32_t; static constexpr int MIN_CHILD_OFFSET = 1; static constexpr int MAX_CHILD_OFFSET = 27; static constexpr int MAX_BASE = (1u << 30) - MAX_CHILD_OFFSET; // exclusive static constexpr int NO_BASE = static_cast<int>(MAX_BASE); static constexpr u32 UNSET_BASE = 0; static constexpr int UNSET_CHECK = MAX_BASE; static constexpr int UNSET_NEXT = 0; static constexpr u32 TERM_MASK = 0x1u; struct Xtn { int check; int next; constexpr explicit Xtn(int c=UNSET_CHECK, int n=UNSET_NEXT) noexcept : check(c), next(n) {} }; std::vector<u32> bases; std::vector<Xtn> xtns; bool isword(const char* const word) const noexcept; bool isword(const std::string& word) const noexcept { return isword(word.c_str()); } // TODO(peter): maybe move this to a "serializers.h"? static std::optional<Tarray> deserialize(const std::string& filename); template <class BItr, class CItr, class NItr> static Tarray make( BItr bases_begin, BItr bases_end, CItr checks_begin, CItr checks_end, NItr nexts_begin, NItr nexts_end ) { Tarray tarray; tarray.bases.assign(bases_begin, bases_end); std::size_t n = std::distance(checks_begin, checks_end); tarray.xtns.insert(tarray.xtns.end(), n, Xtn{}); auto citr = checks_begin; auto nitr = nexts_begin; for (std::size_t i = 0; i < n; ++i) { tarray.xtns[i].check = *citr++; tarray.xtns[i].next = *nitr++; } return tarray; } void dump_stats(std::ostream& os) const; private: friend struct Mafsa; int base(int s) const noexcept; Xtn xtn(int s) const noexcept; int term(int s) const noexcept; void setbase(std::size_t s, int base, bool term) noexcept; };
29.463768
99
0.62912
[ "vector" ]
20ef2d3ee86b59b5310d67c458efb434daa99a0a
5,065
h
C
Code/Editor/IEditorPanelUtils.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Editor/IEditorPanelUtils.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Editor/IEditorPanelUtils.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT */ #ifndef CRYINCLUDE_CRYEDITOR_IPANELEDITORUTILS_H #define CRYINCLUDE_CRYEDITOR_IPANELEDITORUTILS_H #pragma once #include "Cry_Vector3.h" #include "DisplaySettings.h" #include "Include/IDisplayViewport.h" #include "Include/IIconManager.h" #include <qstringlist.h> #include <qkeysequence.h> #include <qevent.h> #include <QShortcutEvent> class CBaseObject; class CViewport; class IQToolTip; struct HotKey { HotKey() : path("") , sequence(QKeySequence()) { } void CopyFrom(const HotKey& other) { path = other.path; sequence = other.sequence; } void SetPath(const char* _path) { path = QString(_path); } void SetSequenceFromString(const char* _sequence) { sequence = QKeySequence::fromString(_sequence); } void SetSequence(const QKeySequence& other) { sequence = other; } bool IsMatch(QString _path) { return path.compare(_path, Qt::CaseInsensitive) == 0; } bool IsMatch(QKeySequence _sequence) { return sequence.matches(_sequence); } bool operator < (const HotKey& other) const { //split the paths into lists compare per level QStringList m_categories = path.split('.'); QStringList o_categories = other.path.split('.'); int m_catSize = m_categories.size(); int o_catSize = o_categories.size(); int size = (m_catSize < o_catSize) ? m_catSize : o_catSize; //sort categories to keep them together for (unsigned int i = 0; i < size; i++) { if (m_categories[i] < o_categories[i]) { return true; } if (m_categories[i] > o_categories[i]) { return false; } } //if comparing a category and a item in that category the category is < item return m_catSize > o_catSize; } QKeySequence sequence; QString path; }; struct IEditorPanelUtils { virtual ~IEditorPanelUtils() {} virtual void SetViewportDragOperation(void(*)(CViewport* viewport, int dragPointX, int dragPointY, void* custom), void* custom) = 0; //PREVIEW WINDOW UTILS//////////////////////////////////////////////////// virtual int PreviewWindow_GetDisplaySettingsDebugFlags(CDisplaySettings* settings) = 0; virtual void PreviewWindow_SetDisplaySettingsDebugFlags(CDisplaySettings* settings, int flags) = 0; //HOTKEY UTILS//////////////////////////////////////////////////////////// virtual bool HotKey_Import() = 0; virtual void HotKey_Export() = 0; virtual QKeySequence HotKey_GetShortcut(const char* path) = 0; virtual bool HotKey_IsPressed(const QKeyEvent* event, const char* path) = 0; virtual bool HotKey_IsPressed(const QShortcutEvent* event, const char* path) = 0; virtual bool HotKey_LoadExisting() = 0; virtual void HotKey_SaveCurrent() = 0; virtual void HotKey_BuildDefaults() = 0; virtual void HotKey_SetKeys(QVector<HotKey> keys) = 0; virtual QVector<HotKey> HotKey_GetKeys() = 0; virtual QString HotKey_GetPressedHotkey(const QKeyEvent* event) = 0; virtual QString HotKey_GetPressedHotkey(const QShortcutEvent* event) = 0; virtual void HotKey_SetEnabled(bool val) = 0; virtual bool HotKey_IsEnabled() const = 0; //TOOLTIP UTILS/////////////////////////////////////////////////////////// //! Loads a table of tooltip configuration data from an xml file. virtual void ToolTip_LoadConfigXML(QString filepath) = 0; //! Initializes a QToolTipWidget from loaded configuration data (see ToolTip_LoadConfigXML()) //! \param tooltip Will be initialized using loaded configuration data //! \param path Variable serialization path. Will be used as the key for looking up data in the configuration table. (ex: "Rotation.Rotation_Rate_X") //! \param option Name of a sub-option of the variable specified by "path". (ex: "Emitter_Strength" will look up the tooltip data for "Rotation.Rotation_Rate_X.Emitter_Strength") //! \param optionalData The argument to be used with "special_content" feature. See ToolTip_GetSpecialContentType() and QToolTipWidget::AddSpecialContent(). //! \param isEnabled If false, the tooltip will indicate the reason why the widget is disabled. virtual void ToolTip_BuildFromConfig(IQToolTip* tooltip, QString path, QString option, QString optionalData = "", bool isEnabled = true) = 0; virtual QString ToolTip_GetTitle(QString path, QString option = "") = 0; virtual QString ToolTip_GetContent(QString path, QString option = "") = 0; virtual QString ToolTip_GetSpecialContentType(QString path, QString option = "") = 0; virtual QString ToolTip_GetDisabledContent(QString path, QString option = "") = 0; }; #endif
38.664122
189
0.662389
[ "3d" ]
1f00fbfebb48518fb8a949278015591d594570e9
1,828
h
C
CppP4rhSln/18/CachedObj.h
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
1
2017-04-01T06:57:30.000Z
2017-04-01T06:57:30.000Z
gnu_files/18/CachedObj.h
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
gnu_files/18/CachedObj.h
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
/* * This file contains code from "C++ Primer, Fourth Edition", by Stanley B. * Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Contracts Department * 75 Arlington Street, Suite 300 * Boston, MA 02216 * Fax: (617) 848-7047 */ #ifndef CACHED_OBJ_H #define CACHED_OBJ_H #include <cstddef> template <class T> class CachedObj { public: void *operator new(std::size_t); void operator delete(void *, std::size_t); virtual ~CachedObj() { } void operator delete[](void *, std::size_t); void *operator new[](std::size_t); protected: T *next; private: static void add_to_freelist(T*); static std::allocator<T> alloc_mem; static T *freeStore; static const std::size_t chunk; }; #include "CachedObj.cc" // inclusion compilation model #endif
34.490566
79
0.724289
[ "model" ]
1f17a5f1698c48dcafca6a438b935401a96b8889
91,423
c
C
src/Utility/ACE/elio/elio.c
rustychris/schism
3754530ef57b3a058906432b4a9fca4a670f395e
[ "Apache-2.0" ]
42
2019-08-12T21:48:24.000Z
2022-03-03T03:08:10.000Z
src/Utility/ACE/elio/elio.c
rustychris/schism
3754530ef57b3a058906432b4a9fca4a670f395e
[ "Apache-2.0" ]
42
2019-08-19T21:57:12.000Z
2022-03-03T17:42:01.000Z
src/Utility/ACE/elio/elio.c
rustychris/schism
3754530ef57b3a058906432b4a9fca4a670f395e
[ "Apache-2.0" ]
51
2019-08-09T20:59:07.000Z
2022-03-29T15:48:43.000Z
/*! $Id: elio.c,v 1.60 2012/02/07 19:19:01 pturner Exp $ * * I/O routines for new file format - pturner 11-2002 * */ /*! \mainpage ELIO - Interface to ELCIRC data files. ** ** \section intro Introduction ** ** The ELIO library provides a C-programming language interface to output files generated by ELCIRC. The CVS repository is 'ace/elio' - use: <pre> cvs checkout ace/elio </pre> to get the elio source code as well as the sources for other utilities using the elio library. These codes are documented at the URL: <pre> <a href="http://amb1019.ccalmr.ogi.edu/doc/codes">http://amb1019.ccalmr.ogi.edu/doc/codes</a> </pre> ** ** \section use Building your programs. ** ** Makefile <pre> # # Sample Makefile for use of libelio.a. # # \$Revision\$ # \$Log\$ # # INSTALLDIR = /usr/local/ace OBJS = testel.o # -miee for alphas # CFLAGS = -mieee # for intel CFLAGS = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 LIB = /usr/local/ace/lib CC = gcc -g testel: testel.o \$(CC) \$(CFLAGS) -g testel.c -L\$(LIB) -lelio -lm -o testel </pre> ** ** \section examp Example of use. ** ** The following code reads the header from a data file and prints out a ** summary of what is seen using the ElioPrintHeader() function. ** <pre> // ginfo.c example program - pturner. // // \$Revision\$ // // \$Log\$ // \#include <stdio.h> \#include <stdlib.h> \#include <math.h> \#include "elio.h" int main(int argc, char **argv) { char iname[1024]; FILE *fp; ElcircHeader h; int err; if (argc != 2) { fprintf(stderr, "Usage: \%s <ELCIRC *.6? file>\\n", argv[0]); exit(1); } strcpy(iname, argv[1]); // check that file type is correct if ((fp = fopen(iname, "rb")) == NULL) { fprintf(stderr, "\%s: Unable to open file \%s.\\n", argv[0], iname); exit(1); } if (ElioGetFileType(fp) < 2) { fprintf(stderr, "\%s: Incorrect file type for file \%s.\\n", argv[0], iname); exit(1); } fclose(fp); // Get the header if ((err = ElioGetHeader(iname, &h)) != ELIO_OK) { fprintf(stderr, "\%s: Error in call to GetElcircHeader(), error # \%d.\\n", argv[0], err); exit(1); } ElioPrintHeader(&h); printf("Number of steps in file: \%d\\n", ElioGetNStepsInFile(iname, &h)); ElioFreeHeader(&h); } </pre> Makefile for ginfo.c <pre> # # Sample Makefile for use of libelio.a. # # \$Revision\$ # \$Log\$ # # -miee for alphas # CFLAGS = -mieee # for intel CFLAGS = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 LIB = /usr/local/ace/lib CC = gcc -g ginfo: ginfo.o \$(CC) \$(CFLAGS) -g ginfo.c -L\$(LIB) -lelio -lm -o ginfo </pre> ** **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include <time.h> #include "elio.h" /*! * @def WIN32 * * Windows differences, if true, fix things up for cygwin and Visual C++. * */ #ifdef WIN32 #include <string.h> #define off_t long #define fseeko fseek #define ftello ftell #endif /*! * Error codes, line numbers, not used right now. */ int ElioErr = 0; int ElioSysErr = 0; int ElioLineErr = 0; /*! * Free memory allocated by a previous call to ElioGetHeader() * Calling this on an unallocated Header will likely result * in a seg fault. */ void ElioFreeHeader(ElcircHeader * h) { free(h->zcor); free(h->x); free(h->y); free(h->d); free(h->etype); free(h->icon[0]); free(h->icon[1]); free(h->icon[2]); if (h->v == 3) { free(h->icon[3]); } if (h->v != 4) { free(h->bi); free(h->bisave); } free(h->no); } /*! * Free a previously allocated time step. */ void ElioFreeTimeStep(ElcircTimeStep * t) { if (t->e != NULL) { free(t->e); } if (t->surfind != NULL) { free(t->surfind); } free(t->d); } /*! * Allocate memory for a time step given information in a valid * ElcircHeader. * * Returns ELIO_ERR on failure after cleaning up any current allocations. * Returns ELIO_OK on success. */ int ElioAllocateTimeStep(ElcircHeader * h, ElcircTimeStep * t) { switch (h->v) { case 2: case 3: t->surfind = (int *) malloc(h->np * sizeof(int)); t->d = (float *) malloc(h->nitems * sizeof(float)); t->e = (float *) NULL; if (t->surfind == NULL || t->d == NULL) { return ELIO_ERR; } break; case 4: case 5: t->surfind = (int *) malloc(h->np * sizeof(int)); t->e = (float *) malloc(h->np * sizeof(float)); t->d = (float *) malloc(h->nitems * sizeof(float)); if (t->e == NULL || t->d == NULL) { return ELIO_ERR; } break; } return ELIO_OK; } /*! * Print header information from a valid ElcircHeader struct. * * \param h = Previously filled in ElcircHeader. * */ void ElioPrintHeader(ElcircHeader * h) { int i; printf("Magic: %s\n", h->magic); printf("Version: %s\n", h->version); printf("Start Time: %s\n", h->start_time); printf("Variable Name: %s\n", h->variable_nm); printf("Variable Dim: %s\n", h->variable_dim); printf("Number of Steps: %d\n", h->nsteps); printf("Time Step: %f\n", h->timestep); printf("Skip Steps: %d\n", h->skip); printf("Variable Type: %d\n", h->ivs); printf("Variable Dimension: %d\n", h->i23d); switch (h->v) { case 2: case 3: printf("Data is Z Level\n"); printf("Vertical position: %f\n", h->vpos); printf("Z of MSL: %f\n", h->zmsl); printf("Number of Vertical Levels: %d\n", h->nvrt); printf("Levels:\n"); for (i = 0; i < h->nvrt; i++) { printf(" %02d: %f\n", i, h->zcor[i]); } break; case 4: printf("Data is Sigma Level\n"); printf("ivcor: %d\n", h->ivcor); printf("h0: %f\n", h->h0); printf("hc: %f\n", h->hc); printf("Theta b: %f\n", h->thetab); printf("Theta f: %f\n", h->thetaf); printf("Number of Sigma Levels: %d\n", h->nvrt); printf("Levels:\n"); for (i = 0; i < h->nvrt; i++) { printf(" %02d: %f\n", i, h->zcor[i]); } break; case 5: printf("Data is Sigma+Z\n"); printf("Total number of Levels: %d\n", h->nvrt); printf("Sigma levels ks: %d\n", h->ks); printf("Z levels kz: %d\n", h->kz); printf("h0: %f\n", h->h0); printf("hs: %f\n", h->hs); printf("hc: %f\n", h->hc); printf("Theta b: %f\n", h->thetab); printf("Theta f: %f\n", h->thetaf); printf("Levels:\n"); for (i = 0; i < h->nvrt; i++) { printf(" %02d: %f\n", i, h->zcor[i]); } break; default: printf("Vertical position: %f\n", h->vpos); printf("Z of MSL: %f\n", h->zmsl); printf("Number of Vertical Levels: %d\n", h->nvrt); printf("Levels:\n"); for (i = 0; i < h->nvrt; i++) { printf(" %02d: %f\n", i, h->zcor[i]); } break; } printf("Number of Floats/Step: %d\n", h->nitems); printf("Header Size (bytes): %d\n", h->hsize); printf("Time Step Size (bytes): %d\n", h->ssize); printf("Number of Nodes: %d\n", h->np); printf("Number of Elements: %d\n", h->ne); printf("Internal version number: %d\n", h->v); printf("First Node: 1 -> %f, %f, %f\n", h->x[0], h->y[0], h->d[0]); printf("First Element: 1 -> %d, %d, %d\n", h->icon[0][0], h->icon[1][0], h->icon[2][0]); printf("Last Node: %d -> %f, %f, %f\n", h->np, h->x[h->np - 1], h->y[h->np - 1], h->d[h->np - 1]); printf("Last Element: %d -> %d, %d, %d\n", h->ne, h->icon[0][h->ne - 1], h->icon[1][h->ne - 1], h->icon[2][h->ne - 1]); } /*! * ElioGetTimeStep: Read data for a single time step. * * Input variables: * * \param fp = Open file handle. * \param step = Time step to read starting from 0 to nsteps - 1. * \param h = Valid ElcircHeader struct. * * Output Variables: * * \param t = Valid ElcircTimeStep. * * On success returns ELIO_OK. * * On failure, returns ELIO_FSEEK_ERR or ELIO_FREAD_ERR depending * on the nature of the error. */ int ElioGetTimeStep(FILE * fp, int step, ElcircHeader * h, ElcircTimeStep * t) { off_t skip; int i, n; short *b; skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { return ELIO_FSEEK_ERR; } if (fread(&t->t, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&t->it, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (h->v == 4 || h->v == 5) { if (fread(t->e, sizeof(float), h->np, fp) != h->np) return ELIO_FREAD_ERR; for (i = 0; i < h->np; i++) { t->surfind[i] = h->nvrt; } } else { if (fread(t->surfind, sizeof(int), h->np, fp) != h->np) return ELIO_FREAD_ERR; t->e = (float *) NULL; } if ((n = fread(t->d, sizeof(float), h->nitems, fp)) != h->nitems) { return ELIO_FREAD_ERR; } /* printf("Completed Read of Time Step (%d): Time, Step = %f, %d\n", step, t->t, t->it); */ return ELIO_OK; } /*! * Returns the Z positions of the vertical given the elevation, e. Also * the bottom and surface indexes in i1 and i2. Array Zpos1 is returned * with the valid z values. Only values from zpos1[i1] through zpos[i2] * contain valid data. */ int ElioGetZPos(ElcircHeader * h, double d, double e, int *i1, int *i2, double *zpos1) { int i, ilev1 = 0, ilev2 = 0; for (i = 0; i < h->nvrt; i++) { zpos1[i] = -h->zmsl + h->zcor[i]; } ilev1 = 0; while (-d >= zpos1[ilev1] && ilev1 < h->nvrt) { ilev1++; } zpos1[ilev1] = (-d); ilev2 = h->nvrt - 1; while (e <= zpos1[ilev2] && ilev2 > 0) { ilev2--; } ilev2++; zpos1[ilev2] = e; *i1 = ilev1; *i2 = ilev2; return ELIO_OK; } /*! * Return the surface index for a node. * * Input variables: * * \param fp = Open file handle * \param node = node number starting from 0. * \param step = Time step index starting from 0. * \param h = Valid ElcircHeader struct. */ int ElioGetNodeSurfaceIndex(FILE * fp, int node, int step, ElcircHeader * h) { off_t skip; int retval = -1; int ti; if (node >= h->np || node < 0) { return retval; } skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize + (off_t) 8 + (off_t) (node * 4); if (fseeko(fp, skip, SEEK_SET)) { return ELIO_FSEEK_ERR; } if (fread(&ti, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } return ti; } /*! * Return data for a single node from one time step. * * Input variables: * * \param fp = Open file handle. * \param step = Time step to read starting from 0. * \param node = Node to read starting from 0. * \param h = Valid ElcircHeader struct. * * Output Variables: * * \param t = Pointer to the time for this time step, float. * \param it = Pointer to the current computational time step, integer. * \param bind = Pointer to the bottom index starting from 0. * \param sind = Pointer to the surface index starting from 0. * \param d = Pointer to an array of float values, with valid data from * d[bind] through d[sind]. * * Returns ELIO_OK on success. * Returns ELIO_FSEEK_ERR or ELIO_FREAD_ERR on error. * */ int ElioGetNode(FILE * fp, int step, int node, ElcircHeader * h, float *t, int *it, int *bind, int *sind, float *d) { int i, npts, itmp; float e; off_t skip; *bind = h->bi[node]; if (h->i23d == 3) { /* 3d data */ skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { /* Read time, it, and sind */ return ELIO_FSEEK_ERR; } if (fread(t, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (fread(it, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (h->v == 4) { itmp = h->nvrt; *bind = 0; if (fseeko(fp, node * 4L, SEEK_CUR)) { /* elevation */ return ELIO_FSEEK_ERR; } if (fread(&e, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } } else if (h->v == 5) { itmp = h->nvrt; if (fseeko(fp, node * 4L, SEEK_CUR)) { /* elevation */ return ELIO_FSEEK_ERR; } if (fread(&e, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } } else { if (fseeko(fp, node * 4L, SEEK_CUR)) { /* sind */ return ELIO_FSEEK_ERR; } if (fread(&itmp, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } } *sind = itmp - 1; npts = (h->nvrt - h->bi[node]) * h->ivs; /* number of points to read for this node */ if (fseeko(fp, skip + (off_t) ((2 + h->np + h->no[node]) * 4), SEEK_SET)) { /* skip time, it, and the surf indexes */ return ELIO_FSEEK_ERR; } if (fread(d, sizeof(float), npts, fp) != npts) { return ELIO_FREAD_ERR; } } else if (h->i23d == 2) { /* 2d data - just one or 2 values to read */ skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { /* Read time, it, and sind */ return ELIO_FSEEK_ERR; } if (fread(t, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (fread(it, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (h->v == 4) { itmp = h->nvrt; *bind = 0; if (fseeko(fp, node * 4L, SEEK_CUR)) { /* elevation */ return ELIO_FSEEK_ERR; } if (fread(&e, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } } else if (h->v == 5) { itmp = h->nvrt; if (fseeko(fp, node * 4L, SEEK_CUR)) { /* elevation */ return ELIO_FSEEK_ERR; } if (fread(&e, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } } else { if (fseeko(fp, node * 4L, SEEK_CUR)) { /* Read time, it, and sind */ return ELIO_FSEEK_ERR; } if (fread(&itmp, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } } *sind = itmp - 1; npts = h->ivs; /* number of points to read for this node */ if (fseeko(fp, skip + (off_t) (2L + h->np) * 4L + (off_t) (npts * node * 4L), SEEK_SET)) { /* skip time, it, and the surf indexes */ return ELIO_FSEEK_ERR; } if (fread(d, sizeof(float), npts, fp) != npts) { return ELIO_FREAD_ERR; } } else { return ELIO_ERR; } return ELIO_OK; } /*! * Extract data for a single node from one previously time step. * Works for 2d and 3d data, vector and scalar. * * Input variables: * * \param t = Pointer to previously read time step. * \param h = Pointer to valid ElcircHeader struct. * \param node = Node number starting from 0. * \param bind = Bottom index starting from 0. * \param sind = Surface index starting from 0. * * Output Variables: * * \param d = Pointer to array extracted from timestep struct. * * Returns ELIO_OK on success. * */ int ElioExtractNode(ElcircTimeStep * t, ElcircHeader * h, int node, int bind, int sind, float *d) { int i; if (h->i23d == 2) { if (h->ivs == 2) { d[0] = t->d[h->no[node]]; d[1] = t->d[h->no[node] + 1]; } else { d[0] = t->d[h->no[node]]; } } else { for (i = bind; i <= sind; i++) { if (h->ivs == 2) { d[2 * i] = t->d[h->no[node] + 2 * i - 2 * bind]; d[2 * i + 1] = t->d[h->no[node] + 2 * i + 1 - 2 * bind]; } else { d[i] = t->d[h->no[node] + i - bind]; } } } return ELIO_OK; } /*! * Get data for a single node from one time step - fills in missing data * values to match the old format. * * Input variables: * * \param fp = Pointer to open file handle. * \param step = Time step starting from 0. * \param node = Node number starting from 0. * \param h = Pointer to valid ElcircHeader struct. * * Output Variables: * * \param t = Pointer to time, float. * \param it = Pointer to computational time step, integer. * \param d = Pointer to array of return values, h.nvrt long. * * Returns ELIO_OK on success. * Returns ELIO_FSEEK_ERR and ELIO_FREAD_ERR on error. */ int ElioGetNodeOld(FILE * fp, int step, int node, ElcircHeader * h, float *t, int *it, float *d) { int i, npts, bind, sind, rval = 0; off_t skip; float *tmp; tmp = (float *) malloc(h->nvrt * h->ivs * sizeof(float)); bind = h->bi[node]; if (h->i23d == 3) { /* 3d data */ skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { /* Read time, it, and sind */ rval = ELIO_FSEEK_ERR; goto out; } if (fread(t, sizeof(float), 1, fp) != 1) { rval = ELIO_FREAD_ERR; goto out; } if (fread(it, sizeof(int), 1, fp) != 1) { rval = ELIO_FREAD_ERR; goto out; } if (fseeko(fp, (off_t) (node * 4L), SEEK_CUR)) { rval = ELIO_FSEEK_ERR; goto out; } /* sind */ if (fread(&sind, sizeof(int), 1, fp) != 1) { rval = ELIO_FREAD_ERR; goto out; } npts = (h->nvrt - h->bi[node]) * h->ivs; /* number of points to read for this node */ if (fseeko(fp, skip + (off_t) ((2 + h->np + h->no[node]) * 4), SEEK_SET)) { /* skip time, it, and the surf indexes */ rval = ELIO_FSEEK_ERR; goto out; } if (fread(tmp, sizeof(float), npts, fp) != npts) { rval = ELIO_FREAD_ERR; goto out; } } else if (h->i23d == 2) { /* 2d data - just one or 2 values to read */ skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { /* Read time, it, and sind */ rval = ELIO_FSEEK_ERR; goto out; } if (fread(&t, sizeof(float), 1, fp) != 1) { rval = ELIO_FREAD_ERR; goto out; } if (fread(&it, sizeof(int), 1, fp) != 1) { rval = ELIO_FREAD_ERR; goto out; } if (fseeko(fp, (off_t) (node * 4L), SEEK_CUR)) { /* Read time, it, and sind */ rval = ELIO_FSEEK_ERR; goto out; } if (fread(&sind, sizeof(int), 1, fp) != 1) { rval = ELIO_FREAD_ERR; goto out; } npts = h->ivs; /* number of points to read for this node */ if (fseeko(fp, skip + (off_t) ((2 + h->np) * 4), SEEK_SET)) { /* skip time, it, and the surf indexes */ rval = ELIO_FSEEK_ERR; goto out; } if (fread(tmp, sizeof(float), npts, fp) != npts) { rval = ELIO_FREAD_ERR; goto out; } } else { rval = 9; goto out; } for (i = 0; i < (sind - bind) * h->ivs; i++) { d[i + bind * h->ivs] = tmp[i]; } out:; free(tmp); return rval; } /*! * Get data for a single node from one time step should work for both * sigma and z-level grids. * * Input variables: * * \param fp = Pointer to open file handle. * \param step = Time step starting from 0. * \param elem = Element number. * \param h = Pointer to valid ElcircHeader struct. * \param hh = Pointer to shape function coefficients. * * Output Variables: * * \param t = Pointer to time, float. * \param it = Pointer to computational time step, integer. * \param bind = Pointer to bottom index, integer. * \param sind = Pointer to surface index, integer. * \param d = Pointer to array of return values, h.nvrt long. * * Returns ELIO_OK on success. * Returns ELIO_FSEEK_ERR and ELIO_FREAD_ERR on error. */ int ElioGetXYData2(FILE * fp, int step, int elem, ElcircHeader * h, double *hh, float *t, int *it, int *bind, int *sind, float *d) { int i, j, nn[4], tcnt, cnt[4]; double uret, vret; double *u[4], *v[4], dd[4], vv[4]; float dtmp[4][400]; float dt[400]; /* get the nodes for the element */ for (i = 0; i < h->nvrt * h->ivs; i++) { dt[i] = d[i] = 0.0; } for (i = 0; i < h->etype[elem]; i++) { nn[i] = h->icon[i][elem]; ElioGetNode(fp, step, nn[i], h, t, it, &bind[i], &sind[i], dt); //printf("Node %d element %d %d %d\n", nn[i], elem, bind[i], sind[i]); for (j = 0; j < h->nvrt; j++) { if (h->ivs == 2) { // printf("%d %f %f\n", i, dt[2 * j], dt[2 * j + 1]); if (bind[i] <= j && sind[i] >= j) { dtmp[i][2 * j] = dt[2 * (j - bind[i])]; dtmp[i][2 * j + 1] = dt[2 * (j - bind[i]) + 1]; } else { dtmp[i][2 * j] = 0.0; dtmp[i][2 * j + 1] = 0.0; } } else if (h->ivs == 1) { //printf("ElioGetXYData2 = %d, %d: %f\n", i, j, dt[j]); if (bind[i] <= j && sind[i] >= j) { dtmp[i][j] = dt[j - bind[i]]; } else { dtmp[i][j] = 0.0; } } } } for (j = 0; j < h->nvrt; j++) { uret = -99.0; vret = 0.0; tcnt = 0; for (i = 0; i < h->etype[elem]; i++) { cnt[i] = 0; if (h->ivs == 2) { if (bind[i] <= j && sind[i] >= j) { dd[i] = dtmp[i][2 * j]; vv[i] = dtmp[i][2 * j + 1]; cnt[i]++; tcnt++; } else { dd[i] = 0.0; vv[i] = 0.0; } } else if (h->ivs == 1) { if (bind[i] <= j && sind[i] >= j) { dd[i] = dtmp[i][j]; cnt[i]++; tcnt++; } else { dd[i] = 0.0; } } } if (h->ivs == 2) { if (tcnt && tcnt != h->etype[elem]) { uret = 0.0; vret = 0.0; for (i = 0; i < h->etype[elem]; i++) { uret = uret + cnt[i] * dd[i]; vret = vret + cnt[i] * vv[i]; } uret = uret / tcnt; vret = vret / tcnt; } else if (tcnt == h->etype[elem]) { ElioEval(h->etype[elem], hh, dd, &uret); ElioEval(h->etype[elem], hh, vv, &vret); } d[2 * j] = uret; d[2 * j + 1] = vret; } else if (h->ivs == 1) { if (tcnt && tcnt != h->etype[elem]) { uret = 0.0; for (i = 0; i < h->etype[elem]; i++) { uret = uret + cnt[i] * dd[i]; } uret = uret / tcnt; } else if (tcnt == h->etype[elem]) { ElioEval(h->etype[elem], hh, dd, &uret); } d[j] = uret; } } return ELIO_OK; } /*! * Get data for a single node from one time step for sigma grids * * Input variables: * * \param h = Pointer to valid ElcircHeader struct. * \param elem = Element number. * \param x = x of location to interpolate to. * \param y = y of location to interpolate to. * \param hh = Pointer to shape function coefficients. * \param t = Pointer to valid ElcircTimeStep struct. * * Output Variables: * * \param d = Pointer to array of return values, h.nvrt long. * * Returns ELIO_OK on success. * Returns ELIO_FSEEK_ERR and ELIO_FREAD_ERR on error. */ int ElioInterpTimeStepSigma(ElcircHeader * h, int elem, double x, double y, double *hh, ElcircTimeStep * t, float *d) { int i, j, nn[4], tcnt, cnt[4]; double uret, vret; double *u[4], *v[4], dd[4], vv[4]; float dtmp[4][400]; float dt[400]; /* get the nodes for the element */ for (i = 0; i < h->nvrt * h->ivs; i++) { dt[i] = d[i] = 0.0; } for (i = 0; i < h->etype[elem]; i++) { nn[i] = h->icon[i][elem]; ElioExtractNode(t, h, nn[i], 0, h->nvrt - 1, dt); for (j = 0; j < h->nvrt; j++) { //printf("%d, %d: %f\n", i, j, dt[j]); if (h->ivs == 2) { dtmp[i][2 * j] = dt[2 * j]; dtmp[i][2 * j + 1] = dt[2 * j + 1]; } else if (h->ivs == 1) { dtmp[i][j] = dt[j]; } } } for (j = 0; j < h->nvrt; j++) { for (i = 0; i < h->etype[elem]; i++) { if (h->ivs == 2) { dd[i] = dtmp[i][2 * j]; vv[i] = dtmp[i][2 * j + 1]; } else if (h->ivs == 1) { dd[i] = dtmp[i][j]; } } if (h->ivs == 2) { ElioEval(h->etype[elem], hh, dd, &uret); ElioEval(h->etype[elem], hh, vv, &vret); d[2 * j] = uret; d[2 * j + 1] = vret; } else { ElioEval(h->etype[elem], hh, dd, &uret); d[j] = uret; } //printf("uret = %d, %d: %f\n", i, j, d[j]); } return ELIO_OK; } int ElioInterpTimeStep(ElcircHeader * h, int elem, double x, double y, double *hh, ElcircTimeStep * t, int *bind, int *sind, float *d) { int i, j, nn[4], tcnt, cnt[4]; double uret, vret; double *u[4], *v[4], dd[4], vv[4]; float dtmp[4][400]; float dt[400]; /* get the nodes for the element */ for (i = 0; i < h->nvrt * h->ivs; i++) { dt[i] = d[i] = 0.0; } for (i = 0; i < h->etype[elem]; i++) { nn[i] = h->icon[i][elem]; bind[i] = h->bi[nn[i]]; sind[i] = t->surfind[nn[i]] - 1; ElioExtractNode(t, h, nn[i], bind[i], sind[i], dt); for (j = 0; j < h->nvrt; j++) { if (h->ivs == 2) { if (bind[i] <= j && sind[i] >= j) { dtmp[i][2 * j] = dt[2 * j]; dtmp[i][2 * j + 1] = dt[2 * j + 1]; //printf("values = %d, %d: %f %f\n", i, j, dt[2 * j], dt[2 * j + 1]); } else { dtmp[i][2 * j] = 0.0; dtmp[i][2 * j + 1] = 0.0; } } else if (h->ivs == 1) { //if (h->nvrt == 1) printf("InterpTimeStep = %d, %d: %f %d %d\n", i, j, dt[j], bind[i], sind[i]); if (bind[i] <= j && sind[i] >= j) { //if (tdebug && dt[j] < 0.0) { // printf("InterpTimeStep = %d, %d: %f %d %d\n", i, j, dt[j], bind[i], sind[i]); //} dtmp[i][j] = dt[j]; } else { dtmp[i][j] = 0.0; } } } } for (j = 0; j < h->nvrt; j++) { uret = -99.0; vret = 0.0; tcnt = 0; for (i = 0; i < h->etype[elem]; i++) { cnt[i] = 0; if (h->ivs == 2) { if (bind[i] <= j && sind[i] >= j) { dd[i] = dtmp[i][2 * j]; vv[i] = dtmp[i][2 * j + 1]; cnt[i]++; tcnt++; } else { dd[i] = 0.0; vv[i] = 0.0; } } else if (h->ivs == 1) { if (bind[i] <= j && sind[i] >= j) { dd[i] = dtmp[i][j]; cnt[i]++; tcnt++; } else { dd[i] = 0.0; } } } if (h->ivs == 2) { if (tcnt && tcnt != h->etype[elem]) { uret = 0.0; vret = 0.0; for (i = 0; i < h->etype[elem]; i++) { uret = uret + cnt[i] * dd[i]; vret = vret + cnt[i] * vv[i]; //printf("ElioInterpTimeStep: %d %d %d %lf %lf\n", tcnt, i, cnt[i], dd[i], vv[i]); } uret = uret / tcnt; vret = vret / tcnt; } else if (tcnt == h->etype[elem]) { ElioEval(h->etype[elem], hh, dd, &uret); ElioEval(h->etype[elem], hh, vv, &vret); //printf("ElioInterpTimeStep OK: %lf %lf\n", uret, vret); } d[2 * j] = uret; d[2 * j + 1] = vret; } else if (h->ivs == 1) { if (tcnt && tcnt != h->etype[elem]) { uret = 0.0; for (i = 0; i < h->etype[elem]; i++) { uret = uret + cnt[i] * dd[i]; } uret = uret / tcnt; } else if (tcnt == h->etype[elem]) { ElioEval(h->etype[elem], hh, dd, &uret); } d[j] = uret; } } return ELIO_OK; } /*! * int ElioGetXYData(FILE * fp, int step, double x, double y, ElcircHeader * h, float *t, int *it, int *bind, int *sind, float *d) * * Get data at (x, y) by interpolation. * * \param fp - Open file handle for the file to read. * \param step - Step to read starting from 0 - the first step. * \param x - X. * \param y - Y. * \param h - Elcirc header information previously read. * \param t - Return time from the file. * \param it - Return time step from file. * \param bind - Integer array of 4 values for returning bottom indexes for the element (x, y) is in. * \param sind - Integer array of 4 values for returning surface indexes for the element (x, y) is in. * \param d - Return data values. * * Returns ELIO_OK on success. * Returns ELIO_ERR on unknown failures. * Returns ELIO_FSEEK_ERR on seek failures. * Returns ELIO_FREAD_ERR on read failures. */ int ElioGetXYData(FILE * fp, int step, double x, double y, ElcircHeader * h, float *t, int *it, int *bind, int *sind, float *d) { int i, j, elem, nn[4]; double hh[4], uret; double *u[4], *v[4], dd[4]; float dtmp[4][400]; /* find the element that contains the point */ if ((elem = ElioFindElementXY(h, x, y)) < 0) { printf("elio.GetXY(): Unable to locate element.\n"); return 1; } /* get the nodes for the element */ for (i = 0; i < h->etype[elem]; i++) { nn[i] = h->icon[i][elem]; ElioGetNode(fp, step, nn[i], h, t, it, &bind[i], &sind[i], &dtmp[i][0]); } ElioGetCoefficients(h, elem, x, y, hh); for (i = 0; i < h->nvrt * h->ivs; i++) { d[i] = 0.0; } for (j = 0; j < h->nvrt; j++) { for (i = 0; i < h->etype[elem]; i++) { if (bind[i] >= j && sind[i] < h->nvrt) { dd[i] = dtmp[i][j - bind[i]]; } else { dd[i] = -99.0; } } ElioEval(h->etype[elem], hh, dd, &uret); d[j] = uret; } return ELIO_OK; } /*! * int ElioGetPoint(FILE * fp, int step, int node, int level, ElcircHeader * h, float *t, int *it, float *d) * Get data for a single node from one time step at a particular level (numbered from 0) * * \param fp - Open file handle for the file to read. * \param step - Step to read starting from 0 - the first step. * \param node - Node to read starting from 0. * \param level - Level to read starting from 0. * \param h - Elcirc header information previously read. * \param t - Return time value from data file. * \param it, - Return time step from data file. * \param d - Reurn data value. * * Returns ELIO_OK on success. * Returns ELIO_ERR on unknown failures. * Returns ELIO_FSEEK_ERR on seek failures. * Returns ELIO_FREAD_ERR on read failures. */ int ElioGetPoint(FILE * fp, int step, int node, int level, ElcircHeader * h, float *t, int *it, float *d) { int i, npts, sind; off_t skip; if (h->i23d == 3) { /* 3d data */ skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { /* Read time, it, and sind */ return ELIO_FSEEK_ERR; } if (fread(t, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (fread(it, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (fseeko(fp, node * 4L, SEEK_CUR)) { /* sind */ return ELIO_FSEEK_ERR; } if (fread(&sind, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } npts = h->ivs; /* number of points to read for this node */ if (fseeko(fp, skip + (off_t) ((2 + h->np + h->no[node] + level) * 4), SEEK_SET)) { /* skip time, it, and the surf indexes and go to the particular level of interest */ return ELIO_FSEEK_ERR; } if (fread(d, sizeof(float), npts, fp) != npts) { return ELIO_FREAD_ERR; } //printf("Starting level %d ending level %d\n", h->bi[node], sind); //for (i = 0; i < npts; i++) { // printf("Data %d = %f\n", i + h->bi[node], d[i]); //} //printf("Completed Read of Time Step (%d): Time, Step = %f, %d\n", step, *t, *it); } else if (h->i23d == 2) { /* 2d data - just one or 2 values to read */ skip = (off_t) h->hsize + (off_t) step *(off_t) h->ssize; if (fseeko(fp, skip, SEEK_SET)) { /* Read time, it, and sind */ return ELIO_FSEEK_ERR; } if (fread(&t, sizeof(float), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (fread(&it, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } if (fseeko(fp, node * 4L, SEEK_CUR)) { /* Read time, it, and sind */ return ELIO_FSEEK_ERR; } if (fread(&sind, sizeof(int), 1, fp) != 1) { return ELIO_FREAD_ERR; } npts = h->ivs; /* number of points to read for this node */ if (fseeko(fp, skip + (off_t) ((2 + h->np) * 4), SEEK_SET)) { /* skip time, it, and the surf indexes */ return ELIO_FSEEK_ERR; } if (fread(d, sizeof(float), npts, fp) != npts) { return ELIO_FREAD_ERR; } /* printf("Starting level %d ending level %d\n", h->bi[node], sind); for (i = 0; i < npts; i++) { printf("Data %d = %f\n", i, d[i]); } */ printf("Completed Read of Time Step (%d): Time, Step = %f, %d\n", step, *t, *it); } else { return ELIO_ERR; } return ELIO_OK; } /*! * Read the ElcircHeader from a data file * * Input variables: * * \param fname = Pointer to a character array with the file name to read. * * Output variables: * * \param h = Pointer to ElcircHeader header. Memory will be allocated * to accomodate the internal variables. * * Returns ELIO_OK on success. * Returns non-zero on failure. * * Notes: There are some transformations of header variables performed for * convenience. For 2d variables such as elevations and winds, nvrt (the * number of levels) is set to one, the bottom index for each node is set * to 0 for all nodes. In the case of 3d variables the bottom indices * ('bi') are decremented by one. * */ int ElioGetHeader(char *fname, ElcircHeader * h) { FILE *fp; int *itmp, i, j, ss; if (sizeof(int) != 4 || sizeof(char) != 1 || sizeof(float) != 4) { fprintf(stderr, "Sizeof problems, please investigate: sizeof(char,int,float) = (%d,%d,%d)\n", sizeof(int), sizeof(char), sizeof(float)); exit(1); } fp = fopen(fname, "rb"); if (fp == NULL) { fprintf(stderr, "GetElioHeader(): Unable to open file %s\n", fname); return 1; } if (fread(h->magic, sizeof(char), 48, fp) != 48) return ELIO_FREAD_ERR; h->magic[48] = 0; /* DataFormat v3.0 */ if (strncmp(h->magic, "DataFormat v5.0", 15) == 0) { h->v = 5; h->sigma = 2; /* Sigma + Z-level grid */ } else if (strncmp(h->magic, "DataFormat v4.0", 15) == 0) { h->v = 4; h->sigma = 1; /* sigma-level grid */ } else if (strncmp(h->magic, "DataFormat v3.0", 15) == 0) { h->v = 3; h->sigma = 0; /* Z-level grid */ } else if (strncmp(h->magic, "DataFormat v2.0", 15) == 0) { h->v = 2; h->sigma = 0; /* Z-level grid */ } else { fprintf(stderr, "GetElioHeader(): Unknown version identifier %s\n", h->magic); return (3); } if (fread(h->version, sizeof(char), 48, fp) != 48) return ELIO_FREAD_ERR; h->version[48] = 0; if (fread(h->start_time, sizeof(char), 48, fp) != 48) return ELIO_FREAD_ERR; h->start_time[48] = 0; if (fread(h->variable_nm, sizeof(char), 48, fp) != 48) return ELIO_FREAD_ERR; h->variable_nm[48] = 0; if (fread(h->variable_dim, sizeof(char), 48, fp) != 48) return ELIO_FREAD_ERR; h->variable_dim[48] = 0; if (fread(&h->nsteps, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->timestep, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->skip, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->ivs, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->i23d, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (h->v == 2 || h->v == 3) { if (fread(&h->vpos, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->zmsl, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->nvrt, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; } else if (h->v == 4) { if (fread(&h->ivcor, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->h0, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->hc, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->thetab, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->thetaf, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->nvrt, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; } else if (h->v == 5) { if (fread(&h->nvrt, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->kz, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; h->ks = h->nvrt - h->kz; if (fread(&h->h0, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->hs, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->hc, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->thetab, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->thetaf, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; } h->zcor = (float *) malloc(h->nvrt * sizeof(float)); if (fread(h->zcor, sizeof(float), h->nvrt, fp) != h->nvrt) return ELIO_FREAD_ERR; if (fread(&h->np, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(&h->ne, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; h->x = (float *) malloc(h->np * sizeof(float)); h->y = (float *) malloc(h->np * sizeof(float)); h->d = (float *) malloc(h->np * sizeof(float)); h->bi = (int *) malloc(h->np * sizeof(int)); h->bisave = (int *) malloc(h->np * sizeof(int)); h->no = (int *) malloc(h->np * sizeof(int)); /* offset into data for each node */ for (i = 0; i < h->np; i++) { if (fread(h->x + i, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(h->y + i, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (fread(h->d + i, sizeof(float), 1, fp) != 1) return ELIO_FREAD_ERR; if (h->v != 4) { if (fread(h->bi + i, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; } else { h->bi[i] = 1; } } h->icon[0] = (int *) malloc(h->ne * sizeof(int)); h->icon[1] = (int *) malloc(h->ne * sizeof(int)); h->icon[2] = (int *) malloc(h->ne * sizeof(int)); h->etype = (int *) malloc(h->ne * sizeof(int)); if (h->v == 2) { /* format version 2 */ itmp = (int *) malloc(h->ne * 3 * sizeof(int)); if (fread(itmp, sizeof(int), h->ne * 3, fp) != h->ne * 3) return ELIO_FREAD_ERR; for (i = 0; i < h->ne; i++) { h->etype[i] = 3; h->icon[0][i] = itmp[i * 3] - 1; h->icon[1][i] = itmp[i * 3 + 1] - 1; h->icon[2][i] = itmp[i * 3 + 2] - 1; } free(itmp); } else if (h->v == 3) { /* format version 3 support for quads */ h->icon[3] = (int *) malloc(h->ne * sizeof(int)); for (i = 0; i < h->ne; i++) { if (fread(&h->etype[i], sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; for (j = 0; j < h->etype[i]; j++) { if (fread(&h->icon[j][i], sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; h->icon[j][i]--; } } } else if (h->v == 4 || h->v == 5) { /* format version 4 no support for quads */ for (i = 0; i < h->ne; i++) { if (fread(&h->etype[i], sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; for (j = 0; j < h->etype[i]; j++) { if (fread(&h->icon[j][i], sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; h->icon[j][i]--; } } } /* compute size of data in time step and offsets to each node */ if (h->i23d == 3) { if (h->v != 4) { h->nitems = 0; for (i = 0; i < h->np; i++) { h->bisave[i] = h->bi[i]; if (h->bi[i] > 0) { h->bi[i]--; } else { } h->no[i] = h->nitems; h->nitems += (h->nvrt - h->bi[i]) * h->ivs; //printf("%d: %d %d %d %d %d\n", i, h->nvrt, h->ivs, h->bi[i], h->no[i], h->nitems); } } else { h->nitems = h->ivs * h->nvrt * h->np; for (i = 0; i < h->np; i++) { h->bisave[i] = h->bi[i]; h->bi[i] = 0; h->no[i] = i * h->ivs * h->nvrt; } } } else { h->nvrt = 1; /* only 1 level */ if (h->v != 4) { h->nitems = 0; for (i = 0; i < h->np; i++) { h->bisave[i] = h->bi[i]; h->bi[i] = 0; /* bottom index is always 0 */ h->no[i] = h->nitems; h->nitems += h->ivs; } } else { h->nitems = h->ivs * h->np; for (i = 0; i < h->np; i++) { h->bisave[i] = h->bi[i]; h->bi[i] = 0; /* bottom index is always 0 */ h->no[i] = i * h->ivs; } } } /* get the header size in bytes */ h->hsize = ftello(fp); /* get time step size in bytes */ if (h->v == 3 || h->v == 4 || h->v == 5) { /* version 4 has elevation so size is the same */ h->ssize = 8 + h->np * 4 + h->nitems * 4; } else if (h->v == 2) { h->ssize = 8 + h->np * 4 + h->nitems * 4; } if (fclose(fp)) { return ELIO_FCLOSE_ERR; } return ELIO_OK; } /*! * Allocate memory for an ElcircHeader * * Input/Output variable: * * \param h = Pointer to ElcircHeader header. Memory will be allocated * to accomodate the internal variables. Assumes suitable defaults * have been set for np, ne, and nvrt. Also that other variables * have proper defaults set. * * Returns ELIO_OK on success. * Returns non-zero on failure. * */ int ElioAllocateHeader(ElcircHeader * h) { h->zcor = (float *) malloc(h->nvrt * sizeof(float)); h->x = (float *) malloc(h->np * sizeof(float)); h->y = (float *) malloc(h->np * sizeof(float)); h->d = (float *) malloc(h->np * sizeof(float)); h->bi = (int *) malloc(h->np * sizeof(int)); h->bisave = (int *) malloc(h->np * sizeof(int)); /* save the original bi values */ h->no = (int *) malloc(h->np * sizeof(int)); /* offset into data for each node */ h->icon[0] = (int *) malloc(h->ne * sizeof(int)); h->icon[1] = (int *) malloc(h->ne * sizeof(int)); h->icon[2] = (int *) malloc(h->ne * sizeof(int)); h->icon[3] = (int *) malloc(h->ne * sizeof(int)); h->etype = (int *) malloc(h->ne * sizeof(int)); return ELIO_OK; } int ElioMakeScalarsOld(ElcircHeader * h, float *d, float *dd) { int i, j, k; for (i = 0; i < h->np * h->nvrt; i++) { dd[i] = -99.0; } for (j = 0; j < h->np; j++) { for (k = h->bi[j]; k < h->nvrt; k++) { dd[j * h->nvrt + k] = d[h->no[j] + k - h->bi[j]]; } } return ELIO_OK; } int ElioMakeVectorsOld(ElcircHeader * h, float *d, float *dd) { int i, j, k; float tmp; for (i = 0; i < 2 * h->np * h->nvrt; i++) { dd[i] = 0.0; } for (j = 0; j < h->np; j++) { for (k = h->bi[j]; k < h->nvrt; k++) { tmp = d[h->no[j] + (k - h->bi[j]) * 2]; dd[2 * (j * h->nvrt + k)] = tmp; tmp = d[h->no[j] + (k - h->bi[j]) * 2 + 1]; dd[2 * (j * h->nvrt + k) + 1] = tmp; /* dd[2 * (j * h->nvrt + k)] = d[h->no[j] + (k - h->bi[j]) * 2]; dd[2 * (j * h->nvrt + k) + 1] = d[h->no[j] + (k - h->bi[j]) * 2 + 1]; */ } } return ELIO_OK; } /*! * Return the actual number of time steps in a data file regardless of * what the ElcircHeader says. */ int ElioGetNStepsInFile(char *fname, ElcircHeader * h) { char id[5]; int n; off_t fsize = 0; FILE *fp = fopen(fname, "rb"); if (fp == NULL) { fprintf(stderr, "GetNStepsInFile(): Unable to open file %s\n", fname); return ELIO_OK; } if (fseeko(fp, 0L, SEEK_END)) { return ELIO_FSEEK_ERR; } fsize = ftello(fp); if (fclose(fp)) { return ELIO_FCLOSE_ERR; } fsize = fsize - (off_t) h->hsize; if (h->ssize > 0) { n = fsize / h->ssize; } else { n = -1; } return n; } /*! * Extract a Header for the extracted grid * x, y, isin need to be allocated in advance. * invert = 1 to select outside the region * most == 1 to include an element if a single node is in the region * NOTE: most does not work, if a node is in then every node of every element that uses that node is also in * Need to add some additional logic for most to work. */ int ElioExtractGrid(ElcircHeader * h1, int nb, double *xb, double *yb, int *isin, int invert, int most, ElcircHeader * h2) { int i, j; int n; int np, ne; int n1, n2, n3, n4; double x, y; *h2 = *h1; /* copy the easy stuff */ /* * Find the 'in' nodes and assign the new node numbers for the reduced grid. */ for (i = 0; i < h1->np; i++) { isin[i] = 0; } n = 1; /* start from 1 for truth testing (0 is not in) */ for (i = 0; i < h1->np; i++) { x = (double) h1->x[i]; y = (double) h1->y[i]; if (!isin[i]) { // if most == 1 the test for already in if (invert) { if (!ElioInPolygon(x, y, nb, xb, yb)) { isin[i] = n; n++; } else { isin[i] = 0; } } else { if (ElioInPolygon(x, y, nb, xb, yb)) { isin[i] = n; n++; } else { isin[i] = 0; } } } if (isin[i] && most) { // TODO need to add logic to mark all associated nodes as in also. // crude version - loop over all elements and find elements using this node then // mark all other nodes of the element as in. // Better version uses an edgelist. for (j = 0; j < h1->ne; j++) { n1 = h1->icon[0][j]; n2 = h1->icon[1][j]; n3 = h1->icon[2][j]; if (n1 == i) { if (!isin[n2]) { isin[n2] = n; n++; } if (!isin[n3]) { isin[n3] = n; n++; } } else if (n2 == i) { if (!isin[n1]) { isin[n1] = n; n++; } if (!isin[n3]) { isin[n3] = n; n++; } } else if (n3 == i) { if (!isin[n1]) { isin[n1] = n; n++; } if (!isin[n2]) { isin[n2] = n; n++; } } } } } h2->np = n - 1; /* one extra */ h2->x = (float *) malloc(h2->np * sizeof(float)); h2->y = (float *) malloc(h2->np * sizeof(float)); h2->d = (float *) malloc(h2->np * sizeof(float)); h2->bi = (int *) malloc(h2->np * sizeof(int)); h2->bisave = (int *) malloc(h2->np * sizeof(int)); h2->no = (int *) malloc(h2->np * sizeof(int)); /* * count the number of elements in the new grid */ n = 0; for (i = 0; i < h1->ne; i++) { n1 = h1->icon[0][i]; n2 = h1->icon[1][i]; n3 = h1->icon[2][i]; if (h1->etype[i] == 3) { if (isin[n1] && isin[n2] && isin[n3]) { ++n; } } else if (h1->etype[i] == 4) { n4 = h1->icon[3][i]; if (isin[n1] && isin[n2] && isin[n3] && isin[n4]) { ++n; } } } h2->ne = n; h2->icon[0] = (int *) malloc(h2->ne * sizeof(int)); h2->icon[1] = (int *) malloc(h2->ne * sizeof(int)); h2->icon[2] = (int *) malloc(h2->ne * sizeof(int)); h2->icon[3] = (int *) malloc(h2->ne * sizeof(int)); h2->etype = (int *) malloc(h2->ne * sizeof(int)); /* * Build new header */ n = 0; for (i = 0; i < h1->np; i++) { if (isin[i]) { h2->x[n] = h1->x[i]; h2->y[n] = h1->y[i]; h2->d[n] = h1->d[i]; h2->bi[n] = h1->bi[i]; h2->bisave[n] = h1->bisave[i]; n++; } } /* * use the old node numbers to hash into the list containing the new * node numbers when writing out the table of elements. */ n = 0; for (i = 0; i < h1->ne; i++) { n1 = h1->icon[0][i]; n2 = h1->icon[1][i]; n3 = h1->icon[2][i]; h2->etype[n] = h1->etype[i]; if (h1->etype[i] == 4) { n4 = h1->icon[3][i]; if (isin[n1] && isin[n2] && isin[n3] && isin[n4]) { h2->icon[0][n] = isin[n1] - 1; /* isin starts from 1 */ h2->icon[1][n] = isin[n2] - 1; h2->icon[2][n] = isin[n3] - 1; h2->icon[3][n] = isin[n4] - 1; n++; } } else { if (isin[n1] && isin[n2] && isin[n3]) { h2->icon[0][n] = isin[n1] - 1; /* isin starts from 1 */ h2->icon[1][n] = isin[n2] - 1; h2->icon[2][n] = isin[n3] - 1; n++; } } } /* get the computed elements of the header */ if (h2->i23d == 3) { h2->nitems = 0; for (i = 0; i < h2->np; i++) { h2->no[i] = h2->nitems; h2->nitems += (h2->nvrt - h2->bi[i]) * h2->ivs; } } else { h2->nvrt = 1; /* only 1 level */ h2->nitems = 0; for (i = 0; i < h2->np; i++) { h2->bi[i] = 0; /* bottom index is always 0 */ h2->no[i] = h2->nitems; h2->nitems += h2->ivs; } } /* get the header size in bytes TODO */ /*h2->hsize = ftello(fp); */ /* get time step size in bytes */ h2->ssize = 8 + h2->np * 4 + h2->nitems * 4; return ELIO_OK; } /*! * Extract data from a sampled grid * The header must be created before this function is called */ int ElioExtractData(ElcircHeader * h1, ElcircHeader * h2, int *isin, ElcircTimeStep t1, ElcircTimeStep * t2) { int i, j, n, *si, npts; float *d; *t2 = t1; si = (int *) malloc(h2->np * sizeof(int)); n = 0; for (i = 0; i < h1->np; i++) { if (isin[i]) { si[n] = t1.surfind[i]; n++; } } t2->surfind = si; t2->d = (float *) malloc(h2->nitems * sizeof(float)); n = 0; for (i = 0; i < h1->np; i++) { if (isin[i]) { for (j = 0; j < h1->nvrt - h1->bi[i]; j++) { t2->d[n] = t1.d[h1->no[i] + j]; n++; } } } return ELIO_OK; } /*! * Routines to determine if a point lies in a polygon */ int ElioIntersectToLeft(double x, double y, double x1, double y1, double x2, double y2) { double xtmp, m, b; /* ignore horizontal lines */ if (y1 == y2) { return 0; } /* not contained vertically */ if (((y < y1) && (y < y2)) || ((y > y1) && (y > y2))) { return 0; } /* none of the above, compute the intersection */ if ((xtmp = x2 - x1) != 0.0) { m = (y2 - y1) / xtmp; b = y1 - m * x1; xtmp = (y - b) / m; } else { xtmp = x1; } if (xtmp <= x) { /* check for intersections at a vertex */ /* if this is the max ordinate then accept */ if (y == y1) { if (y1 > y2) { return 1; } else { return 0; } } /* check for intersections at a vertex */ if (y == y2) { if (y2 > y1) { return 1; } else { return 0; } } /* no vertices intersected */ return 1; } return 0; } /*! * Determine if (x,y) is in the polygon xlist[], ylist[]. */ int ElioInPolygon(double x, double y, int n, double *xlist, double *ylist) { int i, l = 0, ll = 0; for (i = 0; i < n; i++) { if ((y < ylist[i] && y < ylist[(i + 1) % n]) || (y > ylist[i] && y > ylist[(i + 1) % n])) { continue; } if ((x < xlist[i] && x < xlist[(i + 1) % n])) { continue; } l += ElioIntersectToLeft(x, y, xlist[i], ylist[i], xlist[(i + 1) % n], ylist[(i + 1) % n]); } return l % 2; } /*! * Locate the element in which x, y is located. * Returns -1 if the element cannot be located, the element number * starting from zero otherwise. * */ int ElioFindElementXY(ElcircHeader * h, double xp, double yp) { int i, j; int n0, n1, n2, n3; double x[4], y[4]; for (i = 0; i < h->ne; i++) { for (j = 0; j < h->etype[i]; j++) { x[j] = h->x[h->icon[j][i]]; y[j] = h->y[h->icon[j][i]]; } if (h->etype[i] == 3) { if (ElioInsideElement(xp, yp, x[0], y[0], x[1], y[1], x[2], y[2])) { return i; } } else { if (ElioInsideElement4(xp, yp, x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3])) { return i; } } } return -1; } /*! * Tolerance for locating point in elements. */ static double ElioInsideElementTol = -1e-05; /*! * Set the tolerance for locating points in elements. */ void ElioSetInsideElementTol(double tol) { ElioInsideElementTol = -tol; } /*! * Determine if (x, y) is inside the triangle given by (x1, y1), (x2, y2), (x3, y3). */ int ElioInsideElement(double x, double y, double x1, double y1, double x2, double y2, double x3, double y3) { if ((x - x1) * (y1 - y2) + (y - y1) * (x2 - x1) < ElioInsideElementTol) return 0; if ((x - x2) * (y2 - y3) + (y - y2) * (x3 - x2) < ElioInsideElementTol) return 0; if ((x - x3) * (y3 - y1) + (y - y3) * (x1 - x3) < ElioInsideElementTol) return 0; return 1; } /*! * Determine if (x, y) is inside the convex quadrangle given by (x1, y1), (x2, y2), (x3, y3), (x4, y4). */ int ElioInsideElement4(double x, double y, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { if ((x - x1) * (y1 - y2) + (y - y1) * (x2 - x1) < ElioInsideElementTol) return 0; if ((x - x2) * (y2 - y3) + (y - y2) * (x3 - x2) < ElioInsideElementTol) return 0; if ((x - x3) * (y3 - y4) + (y - y3) * (x4 - x3) < ElioInsideElementTol) return 0; if ((x - x4) * (y4 - y1) + (y - y4) * (x1 - x4) < ElioInsideElementTol) return 0; return 1; } /*! * Given previously computed nodal coefficients in h, and flow (u, v) at each node compute the flow and return in (uret, vret). * * \param n Integer number of nodes. * \param h Pointer to nodal coefficients. * \param u Pointer to nodal values for u at the nodes. * \param v Pointer to nodal values for u at the nodes. * \param uret Pointer to return value. * \param vret Pointer to return value. */ int ElioEvalFlowXY(int n, double *h, double *u, double *v, double *uret, double *vret) { int i; *uret = 0.0; *vret = 0.0; if (n != 3 && n != 4) { return 1; } else { for (i = 0; i < n; i++) { *uret += h[i] * u[i]; *vret += h[i] * v[i]; } } return ELIO_OK; } int ElioEval(int n, double *h, double *c, double *uret) { int i; *uret = 0.0; if (n != 3 && n != 4) { return 1; } else { for (i = 0; i < n; i++) { *uret += h[i] * c[i]; } } return ELIO_OK; } int ElioEvalScalarXY(int n, double *h, double *c, double *uret) { int i; *uret = 0.0; if (n != 3 && n != 4) { return 1; } else { for (i = 0; i < n; i++) { *uret += h[i] * c[i]; } } return ELIO_OK; } /*! Compute coefficients for interpolation for both triangles and quads using * information from the element number. * * \param h Header struct to write. * \param elem Number of the element from 0. * \param xp X-coordinate of point for interpolation. * \param yp Y-coordinate of point for interpolation. * \param w Coefficients of interpolator. * * Returns ELIO_OK on success and ELIO_ERR on failure. */ int ElioGetCoefficients(ElcircHeader * h, int elem, double xp, double yp, double *w) { double aum, ado, atr, bum, bdo, btr, cum, cdo, ctr; double x1, y1, x2, y2, x3, y3, x4, y4, c1, c2, c3, arei; double xi, eta; int nn[4]; nn[0] = h->icon[0][elem]; nn[1] = h->icon[1][elem]; nn[2] = h->icon[2][elem]; x1 = h->x[nn[0]]; y1 = h->y[nn[0]]; x2 = h->x[nn[1]]; y2 = h->y[nn[1]]; x3 = h->x[nn[2]]; y3 = h->y[nn[2]]; if (h->etype[elem] == 3) { aum = x2 * y3 - x3 * y2; bum = y2 - y3; cum = x3 - x2; ado = x3 * y1 - x1 * y3; bdo = y3 - y1; cdo = x1 - x3; atr = x1 * y2 - x2 * y1; btr = y1 - y2; ctr = x2 - x1; arei = 1.0 / (aum + ado + atr); w[2] = (atr + btr * xp + ctr * yp) * arei; w[1] = (ado + bdo * xp + cdo * yp) * arei; w[0] = 1.0 - w[1] - w[2]; return ELIO_OK; } else { nn[3] = h->icon[3][elem]; x4 = h->x[nn[3]]; y4 = h->y[nn[3]]; ibilinear(x1, x2, x3, x4, y1, y2, y3, y4, xp, yp, &xi, &eta, w); return ELIO_OK; } return ELIO_ERR; } /*! Compute coefficients for interpolation for both triangles and quads using * information from the element number. * * \param h Header struct to write. * \param elem Number of the element from 0. * \param xp X-coordinate of point for interpolation. * \param yp Y-coordinate of point for interpolation. * \param w Coefficients of interpolator. * * Returns ELIO_OK on success and ELIO_ERR on failure. */ int ElioGetCoefficientsGrid(ElioGrid * g, int elem, double xp, double yp, double *w) { double aum, ado, atr, bum, bdo, btr, cum, cdo, ctr; double x1, y1, x2, y2, x3, y3, x4, y4, c1, c2, c3, arei; double xi, eta; int nn[4]; if (g == NULL || elem < 0 || elem >= g->ne) { return ELIO_ERR; } nn[0] = g->icon[0][elem]; nn[1] = g->icon[1][elem]; nn[2] = g->icon[2][elem]; x1 = g->x[nn[0]]; y1 = g->y[nn[0]]; x2 = g->x[nn[1]]; y2 = g->y[nn[1]]; x3 = g->x[nn[2]]; y3 = g->y[nn[2]]; if (g->etype[elem] == 3) { aum = x2 * y3 - x3 * y2; bum = y2 - y3; cum = x3 - x2; ado = x3 * y1 - x1 * y3; bdo = y3 - y1; cdo = x1 - x3; atr = x1 * y2 - x2 * y1; btr = y1 - y2; ctr = x2 - x1; arei = 1.0 / (aum + ado + atr); w[2] = (atr + btr * xp + ctr * yp) * arei; w[1] = (ado + bdo * xp + cdo * yp) * arei; w[0] = 1.0 - w[1] - w[2]; return ELIO_OK; } else { nn[3] = g->icon[3][elem]; x4 = g->x[nn[3]]; y4 = g->y[nn[3]]; ibilinear(x1, x2, x3, x4, y1, y2, y3, y4, xp, yp, &xi, &eta, w); return ELIO_OK; } return ELIO_ERR; } /*! Compute coefficients for interpolation for both triangles and quads using * coordinates of the nodes rather than information from the element number. * * \param n Number of nodes in the element. * \param x Pointer to array with x-coordinate of nodes. * \param y Pointer to array with y-coordinate of nodes. * \param xp X-coordinate of point for interpolation. * \param yp Y-coordinate of point for interpolation. * \param w Coefficients of interpolator. * * Returns ELIO_OK on success and ELIO_ERR on failure. */ int ElioGetCoefficientsXY(int n, double *x, double *y, double xp, double yp, double *w) { double aum, ado, atr, bum, bdo, btr, cum, cdo, ctr; double x1, y1, x2, y2, x3, y3, x4, y4, c1, c2, c3, arei; double xi, eta; x1 = x[0]; y1 = y[0]; x2 = x[1]; y2 = y[1]; x3 = x[2]; y3 = y[2]; if (n == 3) { aum = x2 * y3 - x3 * y2; bum = y2 - y3; cum = x3 - x2; ado = x3 * y1 - x1 * y3; bdo = y3 - y1; cdo = x1 - x3; atr = x1 * y2 - x2 * y1; btr = y1 - y2; ctr = x2 - x1; arei = 1.0 / (aum + ado + atr); w[2] = (atr + btr * xp + ctr * yp) * arei; w[1] = (ado + bdo * xp + cdo * yp) * arei; w[0] = 1.0 - w[1] - w[2]; return ELIO_OK; } if (n == 4) { x4 = x[3]; y4 = y[3]; ibilinear(x1, x2, x3, x4, y1, y2, y3, y4, xp, yp, &xi, &eta, w); return ELIO_OK; } else { return ELIO_ERR; } return ELIO_ERR; } /*! * Define a header for the surface. */ int ElioGetSurfaceHeader(ElcircHeader * h1, ElcircHeader * h2) { int i, j; strncpy(h2->magic, h1->magic, 48); strncpy(h2->version, h1->version, 48); strncpy(h2->start_time, h1->start_time, 48); strncpy(h2->variable_nm, h1->variable_nm, 48); strncpy(h2->variable_dim, h1->variable_dim, 48); h2->nsteps = h1->nsteps; h2->timestep = h1->timestep; h2->skip = h1->skip; h2->ivs = h1->ivs; h2->i23d = h1->i23d; h2->vpos = h1->vpos; h2->zmsl = h1->zmsl; h2->nvrt = h1->nvrt; h2->zcor = (float *) malloc(h1->nvrt * sizeof(float)); for (i = 0; i < h1->nvrt; i++) { h2->zcor = h1->zcor; } h2->np = h1->np; h2->ne = h1->ne; h2->x = (float *) malloc(h1->np * sizeof(float)); h2->y = (float *) malloc(h1->np * sizeof(float)); h2->d = (float *) malloc(h1->np * sizeof(float)); h2->bi = (int *) malloc(h1->np * sizeof(int)); h2->bisave = (int *) malloc(h1->np * sizeof(int)); h2->no = (int *) malloc(h1->np * sizeof(int)); /* offset into data for each node */ for (i = 0; i < h1->np; i++) { h2->x[i] = h1->x[i]; h2->y[i] = h1->y[i]; h2->d[i] = h1->d[i]; h2->bisave[i] = h1->bisave[i]; h2->bi[i] = h1->bi[i]; } h2->icon[0] = (int *) malloc(h1->ne * sizeof(int)); h2->icon[1] = (int *) malloc(h1->ne * sizeof(int)); h2->icon[2] = (int *) malloc(h1->ne * sizeof(int)); for (i = 0; i < h1->ne; i++) { h2->icon[0][i] = h1->icon[0][i]; h2->icon[1][i] = h1->icon[0][i]; h2->icon[2][i] = h1->icon[0][i]; } /* compute size of data in time step and offsets to each node */ h2->nitems = 0; for (i = 0; i < h1->np; i++) { h2->bi[i] = 1; h2->no[i] = h2->nitems; h2->nitems += 1; } /* get the header size in bytes */ /*h2->hsize = ftello(fp); */ /* get time step size in bytes */ h2->ssize = 8 + h2->np * 4 + h2->nitems * 4; return ELIO_OK; } /*! * Get a time step for the surface. Not implemented. */ int ElioGetSurfaceStep(ElcircHeader * h1, ElcircHeader * h2, ElcircTimeStep t1, ElcircTimeStep * t2) { return ELIO_OK; } /*! * Define a header for the bottom. Not implemented. */ int ElioGetBottomHeader(ElcircHeader * h1, ElcircHeader * h2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetBottomStep(ElcircHeader * h1, ElcircHeader * h2, ElcircTimeStep t1, ElcircTimeStep * t2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetTransectHeader(ElcircHeader * h1, int n, double *x, double *y, ElcircHeader * h2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetTransectStep(ElcircHeader * h1, ElcircHeader * h2, int step, int n, double *x, double *y, ElcircTimeStep t1, ElcircTimeStep * t2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetLevelHeader(ElcircHeader * h1, ElcircHeader * h2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetLevelStep(ElcircHeader * h1, ElcircHeader * h2, ElcircTimeStep t1, int level, ElcircTimeStep * t2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetZLevelHeader(ElcircHeader * h1, ElcircHeader * h2) { return ELIO_OK; } /*! Not implemented. */ int ElioGetZLevelStep(ElcircHeader * h1, ElcircHeader * h2, ElcircTimeStep t1, float z, ElcircTimeStep * t2) { return ELIO_OK; } /*! Write the ELCIRC header. * \param fp Pointer to open file handle. * \param h Header struct to write. * * The structure to write should be prepared in advance with an allocated * grid and all members filled in with appropriate values. */ int ElioPutHeader(FILE * fp, ElcircHeader * h) { int *itmp, i, j, bitmp, etmp; if (fp == NULL) { fprintf(stderr, "Bad file pointer\n"); return ELIO_ERR; } /*if (!(strncmp(h->magic, "DataFormat v3.0", 15) == 0)) { fprintf(stderr, "ElioPutHeader(): Version identifier %s, must be 'DataFormat v3.0'\n", h->magic); return (ELIO_ERR); } */ if (fwrite(h->magic, sizeof(char), 48, fp) != 48) return ELIO_FWRITE_ERR; h->magic[48] = 0; if (fseeko(fp, 48L, SEEK_SET)) { return ELIO_FSEEK_ERR; } if (fwrite(h->version, sizeof(char), 48, fp) != 48) return ELIO_FWRITE_ERR; h->version[48] = 0; if (fwrite(h->start_time, sizeof(char), 48, fp) != 48) return ELIO_FWRITE_ERR; h->start_time[48] = 0; if (fwrite(h->variable_nm, sizeof(char), 48, fp) != 48) return ELIO_FWRITE_ERR; h->variable_nm[48] = 0; if (fwrite(h->variable_dim, sizeof(char), 48, fp) != 48) return ELIO_FWRITE_ERR; h->variable_dim[48] = 0; if (fwrite(&h->nsteps, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->timestep, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->skip, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->ivs, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->i23d, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (h->v == 3) { if (fwrite(&h->vpos, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->zmsl, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->nvrt, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; } else if (h->v == 4) { if (fwrite(&h->ivcor, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->h0, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->hc, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->thetab, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->thetaf, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->nvrt, sizeof(int), 1, fp) != 1) return ELIO_FREAD_ERR; } else if (h->v == 5) { if (fwrite(&h->nvrt, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->kz, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->h0, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->hs, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->hc, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->thetab, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->thetaf, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; } if (fwrite(h->zcor, sizeof(float), h->nvrt, fp) != h->nvrt) return ELIO_FWRITE_ERR; if (fwrite(&h->np, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&h->ne, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; for (i = 0; i < h->np; i++) { if (fwrite(h->x + i, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(h->y + i, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(h->d + i, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (h->v != 4) { bitmp = h->bisave[i]; /* subtracted 1 previously, have to add it back */ if (fwrite(&bitmp, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; } } /* for hybrid grids */ for (i = 0; i < h->ne; i++) { if (fwrite(&h->etype[i], sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; for (j = 0; j < h->etype[i]; j++) { etmp = h->icon[j][i] + 1; /* node number start from 0 internally, need to add 1 */ if (fwrite(&etmp, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; } } return ELIO_OK; } /*! * Write a time step. * * \param fp Open filehandle. * \param h Pointer to ELCIRC header. * \param t Value parameter containing time step information to write. */ int ElioPutTimeStep(FILE * fp, ElcircHeader * h, ElcircTimeStep t) { if (fwrite(&t.t, sizeof(float), 1, fp) != 1) return ELIO_FWRITE_ERR; if (fwrite(&t.it, sizeof(int), 1, fp) != 1) return ELIO_FWRITE_ERR; if (h->v != 4) { if (fwrite(t.surfind, sizeof(int), h->np, fp) != h->np) return ELIO_FWRITE_ERR; } else { if (fwrite(t.e, sizeof(float), h->np, fp) != h->np) return ELIO_FWRITE_ERR; } if (fwrite(t.d, sizeof(float), h->nitems, fp) != h->nitems) return ELIO_FWRITE_ERR; //printf("Completed Write of Time Step: Time, Step = %f, %d\n", t.t, t.it); return ELIO_OK; } /*! Not implemented * */ int ElioPutHeaderOld(FILE * fp, ElcircHeader * h) { return ELIO_OK; } /*! Not implemented * */ int ElioPutTimeStepOld(FILE * fp, ElcircHeader * h, ElcircTimeStep t) { return ELIO_OK; } /*! Return the file type. * * Returns -1 on error. */ int ElioGetFileType(FILE * fp) { char id[100]; int retval = -1; if (fread(id, sizeof(char), 15, fp) != 15) { return retval; } id[15] = 0; if (fseeko(fp, 0L, SEEK_SET)) { return retval; } if (strcmp(id, "DataFormat v2.0") == 0) { retval = 2; } else if (strcmp(id, "DataFormat v3.0") == 0) { retval = 3; } else if (strcmp(id, "DataFormat v4.0") == 0) { retval = 4; } else if (strcmp(id, "DataFormat v5.0") == 0) { retval = 5; } return retval; } /*! * Copy header h1 to h2 */ int ElioCopyHeader(ElcircHeader * h1, ElcircHeader * h2) { FILE *fp; int *itmp, i, j, ss; *h2 = *h1; memcpy(h2->magic, h1->magic, 48); memcpy(h2->version, h1->version, 48); memcpy(h2->start_time, h1->start_time, 48); memcpy(h2->variable_nm, h1->variable_nm, 48); memcpy(h2->variable_dim, h1->variable_dim, 48); h2->nsteps = h1->nsteps; h2->timestep = h1->timestep; h2->skip = h1->skip; h2->ivs = h1->ivs; h2->i23d = h1->i23d; h2->vpos = h1->vpos; h2->sigma = h1->sigma; h2->zmsl = h1->zmsl; h2->nvrt = h1->nvrt; h2->zcor = (float *) malloc(h1->nvrt * sizeof(float)); for (i = 0; i < h1->nvrt; i++) { h2->zcor[i] = h2->zcor[i]; } h2->np = h1->np; h2->ne = h1->ne; h2->x = (float *) malloc(h1->np * sizeof(float)); h2->y = (float *) malloc(h1->np * sizeof(float)); h2->d = (float *) malloc(h1->np * sizeof(float)); h2->bi = (int *) malloc(h1->np * sizeof(int)); h2->bisave = (int *) malloc(h1->np * sizeof(int)); h2->no = (int *) malloc(h1->np * sizeof(int)); memcpy(h2->x, h1->x, h1->np * sizeof(float)); memcpy(h2->y, h1->y, h1->np * sizeof(float)); memcpy(h2->d, h1->d, h1->np * sizeof(float)); memcpy(h2->bi, h1->bi, h1->np * sizeof(int)); memcpy(h2->bisave, h1->bisave, h1->np * sizeof(int)); h2->etype = (int *) malloc(h1->ne * sizeof(int)); memcpy(h2->etype, h1->etype, h1->ne * sizeof(int)); h2->icon[0] = (int *) malloc(h1->ne * sizeof(int)); h2->icon[1] = (int *) malloc(h1->ne * sizeof(int)); h2->icon[2] = (int *) malloc(h1->ne * sizeof(int)); h2->icon[3] = (int *) malloc(h1->ne * sizeof(int)); memcpy(h2->icon[0], h1->icon[0], h1->ne * sizeof(int)); memcpy(h2->icon[1], h1->icon[1], h1->ne * sizeof(int)); memcpy(h2->icon[2], h1->icon[2], h1->ne * sizeof(int)); if (h1->icon[3] != NULL) { memcpy(h2->icon[3], h1->icon[3], h1->ne * sizeof(int)); } else { h2->icon[3] = NULL; } h2->nitems = h1->nitems; memcpy(h2->bi, h1->bi, h1->np * sizeof(int)); memcpy(h2->bisave, h1->bisave, h1->np * sizeof(int)); memcpy(h2->no, h1->no, h1->np * sizeof(int)); h2->hsize = h1->hsize; h2->ssize = h1->ssize; return 0; } /*! * Write out data to a single step .61 file */ int ElioPut61File(char *fn, ElcircHeader * h, double *v) { int i; FILE *fp; ElcircTimeStep t; if ((fp = fopen(fn, "w")) == NULL) { return ELIO_ERR; } if (ElioPutHeader(fp, h)) { return ELIO_ERR; } ElioAllocateTimeStep(h, &t); t.t = 0.0; t.it = 1; for (i = 0; i < h->np; i++) { t.d[i] = v[i]; } ElioPutTimeStep(fp, h, t); ElioFreeTimeStep(&t); fclose(fp); return ELIO_OK; } /*! * Return the area for the given element. Element numbering starts from 0. * * \param h - Previously read header. * \param elem - Element number from 0 to compute the center. * * Returns 0.0 on error. */ double ElioGetElementArea(ElcircHeader * h, int elem) { int n1, n2, n3, n4; double ar = 0.0; double x1, y1, x2, y2, x3, y3, x4, y4; if (elem >= 0 && elem < h->ne) { n1 = h->icon[0][elem]; n2 = h->icon[1][elem]; n3 = h->icon[2][elem]; x1 = h->x[n1]; x2 = h->x[n2]; x3 = h->x[n3]; y1 = h->y[n1]; y2 = h->y[n2]; y3 = h->y[n3]; if (h->etype[elem] == 3) { ar = 0.5 * ((x1 * y2 - x2 * y1) + (x2 * y3 - x3 * y2) + (x3 * y1 - x1 * y3)); } else if (h->etype[elem] == 4) { n4 = h->icon[3][elem]; x4 = h->x[n4]; y4 = h->y[n4]; ar = 0.5 * ((x1 * y2 - x2 * y1) + (x2 * y3 - x3 * y2) + (x3 * y4 - x4 * y3) + (x4 * y1 - x1 * y4)); } } return ar; } /*! * Return the center of the element 'elem' in (cx, cy). * * \param h - Previously read header. * \param elem - Element number from 0 to compute the center. * \param *cx - Returns x. * \param *cy - Returns y. * * Returns ELIO_OK on success. * Returns ELIO_ERR on failure. */ int ElioGetElementCenter(ElcircHeader * h, int elem, double *cx, double *cy) { int i, n; if (!h || h->ne <= 0 || elem < 0 || (h->etype[elem] != 3 && h->etype[elem] != 4)) { return ELIO_ERR; } *cx = *cy = 0.0; for (i = 0; i < h->etype[elem]; i++) { n = h->icon[i][elem]; *cx += h->x[n]; *cy += h->y[n]; } *cx /= h->etype[elem]; *cy /= h->etype[elem]; return ELIO_OK; } /*! * Return the center of the element 'elem' in (cx, cy). * * \param g - Previously read grid. * \param elem - Element number from 0 to compute the center. * \param *cx - Returns x. * \param *cy - Returns y. * * Returns ELIO_OK on success. * Returns ELIO_ERR on failure. */ int ElioGetGridElementCenter(ElioGrid * g, int elem, double *cx, double *cy) { int i, n; if (!g || g->ne <= 0 || elem < 0 || (g->etype[elem] != 3 && g->etype[elem] != 4)) { return ELIO_ERR; } *cx = *cy = 0.0; for (i = 0; i < g->etype[elem]; i++) { n = g->icon[i][elem]; *cx += g->x[n]; *cy += g->y[n]; } *cx /= g->etype[elem]; *cy /= g->etype[elem]; return ELIO_OK; } /*! * Return the area for the given element. Element numbering starts from 0. * * Returns 0.0 on error. */ double ElioGetGridElementArea(ElioGrid * g, int elem) { int n1, n2, n3, n4; double ar = 0.0; double x1, y1, x2, y2, x3, y3, x4, y4; if (elem >= 0 && elem < g->ne) { n1 = g->icon[0][elem]; n2 = g->icon[1][elem]; n3 = g->icon[2][elem]; x1 = g->x[n1]; x2 = g->x[n2]; x3 = g->x[n3]; y1 = g->y[n1]; y2 = g->y[n2]; y3 = g->y[n3]; if (g->etype[elem] == 3) { ar = 0.5 * ((x1 * y2 - x2 * y1) + (x2 * y3 - x3 * y2) + (x3 * y1 - x1 * y3)); } else if (g->etype[elem] == 4) { n4 = g->icon[3][elem]; x4 = g->x[n4]; y4 = g->y[n4]; ar = 0.5 * ((x1 * y2 - x2 * y1) + (x2 * y3 - x3 * y2) + (x3 * y4 - x4 * y3) + (x4 * y1 - x1 * y4)); } } return ar; } /*! * Read a grid * * \param gname - Grid file name * \param g - Pointer to a grid structure * * Returns ELIO_OK on success. * Returns ELIO_ERR on failure. */ int ElioReadGrid(char *gname, ElioGrid * g) { FILE *fp; char buf[1024]; int i; if ((fp = fopen(gname, "rb")) == NULL) { return ELIO_ERR; } fgets(buf, 255, fp); fgets(buf, 255, fp); sscanf(buf, "%d %d", &g->ne, &g->np); g->x = (double *) malloc(g->np * sizeof(double)); g->y = (double *) malloc(g->np * sizeof(double)); g->d = (double *) malloc(g->np * sizeof(double)); g->etype = (int *) malloc(g->ne * sizeof(int)); for (i = 0; i < 4; i++) { g->icon[i] = (int *) malloc(g->ne * sizeof(int)); } for (i = 0; i < g->np; i++) { fgets(buf, 255, fp); sscanf(buf, "%*d %lf %lf %lf", &g->x[i], &g->y[i], &g->d[i]); } for (i = 0; i < g->ne; i++) { fgets(buf, 255, fp); sscanf(buf, "%*d %d %d %d %d %d", &g->etype[i], &g->icon[0][i], &g->icon[1][i], &g->icon[2][i], &g->icon[3][i]); g->icon[0][i]--; g->icon[1][i]--; g->icon[2][i]--; if (g->etype[i] == 3) { g->icon[3][i] = -1; } else { g->icon[3][i]--; } } /* could be a boundary in this grid file, try to read it //3 = Number of open boundaries //91 = Total number of open boundary nodes //85 = Number of nodes for open boundary 1 if (fgets(buf, 255, fp) != NULL) { if (sscanf(buf, "%d", &g->nopen) == 1) { if (fgets(buf, 255, fp) != NULL) { if (sscanf(buf, "%d", &g->ntotalopen) == 1) { for (i=0;i<g->nopen;i++) { if (sscanf(buf, "%d %d", &g->nopen) == 1) { if (sscanf(buf, "%d", &g->ntotalopen) == 1) { } } } } } } } */ fclose(fp); return ELIO_OK; } /*! * Free a grid * * \param g - Pointer to a grid structure with already allocated memory * * Returns ELIO_OK on success. * * No checking is done on validity of the pointers being freed */ int ElioFreeGrid(ElioGrid *g) { int i; free(g->x); free(g->y); free(g->d); free(g->etype); for (i = 0; i < 4; i++) { free(g->icon[i]); } return ELIO_OK; } int ElioFindElementInGrid(ElioGrid * g, double xp, double yp) { int i, j; int n0, n1, n2, n3; double x[4], y[4]; for (i = 0; i < g->ne; i++) { for (j = 0; j < g->etype[i]; j++) { x[j] = g->x[g->icon[j][i]]; y[j] = g->y[g->icon[j][i]]; } //printf("ElioInsideElement %lf %lf %lf %lf %lf %lf %lf %lf\n", xp, yp, x[0], y[0], x[1], y[1], x[2], y[2]); if (g->etype[i] == 3) { if (ElioInsideElement(xp, yp, x[0], y[0], x[1], y[1], x[2], y[2])) { return i; } } else { if (ElioInsideElement4(xp, yp, x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3])) { return i; } } } return -1; } int ElioGridFindNearestNode(ElioGrid * g, double x, double y) { int i, ind = -1; double radius; double tmp, *xord = g->x, *yord = g->y; if (g->np > 0) { radius = hypot((x - xord[0]), (y - yord[0])); ind = 0; for (i = 1; i < g->np; i++) { tmp = hypot((x - xord[i]), (y - yord[i])); if (tmp < radius) { radius = tmp; ind = i; } } } else { ind = -1; } return ind; } int ElioFindNearestNode(ElcircHeader * h, double x, double y) { int i, ind; double radius; double tmp; float *xord = h->x, *yord = h->y; if (h->np > 0) { radius = hypot((x - xord[0]), (y - yord[0])); ind = 0; for (i = 1; i < h->np; i++) { tmp = hypot((x - xord[i]), (y - yord[i])); if (tmp < radius) { radius = tmp; ind = i; } } } else { ind = -1; } return ind; } int ElioWriteGrid(char *gname, ElioGrid * g) { FILE *fp; char buf[1024]; int i; if ((fp = fopen(gname, "wb")) == NULL) { return ELIO_ERR; } fprintf(fp, "Grid\n"); fprintf(fp, "%d %d\n", g->ne, g->np); for (i = 0; i < g->np; i++) { fprintf(fp, "%d %lf %lf %lf\n", i + 1, g->x[i], g->y[i], g->d[i]); } for (i = 0; i < g->ne; i++) { if (g->etype[i] == 3) { fprintf(fp, "%d 3 %d %d %d\n", i + 1, g->icon[0][i] + 1, g->icon[1][i] + 1, g->icon[2][i] + 1); } else if (g->etype[i] == 4) { fprintf(fp, "%d 4 %d %d %d %d\n", i + 1, g->icon[0][i] + 1, g->icon[1][i] + 1, g->icon[2][i] + 1, g->icon[3][i] + 1); } } fclose(fp); return ELIO_OK; } /*! * Time/date functions. */ static int corietime = 0; static double coriestart = 0; /*! * Turn on CORIE time, should be called just once in any program. * Multiple calls will foul things up, so don't do it. */ void ElioSetCorieTime(int b) { corietime = b; if (b) { putenv("TZ=PST"); coriestart = ElioGetDay(12, 31, 1995, 0, 0, 0); } else { coriestart = 0.0; } } /*! * Set corietime from a string. 4 digits for year. */ void ElioSetStartTime(int b, char *t) { int y, m, d, h, mi, s; corietime = b; if (b) { sscanf(t, "%4d%2d%2d%2d%2d%2d", &y, &m, &d, &h, &mi, &s); coriestart = ElioGetDay(m, d, y, h, mi, s); } else { coriestart = 0.0; } } /*! * Return the corietime constant. If non-zero then corie time is active. */ int ElioGetCorieDayConstant(void) { return corietime; } /*! * Return corieday relative to now. The variable 'when' can be +-. */ double ElioGetCorieDay(int when) { double jd = 1; time_t t; t = time(NULL) + when * 86400; jd = ElioGetDay(12, 31, 1995, 0, 0, 0); jd = t / 86400.0 - jd; return jd; } /*! * Return the CORIE day or UNIX day + hms as a real number. */ double ElioGetDay(int mon, int day, int year, int h, int mi, double se) { double frac = (int) se - se; struct tm t; time_t j; t.tm_sec = se; t.tm_min = mi; t.tm_hour = h; t.tm_mday = day; t.tm_mon = mon - 1; t.tm_year = year - 1900; j = mktime(&t); return ((double) j / 86400.0 - coriestart); } /*! * Convert a CORIE or UNIX day number to m-d-y hhmmss. */ void ElioGetDate(double jd, int *m, int *d, int *y, int *h, int *mi, double *sec) { struct tm *t; time_t seconds = (jd + coriestart) * 86400.0; t = gmtime(&seconds); *sec = t->tm_sec; *mi = t->tm_min; *h = t->tm_hour; *d = t->tm_mday; *m = t->tm_mon + 1; *y = t->tm_year + 1900; } /*! * Convert a day number to y-yearday hhmmss. */ void ElioGetYearDay(double jd, int *y, int *yd, int *h, int *mi, double *sec) { struct tm *t; time_t seconds = (jd + coriestart) * 86400.0; t = gmtime(&seconds); *sec = t->tm_sec; *mi = t->tm_min; *h = t->tm_hour; *yd = t->tm_yday + 1; *y = t->tm_year + 1900; } /*! * Inverse bilinear mapping for quadrangles from Joseph. * Convexity of the quad must have been checked, and (x,y) must * be inside the quad. * */ int ibilinear(double x1, double x2, double x3, double x4, double y1, double y2, double y3, double y4, double x, double y, double *xi, double *eta, double *shapef) { double axi[2], aet[2], bxy[2], root_xi[2], root_et[2]; double x0, y0, dxi, deta, dd, beta, delta, dgamma; int i, j, icount, icaseno; static double SMALL = 1.0e-5; //!... Consts. x0 = (x1 + x2 + x3 + x4) / 4.0; y0 = (y1 + y2 + y3 + y4) / 4.0; axi[0] = x2 - x1 + x3 - x4; axi[1] = y2 - y1 + y3 - y4; aet[0] = x3 + x4 - x1 - x2; aet[1] = y3 + y4 - y1 - y2; bxy[0] = x1 - x2 + x3 - x4; bxy[1] = y1 - y2 + y3 - y4; dxi = 2 * ((x3 - x4) * (y1 - y2) - (y3 - y4) * (x1 - x2)); deta = 2 * ((x4 - x1) * (y3 - y2) - (y4 - y1) * (x3 - x2)); //!... Inverse mapping if ((fabs(bxy[0]) < SMALL && fabs(bxy[1]) < SMALL) || (fabs(dxi) < SMALL && fabs(deta) < SMALL)) { icaseno = 1; // if (dxi == 0.0 && deta == 0.0) { dd = axi[0] * aet[1] - axi[1] * aet[0]; if (dd == 0.0) { fprintf(stderr, "Case 1 error: %lf\n", dd); return ELIO_ERR; } *xi = 4 * (aet[1] * (x - x0) - aet[0] * (y - y0)) / dd; *eta = 4 * (axi[0] * (y - y0) - axi[1] * (x - x0)) / dd; } else if (fabs(dxi) < SMALL && fabs(deta) >= SMALL) { // } else if (dxi == 0 && deta != 0) { icaseno = 2; *eta = 4 * (bxy[1] * (x - x0) - bxy[1] * (y - y0)) / deta; dd = (axi[0] + *eta * bxy[0]) * (axi[0] + *eta * bxy[0]) + (axi[1] + *eta * bxy[1]) * (axi[1] + *eta * bxy[1]); if (dd == 0) { fprintf(stderr, "Case 2 error: &lf\n", dd); return ELIO_ERR; } *xi = ((4 * (x - x0) - *eta * aet[0]) * (axi[0] + *eta * bxy[0]) + (4 * (y - y0) - *eta * aet[1]) * (axi[1] + *eta * bxy[1])) / dd; ; } else if (fabs(dxi) >= SMALL && fabs(deta) < SMALL) { icaseno = 3; // } else if (dxi != 0 && deta == 0) { *xi = 4 * (bxy[1] * (x - x0) - bxy[0] * (y - y0)) / dxi; dd = (aet[0] + *xi * bxy[0]) * (aet[0] + *xi * bxy[0]) + (aet[1] + *xi * bxy[1]) * (aet[1] + *xi * bxy[1]); if (dd == 0) { fprintf(stderr, "Case 3 error: &lf\n", dd); return ELIO_ERR; } *eta = ((4 * (x - x0) - *xi * axi[0]) * (aet[0] + *xi * bxy[0]) + (4 * (y - y0) - *xi * axi[1]) * (aet[1] + *xi * bxy[1])) / dd; ; } else { icaseno = 4; beta = aet[1] * axi[0] - aet[0] * axi[1] - 4 * (bxy[1] * (x - x0) - bxy[0] * (y - y0)); dgamma = 4 * (aet[0] * (y - y0) - aet[1] * (x - x0)); delta = beta * beta - 4 * dgamma * dxi; if (delta == 0) { *xi = (-beta / 2.0 / dxi); *eta = (4 * (bxy[1] * (x - x0) - bxy[0] * (y - y0)) - *xi * dxi) / deta; } else if (delta > 0.0) { root_xi[0] = (-beta + sqrt(delta)) / 2 / dxi; root_xi[1] = (-beta - sqrt(delta)) / 2 / dxi; icount = 0; for (i = 0; i < 2; i++) { root_et[i] = (4 * (bxy[1] * (x - x0) - bxy[0] * (y - y0)) - root_xi[i] * dxi) / deta; if (fabs(root_xi[i]) <= 1.1 && fabs(root_et[i]) <= 1.1) { *xi = root_xi[i]; *eta = root_et[i]; icount = icount + 1; } } if (icount == 2 && fabs(root_xi[0] - root_xi[1]) < SMALL) { } else if (icount != 1) { fprintf(stderr, "Abnormal instances %lf %lf %d\n", root_xi[0], root_et[1], icount); return ELIO_ERR; } } else { fprintf(stderr, "No roots %lf\n", delta); return ELIO_ERR; } } if (fabs(*xi) > 1.1 || fabs(*eta) > 1.1) { fprintf(stderr, "Out of bound in ibilinear %lf %lf\n", *xi, *eta); return ELIO_ERR; } *xi = (*xi > -1.0) ? *xi : -1.0; *eta = (*eta > -1.0) ? *eta : -1.0; *xi = (*xi < 1.0) ? *xi : 1.0; *eta = (*eta < 1.0) ? *eta : 1.0; //xi=dmin1(1.0,dmax1(xi,-1.0)); //eta=dmin1(1.0,dmax1(eta,-1.0)); shapef[0] = (1 - *xi) * (1 - *eta) / 4; shapef[1] = (1 + *xi) * (1 - *eta) / 4; shapef[2] = (1 + *xi) * (1 + *eta) / 4; shapef[3] = (1 - *xi) * (1 + *eta) / 4; return ELIO_OK; } static double C(double sigma, ElcircHeader * h) { return (1 - h->thetab) * sinh(h->thetaf * sigma) / sinh(h->thetaf) + h->thetab * (tanh(h->thetaf * (sigma + 0.5)) - tanh(h->thetaf * 0.5)) / (2.0 * tanh(h->thetaf * 0.5)); } /*! * Compute the depth at a given node and level for a sigma grid. * * Input variables: * * \param node = Node number starting from 0 * \param level = Level number starting from 0 * \param eh = Pointer to populated ElcircHeader struct * * Returns depth. * * Fortran code from ELCIRC * * do k=1,nvrt * z(i,k)=peta(i)*(1+sigma(k))+h_c*sigma(k)+(dp(i)-h_c)*cs(k) * ! Abnormal cases * if(ivcor==2.and.(dp(i)<=h_c.or.peta(i)<=-h_c-(dp(i)-h_c)*theta_f/dsinh(theta_f))) then * iback(i)=0 * z(i,k)=peta(i)*(1+sigma(k))+dp(i)*sigma(k) * endif * if(k>=2.and.z(i,k)-z(i,k-1)<=0) then * write(11,*)'Inverted z-levels at:',i,k,z(i,k)-z(i,k-1),peta(i),dp(i) * stop * endif * enddo !k * */ double ElioGetSigmaDepthAtNode(int node, int level, float eta, ElcircHeader * eh) { double z, sigma, h; sigma = eh->zcor[level]; h = eh->d[node]; if (eh->ivcor == 1) { z = (h + eta) * sigma + eta; } else if (eh->ivcor == 2) { if ((eta + h) > eh->h0 && h > eh->hc && eta > (-eh->hc - (h - eh->hc) * eh->thetaf / sinh(eh->thetaf))) { z = eta * (1.0 + sigma) + eh->hc * eta + (h - eh->hc) * C(sigma, eh); } else { z = (h + eta) * sigma + eta; } } return z; } int ElioGetSigmaDepth(int node, float eta, ElcircHeader * eh, double *depths) { double z, sigma, h; int i; for (i = 0; i < eh->nvrt; i++) { depths[i] = ElioGetSigmaDepthAtNode(node, i, eta, eh); } return ELIO_OK; } /*! * Compute the depth at a given XY location and level for a sigma grid. * * Input variables: * * \param x = X co-ordinate of location * \param y = Y co-ordinate of location * \param level = Level number starting from 0 * \param eh = Pointer to populated ElcircHeader struct * * Returns depth. * */ double ElioGetSigmaDepthAtXY(double x, double y, int level, float e, ElcircHeader * eh) { double H, h, eta, sigma; /* Need to interpolate elevation and depth */ //H = eh->d[node] + e; h = H * eh->zcor[level] + e; return h; } /*! * Compute the depth at a given XYZ location for a sigma grid. * * Input variables: * * \param x = X co-ordinate of location * \param y = Y co-ordinate of location * \param z = z co-ordinate of location * \param eh = Pointer to populated ElcircHeader struct * * Returns depth. * */ double ElioGetSigmaDepthAtXYZ(double x, double y, double z, float e, ElcircHeader * eh) { double H, h, eta, sigma; //H = eh->d[node] + e; //h = H * eh->zcor[level] + e; return h; } /*! * Return the min/max value in an array of doubles, utility function. * * Input variables: * * \param n = Number of doubles. * \param ar = Pointer to the doubles - assumed to be a valid pointer. * * Returns minimum double found in the array. * */ int ElioMinMax(int n, double *ar, double *dmin, double *dmax) { int i; if (ar == (double *) NULL) { return ELIO_ERR; } *dmax = *dmin = ar[0]; for (i = 1; i < n; i++) { if (*dmin > ar[i]) { *dmin = ar[i]; } if (*dmax < ar[i]) { *dmax = ar[i]; } } return ELIO_OK; } /*! * Return the minimum value in an array of ints, utility function. * * Input variables: * * \param n = Number of integers. * \param iar = Pointer to the integers - assumed to be a valid pointer. * * Returns minimum integer found in the array. * */ int ElioIntMin(int n, int *iar) { int i, im = 0; im = iar[0]; for (i = 1; i < n; i++) { if (im > iar[i]) { im = iar[i]; } } return im; } /*! * Return the maximum value in an array of ints, utility function. * * Input variables: * * \param n = Number of integers. * \param iar = Pointer to the integers - assumed to be a valid pointer. * * Returns maximum integer found in the array. * */ int ElioIntMax(int n, int *iar) { int i, im = 0; im = iar[0]; for (i = 1; i < n; i++) { if (im < iar[i]) { im = iar[i]; } } return im; } /*! * Return the numeric file version number 2, 3, 4 * * Input variables: * * \param fname = File name. * */ int ElioGetFileVersion(char *fname) { FILE *fp; char magic[50]; fp = fopen(fname, "rb"); if (fp == NULL) { fprintf(stderr, "ElioGetFileVersion(): Unable to open file %s\n", fname); return -1; } if (fread(magic, sizeof(char), 48, fp) != 48) return ELIO_FREAD_ERR; magic[48] = 0; /* DataFormat v3.0 */ if (strncmp(magic, "DataFormat v4.0", 15) == 0) { return 4; } else if (strncmp(magic, "DataFormat v5.0", 15) == 0) { return 5; } else if (strncmp(magic, "DataFormat v3.0", 15) == 0) { return 3; } else if (strncmp(magic, "DataFormat v2.0", 15) == 0) { return 2; } else { return -1; } fclose(fp); } /*! * Find the interval in an array containing the double d, return -1 * if no interval found. Data point is located in between index returned * and index + 1. * * Input variables: * * \param n = Number of items in *data. * \param data = Array to search. * \param d = Item to locate. * * Returns 0 based index found or -1 if less than or n if greater than. * */ int ElioFindIndex(int n, double *data, double d) { int i; if (d < data[0]) { return -1; } if (d > data[n - 1]) { return n; } for (i = 0; i < n - 1; i++) { if (d >= data[i] && d <= data[i + 1]) { return i; } } /* Not reached */ return -1; } /*! * Given an array of depths and scalar quatities, interpolate * the scalar values to all the points in *zp. Clamp to values at * either end if point to find is out of range. Output to *sp. * * Input variables: * * \param n = Number of items in *z. * \param z = Depths. * \param s = Scalar value. * \param np = number of points to interpolate. * \param zp = Depths to interpolate to. * \param sp = Interpolated scalar values. */ void ElioInterpolateArray(int n, double *z, double *s, int np, double *zp, double *sp) { int i, j, l1, l2; double tmp; for (j = 0; j < np; j++) { /* Use minimum value */ if (zp[j] < z[0]) { sp[j] = s[0]; /* Use maximum value */ } else if (zp[j] > z[n - 1]) { sp[j] = s[n - 1]; /* Use interpolated value */ } else { for (i = 0; i < n - 1; i++) { l1 = i; l2 = i + 1; if (zp[j] >= z[l1] && zp[j] <= z[l2]) { break; } } tmp = (z[l2] - z[l1]); if (tmp != 0.0) { sp[j] = (zp[j] - z[l1]) / (z[l2] - z[l1]) * (s[l2] - s[l1]) + s[l1]; } else { fprintf(stderr, "Elio: In ElioInterpolateArray(), z[l2] - z[l1] == 0.0\n"); sp[j] = -9999.0; } } } } /*! * Given an array of depths and scalar quantities, interpolate * a scalar value given the depth. Clamp to value at * either end if point to find is out of range. returns the * interplated value. * * Input variables: * * \param n = Number of items in *z. * \param z = Depths. * \param s = Scalar value. * \param zp = Depth to interpolate to. */ double ElioInterpolate(int n, double *z, double *s, double zp) { int i, l1, l2; double sp = 0.0; double tmp; /* Use minimum value */ if (zp < z[0]) { sp = s[0]; /* Use maximum value */ } else if (zp > z[n - 1]) { sp = s[n - 1]; /* Use interpolated value */ } else { for (i = 0; i < n - 1; i++) { l1 = i; l2 = i + 1; if (zp >= z[l1] && zp <= z[l2]) { break; } } tmp = (z[l2] - z[l1]); if (tmp != 0.0) { sp = (zp - z[l1]) / (z[l2] - z[l1]) * (s[l2] - s[l1]) + s[l1]; } else { fprintf(stderr, "Elio: In ElioInterpolate(), z[l2] - z[l1] == 0.0\n"); sp = -9999.0; } } return sp; } /*! * Given an array of depths and scalar quantities, interpolate * a scalar value given the index as found from ElioFindIndex(). * Clamp to value at either end if point to find is out of range. * * Input variables: * * \param n = Number of items in *z. * \param z = Depths. * \param s = Scalar value. * \param ind = Index value. * \param zp = Depth to use for interpolation. */ double ElioInterpolateAtIndex(int n, double *z, double *s, int ind, double zp) { int i, l1, l2; double sp = 0.0; double tmp; /* Use minimum value */ if (ind < 0) { sp = s[0]; /* Use maximum value */ } else if (ind == n) { sp = s[n - 1]; /* Use interpolated value */ } else { l1 = ind; l2 = ind + 1; tmp = (z[l2] - z[l1]); if (tmp != 0.0) { sp = (zp - z[l1]) / (z[l2] - z[l1]) * (s[l2] - s[l1]) + s[l1]; } else { //fprintf(stderr, "Elio: In ElioInterpolateAtIndex(), z[l2] - z[l1] == 0.0\n"); sp = -9999.0; } } return sp; } /*! * Given an array of depths and scalar quantities, interpolate * a scalar value given the index as found from ElioFindIndex(). * Clamp to value at either end if point to find is out of range. * * Input variables: * * \param n = Number of items in *z. * \param z = Depths. * \param s = Scalar value. * \param ind = Index value. * \param zp = Depth to use for interpolation. */ int ElioMakeDepthsOld(ElcircHeader * h, float *d, float *dd) { int i, j, k; for (i = 0; i < h->np * h->nvrt; i++) { dd[i] = -99.0; } for (j = 0; j < h->np; j++) { // Fill in missing depth values in file - only for Z levels. for (k = 0; k < h->kz; k++) { dd[j * h->nvrt + k] = h->zcor[k]; } // Fill in depth values from zcor. for (k = h->bi[j]; k < h->nvrt; k++) { dd[j * h->nvrt + k] = d[h->no[j] + k - h->bi[j]]; } } return ELIO_OK; } /*! * Replace the nodes in the grid h with the nodes found in grid g. * * Useful for transforming a run done in one projection to another. * */ int ElioReplaceElcircGrid(ElcircHeader * h, ElioGrid * g) { int i; if (h->np != g->np) { return ELIO_ERR; } for (i = 0; i < g->np; i++) { h->x[i] = g->x[i]; h->y[i] = g->y[i]; } return ELIO_OK; } /*! * Get the grid from a header and stuff it in an ElioGrid struture * */ int ElioGetGrid(ElcircHeader * h, ElioGrid * g) { int i; g->ne = h->ne; g->np = h->np; g->x = (double *) malloc(g->np * sizeof(double)); g->y = (double *) malloc(g->np * sizeof(double)); g->d = (double *) malloc(g->np * sizeof(double)); g->etype = (int *) malloc(g->ne * sizeof(int)); for (i = 0; i < 4; i++) { g->icon[i] = (int *) malloc(g->ne * sizeof(int)); } for (i = 0; i < g->np; i++) { g->x[i] = h->x[i]; g->y[i] = h->y[i]; g->d[i] = h->d[i]; } for (i = 0; i < g->ne; i++) { g->etype[i] = h->etype[i]; g->icon[0][i] = h->icon[0][i]; g->icon[1][i] = h->icon[1][i]; g->icon[2][i] = h->icon[2][i]; if (g->etype[i] == 4) { g->icon[3][i] = h->icon[3][i]; } } return ELIO_OK; }
27.048225
175
0.541133
[ "shape", "vector", "3d" ]
1f1b0080a0846d7f2c8313d96c3242bfe3ae4d78
13,367
h
C
CDAWiFi/CDAWiFi/CDAWiFiTypes.h
colemancda/CoreWLAN-ObjFW
e53bc1d7034fa2a7fde662eb676a551f76042b2e
[ "MIT" ]
2
2015-03-01T06:30:02.000Z
2021-02-01T10:19:47.000Z
CDAWiFi/CDAWiFi/CDAWiFiTypes.h
colemancda/CoreWLAN-ObjFW
e53bc1d7034fa2a7fde662eb676a551f76042b2e
[ "MIT" ]
null
null
null
CDAWiFi/CDAWiFi/CDAWiFiTypes.h
colemancda/CoreWLAN-ObjFW
e53bc1d7034fa2a7fde662eb676a551f76042b2e
[ "MIT" ]
null
null
null
// // CDAWiFiTypes.h // CDAWiFi // // Created by Alsey Coleman Miller on 2/28/15. // Copyright (c) 2015 ColemanCDA. All rights reserved. // /*! * @typedef CWErr * * @abstract Error codes corresponding to the CWErrorDomain domain. * * @constant CDAWiFiNoErr * Success. * * @constant CDAWiFiEAPOLErr * EAPOL-related error. * * @constant CDAWiFiInvalidParameterErr * Parameter error. * * @constant CDAWiFiNoMemoryErr * Memory allocation failed. * * @constant CDAWiFiUnknownErr * Unexpected error condition encountered for which no error code exists. * * @constant CDAWiFiNotSupportedErr * Operation not supported. * * @constant CDAWiFiInvalidFormatErr * Invalid protocol element field detected. * * @constant CDAWiFiTimeoutErr * Operation timed out. * * @constant CDAWiFiUnspecifiedFailureErr * Access point did not specify a reason for authentication/association failure. * * @constant CDAWiFiUnsupportedCapabilitiesErr * Access point cannot support all requested capabilities. * * @constant CDAWiFiReassociationDeniedErr * Reassociation was denied because the access point was unable to determine that an association exists. * * @constant CDAWiFiAssociationDeniedErr * Association was denied for an unspecified reason. * * @constant CDAWiFiAuthenticationAlgorithmUnsupportedErr * Specified authentication algorithm is not supported. * * @constant CDAWiFiInvalidAuthenticationSequenceNumberErr * Authentication frame received with an authentication sequence number out of expected sequence. * * @constant CDAWiFiChallengeFailureErr * Authentication was rejected because of a challenge failure. * * @constant CDAWiFiAPFullErr * Access point is unable to handle another associated station. * * @constant CDAWiFiUnsupportedRateSetErr * Interface does not support all of the rates in the basic rate set of the access point. * * @constant CDAWiFiShortSlotUnsupportedErr * Association denied because short slot time option is not supported by requesting station. * * @constant CDAWiFiDSSSOFDMUnsupportedErr * Association denied because DSSS-OFDM is not supported by requesting station. * * @constant CDAWiFiInvalidInformationElementErr * Invalid information element included in association request. * * @constant CDAWiFiInvalidGroupCipherErr * Invalid group cipher requested. * * @constant CDAWiFiInvalidPairwiseCipherErr * Invalid pairwise cipher requested. * * @constant CDAWiFiInvalidAKMPErr * Invalid authentication selector requested. * * @constant CDAWiFiUnsupportedRSNVersionErr * Invalid WPA/WPA2 version specified. * * @constant CDAWiFiInvalidRSNCapabilitiesErr * Invalid RSN capabilities specified in association request. * * @constant CDAWiFiCipherSuiteRejectedErr * Cipher suite rejected due to network security policy. * * @constant CDAWiFiInvalidPMKErr * PMK rejected by the access point. * * @constant CDAWiFiSupplicantTimeoutErr * WPA/WPA2 handshake timed out. * * @constant CDAWiFiHTFeaturesNotSupportedErr * Association was denied because the requesting station does not support HT features. * * @constant CDAWiFiPCOTransitionTimeNotSupportedErr * Association was denied because the requesting station does not support the PCO transition time required by the AP. * * @constant CDAWiFiReferenceNotBoundErr * No interface is bound to the CWInterface object. * * @constant CDAWiFiIPCFailureErr * Error communicating with a separate process. * * @constant CDAWiFiOperationNotPermittedErr * Calling process does not have permission to perform this operation. * * @constant CDAWiFiErr * Generic error, no specific error code exists to describe the error condition. */ /* Error codes corresponding to the CDAWiFiErrorDomain domain. */ typedef enum { CDAWiFiNoError = 0, CDAWiFiEAPOLError = 1, CDAWiFiInvalidParameterError = -3900, CDAWiFiNoMemoryError = -3901, CDAWiFiUnknownError = -3902, CDAWiFiNotSupportedError = -3903, CDAWiFiInvalidFormatError = -3904, CDAWiFiTimeoutError = -3905, CDAWiFiUnspecifiedFailureError = -3906, CDAWiFiUnsupportedCapabilitiesError = -3907, CDAWiFiReassociationDeniedError = -3908, CDAWiFiAssociationDeniedError = -3909, CDAWiFiAuthenticationAlgorithmUnsupportedError = -3910, CDAWiFiInvalidAuthenticationSequenceNumberError = -3911, CDAWiFiChallengeFailureError = -3912, CDAWiFiAPFullError = -3913, CDAWiFiUnsupportedRateSetError = -3914, CDAWiFiShortSlotUnsupportedError = -3915, CDAWiFiDSSSOFDMUnsupportedError = -3916, CDAWiFiInvalidInformationElementError = -3917, CDAWiFiInvalidGroupCipherError = -3918, CDAWiFiInvalidPairwiseCipherError = -3919, CDAWiFiInvalidAKMPError = -3920, CDAWiFiUnsupportedRSNVersionError = -3921, CDAWiFiInvalidRSNCapabilitiesError = -3922, CDAWiFiCipherSuiteRejectedError = -3923, CDAWiFiInvalidPMKError = -3924, CDAWiFiSupplicantTimeoutError = -3925, CDAWiFiHTFeaturesNotSupportedError = -3926, CDAWiFiPCOTransitionTimeNotSupportedError = -3927, CDAWiFiReferenceNotBoundError = -3928, CDAWiFiIPCFailureError = -3929, CDAWiFiOperationNotPermittedError = -3930, /* Generic error, no specific error code exists to describe the error condition. */ CDAWiFiGenericError = -3931, } CDAWiFiError; /*! * @typedef CWPHYMode * * @abstract Type describing the IEEE 802.11 physical layer mode. * * @constant CDAWiFiPHYModeNone * * @constant CDAWiFiPHYMode11a * IEEE 802.11a physical layer mode. * * @constant CDAWiFiPHYMode11b * IEEE 802.11b physical layer mode. * * @constant CDAWiFiPHYMode11g * IEEE 802.11g physical layer mode. * * @constant CDAWiFiPHYMode11n * IEEE 802.11n physical layer mode. * * @constant CDAWiFiPHYMode11ac * IEEE 802.11ac physical layer mode. */ typedef enum { CDAWiFiPHYModeNone = 0, CDAWiFiPHYMode11a = 1, CDAWiFiPHYMode11b = 2, CDAWiFiPHYMode11g = 3, CDAWiFiPHYMode11n = 4, CDAWiFiPHYMode11ac = 5, } CDAWiFiPHYMode; /*! * @typedef CWInterfaceMode * * @abstract Wi-Fi interface operating modes returned by -[CWInterface interfaceMode]. * * @constant CDAWiFiInterfaceModeNone * Interface is not in any mode. * * @constant CDAWiFiInterfaceModeStation * Interface is participating in an infrastructure network as a non-AP station. * * @constant CDAWiFiInterfaceModeIBSS * Interface is participating in an IBSS network. * * @constant CDAWiFiInterfaceModeHostAP * Interface is participating in an infrastructure network as an access point. */ typedef enum { CDAWiFiInterfaceModeNone = 0, CDAWiFiInterfaceModeStation = 1, CDAWiFiInterfaceModeIBSS = 2, CDAWiFiInterfaceModeHostAP = 3, } CDAWiFiInterfaceMode; /*! * @typedef CWSecurity * * @abstract Wi-Fi security types. * * @constant CDAWiFiSecurityNone * Open System authentication. * * @constant CDAWiFiSecurityWEP * WEP security. * * @constant CDAWiFiSecurityWPAPersonal * WPA Personal authentication. * * @constant CDAWiFiSecurityWPAPersonalMixed * WPA/WPA2 Personal authentication. * * @constant CDAWiFiSecurityWPA2Personal * WPA2 Personal authentication. * * @constant CDAWiFiSecurityDynamicWEP * Dynamic WEP security. * * @constant CDAWiFiSecurityWPAEnterprise * WPA Enterprise authentication. * * @constant CDAWiFiSecurityWPAEnterpriseMixed * WPA/WPA2 Enterprise authentication. * * @constant CDAWiFiSecurityWPA2Enterprise * WPA2 Enterprise authentication. * * @constant CDAWiFiSecurityUnknown * Unknown security type. */ typedef enum { CDAWiFiSecurityNone = 0, CDAWiFiSecurityWEP = 1, CDAWiFiSecurityWPAPersonal = 2, CDAWiFiSecurityWPAPersonalMixed = 3, CDAWiFiSecurityWPA2Personal = 4, CDAWiFiSecurityPersonal = 5, CDAWiFiSecurityDynamicWEP = 6, CDAWiFiSecurityWPAEnterprise = 7, CDAWiFiSecurityWPAEnterpriseMixed = 8, CDAWiFiSecurityWPA2Enterprise = 9, CDAWiFiSecurityEnterprise = 10, CDAWiFiSecurityUnknown = INTMAX_MAX, } CDAWiFiSecurity; /*! * @typedef CWIBSSModeSecurity * * @abstract IBSS security types used in -[CWInterface startIBSSModeWithSSID:security:channel:password:error:]. * * @constant CDAWiFiIBSSModeSecurityNone * Open System authentication. * * @constant CDAWiFiIBSSModeSecurityWEP40 * WEP security. * * @constant CDAWiFiIBSSModeSecurityWEP104 * WPA Personal authentication. */ typedef enum { CDAWiFiIBSSModeSecurityNone = 0, CDAWiFiIBSSModeSecurityWEP40 = 1, CDAWiFiIBSSModeSecurityWEP104 = 2, } CDAWiFiIBSSModeSecurity; /*! * @typedef CWChannelWidth * * @abstract Channel width values returned by -[CWChannel channelWidth]. * * @constant CDAWiFiChannelWidthUnknown * Unknown channel width. * * @constant CDAWiFiChannelWidth20MHz * 20MHz channel width. * * @constant CDAWiFiChannelWidth40MHz * 40MHz channel width. * * @constant CDAWiFiChannelWidth80MHz * 80MHz channel width. * * @constant CDAWiFiChannelWidth160MHz * 160MHz channel width. */ typedef enum { CDAWiFiChannelWidthUnknown = 0, CDAWiFiChannelWidth20MHz = 1, CDAWiFiChannelWidth40MHz = 2, CDAWiFiChannelWidth80MHz = 3, CDAWiFiChannelWidth160MHz = 4, } CDAWiFiChannelWidth; /*! * @typedef CWChannelBand * * @abstract Channel band values returned by -[CWChannel channelBand]. * * @constant CDAWiFiChannelBandUnknown * Unknown channel band. * * @constant CDAWiFiChannelBand2GHz * 2.4GHz channel band. * * @constant CDAWiFiChannelBand5GHz * 5GHz channel band. */ typedef enum { CDAWiFiChannelBandUnknown = 0, CDAWiFiChannelBand2GHz = 1, CDAWiFiChannelBand5GHz = 2, } CDAWiFiChannelBand; /*! * @typedef CWCipherKeyFlags * * @abstract Cipher key flags used in -[CWInterface setWEPKey:flags:index:error:]. * * @constant CDAWiFiCipherKeyFlagsNone * Open System authentication. * * @constant CDAWiFiCipherKeyFlagsUnicast * Cipher key will be used for unicast packets. * * @constant CDAWiFiCipherKeyFlagsMulticast * Cipher key will be used for multicast packets. * * @constant CDAWiFiCipherKeyFlagsTx * Cipher key will be used for packets sent from the interface. * * @constant CDAWiFiCipherKeyFlagsRx * Cipher key will be used for packets received by the interface. */ typedef enum { CDAWiFiCipherKeyFlagsNone = 0, CDAWiFiCipherKeyFlagsUnicast = (1UL << 1), CDAWiFiCipherKeyFlagsMulticast = (1UL << 2), CDAWiFiCipherKeyFlagsTx = (1UL << 3), CDAWiFiCipherKeyFlagsRx = (1UL << 4), } CDAWiFiCipherKeyFlags; /*! * @typedef CWKeychainDomain * * @abstract Keychain domain types used by CoreWLAN keychain methods. * * @constant CDAWiFiKeychainDomainNone * No keychain domain specified. * * @constant CDAWiFiKeychainDomainUser * The user keychain domain. If iCloud Keychain is enabled, the iCloud keychain is the user keychain. * * @constant CDAWiFiKeychainDomainSystem * The system keychain domain. */ typedef enum { CDAWiFiKeychainDomainNone = 0, CDAWiFiKeychainDomainUser = 1, CDAWiFiKeychainDomainSystem = 2, } CDAWiFiKeychainDomain; /*! * @typedef CWEventType * * @abstract Wi-Fi event types used in -[CWWiFiClient startMonitoringEventWithType:error:]. * * @constant CWEventTypeNone * No event type specified. * * @constant CWEventTypePowerDidChange * Posted when the power state of any Wi-Fi interface changes. * * @constant CWEventTypeSSIDDidChange * Posted when the current SSID of any Wi-Fi interface changes. * * @constant CWEventTypeBSSIDDidChange * Posted when the current BSSID of any Wi-Fi interface changes. * * @constant CWEventTypeCountryCodeDidChange * Posted when the adopted country code of any Wi-Fi interface changes. * * @constant CWEventTypeLinkDidChange * Posted when the link state for any Wi-Fi interface changes. * * @constant CWEventTypeLinkQualityDidChange * Posted when the RSSI or transmit rate for any Wi-Fi interface changes. * * @constant CWEventTypeModeDidChange * Posted when the operating mode of any Wi-Fi interface changes. * * @constant CWEventTypeScanCacheUpdated * Posted when the scan cache of any Wi-Fi interface is updated with new scan results. * * @constant CWEventTypeUnknown * Unknown event type. */ typedef enum { CDAWiFiEventTypeNone = 0, CDAWiFiEventTypePowerDidChange = 1, CDAWiFiEventTypeSSIDDidChange = 2, CDAWiFiEventTypeBSSIDDidChange = 3, CDAWiFiEventTypeCountryCodeDidChange = 4, CDAWiFiEventTypeLinkDidChange = 5, CDAWiFiEventTypeLinkQualityDidChange = 6, CDAWiFiEventTypeModeDidChange = 7, CDAWiFiEventTypeScanCacheUpdated = 8, CDAWiFiEventTypeUnknown = INTMAX_MAX } CDAWiFiEventType;
30.728736
117
0.720431
[ "object" ]
1f24f53998a04652363cf173a9910be7a176daa6
39,598
c
C
src/W32StrC.c
2kranki/libCmn
4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce
[ "Unlicense" ]
2
2017-03-23T15:23:56.000Z
2021-03-04T09:54:54.000Z
src/W32StrC.c
2kranki/libCmn
4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce
[ "Unlicense" ]
null
null
null
src/W32StrC.c
2kranki/libCmn
4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce
[ "Unlicense" ]
null
null
null
// vi:nu:et:sts=4 ts=4 sw=4 /* * File: W32StrC.c * Generated 01/23/2020 22:22:04 * */ /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> */ //***************************************************************** //* * * * * * * * * * * * Data Definitions * * * * * * * * * * * //***************************************************************** /* Header File Inclusion */ #include <W32StrC_internal.h> #include <crc.h> #include <trace.h> #ifdef __cplusplus extern "C" { #endif /**************************************************************** * * * * * * * * * * * Internal Subroutines * * * * * * * * * * ****************************************************************/ //--------------------------------------------------------------- // F r e e L i n e //--------------------------------------------------------------- bool W32StrC_FreeLine( W32STRC_DATA *this ) { // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate( this ) ) { DEBUG_BREAK(); return false; } #endif if (this->pArray) { if (obj_Flag(this, W32STRC_FLAG_MALLOC)) { mem_Free((void *)this->pArray); obj_FlagOff(this, W32STRC_FLAG_MALLOC); } this->pArray = NULL; this->len = 0; } // Return to caller. return true; } //--------------------------------------------------------------- // S e t u p //--------------------------------------------------------------- bool W32StrC_SetupA( W32STRC_DATA *this, const char *pStrA ) { uint32_t i; W32CHR_T *pInsert; W32CHR_T chr; uint32_t len; // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate( this ) ) { DEBUG_BREAK(); return false; } #endif W32StrC_FreeLine(this); len = (uint32_t)utf8_StrLenA(pStrA); // Create the new string from this one. this->pArray = mem_Malloc((len + 1) * sizeof(W32CHR_T)); if (NULL == this->pArray) { DEBUG_BREAK(); return false; } obj_FlagOn(this, W32STRC_FLAG_MALLOC); // Move in the data. pInsert = (W32CHR_T *)this->pArray; for (i=0; i<len; ++i) { chr = utf8_Utf8ToW32_Scan(&pStrA); *pInsert++ = chr; } *pInsert = '\0'; this->len = len; W32StrC_Reset(this); // Return to caller. return true; } bool W32StrC_SetupW32( W32STRC_DATA *this, uint32_t len, const W32CHR_T *pStrW32 ) { // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate( this ) ) { DEBUG_BREAK(); return false; } #endif W32StrC_FreeLine(this); if (0 == len) { len = (uint32_t)utf8_StrLenW32(pStrW32); } // Create the new string from this one. this->pArray = mem_Malloc((len + 1) * sizeof(W32CHR_T)); if (NULL == this->pArray) { DEBUG_BREAK(); return false; } obj_FlagOn(this, W32STRC_FLAG_MALLOC); // Move in the data. memmove((W32CHR_T *)this->pArray, pStrW32, ((len + 1) * sizeof(W32CHR_T))); this->len = len; W32StrC_Reset(this); // Return to caller. return true; } bool W32StrC_SetupW32Con( W32STRC_DATA *this, uint32_t len, const W32CHR_T *pStrW32 ) { // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate( this ) ) { DEBUG_BREAK(); return false; } #endif W32StrC_FreeLine(this); if (0 == len) { len = (uint32_t)utf8_StrLenW32(pStrW32); } this->pArray = pStrW32; this->len = len; W32StrC_Reset(this); // Return to caller. return true; } /**************************************************************** * * * * * * * * * * * External Subroutines * * * * * * * * * * ****************************************************************/ //=============================================================== // *** Class Methods *** //=============================================================== W32STRC_DATA * W32StrC_Alloc ( void ) { W32STRC_DATA *this; uint32_t cbSize = sizeof(W32STRC_DATA); // Do initialization. this = obj_Alloc( cbSize ); // Return to caller. return this; } W32STRC_DATA * W32StrC_New ( void ) { W32STRC_DATA *this; this = W32StrC_Alloc( ); if (this) { this = W32StrC_Init(this); } return this; } W32STRC_DATA * W32StrC_NewA ( const char *pStrA ) { W32STRC_DATA *this; bool fRc; this = W32StrC_New( ); if (this) { fRc = W32StrC_SetupA(this, pStrA); if (!fRc) { obj_Release(this); this = OBJ_NIL; } } return this; } W32STRC_DATA * W32StrC_NewConW32 ( const W32CHR_T *pStrW32 ) { W32STRC_DATA *this; this = W32StrC_New( ); if (this && pStrW32) { this->pArray = (W32CHR_T *)pStrW32; this->len = (uint32_t)utf8_StrLenW32(pStrW32); } return( this ); } W32STRC_DATA * W32StrC_NewW32 ( const W32CHR_T *pStrW32 ) { W32STRC_DATA *this; bool fRc; this = W32StrC_New( ); if (this) { fRc = W32StrC_SetupW32(this, 0, pStrW32); if (!fRc) { obj_Release(this); this = OBJ_NIL; } } return( this ); } W32STRC_DATA * W32StrC_NewFromW32 ( uint32_t len, const W32CHR_T *pStrW32 ) { W32STRC_DATA *this; bool fRc; this = W32StrC_New( ); if (this) { fRc = W32StrC_SetupW32(this, len, pStrW32); if (!fRc) { obj_Release(this); this = OBJ_NIL; } } return( this ); } //=============================================================== // P r o p e r t i e s //=============================================================== //--------------------------------------------------------------- // C R C //--------------------------------------------------------------- uint32_t W32StrC_getCrcIEEE( W32STRC_DATA *this ) { CRC_DATA *pCrc = OBJ_NIL; uint32_t crc = 0; #ifdef NDEBUG #else if( !W32StrC_Validate(this) ) { DEBUG_BREAK(); } #endif pCrc = crc_New(CRC_TYPE_IEEE_32); crc = crc_AccumBlock( pCrc, (this->len * sizeof(W32CHR_T)), (const uint8_t *)this->pArray ); obj_Release(pCrc); pCrc = OBJ_NIL; return crc; } //--------------------------------------------------------------- // D a t a //--------------------------------------------------------------- const W32CHR_T * W32StrC_getData ( W32STRC_DATA *this ) { // Validate the input parameters. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return OBJ_NIL; } #endif return this->pArray; } //--------------------------------------------------------------- // L e n g t h //--------------------------------------------------------------- uint32_t W32StrC_getLength( W32STRC_DATA *this ) { #ifdef NDEBUG #else if( !W32StrC_Validate(this) ) { DEBUG_BREAK(); } #endif return this->len; } //--------------------------------------------------------------- // S i z e //--------------------------------------------------------------- uint32_t W32StrC_getSize ( W32STRC_DATA *this ) { #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return 0; } #endif return this->len; } //--------------------------------------------------------------- // S u p e r //--------------------------------------------------------------- OBJ_IUNKNOWN * W32StrC_getSuperVtbl ( W32STRC_DATA *this ) { // Validate the input parameters. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return 0; } #endif return this->pSuperVtbl; } //=============================================================== // M e t h o d s //=============================================================== //--------------------------------------------------------------- // A d v a n c e //--------------------------------------------------------------- void W32StrC_Advance ( W32STRC_DATA *this, int32_t offset ) { //ERESULT eRc; uint32_t amt; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); // return ERESULT_INVALID_OBJECT; return; } #endif amt = obj_getMisc(this); amt += offset; obj_setMisc(this, amt); } //--------------------------------------------------------------- // A s s i g n //--------------------------------------------------------------- /*! Assign the contents of this object to the other object (ie this -> other). Any objects in other will be released before a copy of the object is performed. Example: @code ERESULT eRc = W32StrC_Assign(this,pOther); @endcode @param this object pointer @param pOther a pointer to another W32STRC object @return If successful, ERESULT_SUCCESS otherwise an ERESULT_* error */ ERESULT W32StrC_Assign ( W32STRC_DATA *this, W32STRC_DATA *pOther ) { ERESULT eRc; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return ERESULT_INVALID_OBJECT; } if (!W32StrC_Validate(pOther)) { DEBUG_BREAK(); return ERESULT_INVALID_OBJECT; } #endif // Assign any Super(s). if (this->pSuperVtbl && (this->pSuperVtbl->pWhoAmI() != OBJ_IDENT_OBJ)) { if (this->pSuperVtbl->pAssign) { eRc = this->pSuperVtbl->pAssign(this, pOther); if (ERESULT_FAILED(eRc)) { return eRc; } } } // Release objects and areas in other object. W32StrC_FreeLine(pOther); // Create a copy of objects and areas in this object placing // them in other. if (this->pArray) { W32StrC_SetupW32(pOther, 0, this->pArray); } // Copy other data from this object to other. //goto eom; // Return to caller. eRc = ERESULT_SUCCESS; eom: return eRc; } //--------------------------------------------------------------- // C o m p a r e //--------------------------------------------------------------- int W32StrC_Compare ( W32STRC_DATA *this, W32STRC_DATA *pOther ) { //ERESULT eRc = ERESULT_SUCCESS_EQUAL; int i = -1; #ifdef xyzzy const char *pStr1; const char *pStr2; #endif #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); //return ERESULT_INVALID_OBJECT; return -2; } if (!W32StrC_Validate(pOther)) { DEBUG_BREAK(); //return ERESULT_INVALID_PARAMETER; return -2; } #endif i = W32Str_Cmp(this->pArray, pOther->pArray); return i; } int W32StrC_CompareA ( W32STRC_DATA *this, const char *pString ) { //ERESULT eRc = ERESULT_SUCCESS_EQUAL; const W32CHR_T *pStr1; W32CHR_T chr2; int i = -1; // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate( this ) ) { DEBUG_BREAK(); //return ERESULT_INVALID_OBJECT; return -2; } if (NULL == pString) { DEBUG_BREAK(); //return ERESULT_INVALID_PARAMETER; return -2; } #endif pStr1 = this->pArray; for( ;; ) { chr2 = utf8_Utf8ToW32_Scan(&pString); if( *pStr1 ) ; else { if( chr2 ) //eRc = ERESULT_SUCCESS_LESS_THAN; i = -1; break; } if( chr2 ) ; else { if( *pStr1 ) //eRc = ERESULT_SUCCESS_GREATER_THAN; i = 1; break; } i = *pStr1 - chr2; if( i ) { break; } ++pStr1; } if (i < 0) i = -1; else if (i > 0) i = 1; // Return to caller. return i; } int W32StrC_CompareW32 ( W32STRC_DATA *this, const W32CHR_T *pString ) { //ERESULT eRc = ERESULT_SUCCESS_EQUAL; int i = -1; // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate( this ) ) { DEBUG_BREAK(); //return ERESULT_INVALID_OBJECT; return -1; } #endif i = W32Str_Cmp(this->pArray, pString); // Return to caller. return i; } //--------------------------------------------------------------- // C o p y //--------------------------------------------------------------- /*! Copy the current object creating a new object. Example: @code W32StrC *pCopy = W32StrC_Copy(this); @endcode @param this object pointer @return If successful, a W32STRC object which must be released, otherwise OBJ_NIL. @warning Remember to release the returned object. */ W32STRC_DATA * W32StrC_Copy ( W32STRC_DATA *this ) { W32STRC_DATA *pOther = OBJ_NIL; #ifdef W32STRC_IS_CONSTANT #else ERESULT eRc; #endif // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return OBJ_NIL; } #endif #ifdef W32STRC_IS_CONSTANT obj_Retain(this); pOther = this; #else pOther = W32StrC_New( ); if (pOther) { eRc = W32StrC_Assign(this, pOther); if (ERESULT_HAS_FAILED(eRc)) { obj_Release(pOther); pOther = OBJ_NIL; } } #endif // Return to caller. //obj_Release(pOther); return pOther; } //--------------------------------------------------------------- // D e a l l o c //--------------------------------------------------------------- void W32StrC_Dealloc ( OBJ_ID objId ) { W32STRC_DATA *this = objId; //ERESULT eRc; // Do initialization. if (NULL == this) { return; } #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return; } #endif #ifdef XYZZY if (obj_IsEnabled(this)) { ((W32STRC_VTBL *)obj_getVtbl(this))->devVtbl.pStop((OBJ_DATA *)this,NULL); } #endif W32StrC_FreeLine(this); obj_setVtbl(this, this->pSuperVtbl); // pSuperVtbl is saved immediately after the super // object which we inherit from is initialized. this->pSuperVtbl->pDealloc(this); this = OBJ_NIL; // Return to caller. } //--------------------------------------------------------------- // D e e p C o p y //--------------------------------------------------------------- /*! Copy the current object creating a new object. Example: @code W32StrC *pDeepCopy = W32StrC_Copy(this); @endcode @param this object pointer @return If successful, a W32STRC object which must be released, otherwise OBJ_NIL. @warning Remember to release the returned object. */ W32STRC_DATA * W32StrC_DeepyCopy ( W32STRC_DATA *this ) { W32STRC_DATA *pOther = OBJ_NIL; ERESULT eRc; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return OBJ_NIL; } #endif pOther = W32StrC_New( ); if (pOther) { eRc = W32StrC_Assign(this, pOther); if (ERESULT_HAS_FAILED(eRc)) { obj_Release(pOther); pOther = OBJ_NIL; } } // Return to caller. return pOther; } //--------------------------------------------------------------- // D i s a b l e //--------------------------------------------------------------- /*! Disable operation of this object. @param this object pointer @return if successful, ERESULT_SUCCESS. Otherwise, an ERESULT_* error code. */ ERESULT W32StrC_Disable ( W32STRC_DATA *this ) { //ERESULT eRc; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return ERESULT_INVALID_OBJECT; } #endif // Put code here... obj_Disable(this); // Return to caller. return ERESULT_SUCCESS; } //--------------------------------------------------------------- // E n a b l e //--------------------------------------------------------------- /*! Enable operation of this object. @param this object pointer @return if successful, ERESULT_SUCCESS. Otherwise, an ERESULT_* error code. */ ERESULT W32StrC_Enable ( W32STRC_DATA *this ) { //ERESULT eRc; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return ERESULT_INVALID_OBJECT; } #endif obj_Enable(this); // Put code here... // Return to caller. return ERESULT_SUCCESS; } //--------------------------------------------------------------- // H a s h //--------------------------------------------------------------- uint32_t W32StrC_Hash( W32STRC_DATA *this ) { uint32_t hash = 0; #ifdef NDEBUG #else if( !W32StrC_Validate(this) ) { DEBUG_BREAK(); } #endif if (this->pArray) { hash = str_HashW32(this->pArray, NULL); } return hash; } //--------------------------------------------------------------- // I n i t //--------------------------------------------------------------- W32STRC_DATA * W32StrC_Init ( W32STRC_DATA *this ) { uint32_t cbSize = sizeof(W32STRC_DATA); //ERESULT eRc; if (OBJ_NIL == this) { return OBJ_NIL; } /* cbSize can be zero if Alloc() was not called and we are * are passed the address of a zero'd area. */ //cbSize = obj_getSize(this); // cbSize must be set in Alloc(). if (cbSize == 0) { DEBUG_BREAK(); obj_Release(this); return OBJ_NIL; } //this = (OBJ_ID)other_Init((OTHER_DATA *)this); // Needed for Inheritance this = (OBJ_ID)obj_Init(this, cbSize, OBJ_IDENT_W32STRC); if (OBJ_NIL == this) { DEBUG_BREAK(); obj_Release(this); return OBJ_NIL; } //obj_setSize(this, cbSize); // Needed for Inheritance this->pSuperVtbl = obj_getVtbl(this); obj_setVtbl(this, (OBJ_IUNKNOWN *)&W32StrC_Vtbl); JsonIn_RegisterClass(W32StrC_Class()); /* this->pArray = objArray_New( ); if (OBJ_NIL == this->pArray) { DEBUG_BREAK(); obj_Release(this); return OBJ_NIL; } */ #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); obj_Release(this); return OBJ_NIL; } #if defined(__APPLE__) && defined(XYZZY) fprintf( stderr, "W32StrC::sizeof(W32STRC_DATA) = %lu\n", sizeof(W32STRC_DATA) ); #endif BREAK_NOT_BOUNDARY4(sizeof(W32STRC_DATA)); #endif return this; } //--------------------------------------------------------------- // I s E n a b l e d //--------------------------------------------------------------- ERESULT W32StrC_IsEnabled ( W32STRC_DATA *this ) { //ERESULT eRc; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return ERESULT_INVALID_OBJECT; } #endif if (obj_IsEnabled(this)) { return ERESULT_SUCCESS_TRUE; } // Return to caller. return ERESULT_SUCCESS_FALSE; } //--------------------------------------------------------------- // L e f t //--------------------------------------------------------------- W32STRC_DATA * W32StrC_Left( W32STRC_DATA *this, uint32_t len ) { W32STRC_DATA *pNewStr = OBJ_NIL; // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate(this) ) { DEBUG_BREAK(); return OBJ_NIL; } if (len == 0) { DEBUG_BREAK(); return OBJ_NIL; } #endif // Create the new string from this one. pNewStr = W32StrC_Mid(this, 1, len); // Return to caller. return pNewStr; } //--------------------------------------------------------------- // L o o k A h e a d //--------------------------------------------------------------- W32CHR_T W32StrC_LookAhead( W32STRC_DATA *this, uint32_t offset // Relative to 1 ) { //ERESULT eRc; uint32_t amt = 0; W32CHR_T chr = 0; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); // return ERESULT_INVALID_OBJECT; return 0; } #endif amt = obj_getMisc(this); amt += offset - 1; if (amt < W32StrC_getLength(this)) chr = this->pArray[amt]; return chr; } //--------------------------------------------------------------- // M a t c h //--------------------------------------------------------------- bool W32StrC_MatchChr( W32STRC_DATA *this, W32CHR_T chr ) { int32_t index; bool fMatch = true; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); // return ERESULT_INVALID_OBJECT; return 0; } #endif index = obj_getMisc(this); if (index < W32StrC_getLength(this)) ; else { return false; } if (chr == this->pArray[index]) ; else { fMatch = false; } if (fMatch) { obj_setMisc(this, index+1); } return fMatch; } bool W32StrC_MatchStrA( W32STRC_DATA *this, const char *pStrA ) { W32CHR_T chr; int32_t index; int32_t len = 0; bool fMatch = true; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); // return ERESULT_INVALID_OBJECT; return 0; } #endif index = obj_getMisc(this); if (index < W32StrC_getLength(this)) ; else { return false; } for (;;) { chr = utf8_Utf8ToW32_Scan( &pStrA ); if (chr == '\0') { if (len) break; else { fMatch = false; } break; } if (chr == this->pArray[index]) { ++index; ++len; } else { fMatch = false; break; } } if (fMatch) { obj_setMisc(this, index); } return fMatch; } //--------------------------------------------------------------- // M i d //--------------------------------------------------------------- W32STRC_DATA * W32StrC_Mid( W32STRC_DATA *this, uint32_t offset, /* Relative to 1 */ uint32_t len ) { W32STRC_DATA *pNewStr = OBJ_NIL; uint32_t lenStr = W32StrC_getLength(this); W32CHR_T *pArray; // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate(this) ) { DEBUG_BREAK(); return OBJ_NIL; } if (offset > lenStr) { DEBUG_BREAK(); return OBJ_NIL; } if (len == 0) { DEBUG_BREAK(); return OBJ_NIL; } if ((0 == lenStr) || ((offset + len - 1) > lenStr)) { DEBUG_BREAK(); return OBJ_NIL; } #endif // Create the new string from this one. pNewStr = W32StrC_New(); pArray = mem_Malloc((len + 1) * sizeof(W32CHR_T)); if (NULL == pArray) { DEBUG_BREAK(); obj_Release(pNewStr); return OBJ_NIL; } memmove(pArray, &this->pArray[offset-1], (len * sizeof(W32CHR_T))); pArray[len] = 0; pNewStr->pArray = pArray; pNewStr->len = len; obj_FlagOn(pNewStr, W32STRC_FLAG_MALLOC); // Return to caller. return pNewStr; } //--------------------------------------------------------------- // Q u e r y I n f o //--------------------------------------------------------------- /*! Return information about this object. This method can translate methods to strings and vice versa, return the address of the object information structure. Example: @code // Return a method pointer for a string or NULL if not found. void *pMethod = W32StrC_QueryInfo(this, OBJ_QUERYINFO_TYPE_METHOD, "xyz"); @endcode @param objId object pointer @param type one of OBJ_QUERYINFO_TYPE members (see obj.h) @param pData for OBJ_QUERYINFO_TYPE_INFO, this field is not used, for OBJ_QUERYINFO_TYPE_METHOD, this field points to a character string which represents the method name without the object name, "W32StrC", prefix, for OBJ_QUERYINFO_TYPE_PTR, this field contains the address of the method to be found. @return If unsuccessful, NULL. Otherwise, for: OBJ_QUERYINFO_TYPE_INFO: info pointer, OBJ_QUERYINFO_TYPE_METHOD: method pointer, OBJ_QUERYINFO_TYPE_PTR: constant UTF-8 method name pointer */ void * W32StrC_QueryInfo ( OBJ_ID objId, uint32_t type, void *pData ) { W32STRC_DATA *this = objId; const char *pStr = pData; if (OBJ_NIL == this) { return NULL; } #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return NULL; } #endif switch (type) { case OBJ_QUERYINFO_TYPE_OBJECT_SIZE: return (void *)sizeof(W32STRC_DATA); break; case OBJ_QUERYINFO_TYPE_CLASS_OBJECT: return (void *)W32StrC_Class(); break; case OBJ_QUERYINFO_TYPE_DATA_PTR: switch (*pStr) { case 'S': if (str_Compare("SuperClass", (char *)pStr) == 0) { return (void *)(obj_getInfo(this)->pClassSuperObject); } break; default: break; } break; case OBJ_QUERYINFO_TYPE_INFO: return (void *)obj_getInfo(this); break; case OBJ_QUERYINFO_TYPE_METHOD: switch (*pStr) { case 'D': if (str_Compare("Disable", (char *)pStr) == 0) { return W32StrC_Disable; } break; case 'E': if (str_Compare("Enable", (char *)pStr) == 0) { return W32StrC_Enable; } break; case 'P': #ifdef W32STRC_JSON_SUPPORT if (str_Compare("ParseJsonFields", (char *)pStr) == 0) { return W32StrC_ParseJsonFields; } if (str_Compare("ParseJsonObject", (char *)pStr) == 0) { return W32StrC_ParseJsonObject; } #endif break; case 'T': if (str_Compare("ToDebugString", (char *)pStr) == 0) { return W32StrC_ToDebugString; } #ifdef W32STRC_JSON_SUPPORT if (str_Compare("ToJsonFields", (char *)pStr) == 0) { return W32StrC_ToJsonFields; } if (str_Compare("ToJson", (char *)pStr) == 0) { return W32StrC_ToJson; } #endif break; default: break; } break; case OBJ_QUERYINFO_TYPE_PTR: if (pData == W32StrC_ToDebugString) return "ToDebugString"; #ifdef W32STRC_JSON_SUPPORT if (pData == W32StrC_ToJson) return "ToJson"; #endif break; default: break; } return this->pSuperVtbl->pQueryInfo(objId, type, pData); } //--------------------------------------------------------------- // R e s e t //--------------------------------------------------------------- void W32StrC_Reset ( W32STRC_DATA *this ) { //ERESULT eRc; uint32_t amt = 0; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); // return ERESULT_INVALID_OBJECT; return; } #endif obj_setMisc(this, amt); } //--------------------------------------------------------------- // R i g h t //--------------------------------------------------------------- W32STRC_DATA * W32StrC_Right( W32STRC_DATA *this, uint32_t len ) { W32STRC_DATA *pNewStr = OBJ_NIL; // Do initialization. #ifdef NDEBUG #else if( !W32StrC_Validate(this) ) { DEBUG_BREAK(); return OBJ_NIL; } if ((len == 0) || (len > this->len)) { DEBUG_BREAK(); return OBJ_NIL; } #endif // Create the new string from this one. pNewStr = W32StrC_Mid(this, (this->len - len + 1), len); // Return to caller. return pNewStr; } //--------------------------------------------------------------- // T o S t r i n g //--------------------------------------------------------------- /*! Create a string that describes this object and the objects within it. Example: @code ASTR_DATA *pDesc = W32StrC_ToDebugString(this,4); @endcode @param this object pointer @param indent number of characters to indent every line of output, can be 0 @return If successful, an AStr object which must be released containing the description, otherwise OBJ_NIL. @warning Remember to release the returned AStr object. */ ASTR_DATA * W32StrC_ToDebugString ( W32STRC_DATA *this, int indent ) { ERESULT eRc; //int j; ASTR_DATA *pStr; //ASTR_DATA *pWrkStr; const OBJ_INFO *pInfo; // Do initialization. #ifdef NDEBUG #else if (!W32StrC_Validate(this)) { DEBUG_BREAK(); return OBJ_NIL; } #endif pInfo = obj_getInfo(this); pStr = AStr_New(); if (OBJ_NIL == pStr) { DEBUG_BREAK(); return OBJ_NIL; } if (indent) { AStr_AppendCharRepeatA(pStr, indent, ' '); } eRc = AStr_AppendPrint( pStr, "{%p(%s) size=%d retain=%d\n", this, pInfo->pClassName, W32StrC_getSize(this), obj_getRetainCount(this) ); #ifdef XYZZY if (this->pData) { if (((OBJ_DATA *)(this->pData))->pVtbl->pToDebugString) { pWrkStr = ((OBJ_DATA *)(this->pData))->pVtbl->pToDebugString( this->pData, indent+3 ); AStr_Append(pStr, pWrkStr); obj_Release(pWrkStr); } } #endif if (indent) { AStr_AppendCharRepeatA(pStr, indent, ' '); } eRc = AStr_AppendPrint( pStr, " %p(%s)}\n", this, pInfo->pClassName ); return pStr; } //--------------------------------------------------------------- // V a l i d a t e //--------------------------------------------------------------- #ifdef NDEBUG #else bool W32StrC_Validate ( W32STRC_DATA *this ) { // WARNING: We have established that we have a valid pointer // in 'this' yet. if (this) { if (obj_IsKindOf(this, OBJ_IDENT_W32STRC)) ; else { // 'this' is not our kind of data. We really don't // know what that it is at this point. return false; } } else { // 'this' is NULL. return false; } // Now, we have validated that we have a valid pointer in // 'this'. if (!(obj_getSize(this) >= sizeof(W32STRC_DATA))) { return false; } // Return to caller. return true; } #endif #ifdef __cplusplus } #endif
24.967213
89
0.402293
[ "object" ]
1f25949022bbd5d9936c67f8846a91d1134b91a5
58,873
c
C
src/takepatch.c
gspu/bitkeeper
994fb651a4045b221e33703fc3d665c3a34784e1
[ "Apache-2.0" ]
342
2016-05-10T14:59:07.000Z
2022-03-09T23:45:43.000Z
src/takepatch.c
rvs/bitkeeper
616740d0daad99530951e46ab48e577807cbbaf4
[ "Apache-2.0" ]
4
2016-05-16T20:14:27.000Z
2020-10-04T19:59:25.000Z
src/takepatch.c
rvs/bitkeeper
616740d0daad99530951e46ab48e577807cbbaf4
[ "Apache-2.0" ]
78
2016-05-10T15:53:30.000Z
2022-03-09T23:46:06.000Z
/* * Copyright 1999-2016 BitMover, Inc * * 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 "sccs.h" #include "bam.h" #include "nested.h" #include <time.h> #include "range.h" #include "progress.h" #include "graph.h" /* * takepatch - apply a BitKeeper patch file * * XXX - should take an option directory name or read the environment for * a directory. * * Patch format: * * == filename == * key_of_root_delta * key_of_parent_delta * * D 1.159 99/02/06 16:57:48 lm 160/55/6481 * .... * * diffs * * Repeats. */ #define CLEAN_RESYNC 1 /* blow away the RESYNC dir */ #define CLEAN_PENDING 2 /* blow away the PENDING dir */ #define CLEAN_OK 4 /* but exit 0 anyway */ #define CLEAN_FLAGS 8 /* Note that nway return are clean flags */ #define SHOUT() fputs("\n=================================== "\ "ERROR ====================================\n", stderr); #define SHOUT2() fputs("======================================="\ "=======================================\n", stderr); #define NOTICE() fputs("------------------------------------"\ "---------------------------------------\n", stderr); private ser_t getRecord(sccs *s, FILE *f); private void errorMsg(char *msg, char *arg1, char *arg2); private int extractPatch(char *name, FILE *p); private int extractDelta(char *name, sccs *sreal, sccs *scratch, int newFile, FILE *f, hash *countFiles, int *np); private int applyCsetPatch(sccs *s, int *nfound, int newFile); private void insertPatch(patch *p, int strictOrder); private int reversePatch(void); private void initProject(void); private FILE *init(char *file); private void cleanup(int what); private void freePatchList(void); private void badpath(sccs *s, ser_t tot); private int skipPatch(FILE *p); private void getChangeSet(void); private int sfio(FILE *m, int files); private int parseFeatures(char *next); private int sendPatch(char *name, FILE *in); private int stopNway(int n, int *conflicts, int *numcsets); typedef struct { /* command line options */ int pbars; /* --progress: progress bars, default is off */ int mkpatch; /* -m: act like makepatch verbose */ int collapsedups; /* -D: allow csets in BitKeeper/etc/collapsed */ int parallel; /* -j: do N takepatches in parallel */ int nway; /* This is one of the parallel threads */ int automerge; /* do automerging */ /* global state */ u64 N; /* number of ticks */ FILE **outlist; /* parallel popen file handles */ int *sent; /* how many bytes written to each channel */ /* modes enabled in patch */ u8 fast; /* Fast patch mode */ u8 port; /* patch created with 'bk port' */ u8 bkmerge; /* bk-style includes */ /* The patch from stdin or file */ FILE *p; /* old globals */ int echo; /* verbose level, more means more diagnostics */ int line; /* line number in the patch file */ patch *patchList; /* patches for a file */ int conflicts; /* number of conflicts over all files */ int newProject; /* command line opt to create a new repo */ int saveDirs; /* save directories even if errors */ MDBM *idDB; /* key to pathname db, set by init or rebuilt */ MDBM *goneDB; /* key to gone database */ int noConflicts; /* if set, abort on conflicts */ char pendingFile[MAXPATH]; char *input; /* input file name, * either "-" or a patch file */ char *comments; /* -y'comments', pass to resolve. */ char **errfiles; /* files had errors during apply */ char **edited; /* files that were in modified state */ int needlock; /* we're top-level, grab a lock */ } Opts; private Opts *opts; /* * Table of feature names mapping to the option it enables. */ private struct { char *name; int offset; } features[] = { {"PORT", offsetof(Opts, port)}, {"BKMERGE", offsetof(Opts, bkmerge)}, {0} }; int takepatch_main(int ac, char **av) { FILE *f; char *buf; int c; int rc; int files = 0; char *t; int error = 0; int remote = 0; /* remote csets */ int resolve = 0; int textOnly = 0; ticker *tick = 0; longopt lopts[] = { { "progress", 300, }, { "Nway", 310, }, { "port", 315, }, { "fast", 320, }, { "bkmerge", 321, }, { "no-automerge", 325, }, { 0, 0 }, }; setmode(0, O_BINARY); /* for win32 */ opts = new(Opts); opts->input = "-"; opts->automerge = 1; while ((c = getopt(ac, av, "acDFf:ij;LmqsStTvy;", lopts)) != -1) { switch (c) { case 'q': /* undoc 2.0 */ case 's': /* undoc 2.0 */ opts->echo = opts->pbars = 0; break; case 'a': resolve++; break; /* doc 2.0 */ case 'c': opts->noConflicts++; break; /* doc 2.0 */ case 'D': opts->collapsedups++; break; case 'F': break; /* obsolete */ case 'f': /* doc 2.0 */ opts->input = optarg; break; case 'i': opts->newProject++; break; /* doc 2.0 */ case 'j': if ((opts->parallel = atoi(optarg)) <= 1) { /* if they set it to <= 1 then disable */ opts->parallel = -1; } else if (opts->parallel > PARALLEL_MAX) { opts->parallel = PARALLEL_MAX; /* cap it */ } break; case 'm': opts->mkpatch++; break; /* doc 2.0 */ case 'S': opts->saveDirs++; break; /* doc 2.0 */ case 'T': textOnly++; break; /* doc 2.0 */ case 'v': /* doc 2.0 */ opts->pbars = 0; opts->echo++; break; case 'y': opts->comments = optarg; break; case 300: opts->pbars = 1; break; case 310: opts->nway = 1; break; case 315: opts->port = 1; break; case 320: opts->fast = 1; break; case 321: opts->bkmerge = 1; break; case 325: opts->automerge = 0; break; default: bk_badArg(c, av); } } if (opts->newProject) putenv("_BK_NEWPROJECT=YES"); if (opts->nway) { unless (getenv("_BK_CALLSTACK")) { fprintf(stderr, "--Nway is internal option\n"); free(opts); return (-1); } opts->p = stdin; goto doit; } unless (opts->parallel) opts->parallel = parallel(".", WRITER); /* * I want to revisit this, this change breaks regressions but * I think it was good for 20% on pulls. Need to remeasure. unless (opts->parallel) opts->parallel = cpus(); */ if (getenv("TAKEPATCH_SAVEDIRS")) opts->saveDirs++; if ((t = getenv("BK_NOTTY")) && *t && (opts->echo == 3)) { opts->echo = 2; } if (av[optind]) usage(); /* we're takepatch on the cmdline, we need a lock */ if (streq(getenv("_BK_CALLSTACK"), "takepatch")) opts->needlock = 1; opts->p = init(opts->input); if (sane(0, 0)) exit(1); /* uses _BK_NEWPROJECT */ doit: if (opts->newProject) { unless (opts->idDB = mdbm_open(NULL, 0, 0, GOOD_PSIZE)) { perror("mdbm_open"); cleanup(CLEAN_PENDING|CLEAN_RESYNC); } } else { /* OK if this returns NULL */ opts->goneDB = loadDB(GONE, 0, DB_GONE); unless (opts->idDB = loadDB(IDCACHE, 0, DB_IDCACHE)) { perror("SCCS/x.id_cache"); exit(1); } } /* * Find a file and go do it. */ while (buf = fgetline(opts->p)) { ++opts->line; unless (strncmp(buf, "== ", 3) == 0) { if (opts->echo > 7) { fprintf(stderr, "skipping: %s", buf); } continue; } /* * If we see the SFIO header then consider the patch ended. * We'll fall through to sfio to unpack. */ if (streq(buf, "== @SFIO@ ==")) { if (tick) { progress_done(tick, error < 0 ? "FAILED" : "OK"); tick = 0; } if (rc = sfio(opts->p, (int)(opts->N - files))) { error = -1; } break; } if (opts->echo>4) fprintf(stderr, "%s\n", buf); unless ((t = strrchr(buf, ' ')) && streq(t, " ==")) { SHOUT(); fprintf(stderr, "Bad patch: %s\n", buf); cleanup(CLEAN_RESYNC); } *t = 0; t = &buf[3]; /* gfile */ /* SFIO needs rootkey, so unpack ChangeSet in this thread */ if ((opts->parallel > 0) && (!streq(t, GCHANGESET) || !opts->newProject)) { rc = sendPatch(t, opts->p); } else { t = name2sccs(t); rc = extractPatch(t, opts->p); free(t); } if (!files && opts->pbars) { tick = progress_start(PROGRESS_BAR, opts->N); } files++; if (tick) progress(tick, files); if (rc < 0) { error = rc; continue; } remote += rc; } if (opts->parallel > 0) { if (rc = stopNway(opts->parallel, &opts->conflicts, &remote)) { error = rc; } } if ((opts->p != stdin) && fclose(opts->p)) { perror(opts->input); opts->p = 0; /* don't try to close again */ cleanup(CLEAN_RESYNC); } opts->p = 0; if (opts->idDB) { mdbm_close(opts->idDB); opts->idDB = 0; } if (opts->goneDB) { mdbm_close(opts->goneDB); opts->goneDB = 0; } if (tick) progress_done(tick, error < 0 ? "FAILED" : "OK"); if (error < 0) { /* XXX: Save? Purge? */ cleanup(CLEAN_RESYNC); } #ifdef SIGXFSZ if (getenv("_BK_SUICIDE")) kill(getpid(), SIGXFSZ); #endif if (opts->nway) { if (remote) printf("r %d\n", remote); if (opts->conflicts) printf("c %u\n", opts->conflicts); goto done; } if (opts->echo || opts->pbars) { files = 0; if (f = popen("bk gfiles RESYNC", "r")) { while (t = fgetline(f)) ++files; pclose(f); } if (opts->pbars) { t = opts->conflicts ? aprintf("%3d", opts->conflicts) : strdup(" no"); Fprintf("BitKeeper/log/progress-sum", "%3d changeset%s %s merge%s in %3d file%s\n", remote, remote == 1 ? ", " : "s,", t, opts->conflicts == 1 ? " " : "s", files, files == 1 ? "" : "s"); } else { fprintf(stderr, "takepatch: " "%d new changeset%s, %d conflicts in %d files\n", remote, remote == 1 ? "" : "s", opts->conflicts, files); } } unless (remote) { /* * The patch didn't contain any new csets and so we don't * need to run resolve. * We should still run the post resolve trigger. */ if (resolve) { putenv("BK_STATUS=REDUNDANT"); trigger("resolve", "post"); } cleanup(CLEAN_RESYNC | CLEAN_PENDING | CLEAN_OK); } /* * The ideas here are to (a) automerge any hash-like files which * we maintain, and (b) converge on the oldest inode for a * particular file. The converge code will make sure all of the * inodes are present. */ if (opts->conflicts) converge_hash_files(); /* * There are instances (contrived) where the ChangeSet * file will not be in the RESYNC tree. Make sure that * it is. This will prevent resolve from failing and * hopefully those scary support emails. */ getChangeSet(); if (resolve) { char *resolve[] = {"bk", "-?BK_NO_REPO_LOCK=YES", "resolve", "-S", 0, 0, 0, 0, 0, 0}; int i = 3; if (opts->echo) { fprintf(stderr, "Running resolve to apply new work...\n"); } unless (opts->echo) resolve[++i] = "-q"; if (textOnly) resolve[++i] = "-T"; if (opts->noConflicts) resolve[++i] = "-c"; if (opts->comments) { resolve[++i] = aprintf("-y%s", opts->comments); } i = spawnvp(_P_WAIT, resolve[0], resolve); unless (WIFEXITED(i)) return (-1); error = WEXITSTATUS(i); } done: freeLines(opts->errfiles, free); freeLines(opts->edited, free); free(opts); return (error); } private void getChangeSet(void) { if (exists(CHANGESET)) { unless (exists(ROOT2RESYNC "/" CHANGESET)) { fileCopy(CHANGESET, ROOT2RESYNC "/" CHANGESET); } } } private hash * loadCollapsed(void) { FILE *f; hash *db = 0; char *p; char buf[MAXLINE]; if (opts->collapsedups) return (0); f = popen("bk annotate -ar " COLLAPSED, "r"); while (fnext(buf, f)) { chomp(buf); unless (db) db = hash_new(HASH_MEMHASH); /* ignore dups, we don't care */ p = strchr(buf, '\t'); assert(p); *p++ = 0; hash_insertStr(db, p, buf); } pclose(f); return (db); } /* * XXX: when this function evolves to be called with a real sccs * * take out the hack in sccs_getInit to check sc->version != 0xff. */ private ser_t getRecord(sccs *s, FILE *f) { int e = 0; ser_t d; d = sccs_getInit(s, 0, f, DELTA_PATCH|DELTA_TAKEPATCH, &e, 0, 0); if (!d || e) { fprintf(stderr, "takepatch: bad delta record near line %d\n", opts->line); exit(1); } return (d); } private void shout(void) { static int shouted = 0; if (shouted) return; /* already done shouting */ SHOUT(); shouted = 1; } /* * Extract a contiguous set of deltas for a single file from the patch file. * "name" is the cset name, i.e., the most recent name in the csets being * sent; it might be different than the local name. */ private int extractPatch(char *name, FILE *p) { ser_t tmp; sccs *s = 0, *new_s = 0, *scratch = 0; FILE *perfile = 0; int newFile = 0; int cset; char *gfile = 0; int nfound = 0, rc; hash *countFiles = 0; /* hash of rootkeys seen in cset patches */ char *t; int newsfile; /* * Patch format for continuing file: * == filename == * lm||19970518232929 * lm@lm.bitmover.com|sccs/slib.c|19990130201757 * D 1.159 99/02/06 16:57:48-08:00 lm@lm.bitmover.com +160 -55 * etc. * * Patch format for new file: * == filename == * New file: filename as of creation time * perfile information (encoding, etc) * * lm||19970518232929 * D 1.1 99/02/23 00:29:01-08:00 lm@lm.bitmover.com +128 -0 * etc. * * Tue Mar 28 2000 * == filename == * Grafted file: filename as of creation time * {same as above, no perfile.} */ t = fgetline(p); opts->line++; if (strneq("New file: ", t, 10)) { char *resyncFile; newFile = 1; perfile = fmem(); while (t = fgetline(p)) { fputs(t, perfile); fputc('\n', perfile); unless (*t) break; } rewind(perfile); resyncFile = aprintf(ROOT2RESYNC "/%s", name); unless (new_s = sccs_init(resyncFile, SILENT)) { SHOUT(); fprintf(stderr, "takepatch: can't create %s\n", resyncFile); free(resyncFile); goto error; } new_s->bitkeeper = 1; /* XXX: not set in sccs_init ?? */ free(resyncFile); if (sccs_getperfile(new_s, perfile, &opts->line)) goto error; rewind(perfile); t = fgetline(p); opts->line++; } if (strneq("Grafted file: ", t, 14)) { t = fgetline(p); opts->line++; } if (opts->newProject && !newFile) errorMsg("tp_notfirst", 0, 0); t = strdup(t); if (opts->echo>4) fprintf(stderr, "%s\n", t); s = sccs_keyinit(0, t, SILENT, opts->idDB); if (s && !s->cksumok) goto error; /* * Unless it is a brand new workspace, or a new file, * rebuild the id cache if look up failed. * * If the file is gone, it's an error to get updates to that file. * * XXX - we need some test cases in the regression scripts for this. * a) move the file and make sure it finds it * b) move the file and send a new file over and make sure it finds * it. */ unless (s || new_s) { if (gone(t, opts->goneDB)) { if (getenv("BK_GONE_OK")) { skipPatch(p); return (0); } else { errorMsg("tp_gone_error", t, 0); } } SHOUT(); fprintf(stderr, "takepatch: can't find key '%s' in id cache\n", t); error: if (new_s && (new_s != s)) sccs_free(new_s); if (perfile) fclose(perfile); if (gfile) free(gfile); free(t); if (s) sccs_free(s); opts->errfiles = addLine(opts->errfiles, sccs2name(name)); return (-1); } /* * They may have sent us a patch from 1.0, so the patch looks like a * new file. But if we have a match, we want to use it. */ if (s) { if (newFile && (opts->echo > 4)) { fprintf(stderr, "takepatch: new file %s already exists.\n", name); } if (opts->echo > 7) { fprintf(stderr, "takepatch: file %s found.\n", s->sfile); } if (EDITED(s)) { int cleanflags = SILENT|CLEAN_SHUTUP|CLEAN_CHECKONLY; if (sccs_clean(s, cleanflags)) { opts->edited = addLine(opts->edited, sccs2name(s->sfile)); sccs_free(s); s = 0; goto error; } else { sccs_restart(s); } } else if (s->state & S_PFILE) { if (xfile_delete(s->gfile, 'p')) { fprintf(stderr, "takepatch: unlink(%s): %s\n", s->sfile, strerror(errno)); goto error; } s->state &= ~S_PFILE; } tmp = sccs_top(s); unless (CSET(s)) { unless (sccs_patheq(PATHNAME(s, tmp), s->gfile)) { badpath(s, tmp); goto error; } } unless (tmp = sccs_findKey(s, t)) { shout(); fprintf(stderr, "takepatch: can't find root delta '%s' in %s\n", t, name); goto error; } unless (sccs_ino(s) == tmp) { shout(); fprintf(stderr, "takepatch: root deltas do not match in %s\n", name); goto error; } } else { /* create a new file */ /* * ChangeSet is special, don't rename it, * because "resolve" expects to find a ChangeSet * file in its normal location. * ChangeSet is never renamed, so * it is safe to assume there is no * name conflict for the ChangeSet file. */ assert(new_s); if (streq(name, "SCCS/s.ChangeSet") && exists("SCCS/s.ChangeSet")) { errorMsg("tp_changeset_exists", 0, 0); } if (opts->echo > 3) { fprintf(stderr, "takepatch: new file %s\n", t); } } cset = s ? CSET(s) : CSET(new_s); if (opts->pbars && cset) { countFiles = hash_new(HASH_MEMHASH); opts->N++; /* count the cset file */ } scratch = new(sccs); while (extractDelta( name, s, scratch, newFile, p, countFiles, &nfound)) { if (newFile) newFile = 2; } sccs_free(scratch); if (countFiles) { hash_free(countFiles); countFiles = 0; } gfile = sccs2name(name); if (opts->echo > 1) fprintf(stderr, "Updating %s", gfile); newsfile = !s; unless (s) { s = new_s; new_s = 0; } rc = applyCsetPatch(s, &nfound, newsfile); s = 0; /* applyCsetPatch calls sccs_free */ unless (cset) nfound = 0; /* only count csets */ if (opts->echo > 1) fputc('\n', stderr); if (perfile) fclose(perfile); if (streq(gfile, "BitKeeper/etc/config")) { /* * If we have rewritten the config file we need to * flush the cache of config data in the project * struct. */ proj_reset(0); } free(gfile); free(t); if (new_s) sccs_free(new_s); if (s) sccs_free(s); if (rc < 0) { cleanup(CLEAN_RESYNC); return (rc); } return (nfound); } /* * Extract one delta from the patch file. * Deltas end on the first blank line. */ private int extractDelta(char *name, sccs *sreal, sccs *scratch, int newFile, FILE *f, hash *countFiles, int *np) { ser_t d, tmp; char buf[MAXPATH]; char *b, *sep; char *pid = 0; int c, i; int ignore = 0; size_t len; patch *p; FILE *init = 0; if (newFile == 1) goto delta1; b = fgetline(f); opts->line++; if (opts->echo>4) fprintf(stderr, "%s\n", b); if (strneq(b, "# Patch checksum=", 17)) return 0; pid = strdup(b); /* buffer the required init block */ delta1: while ((b = fgetline(f)) && *b) { unless (init) init = fmem(); fputs(b, init); fputc('\n', init); opts->line++; if (opts->echo>4) fprintf(stderr, "%s\n", b); } if (b) opts->line++; assert(init); rewind(init); /* go get the delta table entry for this delta */ d = getRecord(scratch, init); rewind(init); /* * 11/29/02 - we fill in dangling deltas by pretending they are * incoming deltas which we do not already have. In the patch * they are not going to be dangling so the flag is clear; * applying the patch will clear the flag and the code paths * are all happier this way. */ if (!opts->fast && sreal && sccs_sdelta(scratch, d, buf) && (tmp = sccs_findKey(sreal, buf)) && !DANGLING(sreal, tmp)) { if (opts->echo > 3) { fprintf(stderr, "takepatch: delta %s already in %s, skipping it.\n", REV(sreal, tmp), sreal->sfile); } free(pid); fclose(init); init = 0; /* Eat diffs */ while ((b = fgetln(f, &len)) && (len > 1)) opts->line++; opts->line++; } else { if (ignore) { /* fastpatch - ignore init block, keep diffs */ fclose(init); init = 0; } p = new(patch); if (init) { p->initMem.buf = fmem_close(init, &len); p->initMem.len = len; p->initMem.size = len; /* really +1 */ init = 0; } if (opts->echo>5) fprintf(stderr, "\n"); p->remote = 1; p->pid = pid; sccs_sdelta(scratch, d, buf); p->me = strdup(buf); sccs_sortkey(scratch, d, buf); p->sortkey = strdup(buf); p->localFile = sreal ? strdup(sreal->sfile) : 0; sprintf(buf, "RESYNC/%s", name); p->resyncFile = strdup(buf); p->order = DATE(scratch, d); c = opts->line; while (b = fgetln(f, &len)) { if (len && (b[len-1] == '\n')) --len; b[len] = 0; unless (len) break; unless (p->diffMem) p->diffMem = fmem(); if (countFiles && (*b == '>')) { i = opts->fast ? 1 : 2; sep = separator(&b[i]); assert(sep); *sep = 0; if (!changesetKey(&b[i]) && hash_insertStr(countFiles, &b[i], 0)) { opts->N++; /* for progress bar */ } *sep = ' '; } fputs(b, p->diffMem); fputc('\n', p->diffMem); opts->line++; if (opts->echo>5) fprintf(stderr, "%s\n", b); } if (p->diffMem) rewind(p->diffMem); if (opts->fast) { /* header and diff are not connected */ if (FLAGS(scratch, d) & D_META) p->meta = 1; } else if (FLAGS(scratch, d) & D_META) { p->meta = 1; assert(c == opts->line); assert(!p->diffMem); } opts->line++; if (opts->echo>5) fprintf(stderr, "\n"); (*np)++; insertPatch(p, 1); } sccs_freedelta(scratch, d); if ((c = getc(f)) != EOF) { ungetc(c, f); return (c != '='); } return (0); } /* * Skip to the next file start. * Deltas end on the first blank line. */ private int skipPatch(FILE *p) { char *b; int c; do { b = fgetline(p); opts->line++; if (strneq(b, "# Patch checksum=", 17)) return 0; /* Eat metadata */ while ((b = fgetline(p)) && *b) opts->line++; opts->line++; /* Eat diffs */ while ((b = fgetline(p)) && *b) opts->line++; opts->line++; if ((c = getc(p)) == EOF) return (0); ungetc(c, p); } while (c != '='); return (0); } private void errorMsg(char *msg, char *arg1, char *arg2) { SHOUT(); getMsg2(msg, arg1, arg2, 0, stderr); cleanup(CLEAN_RESYNC|CLEAN_PENDING); } private void badpath(sccs *s, ser_t tot) { SHOUT(); getMsg2("tp_badpath", s->gfile, PATHNAME(s, tot), 0, stderr); } private void badXsum(int a, int b) { SHOUT(); if (opts->echo > 3) { char *p = aprintf(" (%x != %x)", a, b); getMsg("tp_badXsum", p, 0, stderr); free(p); } else { getMsg("tp_badXsum", "", 0, stderr); } cleanup(CLEAN_PENDING|CLEAN_RESYNC); /* XXX - should clean up everything if this was takepatch -i */ } /* * This tries within a reasonable amount of effort to write the * SCCS file only once. This can be done because the sccs struct * is in memory and can be fiddled with carefully. The weaving * of new information is done when we are done fiddling with the sccs * file and write out the table, then weave the new deltas into the * body. While this is doable for the general weave case, it is * very doable for the ChangeSet file (or any hash file) because * the weave is an ordered set of blocks, youngest to oldest. * So by building a table of blocks to weave, as well as a way to * know how to increment the serial number of existing blocks, it * is possible to only write the file once. */ private int applyCsetPatch(sccs *s, int *nfound, int newFile) { patch *p; FILE *iF; FILE *dF; ser_t d = 0; ser_t top; ser_t remote_tagtip = 0; int n = 0; int j; int psize = *nfound; int confThisFile; FILE *csets = 0, *f; hash *cdb; char *topkey = 0; char csets_in[MAXPATH]; char buf[MAXKEY]; char *resyncFile; assert(s); if (CSET(s)) T_PERF("applyCsetPatch(start)"); reversePatch(); unless (p = opts->patchList) { sccs_free(s); return (0); } if (opts->echo > 7) { fprintf(stderr, "L=%s\nR=%s\nP=%s\nM=%s\n", p->localFile, p->resyncFile, p->pid, p->me); } resyncFile = p->resyncFile; if (newFile) { /* good to go */ } else if (getenv("_BK_COPY_SFILE")) { if (fileCopy(s->sfile, p->resyncFile)) { fprintf(stderr, "Copy of %s to %s failed", s->sfile, p->resyncFile); perror("takepatch-copy"); goto err; } sccs_free(s); unless (s = sccs_init(p->resyncFile, INIT_MUSTEXIST|SILENT)) { SHOUT(); fprintf(stderr, "takepatch: can't init %s\n", p->resyncFile); goto err; } if (CSET(s)) { cmdlog_addnote( "_BK_COPY_SFILE", getenv("_BK_COPY_SFILE")); } } else { sccs_writeHere(s, p->resyncFile); } /* serial is not stable */ if (top = sccs_top(s)) { sccs_sdelta(s, top, buf); topkey = strdup(buf); top = 0; } assert(s); if (opts->bkmerge != BKMERGE(s)) { /* * Take the patch in the remote repo's format. * sccs_startWrite will put the file back in the local form. */ if (graph_convert(s, 0)) goto err; } cweave_init(s, psize); *nfound = 0; while (p) { n++; if (opts->echo>9) { fprintf(stderr, "PID: %s\nME: %s\n", p->pid ? p->pid : "none", p->me); } assert(p->initMem.buf); iF = fmem_buf(p->initMem.buf, p->initMem.len); dF = p->diffMem; d = 0; /* in this case, parent */ if (p->pid) { unless (d = sccs_findKey(s, p->pid)) { if ((opts->echo == 2) || (opts->echo == 3)) { fprintf(stderr, " \n"); } errorMsg("tp_ahead", p->pid, s->sfile); /*NOTREACHED*/ } } if (opts->echo>9) { fprintf(stderr, "Child of %s", d ? REV(s, d) : "none"); if (p->meta) { fprintf(stderr, " meta\n"); } else { fprintf(stderr, " data\n"); } } /* passing in d = parent, setting d = new or existing */ if (d = cset_insert(s, iF, dF, d, opts->fast)) { if (d == D_INVALID) cleanup(CLEAN_RESYNC|CLEAN_PENDING); (*nfound)++; p->serial = d; if ((FLAGS(s, d) & D_REMOTE) && SYMGRAPH(s, d)) { remote_tagtip = d; } } fclose(iF); /* dF needs to stick around until write */ p = p->next; } unless (*nfound) goto done; /* * pull -r can propagate a non-tip tag element as the tip. * We have to mark it here before writing the file out. */ if (remote_tagtip) { d = remote_tagtip; assert(FLAGS(s, d)); if (!SYMLEAF(s, d)) { assert(CSET(s)); FLAGS(s, d) |= D_SYMLEAF; debug((stderr, "takepatch: adding leaf to tag " "delta %s (serial %d)\n", REV(s, d), d)); } } /* * When porting in a csetfile, need to ignore path names * XXX: component moves looks will break this. */ if (topkey) top = sccs_findKey(s, topkey); if (opts->port && CSET(s)) { int portLocal = 0; char *path; assert(topkey); // no porting a new component; use attach for (d = 0, p = opts->patchList; p; p = p->next) { d = p->serial; unless (d && (FLAGS(s, d) & D_REMOTE)) continue; unless (PARENT(s, d)) continue; /* rootkey untouched */ /* * We don't yet support component rename. */ if (!streq(PATHNAME(s, top), (path = PATHNAME(s, PARENT(s, d)))) || (MERGE(s, d) && !streq(PATHNAME(s, top), (path = PATHNAME(s, MERGE(s, d)))))) { getMsg2("tp_portrename", PATHNAME(s, top), path, 0, stderr); cleanup(CLEAN_RESYNC|CLEAN_PENDING); /*NOTREACHED*/ } sccs_setPath(s, d, PATHNAME(s, PARENT(s, d))); if (TAG(s, d)) continue; if (proj_isComponent(s->proj)) { /* Sanity assertion - can't port to self */ if (streq(CSETFILE(s, d), proj_rootkey(proj_product(s->proj)))) { portLocal = 1; } } else { /* * If porting to a standalone, we need to add * back the cset marks. */ if (d != TREE(s)) FLAGS(s, d) |= D_CSET; } } if (portLocal) { /* illegal to port local */ reversePatch(); /* new to old */ SHOUT(); for (d = 0, p = opts->patchList; p; p = p->next) { unless ((d = p->serial) && (FLAGS(s, d) & D_REMOTE) && !TAG(s, d)) { continue; } unless ((FLAGS(s, d) & D_SET) || streq(CSETFILE(s, d), proj_rootkey(proj_product(s->proj)))) { continue; } EACH_PARENT(s, p->serial, d, j) { FLAGS(s, d) |= D_SET; } d = p->serial; if (FLAGS(s, d) & D_SET) continue; /* only print error message for tips */ sccs_sdelta(s, d, buf); /* * I'd like to use md5root but I just added * support for md5keys to key2path so not yet. */ getMsg2("tp_portself", proj_rootkey(s->proj), buf, 0, stderr); } cleanup(CLEAN_RESYNC|CLEAN_PENDING); /*NOTREACHED*/ } } if (CSET(s) && (opts->echo == 3)) fputs(", ", stderr); assert(opts->bkmerge == BKMERGE(s)); if (mkdirf(resyncFile) == -1) { if (errno == EINVAL) { getMsg("reserved_name", resyncFile, '=', stderr); return (-1); } } if (cset_write(s, (opts->echo == 3), opts->fast)) { SHOUT(); fprintf(stderr, "takepatch: can't update %s\n", s->sfile); goto err; } if (CSET(s)) T_PERF("cset_write"); s = sccs_restart(s); assert(s); unless (CSET(s)) goto markup; if (cdb = loadCollapsed()) { for (p = opts->patchList; p; p = p->next) { d = p->serial; unless (d && (FLAGS(s, d) & D_REMOTE)) continue; sccs_md5delta(s, d, buf); if (hash_fetchStr(cdb, buf)) { /* find cset that added that entry */ sprintf(buf, "bk -R r2c -r%s " COLLAPSED, (char *)cdb->vptr); f = popen(buf, "r"); fnext(buf, f); chomp(buf); pclose(f); errorMsg("takepatch-collapsed", cdb->kptr, buf); hash_free(cdb); goto err; } } hash_free(cdb); } /* examine incoming csets and looks for updates to components with * pending deltas */ if (proj_isProduct(0)) { for (p = opts->patchList; p; p = p->next) { char *t, *s; char key[MAXKEY]; unless (p->diffMem) continue; rewind(p->diffMem); while (t = fgetline(p->diffMem)) { unless (*t == '>') continue; ++t; /* skip '>' */ unless (opts->fast) ++t; /* skip space */ s = separator(t); strncpy(key, t, s-t); key[s-t] = 0; unless (changesetKey(key)) continue; t = key2path(key, opts->idDB, opts->goneDB, 0); if (sccs_isPending(t)) { dirname(t); /* strip /ChangeSet */ getMsg("tp_uncommitted", t, 0, stderr); free(t); goto err; } free(t); } } } sprintf(csets_in, "%s/%s", ROOT2RESYNC, CSETS_IN); csets = fopen(csets_in, "w"); assert(csets); for (p = opts->patchList; p; p = p->next) { d = p->serial; unless (d && (FLAGS(s, d) & D_REMOTE)) continue; sccs_sdelta(s, d, buf); fprintf(csets, "%s\n", buf); } fclose(csets); markup: /* * D_REMOTE used in sccs_resolveFiles() * D_SET used in cset_resum() */ for (d = 0, p = opts->patchList; p; p = p->next) { /* * In fastpatch, diffMem is not related to initMem, so * just clear all of them. * win32: must fclose after cset_write */ if (p->diffMem) fclose(p->diffMem); p->diffMem = 0; d = p->serial; unless (d && (FLAGS(s, d) & D_REMOTE)) continue; FLAGS(s, d) |= D_SET; /* for resum() */ } if (!CSET(s) && top && (DANGLING(s, top) || !(FLAGS(s, top) & D_CSET))) { ser_t a, b; if (DANGLING(s, top) && sccs_findtips(s, &a, &b)) { fprintf(stderr, "takepatch: monotonic file %s " "has dangling deltas\n", s->sfile); goto err; } if (!(FLAGS(s, top) & D_CSET) && sccs_isleaf(s, top)) { /* uncommitted error for dangling is backward compat */ char *t = sccs2name(opts->patchList->localFile); SHOUT(); getMsg("tp_uncommitted", t, 0, stderr); free(t); goto err; } } /* * Make a new changeset node in resolve if no new node created */ s->state |= S_SET; if (CSET(s)) { if (opts->echo == 3) fputs(", ", stderr); if (cset_resum(s, 0, 0, opts->echo == 3, 1)) { getMsg("takepatch-chksum", 0, '=', stderr); goto err; } if (opts->echo == 3) progress_nldone(); } else if (!BAM(s)) { for (d = TABLE(s); d >= TREE(s); d--) { unless ((FLAGS(s, d) & D_SET) && !TAG(s, d)) continue; if (sccs_resum(s, d, 0, 0)) { getMsg("takepatch-chksum", 0, '=', stderr); goto err; } } } if ((confThisFile = sccs_resolveFiles(s, opts->automerge)) < 0) { goto err; } if (!confThisFile && (s->state & S_CSET) && sccs_adminFlag(s, SILENT|ADMIN_BK)) { confThisFile++; /* yeah, the count is slightly off if there were conflicts */ } opts->conflicts += confThisFile; if (BAM(s) && !bp_hasBAM()) { /* this shouldn't be needed... */ if (touch(BAM_MARKER, 0664)) perror(BAM_MARKER); } done: if (CSET(s)) T_PERF("done cset"); sccs_free(s); s = 0; if (opts->noConflicts && opts->conflicts) { errorMsg("tp_noconflicts", 0, 0); } freePatchList(); if (topkey) free(topkey); opts->patchList = 0; return (0); err: if (topkey) free(topkey); if (s) sccs_free(s); return (-1); } /* * Return true if 'a' is earlier than 'b' */ private int earlierPatch(patch *a, patch *b) { int ret; if (a->order < b->order) return 1; if (a->order > b->order) return 0; ret = strcmp(a->sortkey, b->sortkey); if (ret < 0) return 1; if (ret > 0) return 0; assert("Can't figure out the order of deltas\n" == 0); return (-1); /* shut off VC++ comipler warning */ } /* * Insert the delta in the list in sorted time order. * The global patchList points at the newest/youngest. */ private void insertPatch(patch *p, int strictOrder) { patch *t; if (!opts->patchList || earlierPatch(opts->patchList, p)) { p->next = opts->patchList; opts->patchList = p; return; } else if (strictOrder) { fprintf(stderr, "%s: patch not in old to new order:\n%s\n%s\n", prog, opts->patchList->me, p->me); cleanup(CLEAN_RESYNC); } /* * We know that t is pointing to a node that is younger than us. */ for (t = opts->patchList; t->next; t = t->next) { if (earlierPatch(t->next, p)) { p->next = t->next; t->next = p; return; } } /* * There is no next field and we know that t->order is > date. */ assert(earlierPatch(p, t)); t->next = p; } /* * Reverse order to optimize reading * patchList will be left pointing at the oldest delta in the patch */ private int reversePatch(void) { int n = 0; /* t - temp; f - forward; p - previous */ patch *t, *f, *p; if (!opts->patchList) return (n); for (p = 0, t = opts->patchList; t; t = f) { f = t->next; t->next = p; p = t; ++n; } assert(p); opts->patchList = p; return (n); } private void freePatchList(void) { patch *p; for (p = opts->patchList; p; ) { patch *next = p->next; if (p->initFile) { unlink(p->initFile); free(p->initFile); } if (p->diffFile) { unlink(p->diffFile); free(p->diffFile); } if (p->localFile) free(p->localFile); if (p->initMem.buf) free(p->initMem.buf); free(p->resyncFile); if (p->pid) free(p->pid); if (p->me) free(p->me); if (p->sortkey) free(p->sortkey); free(p); p = next; } } /* * Create enough stuff that the tools can find the project root. */ private void initProject(void) { unless (emptyDir(".")) { SHOUT(); fprintf(stderr, "takepatch: -i can only be used in an empty directory\n"); SHOUT2(); /* * We MUST exit here. It is an invariant that if we are not * empty we abort. See cleanup(). */ exit(1); } sccs_mkroot("."); /* * Make new repo with new features * Who uses takepatch -i to make a repo? * XXX: doesn't work correctly with nested. * * From setup.c, in the non-compat, non-component case. * There's more code in setup.c to do nested component. */ features_set(0, (FEAT_FILEFORMAT & ~FEAT_BWEAVEv2) | FEAT_SCANDIRS, 1); } private void resync_lock(void) { FILE *f; if (opts->needlock) cmdlog_lock(CMD_WRLOCK); /* * See if we can lock the tree. * We assume that a higher level program called repository_wrlock(), * we're just doing the RESYNC part. * * Note: bk's mkdir will pass if RESYNC already exists so we need * to test that separately. */ if ((isdir("RESYNC") && !nested_mine(0, getenv("_BK_NESTED_LOCK"), 1)) || mkdir("RESYNC", 0777)) { fprintf(stderr, "takepatch: cannot create RESYNC dir.\n"); repository_lockers(0); cleanup(0); } unless (mkdir("RESYNC/BitKeeper", 0777) == 0) { SHOUT(); perror("mkdir"); cleanup(CLEAN_RESYNC); } sccs_mkroot("RESYNC"); unless (f = fopen("RESYNC/BitKeeper/tmp/pid", "w")) { SHOUT(); perror("RESYNC/BitKeeper/tmp/pid"); cleanup(CLEAN_RESYNC); } fprintf(f, "%u\n", getpid()); if (proj_isProduct(0)) { mkdirp("RESYNC/BitKeeper/log"); touch("RESYNC/BitKeeper/log/PRODUCT", 0644); } fclose(f); } /* * Next line is patch checksum, then SFIO data follows. */ private int sfio(FILE *m, int files) { char *t; FILE *f = 0; sccs *s = 0, *sr = 0; ser_t d; size_t n; char *flist; int rc = -1, rlen; int bkfile = (features_test(0, FEAT_BKFILE) != 0); int bkmerge = (features_test(0, FEAT_BKMERGE) != 0); char buf[MAXLINE]; char key[MAXKEY]; unless ((t = fgetline(m)) && !*t && (t = fgetline(m)) && strneq(t, "# Patch checksum=", 17)) { return (-1); } flist = bktmp(0); if (opts->pbars && (files > 0)) { sprintf(key, "-N%d --takepatch", files); } else if (opts->echo > 1) { sprintf(key, "-v -P'Updating '"); } else { sprintf(key, "-q"); } sprintf(buf, "bk sfio -eigB %s - > '%s'", key, flist); fflush(stdout); chdir(ROOT2RESYNC); f = popen(buf, "w"); chdir(RESYNC2ROOT); unless (f) { perror(prog); goto err; }; while ((n = fread(buf, 1, sizeof(buf), m)) > 0) { fwrite(buf, 1, n, f); } if (opts->echo > 1) progress_nldone(); if (pclose(f)) { fprintf(stderr, "takepatch: BAM sfio -i failed.\n"); f = 0; goto err; } /* process each file unpacked */ unless (f = fopen(flist, "r")) { perror(prog); goto err; } strcpy(buf, ROOT2RESYNC "/"); t = buf + strlen(buf); rlen = sizeof(buf) - strlen(buf); /* space in buf after RESYNC/ */ while (fgets(t, rlen, f)) { chomp(t); if (strchr(t, '|')) continue; /* skip BAM keys */ unless (sr = sccs_init(buf, SILENT|INIT_NOCKSUM|INIT_MUSTEXIST)) { fprintf(stderr, "takepatch: can't open %s\n", buf); goto err; } if ((bkfile != BKFILE(sr)) || (bkmerge != BKMERGE(sr))) { sccs_newchksum(sr); /* fix format */ } sccs_sdelta(sr, sccs_ino(sr), key); /* rootkey */ /* Check the original version of this file */ unless (s = sccs_keyinit(0, key, INIT_NOCKSUM, opts->idDB)) { /* must be new file? */ sccs_free(sr); sr = 0; continue; } assert(!CSET(s)); /* some more logic is needed for cset */ /* local diffs are bad */ if (sccs_clean(s, SILENT|CLEAN_SHUTUP|CLEAN_CHECKONLY)) { opts->edited = addLine(opts->edited, sccs2name(s->sfile)); goto err; } if (DANGLING(s, TABLE(s))) { fprintf(stderr, "takepatch: monotonic file %s " "has dangling deltas\n", s->sfile); goto err; } sccs_sdelta(s, TABLE(s), key); /* local tipkey */ unless (d = sccs_findKey(sr, key)) { /* * I can't find local tipkey in resync file. * This might be because it is a pending delta, if * so complain about that, otherwise just complain. * Note, it is OK to have a pending delta that * has been committed in the resync version, the old * code used to ignore these duplicate deltas. */ /* because of pending deltas? */ unless (FLAGS(s, TABLE(s)) & D_CSET) { SHOUT(); getMsg("tp_uncommitted", s->gfile, 0, stderr); } else { fprintf(stderr, "takepatch: key '%s' not found " "in sfile %s\n", key, buf); } goto err; } /* mark remote-only deltas */ range_walkrevs(sr, L(d), 0, 0, walkrevs_setFlags, (void*)D_REMOTE); /* * techically, FLAGS(s, d) |= D_LOCAL, but D_LOCAL goes away * in /home/bk/bk and the way resolveFiles is written, it * does the right thing with or without D_LOCAL. */ FLAGS(s, d) |= D_LOCAL; if (sccs_resolveFiles(sr, opts->automerge) < 0) goto err; sccs_free(s); sccs_free(sr); s = sr = 0; } rc = 0; err: if (f) fclose(f); unlink(flist); free(flist); if (s) sccs_free(s); if (sr) sccs_free(sr); return (rc); } /* * The verifier engine from the old init. It used to be a bubble * in the pipeline to read and verify the stdin, then takepatch it. * Now it is is done in parallel though I/O layering. * * Init builds it up and gets it going. fclose() tears it down. * Note: need to fclose this stuff. Also think about checksumming * in a different thread or in this one. * * The I/O layer has some braindeadness to make it easier to read. * We are reading and parsing lines, which might not fit into the * buffer handed to us to fill. Save in a 'leftover' fmem, and * the next readPatch call, only return what is in that buffer until * it is empty, then fclose the fmem(). We could keep the fmem open, * but this easier to know it works: if fmem, return it, else read * new data. In reality, fmem never used. */ typedef struct { FILE *leftover; /* fmem of extra crud for next time */ FILE *pending; /* fmem of extra crud for next time */ FILE *fin; /* the file it is sitting on */ long bytecount; /* size of pending file for logs */ uLong sumC, sumR; /* The computed and real checksum */ /* state bits */ u32 longline:1; /* a continuation of earlier line */ u32 newline:1; /* current line is a newline */ u32 preamble_nl:1; /* previous line was a newline */ u32 preamble:1; /* looking for patch version */ u32 version:1; /* previous line was Patch vers: ... */ u32 type:1; /* looking for patch type */ u32 versionblank:1; /* previous line was \n after vers */ u32 filename:1; /* previous line was == file == */ u32 first:1; /* previous line was == file == */ u32 perfile:1; /* previous line was perfile stuff */ u32 perblank:1; /* previous line was per blank */ u32 metadata:1; /* previous line was meta data block */ u32 metaline:1; /* previous line was 48x- */ u32 metablank:1; /* previous line was \n after meta */ u32 diffs:1; /* previous line was diffs */ u32 diffsblank:1; /* previous line was \n after diffs */ u32 sfiopatch:1; /* previous line was == @SFIO == */ u32 sfiopending:1; /* saw SFIO, but wait until checksum */ u32 sfio:1; /* parse the sfio */ u32 nosum:1; /* turn off checksumming */ } pstate; private int patchRead(void *cookie, char *outbuf, int outlen) { pstate *st = (pstate *)cookie; char *p; size_t left = outlen, len = 0, count = 0; char buf[MAXLINE]; if (st->leftover && (p = fmem_peek(st->leftover, &len)) && len) { /* If we have overflow from last time, just return it */ count = min(len, left); memcpy(outbuf, p, count); outbuf += count; left -= count; if (len -= count) { memmove(p, &p[count], len); ftrunc(st->leftover, len); } else { fclose(st->leftover); st->leftover = 0; } return (outlen - left); } if (st->sfio) { len = fread(outbuf, 1, left, st->fin); left -= len; st->bytecount += len; if (st->pending && (len != fwrite(outbuf, 1, len, st->pending))) { // XXX: die or keep going with no pending file? fprintf(stderr, "error saving patch\n"); cleanup(CLEAN_PENDING|CLEAN_RESYNC); } return (outlen - left); } again: assert(left); unless (fnext(buf, st->fin)) { if (st->preamble) errorMsg("tp_nothingtodo", 0, 0); return (outlen - left); } st->newline = (!st->longline && streq("\n", buf)); if (opts->echo > 10) { fprintf(stderr, "ST: "); if (st->newline) fprintf(stderr, "nl "); if (st->longline) fprintf(stderr, "ll "); if (st->preamble_nl) fprintf(stderr, "p_nl "); if (st->preamble) fprintf(stderr, "p "); if (st->version) fprintf(stderr, "v "); if (st->versionblank) fprintf(stderr, "vb "); if (st->filename) fprintf(stderr, "f "); if (st->first) fprintf(stderr, "1 "); if (st->perfile) fprintf(stderr, "pf "); if (st->perblank) fprintf(stderr, "pb "); if (st->metadata) fprintf(stderr, "m "); if (st->metaline) fprintf(stderr, "ml "); if (st->metablank) fprintf(stderr, "mb "); if (st->diffs) fprintf(stderr, "d "); if (st->diffsblank) fprintf(stderr, "db "); if (st->sfiopatch) fprintf(stderr, "patch "); if (st->sfiopending) fprintf(stderr, "psfio "); if (st->sfio) fprintf(stderr, "sfio "); fputs(buf, stderr); } if (opts->echo > 7) fprintf(stderr, "P: %s", buf); if (st->longline) { /* do nothing but pass through the rest of the line */ } else if (st->preamble) { if (st->newline) { st->preamble_nl = 1; } if (st->preamble_nl) { if (streq(buf, PATCH_CURRENT) || (opts->fast = streq(buf, PATCH_FAST))) { st->type = 1; st->preamble = 0; st->preamble_nl = 0; } } } else if (st->type) { if (strneq(buf, PATCH_FEATURES, strsz(PATCH_FEATURES))) { st->type = 0; st->version = 1; } else if (streq(buf, PATCH_REGULAR)) { st->type = 0; st->version = 1; } else { fprintf(stderr, "Expected type\n"); goto error; } } else if (st->version) { if (st->newline) { st->version = 0; st->versionblank = 1; } else { /* false alarm */ if (st->pending) rewind(st->pending); st->preamble = 1; st->version = 0; } } else if (st->versionblank) { if (strneq("== ", buf, 3)) { st->versionblank = 0; st->filename = 1; st->first = 1; } else if (strneq(buf, "# Patch checksum=", 17)) { goto dosum; } else { fprintf(stderr, "Expected '== f =='\n"); error: fprintf(stderr, "GOT: %s", buf); cleanup(CLEAN_PENDING|CLEAN_RESYNC); } } else if (st->filename) { if (st->newline) { fprintf(stderr, "Expected metadata\n"); goto error; } else if (strneq(buf, "New file: ", 10)) { st->perfile = 1; } else { st->metadata = 1; } st->filename = 0; } else if (st->perfile) { if (st->newline) { st->perfile = 0; st->perblank = 1; } } else if (st->perblank) { if (st->newline) { fprintf(stderr, "Expected metadata\n"); goto error; } st->metadata = 1; st->perblank = 0; } else if (st->metadata) { #define DIVIDER "------------------------------------------------\n" if (st->newline) { fprintf(stderr, "Expected metadata\n"); goto error; } else if (streq(buf, DIVIDER)) { st->metadata = 0; st->metaline = 1; } } else if (st->metaline) { if (st->newline) { st->metaline = 0; st->metablank = 1; } else { fprintf(stderr, "Expected metablank\n"); goto error; } } else if (st->metablank) { st->metablank = 0; if (st->newline) { /* no diffs */ st->diffsblank = 1; } else { st->diffs = 1; } } else if (st->diffs || st->sfiopatch) { if (st->newline) { st->sfiopatch = st->diffs = 0; st->diffsblank = 1; } else if (st->sfiopatch) { fprintf(stderr, "Expected newline after @SFIO@\n"); goto error; } } else if (st->diffsblank) { if (strneq("== @SFIO@ ==", buf, 12)) { st->sfiopatch = st->sfiopending = 1; st->diffsblank = 0; } else if (strneq("== ", buf, 3)) { st->diffsblank = 0; st->filename = 1; st->first = 0; } else if (strneq(buf, "# Patch checksum=", 17)) { dosum: st->sumR = strtoul(buf+17, 0, 16); assert(st->sumR != 0); st->nosum = 1; st->diffsblank = 0; if (st->sfiopending) { st->sfiopending = 0; st->sfio = 1; } } else if (st->newline) { fprintf(stderr, "Expected '== f ==' or key\n"); goto error; } else { st->diffsblank = 0; st->metadata = 1; } } st->longline = (strchr(buf, '\n') == 0); if (st->preamble) goto again; if (st->pending) { if (fputs(buf, st->pending) == EOF) { perror("fputs on patch"); cleanup(CLEAN_PENDING|CLEAN_RESYNC); } } // write buf to outbuf and overflow to the fmembuf len = strlen(buf); st->bytecount += len; unless (st->nosum) st->sumC = adler32(st->sumC, buf, len); count = min(len, left); memcpy(outbuf, buf, count); outbuf += count; left -= count; if (len -= count) { unless (st->leftover) st->leftover = fmem(); fwrite(&buf[count], 1, len, st->leftover); } return (outlen - left); } private int patchClose(void *cookie) { pstate *st = (pstate *)cookie; char *note, incoming[MAXPATH]; int rc = !feof(st->fin); opts->p = 0; /* XXX: Hack: block recursive close badXsum/cleanup */ /* save byte count for logs */ Fprintf("BitKeeper/log/byte_count", "%lu\n", st->bytecount); if (st->pending) { assert(st->fin == stdin); rc |= fclose(st->pending); note = aprintf("%u", (u32)st->bytecount); cmdlog_addnote("psize", note); free(note); // and do the rename stuff if all is okay. strcpy(incoming, opts->pendingFile); unless (savefile("PENDING", 0, opts->pendingFile)) { SHOUT(); perror("PENDING"); cleanup(CLEAN_RESYNC); } rename(incoming, opts->pendingFile); if (Fprintf( "RESYNC/BitKeeper/tmp/patch", "%s\n", opts->pendingFile) < 0) { perror("RESYNC/BitKeeper/tmp/patch"); exit(1); } if (opts->echo) { NOTICE(); fprintf(stderr, "takepatch: saved entire patch in %s\n", opts->pendingFile); NOTICE(); } } else { rc |= fclose(st->fin); } unless (rc || (st->sumR == st->sumC)) badXsum(st->sumR, st->sumC); if (st->leftover) fclose(st->leftover); free(st); return (rc); } /* * Go find the change set file and do this relative to that. * Create the RESYNC dir or bail out if it exists. * Put our pid in that dir so that we can figure out if * we are still here. * * This function creates patches in the PENDING directory when the * patches are read from stdin. */ private FILE * init(char *inputFile) { char buf[BUFSIZ]; /* used ONLY for input I/O */ char *root, *t; char *saveFile; int i; FILE *f = 0; pstate *patch; /* * If we are reading from stdin and we get ERROR/Nothing, * then bail out before creating any state. */ if (streq(inputFile, "-")) { if (fnext(buf, stdin)) { if (streq(buf, "ERROR\n")) exit(1); if (streq(buf, "OK-Nothing to resync.\n")) { if (opts->echo) fputs(buf, stderr); exit(0); } for (i = strlen(buf); i; i--) ungetc(buf[i-1], stdin); } else { errorMsg("tp_nothingtodo", 0, 0); } } if (opts->newProject) { initProject(); } else { root = proj_root(0); if (!root && emptyDir(".")) { /* If we are invoked in an empty directory, * assume they meant -i. */ if (opts->echo > 0) { fputs("takepatch: creating new repository.\n", stderr); } initProject(); opts->newProject = 1; } else if (proj_cd2root()) { SHOUT(); fputs("takepatch: can't find package root.\n", stderr); SHOUT2(); exit(1); } } resync_lock(); patch = new(pstate); patch->preamble = 1; if (streq(inputFile, "-")) { patch->fin = stdin; /* * Save the patch in the pending dir * and record we're working on it. We use a .incoming * file and then rename it later. */ unless (savefile("PENDING", ".incoming", opts->pendingFile)) { SHOUT(); perror("PENDING"); cleanup(CLEAN_RESYNC); } saveFile = opts->pendingFile; patch->pending = fopen(opts->pendingFile, "wb"); assert(patch->pending); } else { patch->preamble_nl = 1; /* end of pre-amble */ unless (patch->fin = fopen(inputFile, "r")) { perror(inputFile); cleanup(CLEAN_PENDING|CLEAN_RESYNC); } saveFile = ""; /* Don't let abort or resolve rm patch file */ } if (Fprintf("RESYNC/BitKeeper/tmp/patch", "%s\n", saveFile) < 0) { perror("RESYNC/BitKeeper/tmp/patch"); exit(1); } unless (f = funopen(patch, patchRead, 0, 0, patchClose)) { perror("funopen patch"); exit(1); } while (t = fgetline(f)) { if (strneq(t, PATCH_CURRENT, strsz(PATCH_CURRENT)-1) || (opts->fast = strneq(t, PATCH_FAST, strsz(PATCH_FAST)-1))) { break; } } unless (t) errorMsg("tp_noversline", opts->input, 0); unless (t = fgetline(f)) { cleanup(CLEAN_PENDING|CLEAN_RESYNC); } if (strneq(t, PATCH_FEATURES, strsz(PATCH_FEATURES))) { if (parseFeatures(t + strsz(PATCH_FEATURES))) { cleanup(CLEAN_PENDING|CLEAN_RESYNC); } } else unless (strneq(t, PATCH_REGULAR, strsz(PATCH_REGULAR)-1)) { cleanup(CLEAN_PENDING|CLEAN_RESYNC); } return (f); } private void cleanup(int what) { int i, rc = 1; if (opts->p) { if ((opts->p != stdin) && fclose(opts->p)) { fprintf(stderr, "takepatch: failed closing input stream.\n"); } opts->p = 0; } if (opts->patchList) freePatchList(); if (opts->idDB) mdbm_close(opts->idDB); if (opts->goneDB) mdbm_close(opts->goneDB); for (i = 3; i < 20; ++i) close(i); if (opts->nway) { EACH(opts->errfiles) printf("e %s\n", opts->errfiles[i]); freeLines(opts->errfiles, free); EACH(opts->edited) printf("p %s\n", opts->edited[i]); freeLines(opts->edited, free); exit(what | CLEAN_FLAGS); } if (opts->saveDirs) { fprintf(stderr, "takepatch: neither directory removed.\n"); goto done; } if (what & CLEAN_RESYNC) { rmtree(ROOT2RESYNC); } else { fprintf(stderr, "takepatch: RESYNC directory left intact.\n"); } unless (streq(opts->input, "-")) goto done; if (what & CLEAN_PENDING) { unlink(opts->pendingFile); if (emptyDir("PENDING")) { rmdir("PENDING"); } else { fprintf(stderr, "takepatch: other patches left in PENDING\n"); } } else { if (exists(opts->pendingFile)) { fprintf(stderr, "takepatch: patch left in %s\n", opts->pendingFile); } } done: if (what & CLEAN_OK) { rc = 0; } else { if (opts->edited) { shout(); fprintf(stderr, "The following files are modified locally and " "in the patch:\n"); EACH(opts->edited) { fprintf(stderr, "\t%s\n", opts->edited[i]); } fprintf(stderr, "For more information run \"bk help tp1\"\n"); freeLines(opts->edited, free); } SHOUT2(); if (opts->errfiles) { fprintf(stderr, "Errors during update of the following files:\n"); EACH(opts->errfiles) { fprintf(stderr, "%s\n", opts->errfiles[i]); } SHOUT2(); freeLines(opts->errfiles, free); } } exit(rc); } private int parseFeatures(char *next) { char *t; int i; char buf[MAXLINE]; /* copy upto newline */ t = buf; while (*t++ = *next++) { if (*next == '\n') { *t = 0; break; } } next = buf; while (t = strsep(&next, ", \n")) { unless (*t) continue; for (i = 0;; i++) { unless (features[i].name) { fprintf(stderr, "%s: patch feature %s unknown\n", prog, t); return (-1); } if (streq(features[i].name, t)) { ((u8 *)opts)[features[i].offset] = 1; break; } } } return (0); } private FILE ** startNway(int n) { int i; char *cmd; char *counter; opts->outlist = calloc(n, sizeof(FILE *)); opts->sent = calloc(n, sizeof(int)); cmd = aprintf("bk takepatch --Nway%s%s%s%s%s%s " "> RESYNC/BitKeeper/tmp/nwayXXXXX", opts->collapsedups ? " -D" : "", opts->newProject ? " -i" : "", opts->fast ? " --fast" : "", opts->bkmerge ? " --bkmerge" : "", opts->port ? " --port" : "", opts->automerge ? "" : " --no-automerge"); counter = cmd + strlen(cmd) - 5; for (i = 0; i < n; i++) { sprintf(counter, "%05d", i); unless (opts->outlist[i] = popen(cmd, "w")) { stopNway(n, 0, 0); break; } } free(cmd); return (opts->outlist); } private int stopNway(int n, int *confp, int *numcsetsp) { int i, j, conf = 0, numcsets = 0; int cleanFlags = 0; int ret, rc = 0; char file[] = "RESYNC/BitKeeper/tmp/nwayXXXXX"; char *counter, **data = 0; char cmd, *param; FREE(opts->sent); unless (opts->outlist) return (0); counter = file + strlen(file) - 5; for (i = 0; i < n; i++) { if (opts->outlist[i] && (ret = pclose(opts->outlist[i]))) { unless (WIFEXITED(ret)) { rc = -1; continue; } ret = WEXITSTATUS(ret); if (ret & CLEAN_FLAGS) { ret &= ~CLEAN_FLAGS; /* prefer ERROR to OK */ if (!cleanFlags || ((cleanFlags & CLEAN_OK) && !(ret & CLEAN_OK))) { cleanFlags = ret; } } else { rc = -1; } } sprintf(counter, "%05d", i); data = file2Lines(data, file); EACH_INDEX(data, j) { cmd = *data[j]; param = &data[j][2]; switch (cmd) { case 'c' : /* conflict */ conf += atoi(param); break; case 'e' : /* error */ opts->errfiles = addLine(opts->errfiles, strdup(param)); break; case 'p' : /* edited (pfile) */ opts->edited = addLine(opts->edited, strdup(param)); break; case 'r' : /* csets taken in from remote */ numcsets += atoi(param); break; } free(data[j]); } truncLines(data, 0); } freeLines(data, 0); if (confp) *confp += conf; if (numcsetsp) *numcsetsp += numcsets; free(opts->outlist); opts->outlist = 0; if (cleanFlags) cleanup(cleanFlags); return (rc); } /* * See if parallel started. * start it up. * Find one with smallest sent (sfio code), send to it. * if ChangeSet, count files in patch. * Stop with = or # as first char. * XXX: Can a key begin with # ? */ private int sendPatch(char *name, FILE *in) { int i, c, n, cur, sent; int rc = -1; char *line; size_t len; hash *rk = 0; FILE *out; n = opts->parallel; if (!opts->outlist && !(opts->outlist = startNway(n))) return (-1); if (streq(name, GCHANGESET)) { opts->N++; rk = hash_new(HASH_MEMHASH); } cur = 0; for (i = 0; i < n; i++) { if (opts->sent[i] < opts->sent[cur]) cur = i; } out = opts->outlist[cur]; if (opts->echo > 1) fprintf(stderr, "Updating %s\n", name); sent = fprintf(out, "== %s ==\n", name); again: line = fgetln(in, &len); unless (len) { err: if (ferror(out)) { char *buf[1024]; fprintf(stderr, "Draining patch file (%d)\n", rc); while (fread(buf, 1, sizeof(buf), in)); } goto done; } if ((len > 17) && strneq(line, "# Patch checksum=", 17)) { rc = 0; goto done; } unless (len == fwrite(line, 1, len, out)) goto done; sent += len; /* Per file block */ if ((len > 10) && strneq(line, "New file: ", 10)) { while(line = fgetln(in, &len)) { assert(len); unless (len == fwrite(line, 1, len, out)) goto err; sent += len; if (*line == '\n') break; } unless (len) goto err; } /* delta meta data block */ while(line = fgetln(in, &len)) { assert(len); unless (len == fwrite(line, 1, len, out)) goto err; sent += len; if (*line == '\n') break; } unless (len) goto err; /* delta data block */ while(line = fgetln(in, &len)) { assert(len); unless (len == fwrite(line, 1, len, out)) goto err; sent += len; if (*line == '\n') break; if (rk && (*line == '>')) { char *rkstart, *rkend; assert(line[len - 1] == '\n'); line[len - 1] = 0; /* just a safety net */ rkend = separator(line); assert(rkend); *rkend = 0; rkstart = line + (opts->fast ? 1 : 2); if (!changesetKey(rkstart) && hash_insert(rk, rkstart, rkend-rkstart+1, 0, 0)) { opts->N++; } *rkend = ' '; line[len - 1] = '\n'; } } unless (len) goto err; fflush(out); if ((c = getc(in)) == EOF) goto done; ungetc(c, in); if (c != '=') goto again; rc = 0; done: opts->sent[cur] += sent; // opts->sent[cur]++; /* round robin */ // From sfio.c - see comment in sfio_in_Nway() - look for '20' // opts->sent[cur] += 20; // opts->sent[cur] += sent / (25<<10); if (rk) hash_free(rk); return (rc); }
25.343521
76
0.591086
[ "3d" ]
1f26be907245b0ea13f377ff52f9273e92cc01f8
1,366
c
C
c_programme/marksheet.c
Naz365/gub-cse103
ec9b4ef81296c6ee957fd8a3ae8a2a2f0f27327a
[ "Unlicense" ]
2
2020-02-08T14:49:47.000Z
2020-02-09T09:54:55.000Z
marksheet.c
Naz365/gub-cse103
ec9b4ef81296c6ee957fd8a3ae8a2a2f0f27327a
[ "Unlicense" ]
null
null
null
marksheet.c
Naz365/gub-cse103
ec9b4ef81296c6ee957fd8a3ae8a2a2f0f27327a
[ "Unlicense" ]
2
2020-02-08T14:51:10.000Z
2020-02-09T16:53:22.000Z
#include <stdio.h> #include <string.h> // Use struct as a object or storage structure struct Data { char name[1000]; int id; float chem_marks, math_marks, phy_marks; }; int main() { // Take 5 copy of Data Struct struct Data data[5]; char file[150]; FILE *fp; printf("Enter 5 students details: \n"); for (int i = 0; i < 5; i++) { printf("Student no: %d \n", i + 1); printf("Enter student's first name: \n"); scanf("%s", data[i].name); printf("Enter student's id number: \n"); scanf("%d", &data[i].id); printf("Enter Math marks: \n"); scanf("%f", &data[i].math_marks); printf("Enter Chemistry marks: \n"); scanf("%f", &data[i].chem_marks); printf("Enter Physics marks: \n"); scanf("%f", &data[i].phy_marks); } printf("Enter a filename to save data: \n"); scanf("%s", file); char *filename = strcat(file, ".csv"); fp = fopen(filename, "w+"); fprintf(fp, "Student Id, Student Name, Math, Chemistry, Physics, Percentage"); for (int i = 0; i < 5; i++) { float percentage = (data[i].math_marks + data[i].chem_marks + data[i].phy_marks) / 300.0 * 100; fprintf(fp, "\n %d, %s, %f, %f, %f, %f", data[i].id, data[i].name, data[i].math_marks, data[i].chem_marks, data[i].phy_marks, percentage); } fclose(fp); printf("\n Student's marksheet %s file created \n", filename); }
25.296296
142
0.598097
[ "object" ]
1f2a5b7bf39faf3f97ce14d5b1d042c45cf26837
5,801
c
C
pkgs/libs/glib/src/gobject/tests/dynamictests.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
64
2015-03-06T00:30:56.000Z
2022-03-24T13:26:53.000Z
pkgs/libs/glib/src/gobject/tests/dynamictests.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
12
2020-12-15T08:30:19.000Z
2022-03-13T03:54:24.000Z
pkgs/libs/glib/src/gobject/tests/dynamictests.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
40
2015-02-26T15:31:16.000Z
2022-03-03T23:23:37.000Z
/* GLib testing framework examples and tests * Copyright (C) 2008 Imendio AB * Authors: Tim Janik * * This work is provided "as is"; redistribution and modification * in whole or in part, in any medium, physical or electronic is * permitted without restriction. * * This work 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. * * In no event shall the authors or contributors be liable for any * direct, indirect, incidental, special, exemplary, or consequential * damages (including, but not limited to, procurement of substitute * goods or services; loss of use, data, or profits; or business * interruption) however caused and on any theory of liability, whether * in contract, strict liability, or tort (including negligence or * otherwise) arising in any way out of the use of this software, even * if advised of the possibility of such damage. */ #include <glib.h> #include <glib-object.h> /* This test tests the macros for defining dynamic types. */ static GMutex *sync_mutex = NULL; static gboolean loaded = FALSE; /* MODULE */ typedef struct _TestModule TestModule; typedef struct _TestModuleClass TestModuleClass; #define TEST_TYPE_MODULE (test_module_get_type ()) #define TEST_MODULE(module) (G_TYPE_CHECK_INSTANCE_CAST ((module), TEST_TYPE_MODULE, TestModule)) #define TEST_MODULE_CLASS(class) (G_TYPE_CHECK_CLASS_CAST ((class), TEST_TYPE_MODULE, TestModuleClass)) #define TEST_IS_MODULE(module) (G_TYPE_CHECK_INSTANCE_TYPE ((module), TEST_TYPE_MODULE)) #define TEST_IS_MODULE_CLASS(class) (G_TYPE_CHECK_CLASS_TYPE ((class), TEST_TYPE_MODULE)) #define TEST_MODULE_GET_CLASS(module) (G_TYPE_INSTANCE_GET_CLASS ((module), TEST_TYPE_MODULE, TestModuleClass)) typedef void (*TestModuleRegisterFunc) (GTypeModule *module); struct _TestModule { GTypeModule parent_instance; TestModuleRegisterFunc register_func; }; struct _TestModuleClass { GTypeModuleClass parent_class; }; static GType test_module_get_type (void); static gboolean test_module_load (GTypeModule *module) { TestModule *test_module = TEST_MODULE (module); test_module->register_func (module); return TRUE; } static void test_module_unload (GTypeModule *module) { } static void test_module_class_init (TestModuleClass *class) { GTypeModuleClass *module_class = G_TYPE_MODULE_CLASS (class); module_class->load = test_module_load; module_class->unload = test_module_unload; } static GType test_module_get_type (void) { static GType object_type = 0; if (!object_type) { static const GTypeInfo object_info = { sizeof (TestModuleClass), (GBaseInitFunc) NULL, (GBaseFinalizeFunc) NULL, (GClassInitFunc) test_module_class_init, (GClassFinalizeFunc) NULL, NULL, sizeof (TestModule), 0, (GInstanceInitFunc)NULL }; object_type = g_type_register_static (G_TYPE_TYPE_MODULE, "TestModule", &object_info, 0); } return object_type; } GTypeModule * test_module_new (TestModuleRegisterFunc register_func) { TestModule *test_module = g_object_new (TEST_TYPE_MODULE, NULL); GTypeModule *module = G_TYPE_MODULE (test_module); test_module->register_func = register_func; /* Register the types initially */ g_type_module_use (module); g_type_module_unuse (module); return G_TYPE_MODULE (module); } #define DYNAMIC_OBJECT_TYPE (dynamic_object_get_type ()) typedef GObject DynamicObject; typedef struct _DynamicObjectClass DynamicObjectClass; struct _DynamicObjectClass { GObjectClass parent_class; guint val; }; G_DEFINE_DYNAMIC_TYPE(DynamicObject, dynamic_object, G_TYPE_OBJECT); static void dynamic_object_class_init (DynamicObjectClass *class) { class->val = 42; g_assert (loaded == FALSE); loaded = TRUE; } static void dynamic_object_class_finalize (DynamicObjectClass *class) { g_assert (loaded == TRUE); loaded = FALSE; } static void dynamic_object_init (DynamicObject *dynamic_object) { } static void module_register (GTypeModule *module) { dynamic_object_register_type (module); } #define N_THREADS 100 #define N_REFS 10000 static gpointer ref_unref_thread (gpointer data) { gint i; /* first, syncronize with other threads, */ if (g_test_verbose()) g_print ("WAITING!\n"); g_mutex_lock (sync_mutex); g_mutex_unlock (sync_mutex); if (g_test_verbose ()) g_print ("STARTING\n"); /* ref/unref the klass 10000000 times */ for (i = N_REFS; i; i--) { if (g_test_verbose ()) if (i % 10) g_print ("%d\n", i); g_type_class_unref (g_type_class_ref ((GType) data)); } if (g_test_verbose()) g_print ("DONE !\n"); return NULL; } static void test_multithreaded_dynamic_type_init (void) { GTypeModule *module; DynamicObjectClass *class; /* Create N_THREADS threads that are going to just ref/unref a class */ GThread *threads[N_THREADS]; guint i; module = test_module_new (module_register); /* Not loaded until we call ref for the first time */ class = g_type_class_peek (DYNAMIC_OBJECT_TYPE); g_assert (class == NULL); g_assert (!loaded); /* pause newly created threads */ g_mutex_lock (sync_mutex); /* create threads */ for (i = 0; i < N_THREADS; i++) { threads[i] = g_thread_create (ref_unref_thread, (gpointer) DYNAMIC_OBJECT_TYPE, TRUE, NULL); } /* execute threads */ g_mutex_unlock (sync_mutex); for (i = 0; i < N_THREADS; i++) { g_thread_join (threads[i]); } } int main (int argc, char *argv[]) { g_thread_init (NULL); g_test_init (&argc, &argv, NULL); g_type_init (); sync_mutex = g_mutex_new(); g_test_add_func ("/GObject/threaded-dynamic-ref-unref-init", test_multithreaded_dynamic_type_init); return g_test_run(); }
24.580508
111
0.739183
[ "object" ]
1f2cd849a479594c2471e429593eae063d803591
775
h
C
examples/gl3/drawable.h
ousttrue/tinygizmo
0eb067c4a942af0105097c653b697fe234e94b07
[ "Unlicense" ]
null
null
null
examples/gl3/drawable.h
ousttrue/tinygizmo
0eb067c4a942af0105097c653b697fe234e94b07
[ "Unlicense" ]
null
null
null
examples/gl3/drawable.h
ousttrue/tinygizmo
0eb067c4a942af0105097c653b697fe234e94b07
[ "Unlicense" ]
null
null
null
#pragma once #include <simple_span.h> // #include "gl-api.hpp" struct Drawable { GlShader shader; GlMesh mesh; static std::shared_ptr<Drawable> EditorMesh(); static std::shared_ptr<Drawable> TeapotMesh(); void upload(const void *pV, size_t vSize, size_t vCount, const void *pI, size_t iSize, size_t iCount); template <typename V, typename I> void upload(simple::Span<const V> vertices, simple::Span<const I> indices) { upload(vertices.data(), sizeof(V) * vertices.size(), vertices.size(), indices.data(), sizeof(I) * indices.size(), indices.size()); } void draw(const std::array<float, 3> &eye, const std::array<float, 16> &viewProj, const std::array<float, 16> &model); };
29.807692
79
0.630968
[ "mesh", "model" ]
1f31d02a5ce3050d9db4082e11e7f0d27cf74bc2
6,075
h
C
engine/interior/interiorMap.h
ClayHanson/B4v21-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
1
2020-08-18T19:45:34.000Z
2020-08-18T19:45:34.000Z
engine/interior/interiorMap.h
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
engine/interior/interiorMap.h
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
#ifndef _INTERIORMAP_H_ #define _INTERIORMAP_H_ #include "platform/platform.h" #include "sim/sceneObject.h" #include "collision/convex.h" #include "dgl/gTexManager.h" #include "core/tokenizer.h" #include "collision/convexBrush.h" #include "collision/abstractPolyList.h" #include "interior/interiorMapRes.h" // Pre-define the InteriorMap class so that we can reference it in InteriorMapConvex class InteriorMap; // This is the convex collision implementation for InteriorMap // Once something has collided against a InteriorMap then it creates one of // these for the actual collisions to occur against class InteriorMapConvex : public Convex { typedef Convex Parent; friend class InteriorMap; // So the "owner" object can set some properties when it creates this public: // This is where you set the convex type // Needs to be defined in convex.h in the ConvexType enum InteriorMapConvex() { mType = InteriorMapConvexType; }; ~InteriorMapConvex() {}; protected: Box3F box; // The bounding box of the convex (in object space) InteriorMap* pOwner; // A pointer back to the "owner" object so we can reference the vertices U32 nodeIndex; S32 brushIndex; public: // Return the bounding box transformed into world space Box3F getBoundingBox() const; // Return the bounding box transformed and scaled by the input values Box3F getBoundingBox(const MatrixF& mat, const Point3F& scale) const; // This returns a list of convex faces to collide against void getPolyList(AbstractPolyList* list); // Returns the vertices, faces, and edges of our convex void getFeatures(const MatrixF& mat,const VectorF& n, ConvexFeature* cf); // This returns the furthest point from the input vector Point3F support(const VectorF& v) const; // A helper function that checks the edgelist for duplicates void addEdge(U32 zero, U32 one, U32 base, ConvexFeature* cf); }; class InteriorMap : public SceneObject { friend class InteriorMapConvex; // So the "child" convex(es) can reference the vertices public: typedef SceneObject Parent; // Declare Console Object. DECLARE_CONOBJECT(InteriorMap); protected: // Create and use these to specify custom events. // // NOTE:- Using these allows you to group the changes into related // events. No need to change everything if something minor // changes. Only really important if you have *lots* of these // objects at start-up or you send alot of changes whilst the // game is in progress. // // Use "setMaskBits(InteriorMapMask)" to signal. // - Melv May enum { MoveMask = (1 << 0), RenderModeMask = (1 << 1) }; bool mLoaded; // Make sure we don't load this twice public: enum { TexShaded = 0, SolidShaded, TexWireframe, SolidWireframe, Edges, BrushColors, FaceColors, BspPolys, CollisionHulls, Lighting, TexLighting }; TextureHandle* mTexHandles; TextureHandle* mWhite; StringTableEntry mFileName; // The name of the level StringTableEntry mFilePath; // The path of the level StringTableEntry mTexPath; // The path to the textures U32 mRenderMode; bool mEnableLights; Resource<InteriorMapResource> mInteriorRes; InteriorMapResource::Entity* getEntity(char* classname) { for (U32 i = 0; i < mInteriorRes->mEntities.size(); i++) { if (dStricmp(classname, mInteriorRes->mEntities[i]->classname) == 0) return mInteriorRes->mEntities[i]; } return NULL; } void getEntities(char* classname, VectorPtr<InteriorMapResource::Entity*> ents) { for (U32 i = 0; i < mInteriorRes->mEntities.size(); i++) { if (dStricmp(classname, mInteriorRes->mEntities[i]->classname) == 0) { ents.increment(); ents.last() = mInteriorRes->mEntities[i]; } } } protected: Convex* mConvexList; // I split the render and load functions out of renderObject() and onAdd() for clarity bool render(void); public: // Creation and destruction InteriorMap(void); virtual ~InteriorMap(void); // Utility bool setPath(const char* filename); bool loadTextures(); bool calcTexgenDiv(); // SceneObject // renderObject() is the function that gets called for evey SceneObject void renderObject(SceneState*, SceneRenderImage*); // This function gets called to let you define a few proprties like translucency virtual bool prepRenderImage(SceneState*, const U32 stateKey, const U32 startZone, const bool modifyBaseZoneState = false); // SimObject bool onAdd(); void onRemove(); void onEditorEnable(); void onEditorDisable(); void inspectPostApply(); // NetObject U32 packUpdate(NetConnection *, U32, BitStream *); void unpackUpdate(NetConnection *, BitStream *); // ConObject. static void initPersistFields(); // Collision // castRay() returns the percentage along the line from a starting and an ending point // to where something collides with the object bool castRay(const Point3F&, const Point3F&, RayInfo*); // Called whenever something overlaps our bounding box // This is where the SceneObject can submit convexes to the working list of an object interested in collision data void buildConvex(const Box3F& box, Convex* convex); // Script access functions void removeBrush(S32 brushIndex); // Removes brush from mBrushes and deletes it from memory S32 getTextureCount(); // Returns the number of textures used in the map const char* getTextureName(S32 index); // Returns the name of the texture given the texture's index const char* getTexturePathway(); // Returns the texture for the map Point2I getTextureSize(S32 index); // Returns the requested texture's dimensions S32 getBrushIndex(U32 brushID); }; #endif
30.837563
120
0.683951
[ "render", "object", "vector" ]
1f36db42e158bf441b55520e205d6e66b4826ffd
195
h
C
source/HurtBox.h
GoldenBunny/Millibox
34fcd59bd1e5c1a97c1058032aefba0b11d8e48a
[ "MIT" ]
1
2017-12-15T01:14:06.000Z
2017-12-15T01:14:06.000Z
source/HurtBox.h
GoldenBunny/Millibox
34fcd59bd1e5c1a97c1058032aefba0b11d8e48a
[ "MIT" ]
null
null
null
source/HurtBox.h
GoldenBunny/Millibox
34fcd59bd1e5c1a97c1058032aefba0b11d8e48a
[ "MIT" ]
null
null
null
#pragma once #include<vector> #include<memory> #include"PointGroup.h" class HurtBoxList { std::vector<std::shared_ptr<PointGroup>> hurtboxes_; public: decltype(hurtboxes_)& getHurtboxes(); };
19.5
53
0.758974
[ "vector" ]
1f393ab3b449de790a730d491efed7c064928809
263
h
C
WMPageControllerDemo/WMPageControllerExample/WMPageControllerExample/Controller/WMViewController.h
make2a/WMPageController
0661026a98cce1bbd8318a1a65845b532aeb663a
[ "MIT" ]
3,227
2015-06-15T10:27:57.000Z
2022-03-31T05:46:01.000Z
WMPageControllerDemo/WMPageControllerExample/WMPageControllerExample/Controller/WMViewController.h
make2a/WMPageController
0661026a98cce1bbd8318a1a65845b532aeb663a
[ "MIT" ]
616
2015-06-18T09:27:15.000Z
2021-11-30T08:50:01.000Z
WMPageControllerDemo/WMPageControllerExample/WMPageControllerExample/Controller/WMViewController.h
make2a/WMPageController
0661026a98cce1bbd8318a1a65845b532aeb663a
[ "MIT" ]
741
2015-06-18T01:21:24.000Z
2022-03-23T03:18:41.000Z
// // WMViewController.h // WMPageController // // Created by Mark on 15/6/13. // Copyright (c) 2015年 yq. All rights reserved. // #import <UIKit/UIKit.h> @interface WMViewController : UIViewController @property (nonatomic, strong) NSDictionary *model; @end
18.785714
50
0.714829
[ "model" ]
1f3d2113fbe3611b07e73b80d6924a404c9a6459
349
h
C
src/util/std.h
leonszimmermann/accneat
adf6a9c96f024965232267db3514b6f150c12851
[ "Apache-2.0" ]
null
null
null
src/util/std.h
leonszimmermann/accneat
adf6a9c96f024965232267db3514b6f150c12851
[ "Apache-2.0" ]
null
null
null
src/util/std.h
leonszimmermann/accneat
adf6a9c96f024965232267db3514b6f150c12851
[ "Apache-2.0" ]
1
2020-08-31T08:06:07.000Z
2020-08-31T08:06:07.000Z
#include <algorithm> #include <functional> #include <cctype> #include <climits> #include <cstddef> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <fstream> #include <map> #include <memory> #include <random> #include <regex> #include <set> #include <sstream> #include <string> #include <vector>
18.368421
22
0.690544
[ "vector" ]
1f45885933c0a7a9e911394adba3f36f422102e4
9,256
h
C
tools/bin/pythonSrc/PSI-0.3b2_gp/include/psi.h
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
450
2015-09-05T09:12:51.000Z
2018-08-30T01:45:36.000Z
tools/bin/pythonSrc/PSI-0.3b2_gp/include/psi.h
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1,274
2015-09-22T20:06:16.000Z
2018-08-31T22:14:00.000Z
tools/bin/pythonSrc/PSI-0.3b2_gp/include/psi.h
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
278
2015-09-21T19:15:06.000Z
2018-08-31T00:36:51.000Z
/* The MIT License * * Copyright (C) 2008-2009 Floris Bruynooghe * * Copyright (C) 2008-2009 Abilisoft Ltd. * * * 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 PSI_H #define PSI_H #include <Python.h> #include <time.h> /** Exceptions * * These are created by the module init function. */ extern PyObject *PsiExc_AttrNotAvailableError; extern PyObject *PsiExc_AttrInsufficientPrivsError; extern PyObject *PsiExc_AttrNotImplementedError; extern PyObject *PsiExc_MissingResourceError; extern PyObject *PsiExc_InsufficientPrivsError; /** Create a new PsiTimeSpec object * * This does get the _C_API CObject from the psi._psi module behind the * scenes. */ PyObject *PsiTimeSpec_New(const struct timespec *tv); /** Constants representing status information of attributes * * These constants are for use with the *_status attributes of the *info * structures. The "not implemented" option is set to 0 so that if you * allocate the memory with psi_calloc(3) this will be the default. This * means that things won't blow up if you forget a field or one gets added but * the arch implementation doesn't have it yet (but don't forget to use calloc * instead of malloc for this!). */ #define PSI_STATUS_NI 0 /* not implemented */ #define PSI_STATUS_OK 1 /* data collected fine */ #define PSI_STATUS_NA 2 /* not available for this process */ #define PSI_STATUS_PRIVS 3 /* insufficient priviliges */ /** Check the attribute of an *info structure * * This checks the status attribute passed in against the PSI_STATUS_* * constants and will raise the appropriate Python exception if it is not * PSI_STATUS_OK. The name parameter is used in the Python exception. * * Returns -1 if a Python exception is raised and 0 if not. */ int psi_checkattr(const char* name, const int status); /** Memory management functions * * These are important since memory needs to be allocated in architecture * specific implementations and freed in the global/python part of PSI. * Therefore everyone must use the same memory management functions. By using * these functions it is easy to decide at build time if you want to use the * libc memory allocator or the Python one etc. * * Additionally these function will have set the appropriate Python exception * if they return NULL. */ void *psi_malloc(size_t size); void *psi_realloc(void *ptr, size_t size); void psi_free(void *ptr); void *psi_calloc(size_t size); #define psi_FREE(p) if (p != NULL) psi_free(p) /** String functions, allocating memory on the fly * * These are equivalent to the stdlib ones and their use should be obvious. * Again, in case of error NULL is returned and the correct Python exception * is raised. */ char *psi_strdup(const char *str); char *psi_strndup(const char *str, size_t n); /** Store string in a newly created buffer * * This function is like asprintf() in GNU libc, but if an error occurs a * Python exception will be raised. On success the allocated buffer will have * to be freed using psi_free(). * * The return value is the number of characters allocated for the buffer, or * -1 in case of an error. In case of an error ptr will also be a NULL * pointer. */ int psi_asprintf(char **ptr, const char *template, ...); /** String conversion and formatting * * Do not forget to use the PyOS_* functions for string formatting whenever * possible. They are more portable, see * http://docs.python.org/c-api/conversion.html for their documentation. */ /** Read a file into a newly created buffer * * Allocates a new buffer with psi_malloc, fills it with the file's contents * and returns it. Don't forget to free the buffer with psi_free(). If it * fails buf will point to NULL. * * `path' is really `const' but PyErr_SetFromErrnoWithFilename is not declared * properly. * * Returns the used size of the buffer on success, a negative value with an * OSError raised on failure. -1 for a generic failure and -2 in case of a * permissions problem (interprets the errno value for you). */ int psi_read_file(char **buf, char *path); /** Read a link and allocate space for the string automtically * * This will allocate the space for the target string using psi_malloc(), call * psi_free() on it when you're done. If it fails target will point to NULL. * * The result will be stored in `target' and will be `\0' terminated. * * The `link' parameter is really `const' but PyErr_SetFromErrnoWithFilename * is not declared as such. * * Returns a negative integer on error, with OSError exception raised. -2 is * returned in case of insufficient privileges, -1 for any other errors. The * errno detail will be in the exception. */ int psi_readlink(char **target, char *link); /** Return the number of strings in a buffer * * This function will count the number of `\0' terminated strings in a buffer. * * @param buf: The buffer. * @param size: The size of the buffer. * * @returns the number of `\0's found */ int psi_strings_count(const char *cmdl, const int size); /** Return an array of strings build from a list of strings * * This function will create a new array of strings based on a buffer filled * with consecutive strings. Each element in the returned array must be freed * using psi_free() after which the array itself must be freed with * psi_free(). * * XXX This sucks, surely the implementation can figure out how large the * array needs to be and then allocate it all at once. That would be a * lot more natural. * * @param buf: The buffer, really `const' but compiler is not clever enough. * @param count: The number of strings in the buffer. */ char **psi_strings_to_array(char *buf, const int count); /** Deal with Python 3.0 * * The following macros make dealing with Python 3.0 aka Python 3000 aka py3k * easier. */ #if PY_MAJOR_VERSION >= 3 #define PY3K #endif /* We would like to just use unicode in Python 2.x too but the convenient * PyUnicode_From*() functions don't exist yet there! */ #ifdef PY3K #define PyStr_FromString(...) PyUnicode_FromString(__VA_ARGS__) #define PyStr_FromFormat(...) PyUnicode_FromFormat(__VA_ARGS__) #else #define PyStr_FromString(...) PyString_FromString(__VA_ARGS__) #define PyStr_FromFormat(...) PyString_FromFormat(__VA_ARGS__) #endif /** Deal with old Pythons * * These macro's and definitions help with early Python support. */ #ifndef PyDoc_VAR #define PyDoc_VAR(name) static char name[] #endif #ifndef PyDoc_STR #define PyDoc_STR(str) str #endif #ifndef PyDoc_STRVAR #define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str) #endif #ifndef PyMODINIT_FUNC #define PyMODINIT_FUNC void #endif #if PY_VERSION_HEX < 0x02030000 /* < 2.3 */ #define PyExc_FutureWarning PyExc_Warning #endif #if PY_VERSION_HEX < 0x02040000 /* < 2.4 */ #define Py_CLEAR(op) \ do { \ if (op) { \ PyObject *_py_tmp = (PyObject *)(op); \ (op) = NULL; \ Py_DECREF(_py_tmp); \ } \ } while (0) #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None #define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True #define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False double PyOS_ascii_strtod(const char *nptr, char **endptr); double PyOS_ascii_atof(const char *nptr); #endif #if PY_VERSION_HEX < 0x02050000 /* < 2.5 */ typedef int Py_ssize_t; typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t); #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyErr_WarnEx(EXC, MSG, LVL) PyErr_Warn(EXC, MSG) #endif #if PY_VERSION_HEX < 0x02060000 /* < 2.6 */ #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #define PyImport_ImportModuleNoBlock(NAME) PyImport_ImportModule(NAME) #endif #if PY_VERSION_HEX < 0x03010000 /* < 3.1 */ double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception); #endif #endif /* PSI_H */
32.477193
78
0.723963
[ "object" ]
1f5d9637767b20dbc1bc1e10071ea71bf31a32e6
2,404
h
C
include/Backends/RepriseToClang/ClangGeneratorTypes.h
czen/open-ops
b1ab8da354c4aecc0fe76a562395f5861bffc207
[ "BSD-3-Clause" ]
23
2017-08-01T14:29:48.000Z
2019-10-09T22:27:38.000Z
include/Backends/RepriseToClang/ClangGeneratorTypes.h
czen/open-ops
b1ab8da354c4aecc0fe76a562395f5861bffc207
[ "BSD-3-Clause" ]
2
2017-08-06T08:34:18.000Z
2017-08-08T16:27:38.000Z
include/Backends/RepriseToClang/ClangGeneratorTypes.h
czen/open-ops
b1ab8da354c4aecc0fe76a562395f5861bffc207
[ "BSD-3-Clause" ]
2
2017-08-08T12:25:06.000Z
2019-09-16T15:18:18.000Z
/// ClangGeneratorTypes.h /// Created: 27.02.2013 #ifndef CLANGGENERATORTYPES_H__ #define CLANGGENERATORTYPES_H__ #include "OPS_Core/disable_llvm_warnings_begin.h" #include "clang/AST/ASTContext.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/OwningPtr.h" #include "OPS_Core/disable_llvm_warnings_end.h" #include <vector> namespace clang { class CompilerInstance; class LangOptions; class DiagnosticsEngine; class FileManager; class IdentifierTable; class SelectorTable; class SourceManager; class TargetInfo; class TargetOptions; namespace Builtin { class Context; } } namespace OPS { namespace Backends { namespace Clang { typedef llvm::IntrusiveRefCntPtr <clang::ASTContext> ASTContextPtr; typedef std::vector <ASTContextPtr> ASTContexts; namespace Internal { typedef llvm::IntrusiveRefCntPtr <clang::LangOptions> LangOptionsPtr; typedef llvm::IntrusiveRefCntPtr <clang::DiagnosticsEngine> DiagnosticsEnginePtr; typedef llvm::IntrusiveRefCntPtr <clang::FileManager> FileManagerPtr; typedef llvm::IntrusiveRefCntPtr <clang::SourceManager> SourceManagerPtr; typedef llvm::IntrusiveRefCntPtr <clang::TargetInfo> TargetInfoPtr; typedef llvm::OwningPtr <clang::IdentifierTable> IdentifierTablePtr; typedef llvm::OwningPtr <clang::SelectorTable> SelectorTablePtr; typedef llvm::OwningPtr <clang::Builtin::Context> BuiltinContextPtr; class ASTContextParams { public: // ASTContextParams(); explicit ASTContextParams( clang::TargetOptions& rTargetOptions); ~ASTContextParams(); // // Attributes: public: // void initialize( clang::CompilerInstance& rCompilerInstance); // // Operations: public: // clang::ASTContext* createASTContext(); // private: // LangOptionsPtr m_PLangOptions; DiagnosticsEnginePtr m_PDiagEngine; FileManagerPtr m_PFileManager; SourceManagerPtr m_PSourceManager; TargetInfoPtr m_PTargetInfo; IdentifierTablePtr m_PIdTable; SelectorTablePtr m_PSelectorTable; BuiltinContextPtr m_PBuiltinContext; // }; // class ASTContextParams } // namespace Internal } // namespace Clang } // namespace Backends } // namespace OPS #endif // CLANGGENERATORTYPES_H__ // End of File
21.464286
63
0.710899
[ "vector" ]
1f5de5c699f293d09712d505dbdd1aed2314fa87
8,522
h
C
Library/src/HTAlert.h
bldcm/Libwww
ba230049bbf6246f9c055ddf9c1526fe98ae9a4f
[ "W3C-19980720" ]
1
2021-06-12T16:01:59.000Z
2021-06-12T16:01:59.000Z
Library/src/HTAlert.h
bldcm/Libwww
ba230049bbf6246f9c055ddf9c1526fe98ae9a4f
[ "W3C-19980720" ]
null
null
null
Library/src/HTAlert.h
bldcm/Libwww
ba230049bbf6246f9c055ddf9c1526fe98ae9a4f
[ "W3C-19980720" ]
3
2018-06-09T18:52:08.000Z
2020-09-25T14:19:59.000Z
/* W3C Sample Code Library libwww Library Alert Class ! The Alert Class ! */ /* ** (c) COPYRIGHT MIT 1995. ** Please first read the full copyright statement in the file COPYRIGH. */ /* The Alert class defines a set of methods to be used by libwww for passing prompts and message to the application. In order to maintain libwww application independent and natural language independent, it does not know how to communicate with a user. Note here that a user is a somewhat abstract notion for &nbsp;something that can receive a message or prompt from libwww. A user can for example be a person, but is may also be handled automatically by a robot or a client receiving a response from a HTTP server. Libwww has a set of opcodes that classifies the nature of the message, for example that it is a question that must be confirmed in order to continue a request or simply a progress notification. The application can register a callback for any number of the defined opcodes - in case libwww has a message for an opcode that does not have a method associated, the message is ignored. You can also globally disable any message send from libwww. Note: The library core does not define any message or dialog methods - they are all considered part of the application. However, it comes with a default set of methods which can be initiated using the function HTAlertInit() in HTInit module This module is implemented by HTAlert.c, and it is a part of the W3C Sample Code Library. */ #ifndef HTALERT_H #define HTALERT_H #include "HTReq.h" /* . Message Opcodes and Messages . The callback functions are defined as a generic callback where the caller can pass a set of input parameters and the callee can return a set of outptu parameters. Also note that all the *_PROG_* opcodes are a subset of HT_A_PROGRESS. This means that you easily can register a callback for all progress reports. The callback handler for progress notifications SHOULD NOT be used to interrupt the ongoing message as it is not guaranteed to be in a state to do so. Instead you should use the event handlers or the timers for this. */ typedef enum _HTAlertOpcode { HT_PROG_DNS = 0x1, /* Doing DNS resolution */ HT_PROG_CONNECT = 0x2, /* Connecting Active */ HT_PROG_ACCEPT = 0x4, /* Connecting Passive */ HT_PROG_READ = 0x8, /* Read data */ HT_PROG_WRITE = 0x10, /* Write data */ HT_PROG_DONE = 0x20, /* Request finished */ HT_PROG_INTERRUPT = 0x40, /* Request interrupted */ HT_PROG_OTHER = 0x80, /* Other progress notes */ HT_PROG_TIMEOUT = 0x100, /* Request timed out */ HT_PROG_LOGIN = 0x200, /* Automatic login notifications */ HT_A_PROGRESS = 0xFFFF, /* Get all progress reports - no reply */ /* First word are reserved for progresss notifications */ HT_A_MESSAGE = 0x1<<16, /* Send a message - no reply */ HT_A_CONFIRM = 0x2<<16, /* Want YES or NO back */ HT_A_PROMPT = 0x4<<16, /* Want full dialog */ HT_A_SECRET = 0x8<<16, /* Secret dialog (e.g. password) */ HT_A_USER_PW = 0x10<<16 /* Atomic userid and password */ } HTAlertOpcode; typedef struct _HTAlertPar HTAlertPar; typedef BOOL HTAlertCallback (HTRequest * request, HTAlertOpcode op, int msgnum, const char * dfault, void * input, HTAlertPar * reply); /* If you don't expect any return values then reply can be NULL. The return value of the callback function can be used to indicate confirmation on a prompt (Yes or No). . User Prompts and Questions . This is an enumerated list of messages that can be converted into a string table etc. See the HTDialog module for default initialization of these strings. */ typedef enum _HTAlertMsg { HT_MSG_NULL = -1, HT_MSG_UID = 0, HT_MSG_PROXY_UID, HT_MSG_FTP_UID, HT_MSG_PW, HT_MSG_FILENAME, HT_MSG_ACCOUNT, HT_MSG_METHOD, HT_MSG_MOVED, HT_MSG_RULES, HT_MSG_FILE_REPLACE, HT_MSG_RETRY_AUTHENTICATION, HT_MSG_RETRY_PROXY_AUTH, HT_MSG_REDO, HT_MSG_BIG_PUT, HT_MSG_SOURCE_MOVED, HT_MSG_DESTINATION_MOVED, HT_MSG_REDIRECTION, HT_MSG_PROXY, HT_MSG_CACHE_LOCK, HT_MSG_ACCEPT_COOKIE, HT_MSG_ELEMENTS /* This MUST be the last element */ } HTAlertMsg; /* . Enable or Disable Messages . If you really don't want the library to prompt for anything at all then enable this constant. The default value is Interactive. */ extern void HTAlert_setInteractive (BOOL interative); extern BOOL HTAlert_interactive (void); /* . Creation and Deletion Methods . Message methods are registered in lists. By default a list is not enabled before you assign it as being active. This allows the application to maintain multiple lists of message handlers which can be swapped in and out as neeeded. ( Add a Callback Function ) Register a call back function that is to be called when generating messages, dialog, prompts, progress reports etc. The opcode signifies which call back function to call depending of the type of the message. Opcode can be any combination of the bitflags defined by HTAlertOpcode. If you register one callback for HT_A_PROGRESS then this will get called on all progress notifications. */ extern BOOL HTAlertCall_add (HTList * list, HTAlertCallback * cbf, HTAlertOpcode opcode); /* ( Delete a Callback function ) Unregister a call back function from a list */ extern BOOL HTAlertCall_delete (HTList * list, HTAlertCallback * cbf); /* ( Delete all Callbacks With this Opcode ) Unregister all handlers registered for a given opcode. */ extern BOOL HTAlertCall_deleteOpcode (HTList * list, HTAlertOpcode opcode); /* ( Delete a list of Callback Functions ) Unregisters all call back functions */ extern BOOL HTAlertCall_deleteAll (HTList * list); /* ( Find a Callback Function ) Finds a callback function corresponding to the opcode. If none has been registered then NULL is returned. */ extern HTAlertCallback * HTAlertCall_find(HTList * list, HTAlertOpcode opcode); /* . The Reply Object . The reply object is used for communicating input from the user back to the Library. This is only required to use when for example the user is prompted for a file name etc. You can find several examples on how to use this in the default message and dialog module provided together with the Library. */ extern HTAlertPar * HTAlert_newReply (void); extern void HTAlert_deleteReply (HTAlertPar * old); /* ( Handle the Reply Message ) These methods provide the API for handling the reply message. There are two ways of assigning a message to the reply message - either by copying the buffer or by reusing the same buffer. In the latter case, the caller must make sure not to free the reply message before it has been used. */ extern BOOL HTAlert_setReplyMessage (HTAlertPar * me, const char *message); extern BOOL HTAlert_assignReplyMessage (HTAlertPar * me, char * message); /* You can get the data back again by using this method: */ extern char * HTAlert_replyMessage (HTAlertPar * me); /* */ extern char * HTAlert_replySecret (HTAlertPar * me); extern BOOL HTAlert_setReplySecret (HTAlertPar * me, const char * secret); extern void * HTAlert_replyOutput (HTAlertPar * me); extern BOOL HTAlert_setReplyOutput (HTAlertPar * me, void * output); /* . Active set of Callback Functions . A list can be assigned as being active in which case it is visible for libwww by assigning the list as the global alert list. Libwww does not know about inactive lists of alert handlers. */ extern void HTAlert_setGlobal (HTList * list); extern HTList * HTAlert_global (void); /* ( Global Alert List Methods ) You can assign a callback directly to the global list in which case it becomes immediately available to libwww. In this case you do not need to worry about creating the list - it will be created as well as deleted automatically. Add an Alert Handler */ extern BOOL HTAlert_add (HTAlertCallback * cbf, HTAlertOpcode opcode); /* Delete an Alert Handler You can either delete a handler by referring to its address or to the opcode that it has been registered for. */ extern BOOL HTAlert_delete (HTAlertCallback * cbf); extern BOOL HTAlert_deleteOpcode (HTAlertOpcode opcode); /* Delete all Alert Handlers */ extern BOOL HTAlert_deleteAll (void); /* Find an Alert Handler */ extern HTAlertCallback * HTAlert_find (HTAlertOpcode opcode); /* */ #endif /* @(#) $Id: HTAlert.html,v 2.56 1999/06/30 20:15:03 frystyk Exp $ */
26.383901
81
0.745717
[ "object" ]
1f5ea2a483bdd5df8c4150e738f043ba1ef52d98
2,740
h
C
src/extThree20CSSStyle/Headers/TTCSSGlobalStyle.h
joecaraccio/fantasy
0e27b65cb219744383181c19ac24d24ce312269e
[ "Apache-2.0" ]
2
2015-09-04T16:08:51.000Z
2015-10-30T10:32:19.000Z
src/extThree20CSSStyle/Headers/TTCSSGlobalStyle.h
joecaraccio/fantasy
0e27b65cb219744383181c19ac24d24ce312269e
[ "Apache-2.0" ]
null
null
null
src/extThree20CSSStyle/Headers/TTCSSGlobalStyle.h
joecaraccio/fantasy
0e27b65cb219744383181c19ac24d24ce312269e
[ "Apache-2.0" ]
1
2015-01-23T03:06:28.000Z
2015-01-23T03:06:28.000Z
// // Copyright 2009-2011 Facebook // // 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. // /////////////////////////////////////////////////////////////////////////////////////////////////// // CSS Style helpers #define TTCSSSTYLESHEET ([[TTDefaultCSSStyleSheet globalCSSStyleSheet] styleSheet]) #define TTCSS_color(_SELECTOR, _STATE) \ ([TTCSSSTYLESHEET colorWithCssSelector:_SELECTOR forState:_STATE]) #define TTCSS_backgroundColor(_SELECTOR, _STATE) \ ([TTCSSSTYLESHEET backgroundColorWithCssSelector:_SELECTOR forState:_STATE]) #define TTCSS_font(_SELECTOR, _STATE) \ ([TTCSSSTYLESHEET fontWithCssSelector:_SELECTOR forState:_STATE]) #define TTCSS_shadowColor(_SELECTOR, _STATE) \ ([TTCSSSTYLESHEET textShadowColorWithCssSelector:_SELECTOR forState:_STATE]) #define TTCSS_shadowOffset(_SELECTOR, _STATE) \ ([TTCSSSTYLESHEET textShadowOffsetWithCssSelector:_SELECTOR forState:_STATE]) #define TTCSS_shadowRadius(_SELECTOR, _STATE) \ ([TTCSSSTYLESHEET textShadowRadiusWithCssSelector:_SELECTOR forState:_STATE]) // _VARNAME must be one of: color, backgroundColor, font, shadowColor, shadowOffset, shadowRadius #define TTCSSSTATE(_SELECTOR, _VARNAME, _STATE) \ TTCSS_##_VARNAME(_SELECTOR, _STATE) /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /** * Retrieve a Full CSS Rule (TTCSSRuleSet) for specified selector. */ #define TTCSSRule(selector) (TTCSSRuleSet*)[[TTDefaultCSSStyleSheet\ globalCSSStyleSheet] css:selector] /** * Retrieve an value for a property of an Rule Set (TTCSSRuleSet) for specified selector. */ #define TTCSS(selector,property) [TTCSSRule(selector) property] /** * Apply an CSS style to specified object. * The object must conform with the TTCSSApplyProtocol. */ #define TTApplyCSS(selector,object) [[TTDefaultCSSStyleSheet globalCSSStyleSheet]\ applyCssFromSelector:selector\ toObject:object]
42.153846
99
0.633212
[ "object" ]
1f6447aa962002c1c80e3f4e7d7c26bbf0609464
1,193
h
C
src/HeaderFiller.h
fermi-lat/HepRepSvc
4737c4df08a97ac15c66c0d9997db05529f9d559
[ "BSD-3-Clause" ]
null
null
null
src/HeaderFiller.h
fermi-lat/HepRepSvc
4737c4df08a97ac15c66c0d9997db05529f9d559
[ "BSD-3-Clause" ]
null
null
null
src/HeaderFiller.h
fermi-lat/HepRepSvc
4737c4df08a97ac15c66c0d9997db05529f9d559
[ "BSD-3-Clause" ]
null
null
null
#ifndef HEADERFILLER_H #define HEADERFILLER_H #include <vector> #include <string> #include "Filler.h" class IDataProviderSvc; class HepRepInitSvc; class IRootIoSvc; /** * @class HeaderFiller * * @brief The filler for the Event Header * * This filler is used to populate the HepRep event with info retrived from the * EventHeader. * * @author R.Giannitrapani */ class HeaderFiller: public Filler{ public: HeaderFiller(HepRepInitSvc* /*hrisvc*/, IDataProviderSvc* dpsvc, IRootIoSvc* rootIoSvc ): m_dpsvc(dpsvc), m_rootIoSvc(rootIoSvc) {}; /// This method init the type tree virtual void buildTypes (); /// This method fill the instance tree, using the string vector to decide /// which subinstances to fill virtual void fillInstances (std::vector<std::string>&); /// A method that return true if list contain type /// TODO STL already has this private: /// This is the list of subfillers for the event (MC and Recon) std::vector<IFiller*> m_subFillers; HepRepInitSvc* m_hrisvc; /// A pointer to the DataService IDataProviderSvc* m_dpsvc; /// root svc IRootIoSvc* m_rootIoSvc; }; #endif //HEADERFILLER_H
22.509434
81
0.701593
[ "vector" ]
1f6a6f4fca0313d3c0d1bf5a06db07411256ac84
22,629
h
C
Docs/Lua/Lua_C_API.h
turesnake/tprLearningNotes
cc25dbd108e3aff47f1d63b55591e6a5ea6f061d
[ "MIT" ]
null
null
null
Docs/Lua/Lua_C_API.h
turesnake/tprLearningNotes
cc25dbd108e3aff47f1d63b55591e6a5ea6f061d
[ "MIT" ]
null
null
null
Docs/Lua/Lua_C_API.h
turesnake/tprLearningNotes
cc25dbd108e3aff47f1d63b55591e6a5ea6f061d
[ "MIT" ]
null
null
null
/* * ========================= Lua_C_API.h ========================== * -- tpr -- * ---------------------------------------------------------- * C 部分 API * * ---------------------------- */ #include <unistd.h> //- size_t #include <stdarg.h> //- va_list //--------------------------------------------------- // lua栈。 // 一个不透明的 struct,指向一个线程,通过这个线程,间接获得 lua解释器的 所有 state // Lua library 是完全可重入的,它没有全局变量。 // 有关一个 state/状态机 的所有信息,都可通过这个 struct 来访问 // 库中所有函数的 首参数,就是一个 指向 lua_State 的指针(除了 lua_newstate函数。) typedef struct lua_State lua_State; //--------------------------------------------------- // lua state 使用的 内存分配函数 函数指针。 // 此 内存分配函数,必须提供类似 realloc 的功能,但不完全一样 // param: ud -- 不透明指针, // param: ptr -- 指向一块 block 的指针,这块内存区域将被 allocated / reallocated / freed // param: osize -- block 的旧尺寸/或 // param: nsize -- block 的新尺寸 typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); //- 当 ptr != NULL, osize 应该传入 block 的旧尺寸 //- 当 ptr == NULL, osize 应写入 如下几项之一: // LUA_TSTRING // LUA_TTABLE // LUA_TFUNCTION // LUA_TUSERDATA // LUA_TTHREAD // 若 osize 不为以上之一,lua将分配内存做它用(未查明) //- 若 nsize 为 0。内存分配器必须表现得像个 free()。且返回 NULL // 若 nsize 非 0.内存分配器必须表现得像个 realloc()。 // 此时,如果 内存分配器无法满足 调用者需求,将返回 NULL // lua假定。若 osize>=nsize. 内存分配器将 永不失败。 //---- 例子 ----- // static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { // (void)ud; (void)osize; // if (nsize == 0) { // free(ptr); // return NULL; // } else { // return realloc(ptr, nsize); // } // } //--------------------------------------------------- //- 在一个新的独立的 state/虚拟栈中 创建一个 新线程。 //- param:f -- 内存分配函数。用来执行 lua中的一切内存分配 //- param:ud -- 每次调用本函数时,传递给 f 的一个 不透明指针 lua_State *lua_newstate (lua_Alloc f, void *ud); //-- return: // 若失败,返回 NULL (当无法创建新线程,或新虚拟栈,因为内存不足) // //--------------------------------------------------- // 函数指针,被 lua_load 函数使用。每次需要 chunk 的另一块 piece时 // lua_load 就调用 lua_Reader,传入参数 data, // reader 就 返回一个指针,指向 a block of memory with a new piece of the chunk // 同时反向设置 参数size 的值为 block size。 // block 必须持续存在到 reader 函数下一次被调用 // 为了标记 chunk 的 end。reader必须返回 NULL,或者设置 size 为 0. // 本函数可能返回 任何一块 值大于0 的 piece。 typedef const char * (*lua_Reader) (lua_State *L, void *data, size_t *size); //--------------------------------------------------- // Loads a Lua chunk,但并不运行它。 // param: L -- // param: reader -- 用户提供的函数(指针),用来读取 chunk // param: data -- 不透明值 // param: chunkname -- 给予 chunk 一个name,用于 error msg, debug info // param: mode -- 类似 lua函数 load 中的参数 mode 的用法... // 不同之处在于,若输入值为NULL。等于输入 "bt" // 本函数会自动检测 目标chunk 是文本还是二进制文件,并用不同的方法加载它 // 本函数在内部使用 stack,所以 reader函数在 返回时 必须总是 保证 stack 没有被改动 // If the resulting function has upvalues, its first upvalue is set to // the value of the global environment stored at index LUA_RIDX_GLOBALS in the registry // 当加载 main chunks,this upvalue will be the _ENV variable // Other upvalues are initialized with nil // // int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode); //-- return: // 若返回 -- LUA_OK, (值为0) // 说明运行正确。 // 并把 编译好的 chunk, 以 lua function 的形式 // push 到 lua栈中。 // 若返回 -- LUA_ERRSYNTAX. // 说明在 预编译阶段 发生 syntax error。 // 若返回 -- LUA_ERRMEM: // 内存分配错误(内存不够) // 若返回 -- LUA_ERRGCMM // 说明 在运行一个 __gc metamethod 时发生错误 // 与 被加载的 chunk 无关,是在 垃圾回收器中 发生的错误 //-- 上述各个失败,也将把 error message,push 到 lua栈中。 //--------------------------------------------------- // Loads a string as a Lua chunk // 使用 lua_load 来 加载 chunk,in the 以尾后0结尾的 string s int luaL_loadstring (lua_State *L, const char *s); //-- return: // 返回 lua_load() 函数的返回值 //- 和 lua_load() 一样,本函数只 加载 chunk,不运行它 //--------------------------------------------------- // Calls a function. // 使用规则: // -1- 确保目标函数 已经被 push 进 stack // -2- 然后,相关参数被 以 direct order push 进 stack(第一个参数先入栈) // -3- 最后,再来调用 lua_call。 // param: L // param: nargs -- 参数个数 // param: nresults -- 返回值个数 // 若为 LUA_MULTRET,表示 “接受所有 返回值” void lua_call (lua_State *L, int nargs, int nresults); //- 目标函数 在 lua 中正式调用时,会把 stack 中的 函数变量,参数 都 pop 出来 // 然后,函数运行结束后,会把 返回值 push 进 stack 中。(个数根据参数 nresults 来定 ) // 返回值入栈规则按照 direct order (第一个值先入栈) //- 在调用过程中发生的任何 error,都将 “向上传递” -- propagated upwards (with a longjmp) //- 情确保,在一系列 lua_call 流程后,将 stack 恢复到最初的状态。 //--------------------------------------------------- typedef int lua_KContext; //- tmp // type for continuation-function contexts // 它必须是个 numeric type: // -- 当 intptr_t 是可获得的,此类型被定义为 intptr_t。(可以存储 指针) // -- 否则,被定义为 ptrdiff_t typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); // Type for continuation functions //--------------------------------------------------- // 和 lua_call 功能一样,但允许 the called function to yield void lua_callk (lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k); //--------------------------------------------------- // "protected call" // Calls a function in protected mode // -- 如果在 函数调用期间,没有发生 error,本函数和 lua_call 效果一样 // -- 如果发生任何 error,本函数 catch the error。 // pushes a single value on the stack (the error object) // and returns an error code。 // param: L // param: nargs // param: nresults // param: msgh -- 若为0,放入 stack 中的 error object 会是 the original error object // 否则,msgh is the stack index of a message handler // int lua_pcall (lua_State *L, int nargs, int nresults, int msgh); //- 和 lua_call 一样,本函数也会把 stack 中的 函数变量 和 参数都取出 //-- return: // 若返回 -- LUA_OK (值为0) // 说明运行正确。 // 若返回 -- LUA_ERRRUN // a runtime error // 若返回 -- LUA_ERRMEM: // 内存分配错误(内存不够) // 此时,lua 不会调用 message handler // 若返回 -- LUA_ERRERR // 运行 message handler 时发生 error // 若返回 -- LUA_ERRGCMM // 在运行 a __gc metamethod 时发生 error。 // 此时,lua 不会调用 message handler //--------------------------------------------------- // 和 lua_pcall 功能一样,但允许 the called function to yield int lua_pcallk (lua_State *L, int nargs, int nresults, int msgh, lua_KContext ctx, lua_KFunction k); //------------------------------------------------------------- // Type for C functions. // c函数指针,指向一个 c函数,这个c函数 将被 lua 调用。 //-- 一个c函数 想要被 lua 使用,必须符合特定的 制作规范。尤其是 参数和返回值的传递规则: // -- 先调用 lua_gettop,获得 stack 中元素个数。这些元素 就是 c函数的 参数 // 然后通过 lua_toXXX 系列函数,从 stack 中取出元素,到c函数中,然后使用这些 参数 // -- 当主体内容执行完毕,要将返回值 传递给 lua 时。 // 将 返回值 按照 in direct order (第一个返回值先push)push 到 stack // 最后,在 c函数中,return 返回值的 个数 //-- (被 lua 调用的 C函数,也能返回 多个 返回值) typedef int (*lua_CFunction) (lua_State *L); //--- C函数 示范 --- // static int foo (lua_State *L) { // int n = lua_gettop(L); /* number of arguments */ // lua_Number sum = 0.0; // int i; // for (i = 1; i <= n; i++) { // if (!lua_isnumber(L, i)) { // lua_pushliteral(L, "incorrect argument"); // lua_error(L); // } // sum += lua_tonumber(L, i); // } // lua_pushnumber(L, sum/n); /* first result */ // lua_pushnumber(L, sum); /* second result */ // return 2; /* number of results */ // } //-------------------------------------------------------------- // lua_pushXXX //-------------------------------------------------------------- typedef double lua_Number; //- tmp // The type of floats in Lua // 此类型默认为 double, 但可变为 a single float / a long double // 参见 LUA_FLOAT_TYPE in luaconf.h typedef long long lua_Integer; // The type of integers in Lua // 默认为 long long,/ i64. 但可变为 long / int // 参见 LUA_INT_TYPE in luaconf.h //---- 在 C代码中, 将一个元素 push 到 stack ---- void lua_pushnil (lua_State *L); void lua_pushboolean (lua_State *L, int b); void lua_pushnumber (lua_State *L, lua_Number n); void lua_pushinteger (lua_State *L, lua_Integer n); const char *lua_pushlstring (lua_State *L, const char *s, size_t len); // 此版本的 参数s 指向的字符串 不需要 尾后0. (也不一定记载字符串,可以是二进制任意值) // lua 内部会 复制一份此 字符串,所以在本函数调用介绍后,可把 参数 s代表的字符串立即释放。 // 参数s 可包含任何 二进制数据,包含0 // 返回一指针,指向 lua 内部拷贝的 字符串。 const char *lua_pushstring (lua_State *L, const char *s); // s必须为 以尾后0结束的字符串。 // 此函数通过 strlen 来计算 字符串s 的长度 // 其他行为和 lua_pushlstring 一样 // 如果 参数s 为 NULL, 会向 stack push nil,并且本函数最终返回 NULL void lua_pushboolean (lua_State *L, int b); void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); // Pushes a new C closure // 压入一个 c函数,及其关联变量。本函数将创建一个 c闭包 (通畅给 lua 调用) //-- C Closures -- //- 当一个 C函数被创建,它可能与一些 自由变量有关联。这种 c函数就是 c闭包 // 这些被关联的 自由变量,就叫 upvalues。 // 任何时候,c闭包被调用时,都能访问这些 upvalues //- 当这个 c闭包被调用,它的 upvalues 被设置于 specific pseudo-indices // 这些 pseudo-indices 被 宏lua_upvalueindex 创建 // 第一个 upvalues 位于 lua_upvalueindex(1) // 如果访问一个 越界的 lua_upvalueindex(n),将创建一个 “可访问但无效” 的index //-- 为了将一个 自由变量 与 c函数 绑定, // 首先,这些 变量 必须被 push 到 stack。(第一个变量先 push) // 然后调用 lua_pushcclosure,将 c函数 创建并push 到 stack // 参数n 表示 有多少个 关联变量。上限为 255 //-- 若 参数n 为0. 此时将创建 a light C function // 也就是个一个简单的 函数指针,指向目标 c函数。 // 在这种情况下,本函数永远不会 引起 内存 error void lua_pushcfunction (lua_State *L, lua_CFunction f); // 参数f 为一个普通c函数 的指针。 // 本函数将 创建一个 lua变量(类型为 function)。并将此变量 压入 stack // 这个 函数变量 将被 lua 调用 //-- 任何将被 lua 调用的 c函数,都需要遵循正确的 制作流程。 // 来约定其 参数 和 返回值 的 传递方式 // 参见 lua_CFunction const char *lua_pushfstring (lua_State *L, const char *fmt, ...); // push 格式化的 string。类似 c中的 sprintf // 略 ... void lua_pushglobaltable (lua_State *L); // Pushes the global environment onto the stacks void lua_pushinteger (lua_State *L, lua_Integer n); void lua_pushlightuserdata (lua_State *L, void *p); // Pushes a light userdata onto the stack // 未完... const char *lua_pushliteral (lua_State *L, const char *s); //-- 宏,等同于 lua_pushstring // 只有在 参数s 为 literal string 是,才调用本函数 int lua_pushthread (lua_State *L); // Pushes the thread represented by L onto the stack // Returns 1 if this thread is the main thread of its state void lua_pushvalue (lua_State *L, int index); // Pushes a copy of the element at the given index onto the stack const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp); //-- 等同于 lua_pushfstring. // 区别在于,通过 va_list 来接受 可变参数 //--------------------------------------------------- // 扩充 stack,从而确保 stack 至少拥有 参数n 个 slots。 int lua_checkstack (lua_State *L, int n); //- 本函数永远不会 缩小 stack。如果满足 参数n 大的空间。 // 本函数也不会去 缩小 stack //-- return: // 若 参数n 合规,本函数会扩充 stack,直到满足 参数n // 若 参数n 过大,比如超出 a fixed maximum size,或者无法进一步分配内存 // 本函数会返回 0 (表示false) //--------------------------------------------------- // 类似 lua_checkstack // 如果扩容失败,会抛出指定的 错误信息 error message。 // param: L // param: sz // param: msg -- 构成 error message 的额外信息。 // 可输入 NULL,表示不传入 额外msg void luaL_checkstack (lua_State *L, int sz, const char *msg); //-------------------------------------------------------------- // lua_isXXX //-------------------------------------------------------------- //- 判断 stack 中 索引为 参数index 的元素,为目标类型。 int lua_isnil (lua_State *L, int index); //- 若符合,返回 1,否则返回 0 int lua_isnone (lua_State *L, int index); //- 是否为 is not valid int lua_isnoneornil (lua_State *L, int index); //- 是否为 is not valid / is nil int lua_isboolean (lua_State *L, int index); int lua_isnumber (lua_State *L, int index); //- is a number or a string convertible to a number int lua_isinteger (lua_State *L, int index); int lua_isstring (lua_State *L, int index); //- is a string or a number // (which is always convertible to a string) int lua_istable (lua_State *L, int index); int lua_isthread (lua_State *L, int index); int lua_iscfunction (lua_State *L, int index); //- 是否为 C function int lua_isfunction (lua_State *L, int index); //- 是否为 function (C/Lua皆可) int lua_isuserdata (lua_State *L, int index); //- is a userdata (either full or light) int lua_islightuserdata (lua_State *L, int index); //- 是否为 a light userdata int lua_isyieldable (lua_State *L); //- if the given coroutine can yield //-------------------------------------------------------------- // lua_toXXX //-------------------------------------------------------------- // 从 stack 中提取一个 元素,到 C代码中。 // 即便 stack 中的元素 和调用函数指定的类型不匹配,调用这些函数也没问题 // int lua_toboolean (lua_State *L, int index); //- 将 任意 lua值 转换为 C 中的 “bool值” // -- 若元素为 false/nil, 本函数返回 0 // -- 否则,返回 1 //- 如果你 只想要 stack 中的 bool元素,推荐先用 lua_isboolean 函数检查一下 lua_CFunction lua_tocfunction (lua_State *L, int index); //- 将 stack中的 指定元素,转变为一个 C函数 // 如果 目标元素 不是 c函数,本函数将返回 NULL lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum); //- 读取 stack 中目标元素,将其转换为 一个 c int,并返回出来 // 目标元素 必须是 lua 中的 integer, number, string 类型。 // 否则,本函数 返回 0 //-- 如果 参数isnum 不为 NULL。此槽将被本函数写入一个 bool值(在c中通常是 1/0) // 来表示,本函数是否运行正确 lua_Integer lua_tointeger (lua_State *L, int index); //- 等同于 lua_tointegerx (参数 isnum 为 NULL) const char *lua_tolstring (lua_State *L, int index, size_t *len); //- 读取 stack 中目标元素,将其转换为 一个 c字符串。 // 目标元素 必须是 lua 的 string,number。 // 否则,本函数返回 NULL。 // 如果 目标元素 是 number,本函数会将其 转换为一个 c字符串。 // This change confuses lua_next when lua_tolstring // is applied to keys during a table traversal. //-- 本函数返回一个 字符串指针,指向的字符串 存储在 lua state 中。 // 这个字符串 永远自备 尾后0. (但也能在 字符串体内包含其他0. 意味着可以表示任何二进制数) //-- 由于 lua 拥有 gc,无法保证 本函数的返回的 指针, 在 相关lua变量被移除后,仍然有效。 //-- 如果 参数len 不为NULL,本函数将向 此槽写入 c字符串的 字节数, const char *lua_tostring (lua_State *L, int index); //-- 等同于 lua_tolstring,当 参数len 为 NULL lua_Number lua_tonumberx (lua_State *L, int index, int *isnum); // 目标元素 必须是 lua 的 number, string(将被自动转换为 number) // 否则,本函数 返回0 //-- 如果 参数isnum 不为 NULL。此槽将被本函数写入一个 bool值(在c中通常是 1/0) // 来表示,本函数是否运行正确 lua_Number lua_tonumber (lua_State *L, int index); //-- 等同于 lua_tonumberx(参数 isnum 为 NULL) const void *lua_topointer (lua_State *L, int index); // 目标元素 必须是 lua 的 userdara, table, thread, function // 否则,本函数返回 NULL。 //-- 不同 obj 返回不同的 指针,没有办法将指针 转换回 original value //-- 通常,本函数仅用于 hashing and debug information lua_State *lua_tothread (lua_State *L, int index); // 目标元素 必须是 lua 的 thread. // 否则,本函数 返回 NULL void *lua_touserdata (lua_State *L, int index); // 如果目标元素是 a full userdata,返回其 block address // 如果目标元素是 a light userdata,返回其 指针 // 否则,本函数 返回 NULL //------------------------------------------------------------- // 宏,返回 当前运行的 函数的 第i个 upvalues 的 pseudo-index // 输入 参数i,创建一个对应的 pseudo-index int lua_upvalueindex (int i); //------------------------------------------------------------- // ... int lua_next (lua_State *L, int index); //------------------------------------------------------------- // 返回 stack 中 参数index 指向的 元素 的 类型。 int lua_type (lua_State *L, int index); //-- return // 如果 参数index是 non-valid (but acceptable),返回 LUA_TNONE // LUA_TNIL (0) // LUA_TNUMBER // LUA_TBOOLEAN // LUA_TSTRING // LUA_TTABLE // LUA_TFUNCTION // LUA_TUSERDATA // LUA_TTHREAD // LUA_TLIGHTUSERDATA //------------------------------------------------------------- //-- 返回 stack 中栈顶元素的 idx值(最浅层的那个) // 由于 lua 的起始元素 标号为1,所以,本函数的返回值,也可理解为: // “stack 中元素的 个数” //-- 如果 本函数返回 0,表示 stack 是空的 int lua_gettop (lua_State *L); //------------------------------------------------------------- // 接受任何 参数index(包含0),将 stack 的栈顶指针 指向 此index // 如果,参数index 的值大于 原有 栈顶index,则对 stack 扩容。新增的 元素统统填 nil // 如果 参数index 变小了,则对 stack 缩容。 // 如果 参数index 为0. 则将 stack 彻底清空 void lua_settop (lua_State *L, int index); //- 也可以使用 负数index。 //------------------------------------------------------------- // #define lua_pop(L,n) lua_settop( L, -(n)-1 ) // 从栈顶 弹出 参数n 个元素 void lua_pop (lua_State *L, int n); //------------------------------------------------------------- // 将 stack 中,idx处元素 到 栈顶 这段区域内的元素, 回环旋转 n个位置 // 以 数组 {1,2,3,4} 为例: // 当 参数n 为正数,则 朝向栈顶方向 回环旋转 // 比如说,n=1。 // -- 首先,区域中所有元素,向 栈顶(右侧)移动 n=1 位。 // -- 然后,右侧溢出的数据,回环填入 左侧空缺。 // {4,1,2,3} // 当 参数n 为负数,则 朝向栈底方向 回环旋转 // 比如说,n=1。 // -- 首先,区域中所有元素,向 栈底(左侧)移动 n=1 位。 // -- 然后,左侧溢出的数据,回环填入 右侧空缺。 // {2,3,4,1} //-- 本函数是很多 函数的实现者,比如 lua_remove, lua_insert // 此函数不能用于 pseudo-index。因为 pseudo-index 不是实际上的 stack position void lua_rotate (lua_State *L, int idx, int n); //------------------------------------------------------------- // 将 参数index 指向的 stack 元素移除。并将 它上方的元素下移。来填满这个间隙。 // 这个函数实际是 通过 lua_rotate 实现的: // #define lua_remove(L,idx) (lua_rotate(L,(idx),-1), lua_pop(L,1)) // 此函数不能用于 pseudo-index。因为 pseudo-index 不是实际上的 stack position void lua_remove (lua_State *L, int index); //------------------------------------------------------------- // 将 栈顶元素 插入到 参数index 指向的位置 // 整个操作完成后,原来的 栈顶元素 不再位于栈顶。 // 原来 参数index 位置处的元素(及其上面的所有元素)都将上移 // 这个函数实际是 通过 lua_rotate 实现的: // #define lua_insert(L,idx) lua_rotate(L,(idx),1) // 此函数不能用于 pseudo-index。因为 pseudo-index 不是实际上的 stack position void lua_insert (lua_State *L, int index); //------------------------------------------------------------- // 将 栈顶元素 复制一份,到 参数index 指向的位置。 // 然后 pop 掉这个 栈顶元素(从而实现 “replace” ) void lua_replace (lua_State *L, int index); //------------------------------------------------------------- // 将 参数fromidx 处的元素,复制一份,到 参数toidx处 // 参数fromidx 处的原有元素 将被覆盖 // 参数toidx 处的原有元素,不变 void lua_copy (lua_State *L, int fromidx, int toidx); #define LUA_IDSIZE 1024 //-tmp //------------------------------------------------------------- //- 一个用来容纳 某个 函数/激活态记录 的数段信息的 数据结构。 // lua_getstack函数 只装填这个 结构中的 private部分,用于后续使用 // 剩余部分,通过调用 lua_getinfo 来写入 typedef struct lua_Debug { int event; const char *name; /* (n) */ // 给定function 的 一个 合理的 name // 由于 lua 中的 函数 是 一类成员,它们没有 固定名字: // -- 某些函数 可以是 数个全局变量的 值。 // -- 某些函数 只存储在 一个 table 的作用域内部。 // lua_getinfo 函数 检测 一个函数是如何被 调用的,来找到 合适的名字。 // 如果 lua_getinfo 函数无法找到 名字,就将 本字段 设置为 NULL const char *namewhat; /* (n) */ // 解释 name 字段,根据 function 是怎么被调用的,可以为: // -- "global" // -- "local" // -- "method" // -- "field" // -- "upvalue" // -- "" (空字符串, when no other option seems to apply. ) const char *what; /* (S) */ // -- 若为 "lua" -- function 为 lua函数 // -- 若为 "c" -- function 为 c函数 // -- 若为 "main" -- function 为 一个 chunk 的 main part const char *source; /* (S) */ // 创建 function 的 chunk 的 name。 // -- 如果 source 以 '@' 开头,意味着 目标function 被定义在一个 文件中, // 这个文件名 就是 source 中 '@' 后的那部分字符串 // -- 如果,source 以 '=' 开头,source的后部分字符串 描述 source 在一个 // user-dependent manner。 // -- 如果都不是,说明 function 被直接定义在 source 这个字符串内 int currentline; /* (l) */ // 给定function 的 当前执行行 的 行号。 // 如果没有 行信息提供,此字段 被设置为 -1 int linedefined; /* (S) */ // 函数定义部分 起始行 的 行号 int lastlinedefined; /* (S) */ // 函数定义部分 结尾行 的 行号 unsigned char nups; /* (u) number of upvalues */ // 目标function 的 upvalues 的数量 unsigned char nparams; /* (u) number of parameters */ // 目标function 的 固定参数 的数量 // 若 function 为 c函数,此字段永远为 0 char isvararg; /* (u) */ // true -- 如果 目标function 是 可变参数函数 // 若 function 为 c函数,此字段永远为 true char istailcall; /* (t) */ // true -- 如果 目标function 被 尾调用 // 此时,,目标function 的调用者 不在 stack 中。 // false char short_src[LUA_IDSIZE]; /* (S) */ // source 的 "printable" version。用于 error msg /* private part */ //other fields } lua_Debug; //------------------------------------------------------------- // 获得 解释器运行时 stack 的 信息。 // 此函数 会向 lua_Debug 结构 填入部分数据: // 通过对一个 “在 参数level 运行的function” 的 活跃态记录的 鉴别。 // param: L // param: level -- 0 表示 当前运行函数,1表示 当前函数被调用的那个函数,以此类推。 // 尾调用函数除外:which do not count on the stack // param: ar -- int lua_getstack (lua_State *L, int level, lua_Debug *ar); //- return // 若无错误,返回 1 // 若本函数被一个 大于 stack深度 的 level调用,返回 0 (?) //------------------------------------------------------------- // 获得 特定 函数/函数调用 的 信息。 // 参数ar 必须是一个 有效的活跃态记录,且在此之前 被 lua_getstack函数 填充 // 或 被一个 hook 以 参数的形式给予 (参见 -- lua_Hook ) // 为了获得一个函数的信息,我们将 它 push 到 stack,然后在 参数what 中 输入一个 '>'开头的字符串 // 此时,lua_getinfo 将从 栈顶 pop 出 目标function。 // -- 参数what 以 '>'开头,后跟如下字符: // -- 'n' 填充 name,namewhat // -- 'S' 填充 source, short_src, linedefined, lastlinedefined, what // -- 'l' 填充 currentline // -- 't' 填充 istailcall // -- 'u' 填充 nups, nparams, isvararg // -- 'f' 填充 将给定level 运行的 function push到 stack // -- 'L' 填充 将一个 table push到 stack。这个 table 的 索引, // 是 函数的有效行 的行号(空行,注释行 是无效的) //-- If this option is given together with option 'f', // its table is pushed after the function. int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); //- This function returns 0 on error //- (for instance, an invalid option in what). //------------------------------------------------------------- // 获得一个 给定的活跃态记录/给定function 的 local变量 的 信息。 // -- 给定的活跃态记录: // 参数ar 必须是一个 有效的活跃态记录,且已经被 lua_getstack函数填充。 // 或被一个 hook 以 参数的形式 给予。 // 参数n 是个索引,决定 哪个 local变量 将被检测 // (参见 debug.getlocal,获知 variable indices and names 的细节 ) // 本函数 将 变量的值 push 到 stack,然后 返回它的 name // -- 给定function: // 参数ar 必须为 NULL,被检测的function 必须在 栈顶。 // 此时,只有 lua函数 的 参数 是visible的。(此时没有信息 可知哪个变量是 active的 ) // 以及,没有 值 被 push 到 stack。 // 如果 参数n 大于 active local变量 的数量,本函数返回 NULL(且 push nothing) const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
32.281027
95
0.546511
[ "object" ]
1f7082f95248f36ec827023df30b02a3b04c2cfb
1,070
h
C
src/homework/tic_tac_toe/tic_tac_toe.h
acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-9419312
488936664b188957bcca577123d50ca51d16ac06
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe.h
acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-9419312
488936664b188957bcca577123d50ca51d16ac06
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe.h
acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-9419312
488936664b188957bcca577123d50ca51d16ac06
[ "MIT" ]
1
2020-12-19T04:05:26.000Z
2020-12-19T04:05:26.000Z
//h #ifndef TIC_TAC_TOE_H #define TIC_TAC_TOE_H #include <string> #include <vector> #include<iostream> class TicTacToe { public: TicTacToe(int size) : pegs(size*size, " ") {} TicTacToe(std::vector<std::string> p, std::string win) : pegs{ p }, winner{ win }{}; bool game_over(); void start_game(std::string first_player); void mark_board(int position); std::string get_player() const { return player; } std::string get_winner()const { return winner; } friend std::ostream& operator<<(std::ostream& out, const TicTacToe& t); friend std::istream& operator>>(std::istream& in, TicTacToe& t); protected: virtual bool check_column_win(); virtual bool check_row_win(); virtual bool check_diagonal_win(); std::vector<std::string> pegs; private: void set_next_player(); bool check_board_full(); void clear_board(); void set_winner(); std::string player; std::string winner; }; class Error { public: Error(std::string msg) : message{ msg } {}; std::string get_message()const { return message; }; private: std::string message; }; #endif // !TIC_TAC_TOE_H
23.777778
85
0.713084
[ "vector" ]
1f7853abef81ad53a4e5410c35a5e2189b150156
2,687
c
C
usr.bin/pascal/pdx/runtime/address.c
weiss/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
114
2015-01-18T22:55:52.000Z
2022-02-17T10:45:02.000Z
usr.bin/pascal/pdx/runtime/address.c
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
null
null
null
usr.bin/pascal/pdx/runtime/address.c
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
29
2015-11-03T22:05:22.000Z
2022-02-08T15:36:37.000Z
/*- * Copyright (c) 1980, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.redist.c% */ #ifndef lint static char sccsid[] = "@(#)address.c 8.1 (Berkeley) 06/06/93"; #endif /* not lint */ /* * Some machine and runtime dependent manipulation of a symbol. */ #include "defs.h" #include "runtime.h" #include "sym.h" #include "machine.h" #include "process.h" #include "object.h" #include "mappings.h" #include "sym/classes.h" #include "frame.rep" #include "sym/sym.rep" /* * Calculate the address of a symbol. * If frame is not NIL, then it is the frame associated with the * activation in which the symbol we're interested in is defined. */ ADDRESS address(s, frame) register SYM *s; FRAME *frame; { SYM *f; FRAME *frp; ADDRESS r, *dp, *disp; short offs; f = s->func; if (s->class == FVAR) { offs = f->symvalue.offset; } else { offs = s->symvalue.offset; } if (f == program) { r = (ADDRESS) dispval(MAINBLK) + offs; } else if (f == curfunc && frame == NIL) { dp = curdp(); disp = contents(dp); r = (ADDRESS) disp + offs; } else { if (frame == NIL) { frp = findframe(s->func); if (frp == NIL) { panic("address: findframe returned NIL"); } } else { frp = frame; } r = stkaddr(frp, s->blkno) + offs; } return r; } /* * The next three routines assume the procedure entry code is * * f: tra4 A * ... * A: beg * B: <code for first line> * * Pi gives f, we compute and store A with "findbeginning(f)", * (retrieved by "codeloc(f)"), B is computed by "firstline(f)". * * The procedure "runtofirst" assumes you're at A and want to step to B. * It should be changed to a nop if A is equal to B. */ /* * Find the beginning of a procedure or function. This is a destructive * routine, it changes the value associated with the procedure symbol. * Should only be called once per symbol. */ findbeginning(f) SYM *f; { f->symvalue.funcv.codeloc = nextaddr(f->symvalue.funcv.codeloc, FALSE); } /* * Find the object code associated with the first line of a block. */ ADDRESS firstline(f) SYM *f; { ADDRESS addr; addr = codeloc(f); while (linelookup(addr) == 0) { if (isendofproc(addr)) { return -1; } addr = nextaddr(addr, FALSE); } return addr; } /* * Catcher drops strike three ... */ runtofirst() { stepto(firstline(curfunc)); } /* * Calculate the address of the last line in the program. * This is assumed to be at the physical end. */ ADDRESS lastaddr() { if (objsize == 0) { panic("lastaddr: objsize = 0!"); } return(objsize - sizeof(short)); }
19.903704
75
0.617417
[ "object" ]
1f7db52a550e2379f25f83aa0cc07f51a59fdacc
8,232
h
C
vegastrike/src/cmd/ai/order.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/ai/order.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/ai/order.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
/* * Vega Strike * Copyright (C) 2001-2002 Daniel Horn * * http://vegastrike.sourceforge.net/ * * 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. */ #ifndef _CMD_ORDER_H #define _CMD_ORDER_H #include "gfx/vec.h" #include "cmd/container.h" #include <list> #include <vector> #include <string> /** * Order is the base class for all orders. All orders inherit from Order * Each fighter may have an order they are currently executing. Orders naturally * can queue other orders, and decide which orders may be executed in parallel by those orders' bit codes. * Orders affect their "parent" and may call any function within that parent * Limitation (perhaps resolvable) Orders do not "know" what their parent * is until Execute() time. Perhaps "SetParent" Should be made virtual so that * various variables may be set earlier than at every execution time */ class Animation; typedef std::vector< class varInst* >olist_t; class Order { private: protected: virtual ~Order(); ///The unit this order is attached to Unit *parent; ///The bit code (from ORDERTYPES) that this order is (for parallel execution) unsigned int type; unsigned int subtype; ///Whether or not this order is done bool done; ///If this order applies to a group of units (as in form up with this group) UnitContainer group; ///If this order applies to a physical location in world space QVector targetlocation; ///The queue of suborders that will be executed in parallel according to bit code std::vector< Order* >suborders; ///a bunch of communications that have not been answered CommunicationMessages are actually containing reference to a nice Finite State Machine that can allow a player to have a reasonable conversation with an AI std::list< class CommunicationMessage* >messagequeue; ///changes the local relation of this unit to another...may inform superiors about "good" or bad! behavior depending on the AI virtual void Destructor(); protected: /// this function calls the destructor (needs to be overridden for python; public: virtual void ChooseTarget() { /*not implemented see fire.cpp*/ } virtual bool PursueTarget( Unit*, bool isleader ) { return false; } ///clears the messasges of this order void ClearMessages(); ///The varieties of order types MOVEMENT,FACING, and WEAPON orders may not be mutually executed (lest one engine goes left, the other right) enum ORDERTYPES {MOVEMENT=1, FACING=2, WEAPON=4, CLOAKING=8, ALLTYPES=(1|2|4|8)}; enum SUBORDERTYPES {SLOCATION=1, STARGET=2, SSELF=4}; ///The default constructor setting everything to NULL and no dependency on order Order() : parent(NULL), type(0), subtype(0), done(false), targetlocation( 0, 0, 0 ) { VSCONSTRUCT1( 'O' ) } ///The constructor that specifies what order dependencies this order has Order( int type, int subtype ) : parent(NULL), type(type), subtype(subtype), done(false), targetlocation( 0, 0, 0 ) { VSCONSTRUCT1( 'O' ) } ///The virutal function that unrefs all memory then calls Destruct () which takes care of unreffing this or calling delete on this virtual void Destroy(); ///The function that gets called and executes all queued suborders virtual void Execute(); ///returns a pointer to the first order that may be bitwised ored with that type Order * queryType( unsigned int type ); ///returns a pointer to the first order that may be bitwise ored with any type Order * queryAny( unsigned int type ); ///Erases all orders that bitwise OR with that type void eraseType( unsigned int type ); ///Attaches a group of targets to this order (used for strategery-type games) bool AttachOrder( Unit *targets ); ///Attaches a navigation point to this order bool AttachOrder( QVector target ); ///Attaches a group (form up) to this order bool AttachSelfOrder( Unit *targets ); ///Enqueues another order that will be executed (in parallel perhaps) when next void Execute() is called Order * EnqueueOrder( Order *ord ); ///Replaces the first order of that type in the order queue Order * ReplaceOrder( Order *ord ); bool Done() { return done; } int getType() { return type; } int getSubType() { return subtype; } ///Sets the parent of this Unit. Any virtual functions must call this one virtual void SetParent( Unit *parent1 ) { parent = parent1; } Unit * GetParent() const { return parent; } ///Sends a communication message from the Unit (encapulated in c) to this unit virtual void Communicate( const class CommunicationMessage &c ); ///processes a single message...generally called by the Messages() func virtual void ProcessCommMessage( class CommunicationMessage&c ); ///responds (or does not) to certain messages in the message queue virtual void ProcessCommunicationMessages( float CommRepsonseTime, bool RemoveMessageProcessed ); /// return pointer to order or NULL if not found Order * findOrder( Order *ord ); /// erase that order from the list void eraseOrder( Order *ord ); /// enqueue order as first order Order * EnqueueOrderFirst( Order *ord ); /// returns the orderlist (NULL for orders that haven't got any) virtual olist_t * getOrderList() { return NULL; } virtual void AdjustRelationTo( Unit *un, float factor ); virtual std::string getOrderDescription() { return "empty"; } ///searches the suborders recursively for the first order that has an orderlist Order * findOrderList(); std::string createFullOrderDescription( int level = 0 ); void setActionString( std::string astring ) { actionstring = astring; } std::string getActionString() { return actionstring; } virtual float getMood() { return 0; } protected: std::string actionstring; }; ///Convenience order factory for "clicking to create an order" class OrderFactory { public: virtual int type() { return 0; } OrderFactory() {} virtual Order * newOrder() { return new Order; } }; namespace Orders { ///Executes another order for a number of seconds class ExecuteFor : public Order { private: ///The child order to execute Order *child; ///the time it has executed the child order for float time; ///the total time it can execute child order float maxtime; protected: virtual ~ExecuteFor() {} public: ExecuteFor( Order *chld, float seconds ) : Order( chld->getType(), chld->getSubType() ) , child( chld ) , time( 0 ) , maxtime( seconds ) {} ///Executes child order and then any suborders that may be pertinant void Execute(); ///Removes this order virtual void Destroy() { child->Destroy(); Order::Destroy(); } }; // Execute two orders simultaneously and wait until both has finished. class Join : public Order { public: Join(Unit *parent, Order *firstOrder, Order *secondOrder); void Execute(); private: Order *first; Order *second; }; // Execute one order and prevent other orders with excludeTypes from executing at the same time. class Sequence : public Order { public: Sequence(Unit *parent, Order *order, unsigned int excludeTypes); void Execute(); private: Order *order; }; } // namespace Orders #endif
30.947368
212
0.686224
[ "vector" ]
1f89efc35254ac54eb5b59f43a0923ddca0d53b0
4,436
h
C
include/retdec/dwarfparser/dwarf_base.h
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
include/retdec/dwarfparser/dwarf_base.h
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
include/retdec/dwarfparser/dwarf_base.h
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/** * @file include/retdec/dwarfparser/dwarf_base.h * @brief Declaration of base classes used in dwarfparser. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_DWARFPARSER_DWARF_BASE_H #define RETDEC_DWARFPARSER_DWARF_BASE_H #include <list> #include <map> #include <string> #include <vector> #include <libdwarf/dwarf.h> #include <libdwarf/libdwarf.h> namespace retdec { namespace dwarfparser { // Extern forward declarations. class DwarfFile; class DwarfCU; // Locale forward declarations. template <class T> class DwarfBaseContainer; class DwarfBaseElement; /** * @class DwarfBaseContainer. * @brief Base container class for all container objects used by dwarfparser. */ template <class T> class DwarfBaseContainer { // // Type aliases // public: using iterator = typename std::vector<T*>::iterator; using const_iterator = typename std::vector<T*>::const_iterator; // // Non-virtual functions. // public: DwarfBaseContainer(DwarfFile *file, DwarfBaseElement *elem = nullptr) : m_res(0), m_error(nullptr), m_parentFile(file), m_parentElem(elem) { } std::size_t size() const { return m_data.size(); } void push_back(T *n) { m_data.push_back(n); } bool empty() const { return m_data.empty(); } iterator begin() { return m_data.begin(); } const_iterator begin() const { return m_data.begin(); } iterator end() { return m_data.end(); } const_iterator end() const { return m_data.end(); } DwarfBaseElement *getParentElem() const { return m_parentElem; } DwarfFile *getParentFile() const { return m_parentFile; } // TODO: get element by DIE? DwarfBaseElement *getElemByOffset(Dwarf_Off o); // // Virtual functions. // public: virtual ~DwarfBaseContainer() { for (iterator it=begin(); it!=end(); ++it) delete (*it); m_data.clear(); } virtual void dump() const { for (const_iterator cit=begin(); cit!=end(); ++cit) (*cit)->dump(); } // // Pure virtual functions. // public: virtual T* loadAndGetDie(Dwarf_Die die, unsigned lvl) = 0; // // Data. // protected: std::vector<T*> m_data; ///< Object container. int m_res; ///< Global return value. Dwarf_Error m_error; ///< Global error code. DwarfFile *m_parentFile; ///< Pointer to DWARF file representation. DwarfBaseElement *m_parentElem; ///< Pointer to parent element, if nullptr then parent is DWARF file. public: /** * DIE offset to element mapping. * One element may have multiple offsets -- multiple mappings. * ==> *DO NOT* iterate through this container, use 'm_data'. */ std::map<Dwarf_Off, T*> off2data; }; /** * @class DwarfBaseElement * @brief Base element class for all objects used by dwarfparser. */ class DwarfBaseElement { public: /** * @brief Types element */ enum type_t { CU, FUNCTION, LINE, TYPE, VAR }; DwarfBaseElement(type_t type, DwarfBaseContainer<DwarfBaseElement> *prnt, Dwarf_Off d); virtual ~DwarfBaseElement() {} virtual void dump() const = 0; public: virtual const std::string& getName() const {return name;} type_t getType() const {return m_type;} DwarfBaseContainer<DwarfBaseElement> *getPrntCont() const {return m_parent;} DwarfFile *getParentFile() const {return getPrntCont()->getParentFile();} DwarfCU *getCuParent() const {return m_cuParent;} Dwarf_Debug &getLibdwarfDebug() const; void addOffset(Dwarf_Off o); std::string getDwarfdump2OffsetString() const; public: std::string name; protected: type_t m_type; DwarfBaseContainer<DwarfBaseElement> *m_parent; ///< Pointer to parent container that contains this element. DwarfCU *m_cuParent; ///< Pointer to parent CU element that contains this element. }; /** * @brief Get container's element with provided offset. * @param o Offset. * @return Element with offset. */ template <class T> DwarfBaseElement* DwarfBaseContainer<T>::getElemByOffset(Dwarf_Off o) { auto it = off2data.find(o); if (it != off2data.end()) return it->second; else return nullptr; } } // namespace dwarfparser } // namespace retdec #endif
24.921348
111
0.647881
[ "object", "vector" ]
de5792427562148f6949bbfc299ec87bc967689e
4,745
h
C
src/module/base/Common/src/log/LogManager.h
403712387/cgf
f26d7fa16ec8c7ca7565109b0d7f483cc7ad6288
[ "MIT" ]
2
2020-03-04T06:54:45.000Z
2021-07-21T05:59:08.000Z
src/module/base/Common/src/log/LogManager.h
403712387/cgf
f26d7fa16ec8c7ca7565109b0d7f483cc7ad6288
[ "MIT" ]
null
null
null
src/module/base/Common/src/log/LogManager.h
403712387/cgf
f26d7fa16ec8c7ca7565109b0d7f483cc7ad6288
[ "MIT" ]
3
2019-12-23T02:13:27.000Z
2021-12-09T08:28:50.000Z
#ifndef LOG_MANAGER_H #define LOG_MANAGER_H #include <atomic> #include <vector> #include <mutex> #include <condition_variable> #include "Log.h" #include "log4cplus/logger.h" #include "log4cplus/configurator.h" #include "log4cplus/helpers/stringhelper.h" #include "log4cplus/loggingmacros.h" #include "log4cplus/fileappender.h" using namespace log4cplus; class LogManager { public: static LogManager *getInstance(); // 设置日志的配置文件,如果不设置,则使用默认配置 int setLogConfigFile(const std::string configFile); // 设置日志级别 void setLogLevel(common_log::Log_Level logLevel); // 获取日志级别 common_log::Log_Level getLogLevel(); // 设置过滤关键字 void setFilterWord(const std::string keyWord); // 写日志 void writeLog(const std::string &info, common_log::Log_Level logLevel = common_log::Log_Level_Info, bool forceWrite = false); private: LogManager(); // 初始化 void init(); // 初始化日志配置 bool initConfig(); private: const std::string mDefaultConfig = "config/log.conf"; int mLogLevel = common_log::Log_Level_Info; // 日志级别 Logger mLogger; // 日志的模块类 std::string mConfigFile; // 配置文件名称 std::mutex mHandleLock; // 句柄的锁 std::string mKeyWord; std::string mConfieFileText = \ "/*\n" "*/\n" "#Default level is INFO, but you can use others in your favor\n" "log4cplus.rootLogger=TRACE,DEBUG,ALL_MSGS,ERROR_MSGS,FATAL_MSGS,D\n\n\n" "log4cplus.appender.D=log4cplus::ConsoleAppender\n" "log4cplus.appender.D.layout=log4cplus::PatternLayout\n" "log4cplus.appender.D.layout.ConversionPattern=[%D{%Y-%m-%d %H:%M:%S,%Q}] [%t] %-5p %m%n\n" "log4cplus.appender.ALL_MSGS=log4cplus::RollingFileAppender\n" "log4cplus.appender.ALL_MSGS.MaxFileSize=10MB\n" "log4cplus.appender.ALL_MSGS.CreateDirs=true\n" "log4cplus.appender.ALL_MSGS.MaxBackupIndex=10\n" "log4cplus.appender.ALL_MSGS.File=logs/cgf.log\n" "log4cplus.appender.ALL_MSGS.layout=log4cplus::PatternLayout\n" "log4cplus.appender.ALL_MSGS.layout.ConversionPattern=[%D{%Y-%m-%d %H:%M:%S,%Q}] [%t] %-5p %m%n\n\n" "#Range\n" "log4cplus.appender.ALL_MSGS.filters.1=log4cplus::spi::LogLevelRangeFilter\n" "log4cplus.appender.ALL_MSGS.filters.1.LogLevelMin=TRACE\n" "log4cplus.appender.ALL_MSGS.filters.1.LogLevelMax=FATAL\n" "log4cplus.appender.ALL_MSGS.filters.1.AcceptOnMatch=true\n" "log4cplus.appender.ALL_MSGS.filters.2=log4cplus::spi::DenyAllFilter\n\n" "log4cplus.appender.WARN_MSGS=log4cplus::RollingFileAppender\n" "log4cplus.appender.WARN_MSGS.MaxFileSize=10MB\n" "log4cplus.appender.WARN_MSGS.CreateDirs=true\n" "log4cplus.appender.WARN_MSGS.MaxBackupIndex=5\n" "log4cplus.appender.WARN_MSGS.File=logs/cgf.warn\n" "log4cplus.appender.WARN_MSGS.layout=log4cplus::PatternLayout\n" "log4cplus.appender.WARN_MSGS.layout.ConversionPattern=[%D{%Y-%m-%d %H:%M:%S,%Q}] [%t] %-5p %m%n\n" "log4cplus.appender.WARN_MSGS.filters.1=log4cplus::spi::LogLevelMatchFilter\n" "log4cplus.appender.WARN_MSGS.filters.1.LogLevelToMatch=WARN\n" "log4cplus.appender.WARN_MSGS.filters.1.AcceptOnMatch=true\n" "log4cplus.appender.WARN_MSGS.filters.2=log4cplus::spi::DenyAllFilter\n" "log4cplus.appender.ERROR_MSGS=log4cplus::RollingFileAppender\n" "log4cplus.appender.ERROR_MSGS.MaxFileSize=10MB\n" "log4cplus.appender.ERROR_MSGS.CreateDirs=true\n" "log4cplus.appender.ERROR_MSGS.MaxBackupIndex=5\n" "log4cplus.appender.ERROR_MSGS.File=logs/cgf.error\n" "log4cplus.appender.ERROR_MSGS.layout=log4cplus::PatternLayout\n" "log4cplus.appender.ERROR_MSGS.layout.ConversionPattern=[%D{%Y-%m-%d %H:%M:%S,%Q}] [%t] %-5p %m%n\n" "log4cplus.appender.ERROR_MSGS.filters.1=log4cplus::spi::LogLevelMatchFilter\n" "log4cplus.appender.ERROR_MSGS.filters.1.LogLevelToMatch=ERROR\n" "log4cplus.appender.ERROR_MSGS.filters.1.AcceptOnMatch=true\n" "log4cplus.appender.ERROR_MSGS.filters.2=log4cplus::spi::DenyAllFilter\n" "log4cplus.appender.FATAL_MSGS=log4cplus::RollingFileAppender\n" "log4cplus.appender.FATAL_MSGS.MaxFileSize=10MB\n" "log4cplus.appender.FATAL_MSGS.CreateDirs=true\n" "log4cplus.appender.FATAL_MSGS.MaxBackupIndex=5\n" "log4cplus.appender.FATAL_MSGS.File=logs/cgf.fatal\n" "log4cplus.appender.FATAL_MSGS.layout=log4cplus::PatternLayout\n" "log4cplus.appender.FATAL_MSGS.layout.ConversionPattern=[%D{%Y-%m-%d %H:%M:%S,%Q}] [%t] %-5p %m%n\n" "log4cplus.appender.FATAL_MSGS.filters.1=log4cplus::spi::LogLevelMatchFilter\n" "log4cplus.appender.FATAL_MSGS.filters.1.LogLevelToMatch=FATAL\n" "log4cplus.appender.FATAL_MSGS.filters.1.AcceptOnMatch=true\n" "log4cplus.appender.FATAL_MSGS.filters.2=log4cplus::spi::DenyAllFilter\n"; }; #endif
43.136364
129
0.735722
[ "vector" ]