blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
b5024207ca42ce2264090cc2a26ee3edf55b0e02
0c6ad83017727a71da52800e5d648eaaa646f43b
/Src/Tools/ModelCompiler_Quake3Level/ueModelCompiler_Quake3Level.cpp
4e5f4d4097fe4c1d013852b3b3c53d20bc8584bc
[]
no_license
macieks/uberengine
4a7f707d7dad226bed172ecf9173ab72e7c37c71
090a5e4cf160da579f2ea46b839ece8e1928c724
refs/heads/master
2021-06-06T05:14:16.729673
2018-06-20T21:21:43
2018-06-20T21:21:43
18,791,692
3
0
null
null
null
null
UTF-8
C++
false
false
7,517
cpp
ueModelCompiler_Quake3Level.cpp
#include "ModelCompiler_Common/ueToolModel.h" #include "IO/ioFile.h" #include "ueQuake3Level.h" static ueToolModel* s_dstModel = NULL; static ueToolModel::LOD* s_dstLOD = NULL; static ueMat44 s_quake3Transform; void FromQuake3Vertex(ueToolModel::Vertex& dst, const bsp_vertex_t& src, bool hasLightmap) { dst.m_flags = ueToolModel::Vertex::Flags_HasNormal | ueToolModel::Vertex::Flags_HasColor | ueToolModel::Vertex::Flags_HasTex0; dst.m_pos.Set((const f32*) src.point); dst.m_normal.Set((const f32*) src.normal); dst.m_color = ueColor32(src.color[0], src.color[1], src.color[2], src.color[3]); dst.m_tex[0].Set((const f32*) src.texture); if (hasLightmap) { dst.m_flags |= ueToolModel::Vertex::Flags_HasTex1; dst.m_tex[1].Set((const f32*) src.lightmap); } dst.Transform(s_quake3Transform); } u32 GetMaterialIndex(const bsp_face_t& face, const bsp_shader_t& shader) { ueToolModel::Material mat; mat.m_name = shader.name; ueToolModel::Sampler& colorSampler = mat.m_samplers[ueToolModel::Material::SamplerType_Color]; s_dstModel->DetermineSamplerTexture(shader.name, colorSampler); // dstMat.m_hasLightmap = face.lm_texture >= 0; return s_dstLOD->GetAddMaterial(mat); } bool ImportFromFile(ueToolModel& model, const ueToolModel::ImportSettings& settings, const ueAssetParams& params) { s_dstModel = &model; s_quake3Transform.SetIdentity(); s_quake3Transform.Rotate(ueVec3(1, 0, 0), -UE_PI * 0.5f); s_quake3Transform.Scale(0.3f); // Load whole file ueLogI("Loading Quake 3 BSP Level from '%s'", model.m_sourcePath.c_str()); std::vector<u8> dataVector; if (!vector_u8_load_file(model.m_sourcePath.c_str(), dataVector)) { ueLogE("Failed to load file '%s'", model.m_sourcePath.c_str()); return false; } const u8* data = &dataVector[0]; // Get header bsp_header_t* header = (bsp_header_t*) data; // Get data #define GET_LUMP_SIZE(index) header->lumps[index].size #define GET_LUMP_DATA(index) (data + /*sizeof(bsp_header_t) + */header->lumps[index].offset) const int sizeEntities = GET_LUMP_SIZE(BSP_ENTITIES_LUMP); const int numElements = GET_LUMP_SIZE(BSP_ELEMENTS_LUMP) / sizeof(int); const int numFaces = GET_LUMP_SIZE(BSP_FACES_LUMP) / sizeof(bsp_face_t); const int numLeafFaces = GET_LUMP_SIZE(BSP_LFACES_LUMP) / sizeof(int); const int numLeaves = GET_LUMP_SIZE(BSP_LEAVES_LUMP) / sizeof(bsp_leaf_t); const int numLightmaps = GET_LUMP_SIZE(BSP_LIGHTMAPS_LUMP) / BSP_LIGHTMAP_BANKSIZE; const int numModels = GET_LUMP_SIZE(BSP_MODELS_LUMP) / sizeof(bsp_model_t); const int numNodes = GET_LUMP_SIZE(BSP_NODES_LUMP) / sizeof(bsp_node_t); const int numPlanes = GET_LUMP_SIZE(BSP_PLANES_LUMP) / sizeof(bsp_plane_t); const int numShaders = GET_LUMP_SIZE(BSP_SHADERS_LUMP) / sizeof(bsp_shader_t); const int numVertices = GET_LUMP_SIZE(BSP_VERTICES_LUMP) / sizeof(bsp_vertex_t); const int numLeafBrushes= GET_LUMP_SIZE(BSP_LBRUSHES_LUMP) / sizeof(int); const int numBrushes = GET_LUMP_SIZE(BSP_BRUSH_LUMP) / sizeof(bsp_brush_t); const int numBrushSides = GET_LUMP_SIZE(BSP_BRUSHSIDES_LUMP) / sizeof(bsp_brushside_t); const char* entities = (char*) GET_LUMP_DATA(BSP_ENTITIES_LUMP); const int* elements = (int*) GET_LUMP_DATA(BSP_ELEMENTS_LUMP); const bsp_face_t* faces = (bsp_face_t*) GET_LUMP_DATA(BSP_FACES_LUMP); const int* leafFaces = (int*) GET_LUMP_DATA(BSP_LFACES_LUMP); const bsp_leaf_t* leaves = (bsp_leaf_t*) GET_LUMP_DATA(BSP_LEAVES_LUMP); const unsigned char* lightmaps = (unsigned char*) GET_LUMP_DATA(BSP_LIGHTMAPS_LUMP); const bsp_model_t* models = (bsp_model_t*) GET_LUMP_DATA(BSP_MODELS_LUMP); const bsp_node_t* nodes = (bsp_node_t*) GET_LUMP_DATA(BSP_NODES_LUMP); const bsp_plane_t* planes = (bsp_plane_t*) GET_LUMP_DATA(BSP_PLANES_LUMP); const bsp_shader_t* shaders = (bsp_shader_t*) GET_LUMP_DATA(BSP_SHADERS_LUMP); const bsp_vis_t* vis = (bsp_vis_t*) GET_LUMP_DATA(BSP_VISIBILITY_LUMP); const bsp_vertex_t* vertices = (bsp_vertex_t*) GET_LUMP_DATA(BSP_VERTICES_LUMP); const int* leafBrushes = (int*) GET_LUMP_DATA(BSP_LBRUSHES_LUMP); const bsp_brush_t* brushes = (bsp_brush_t*) GET_LUMP_DATA(BSP_BRUSH_LUMP); const bsp_brushside_t* brushSides=(bsp_brushside_t*) GET_LUMP_DATA(BSP_BRUSHSIDES_LUMP); // Create single LOD s_dstLOD = &vector_push(s_dstModel->m_lods); // Extract meshes and materials ueLogI("Processing faces (%d) ...", numFaces); for (int i = 0; i < numFaces; i++) { const bsp_face_t& srcFace = faces[i]; UE_ASSERT(srcFace.shader >= 0); const bsp_shader_t& shader = shaders[srcFace.shader]; if (shader.surface_flags & SURF_SKIP) continue; const bool isDrawable = !(shader.surface_flags & SURF_NODRAW); const bool isTransparent = !(shader.content_flags & CONTENTS_SOLID) || (shader.content_flags & CONTENTS_TRANSLUCENT); const bool hasLightmap = srcFace.lm_texture >= 0; ueToolModel::Mesh* mesh = NULL; switch (srcFace.type) { // Regular mesh case BSP_FACETYPE_PLANAR: case BSP_FACETYPE_MESH: { mesh = &vector_push(s_dstLOD->m_meshes); for (s32 j = srcFace.vert_start; j < srcFace.vert_start + srcFace.vert_count; j++) { ueToolModel::Vertex& v = vector_push(mesh->m_verts); FromQuake3Vertex(v, vertices[j], hasLightmap); } for (s32 j = srcFace.elem_start; j < srcFace.elem_start + srcFace.elem_count; j += 3) { // Flip triangle indices mesh->m_indices.push_back(elements[j]); mesh->m_indices.push_back(elements[j + 2]); mesh->m_indices.push_back(elements[j + 1]); } break; } // Patch mesh case BSP_FACETYPE_PATCH: { mesh = &vector_push(s_dstLOD->m_meshes); mesh->m_flags = ueToolModel::Mesh::Flags_IsPatch; mesh->m_patch.m_width = srcFace.mesh_cp[0]; mesh->m_patch.m_height = srcFace.mesh_cp[1]; for (s32 j = srcFace.vert_start; j < srcFace.vert_start + srcFace.vert_count; j++) { ueToolModel::Vertex& v = vector_push(mesh->m_patch.m_controlPoints); FromQuake3Vertex(v, vertices[j], hasLightmap); } break; } default: break; } // Set up material if (mesh) { mesh->m_flags |= ueToolModel::Mesh::Flags_IsCollision; string_format(mesh->m_name, "%d_%s", i, shader.name); if (isDrawable) { mesh->m_flags |= ueToolModel::Mesh::Flags_IsDrawable; // if (isTransparent) // mesh->m_flags |= IsTransparent; mesh->m_materialIndex = GetMaterialIndex(srcFace, shader); // mesh->m_lightmapId = srcFace.lm_texture; } } } // Extract lightmaps #if 0 ueLogI("Processing lightmaps (%d) ...", numLightmaps); dstModel.m_lightmaps.resize(numLightmaps); for (int i = 0; i < numLightmaps; ++i) { LightMap& lm = dstModel.m_lightmaps[i];; lm.m_texture.Create(BSP_LIGHTMAP_DIMENSION, BSP_LIGHTMAP_DIMENSION, Format_R8G8B8, lightmapData + i * BSP_LIGHTMAP_BANKSIZE); } #endif // Optionally extract spawn points bool extractSpawnPoints = false; params.GetBoolParam("quake3_extractSpawnPoints", extractSpawnPoints); if (extractSpawnPoints) { std::vector<spawnpoint_t> spawnPoints; Q3_GetSpawnPoints(entities, sizeEntities, spawnPoints); for (u32 i = 0; i < spawnPoints.size(); i++) { const spawnpoint_t& p = spawnPoints[i]; ueToolModel::Node& node = vector_push(s_dstLOD->m_nodes); string_format(node.m_name, "spawn_point_%d", i); node.m_localTransform.SetAxisRotation(ueVec3(0, 1, 0), ueRadToDeg(p.m_angleY)); ueVec3 pos(p.m_pos); s_quake3Transform.TransformCoord(pos); node.m_localTransform.Translate(pos); } } return true; }
26a68fd31ed854cda668560ba6a555d1e6474805
7190717d597ae25d6352d62194389f84b518759e
/include/Parsing/Language/OakOperatorExpressionConstructor.h
ec5139626023c5827dd6970b499ea7ae3110131b
[ "MIT" ]
permissive
OutOfTheVoid/OakC
59ce0447b7e1ac11c4674ff1d85d7b1d1b70109a
773934cc52bd4433f95c8c2de1ee231b8de4d0ad
refs/heads/master
2020-12-30T23:59:48.374911
2017-07-24T06:50:48
2017-07-24T06:50:48
80,559,306
2
0
null
null
null
null
UTF-8
C++
false
false
606
h
OakOperatorExpressionConstructor.h
#ifndef LANGUAGE_PARSING_OAKOPERATOREXPRESSIONCONSTRUCTOR_H #define LANGUAGE_PARSING_OAKOPERATOREXPRESSIONCONSTRUCTOR_H #include <Parsing/IASTConstructor.h> #include <Parsing/ASTConstructionGroup.h> class OakOperatorExpressionConstructor : public IASTConstructor { public: OakOperatorExpressionConstructor (); ~OakOperatorExpressionConstructor (); void TryConstruct ( ASTConstructionInput & Input, ASTConstructionOutput & Output ) const; static OakOperatorExpressionConstructor & Instance (); private: ASTConstructionGroup PrimaryGroup; ASTConstructionGroup ExpressionGroup; }; #endif
ac5c21646f67984cbef787cceeda392ced43f6ee
95fe3000c8d599e18362968570abbb954b0ef9ba
/Source/SwordMaze/Player/HeroCharacter.h
b36c323e7b2e0ce6d304b14af57a81e935630128
[]
no_license
Impulse21/SwordMase
a6cda6fb0648fdb8f592ccedd5518cee9223d326
b2fdd6d9df66193bc6b161cabda27e495322459d
refs/heads/master
2021-05-08T12:05:03.966801
2018-03-17T18:15:10
2018-03-17T18:15:10
119,915,827
0
0
null
null
null
null
UTF-8
C++
false
false
5,359
h
HeroCharacter.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Player/BaseCharacter.h" #include "HeroCharacter.generated.h" USTRUCT(Blueprintable) struct FRPGPlayerInput { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite) bool HoldingDefend; UPROPERTY(EditAnywhere, BlueprintReadWrite) bool HoldingSprint; UPROPERTY(EditAnywhere, BlueprintReadWrite) bool AttackPressed; }; USTRUCT(Blueprintable) struct FRPGEquiptItems { GENERATED_BODY() }; USTRUCT(Blueprintable) struct FRPGDebugFlags { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite) bool DrawUsableLineTrace; }; UENUM(Blueprintable) enum class ECountdownTimerZone : uint8 { CTZ_Normal, CTZ_High, CTZ_Critical }; DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnPlayerScoreUpdate, int, DeltaScore); /** * */ UCLASS() class SWORDMAZE_API AHeroCharacter : public ABaseCharacter { GENERATED_BODY() public: AHeroCharacter(); virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; virtual void Tick(float DeltaTime) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; UFUNCTION(BlueprintCallable, Category = "Player") void AddWeapon(class ABaseWeapon* Weapon); UFUNCTION(BlueprintCallable, Category = Player) void OnDeath(AActor* DamageCauser, FDamageEvent const& DamageEvent) override; UFUNCTION(BlueprintCallable, Category = Player) void StopAllAnimMontages(); /** Getter and setters */ public: /** Returns CameraBoom subobject **/ FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject **/ FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } UFUNCTION(BlueprintPure, Category = Player) FORCEINLINE bool IsWeaponEquiped() const { return (EquipedWeapon != nullptr); }; UFUNCTION(BlueprintCallable, Category = Player) FName GetInventoryAttachPoint(EItemType const& slot); UPROPERTY(BlueprintAssignable, Category = PickupEvent) FOnPlayerScoreUpdate UpdatePlayerScore; UFUNCTION(BlueprintCallable, Category = "Damage") void TraceWeapon(); /** Inputs */ protected: /** Called for forwards/backward input */ void MoveForward(float Value); /** Called for side to side input */ void MoveRight(float Value); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void TurnAtRate(float Rate); /** * Called via input to turn look up/down at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void LookUpAtRate(float Rate); /** Called when Player wants to Sprint */ void OnStartSprinting(); void OnStopSprinting(); /** Player starts defending */ void OnStartDefending(); void OnStopDefending(); /** Player wants to attack */ void OnStartAttacking(); void OnStopAttacking(); UFUNCTION() void OnEquipTimerEnd(); UFUNCTION(BlueprintNativeEvent, Category = Player) void OnPickupOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); UFUNCTION(BlueprintCallable, Category = Player) bool UpdateCurrentTimerZone(); UFUNCTION(BlueprintCallable, Category = Player) float GetZoneTimeDelay(ECountdownTimerZone const& TimerZone); UFUNCTION(BlueprintCallable, Category = Player) void PlayCurrSoundCue(); /** Components */ protected: /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Player) class UBoxComponent* PickupCollector; protected: /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ UPROPERTY(BlueprintReadWrite, Category = Camera) float BaseLookUpRate; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Player) TMap<ECountdownTimerZone, class USoundCue*> SoundMap; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Player) float WeaponEquipTime; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Player) FRPGPlayerInput PlayerInput; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Player) FRPGDebugFlags DebugFlags; UPROPERTY(Transient) class ABaseWeapon* EquipedWeapon; private: UPROPERTY(EditDefaultsOnly, Category = "Equipment") FName PrimaryWeaponSocketName; UPROPERTY(EditDefaultsOnly, Category = "Equipment") FName SecondaryWeaponSocketName; UPROPERTY(EditDefaultsOnly, Category = "Equiptment") FName HeadArmourSocketName; UPROPERTY() FTimerHandle WeaponEquipedTimeHandler; UPROPERTY() FTimerHandle AttackTimeHandler; UPROPERTY() float ElapsedTime; UPROPERTY() ECountdownTimerZone CurrTimerZone; bool bHasNewFocus; };
8075ec6e74d52f2e4348795ee8ecf8265c266bdc
f9c231a866ef7138c033f301becbf24c8bdca633
/Test6/LamLai/21.cpp
2a0d27684163a3689d1bd7e2e3d5fb52d368962a
[]
no_license
cuongnh28/DSAFall2019
3eef8f5e0e1cbe008bd304c847dd9abaa4ad144f
2729d834b3c4a3560bf63aa6d1dcfc7457385246
refs/heads/main
2023-02-02T14:41:39.353309
2020-12-23T16:20:02
2020-12-23T16:20:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
21.cpp
#include<bits/stdc++.h> using namespace std; struct dta{ int val,cnt; }; bool cmp(dta a, dta b){ if(a.cnt>b.cnt) return true; if(a.cnt==b.cnt && a.val<b.val) return true; return false; } void Solve(){ int d[10005],n; dta a[10005]; memset(d,0,sizeof(d)); cin>>n; for(int i=0;i<n;i++){ cin>>a[i].val; d[a[i].val]++; } for(int i=0;i<n;i++){ a[i].cnt=d[a[i].val]; } sort(a,a+n,cmp); for(int i=0;i<n;i++) cout<<a[i].val<<" "; cout<<endl; } int main(){ int t; cin>>t; while(t--){ Solve(); } }
8bc7d57c2fdc692f0bcd526e03f7e17e8bc7df5e
73bd731e6e755378264edc7a7b5d16132d023b6a
/UVA/UVA - 13272.cpp
8c26a0144817e9f410bf1c7cb2ef7a6bdf680c7e
[]
no_license
IHR57/Competitive-Programming
375e8112f7959ebeb2a1ed6a0613beec32ce84a5
5bc80359da3c0e5ada614a901abecbb6c8ce21a4
refs/heads/master
2023-01-24T01:33:02.672131
2023-01-22T14:34:31
2023-01-22T14:34:31
163,381,483
0
3
null
null
null
null
UTF-8
C++
false
false
2,132
cpp
UVA - 13272.cpp
/* Template for vjudge.net Author: Iqbal Hossain Rasel CodeForces: The_Silent_Man AtCoder : IHR57 TopCoder : IHR57 */ #include <bits/stdc++.h> #define pb push_back #define mp make_pair #define ff first #define ss second #define PI acos(-1) #define pi 3.1415926535897932384 #define INF 2147483647 #define EPS 1e-8 #define MOD 1000000007 #define MAX 100005 using namespace std; typedef long long ll; int Set(int mask, int pos){return mask = mask | (1<<pos);} bool check(int mask, int pos){return (bool)(mask & (1<<pos));} stack<pair<char, int> > st; string str; int ans[MAX], dp[MAX]; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int test, caseno = 1; cin>>test; while(test--){ cin>>str; int len = str.size(); memset(ans, 0, sizeof(ans)); memset(dp, 0, sizeof(dp)); for(int i = 0; i < len; i++){ if(str[i] == '<' || str[i] == '(' || str[i] == '[' || str[i] == '{'){ st.push(mp(str[i], i)); } else{ if(st.empty()) continue; if((st.top().ff == '(' && str[i] == ')') || (st.top().ff == '<' && str[i] == '>') || (st.top().ff == '[' && str[i] == ']') || (st.top().ff == '{' && str[i] == '}')){ ans[st.top().ss] = i - st.top().ss + 1; st.pop(); } else{ while(!st.empty()){ st.pop(); } } } } cout<<"Case "<<caseno++<<":"<<endl; int n = len; for(int i = n - 1; i >= 0; i--){ if(ans[i] > 0 && i + ans[i] <= n - 1 && ans[i + ans[i]] > 0){ dp[i] = ans[i] + dp[i + ans[i]]; } else{ dp[i] = ans[i]; } } for(int i = 0; i < n; i++){ cout<<dp[i]<<endl; } while(!st.empty()) st.pop(); } return 0; }
de0865546a23747d0dfc74e2c937ffffb6de8e29
8e5a99d4c3cb79aad54ae5a19f592966b2e4dc31
/Snake/Snake/snake_map.cpp
f3540702b889426181d71aee8e8624c4d95733fe
[]
no_license
Yud-Bet/Snake
c267573beaae72144033c8c6baba97b42bbf9d3e
6ca38d9e524475f5e5262632cd327604851c4cba
refs/heads/master
2022-12-16T08:47:03.957652
2020-07-16T13:45:16
2020-07-16T13:45:16
279,733,713
0
0
null
2020-07-16T10:28:53
2020-07-15T01:41:47
C++
UTF-8
C++
false
false
2,033
cpp
snake_map.cpp
#include "snake_map.h" #include <iostream> #include "my_console.h" #include <time.h> snake_map::snake_map(int width, int height) { w = width; h = height; s_map = new char* [h]; for (int i = 0; i < h; i++) { s_map[i] = new char[w]; } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (i == 0 || j == 0 || j == w - 1 || i == h - 1) { s_map[i][j] = '#'; } else s_map[i][j] = ' '; } } } bool snake_map::is_map_being_eaten(coord head) { for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (s_map[i][j] != ' ') { if (head.x == j && head.y == i) { return true; } } } } return false; } void snake_map::print_map() { gotoxy(0, 0); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (s_map[i][j] != ' ') { gotoxy(j, i); std::cout << char(254); } } } } void Food::print_food() { gotoxy(vitri.x, vitri.y); std::cout << '*'; } coord Food::getVitri() { coord toado; toado.x = vitri.x; toado.y = vitri.y; return toado; } void Food::newfood(Snake& a, snake_map& b) { bool ran{ 0 }; while (ran == false) { srand(time(0)); vitri.x = Randoms(0, a.getw() - 1); vitri.y = Randoms(0, a.geth() - 1); if (!b.is_map_being_eaten(vitri)) { for (int i{ 0 }; i < a.getLength(); i++) { if (!(vitri.x == a.getBody(i).x && vitri.y == a.getBody(i).y)) { ran = true; } else { ran = false; break; } } } else continue; } }
92c3b61037aa84d3ce909bb6069dbd3582baca01
012e897bcab3134e1874e06e9a56c2bdbc4d9a32
/manager/main.cpp
24401872671aafb498c709f6af54fd4ea8c2c395
[]
no_license
007exe/mpkg
45f28774af24bb5917600bee6cdb38b70e5c0e06
82e6ed05d78fa2b19672f09a5c777cb9db5a75d9
refs/heads/master
2022-11-10T13:23:35.651274
2022-10-31T17:41:27
2022-10-31T17:41:27
231,104,359
2
0
null
2019-12-31T14:40:17
2019-12-31T14:40:16
null
UTF-8
C++
false
false
3,199
cpp
main.cpp
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com /**************************************************************** * MOPSLinux packaging system * Package manager - main file * $Id: main.cpp,v 1.30 2007/11/23 01:01:45 i27249 Exp $ ***************************************************************/ #include <QApplication> #include <QPushButton> #include <QListWidget> #include <QWidget> #include <QLocale> #include "tablelabel.h" #include "mainwindow.h" int main(int argc, char *argv[]) { if (getuid()) { // trying to obtain root UID setuid(0); if (getuid()) { string args; for (int i=1; i<argc; ++i) { args += string(argv[i]) + " "; } return system("xdg-su -c \"" + string(argv[0]) + " " + args + "\""); } } setlocale(LC_ALL, ""); bindtextdomain( "mpkg", "/usr/share/locale"); textdomain("mpkg"); QApplication app(argc, argv); QTranslator translator; QLocale lc; translator.load("pkgmanager_" + lc.name(), "/usr/share/mpkg"); app.installTranslator(&translator); MainWindow mw; QObject::connect(mw.ui.selectAllButton, SIGNAL(clicked()), &mw, SLOT(selectAll())); QObject::connect(mw.ui.deselectAllButton, SIGNAL(clicked()), &mw, SLOT(deselectAll())); QObject::connect(mw.ui.actionQuit, SIGNAL(triggered()), &mw, SLOT(quitApp())); QObject::connect(mw.ui.quitButton, SIGNAL(clicked()), &mw, SLOT(quitApp())); QObject::connect(mw.ui.applyButton, SIGNAL(clicked()), &mw, SLOT(commitChanges())); QObject::connect(mw.ui.actionAbout, SIGNAL(triggered()), &mw, SLOT(showAbout())); QObject::connect(mw.ui.actionReset_changes, SIGNAL(triggered()), &mw, SLOT(resetChanges())); QObject::connect(mw.ui.actionReset_all_queue, SIGNAL(triggered()), &mw, SLOT(resetQueue())); QObject::connect(mw.ui.actionPreferences, SIGNAL(triggered()), &mw, SLOT(showPreferences())); QObject::connect(mw.ui.actionAdd_remove_repositories, SIGNAL(triggered()), &mw, SLOT(showAddRemoveRepositories())); QObject::connect(mw.ui.actionClean_cache, SIGNAL(triggered()), &mw, SLOT(cleanCache())); QObject::connect(mw.ui.actionShow_installed, SIGNAL(triggered()), &mw, SLOT(applyPackageFilter())); QObject::connect(mw.ui.actionShow_deprecated, SIGNAL(triggered()), &mw, SLOT(applyPackageFilter())); QObject::connect(mw.ui.actionShow_available, SIGNAL(triggered()), &mw, SLOT(applyPackageFilter())); QObject::connect(mw.ui.actionShow_queue, SIGNAL(triggered()), &mw, SLOT(applyPackageFilter())); QObject::connect(mw.ui.actionShow_configexist, SIGNAL(triggered()), &mw, SLOT(applyPackageFilter())); QObject::connect(mw.ui.actionShow_unavailable, SIGNAL(triggered()), &mw, SLOT(applyPackageFilter())); QObject::connect(mw.ui.actionCore_settings, SIGNAL(triggered()), &mw, SLOT(showCoreSettings())); QObject::connect(mw.ui.actionUpdate_data, SIGNAL(triggered()), &mw, SLOT(updateData())); QObject::connect(mw.ui.packageTable, SIGNAL(itemSelectionChanged()), &mw, SLOT(showPackageInfo())); QObject::connect(mw.ui.quickPackageSearchEdit, SIGNAL(textEdited(const QString &)), &mw, SLOT(applyPackageFilter())); int ret = app.exec(); return ret; }
f40c27d6f14cc03fe61ab045b13ad8150176aef1
115615009471b90924bcdc8229c27b75e2530aee
/DebugDiag.Native.DbgExt/Memory.h
59a8d59a6ac4c775947c2adc5973dc77ce4aef34
[ "MIT" ]
permissive
alxbl/DebugDiag.Native
9018b28427f8f63e7d5a2268d52d22bb7a5a95db
6a629caa892d2c6ef8e7ccfacb77ea95b887715a
refs/heads/master
2016-09-06T19:33:14.996389
2015-06-08T03:02:50
2015-06-08T03:02:50
24,581,557
1
1
null
null
null
null
UTF-8
C++
false
false
857
h
Memory.h
#pragma once #include "stdafx.h" /// Memory helpers on top of DbgEng. class Memory { public: static const size_t PtrSize; static ULONG_PTR ReadPointer(ULONG_PTR address); static ULONG_PTR ReadQWord(ULONG_PTR address); static ULONG_PTR ReadDWord(ULONG_PTR address); static ULONG_PTR ReadWord(ULONG_PTR address); static ULONG_PTR ReadByte(ULONG_PTR address); /// Generic Read for n bytes. /// @param address the address at which to read memory in the dump. /// @param lpBuffer a pointer to the buffer in which to place the read memory. /// @param count the number of bytes to read from the memory /// @param lpcbBytesRead a pointer to an unsigned long where the number of bytes read will be stored. static void Read(ULONG_PTR address, PVOID lpBuffer, ULONG count, PULONG lpcbBytesRead); };
e1ed0f37b15c2f183dec9d282898001110129115
14a9191fa9a0ee0dd7080ede93dc2d9df210a9aa
/src/errorReceiver.cpp
7a45d8ada63657dee46efe445aad6b0d89b1711f
[ "MIT" ]
permissive
tositeru/watagashi-buildsystem
8ef306b5c4584cd88dfdb93835d51fad489132c0
d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4
refs/heads/master
2020-03-18T16:20:58.936747
2018-07-26T04:27:40
2018-07-26T04:27:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,325
cpp
errorReceiver.cpp
#include "errorReceiver.h" #include <iostream> using namespace std; namespace watagashi { ErrorReceiver::ErrorReceiver(){} ErrorReceiver::~ErrorReceiver(){} void ErrorReceiver::clear() { this->mMessages.clear(); } void ErrorReceiver::receive( MessageType type, size_t line, const std::string& message) { Message msg; msg.type = type; msg.message = this->attachMessageTypePrefix(message, type, line); //msg.message = this->attachTag(msg.message); this->mMessages.push_back(msg); } bool ErrorReceiver::empty()const { return this->mMessages.empty(); } bool ErrorReceiver::hasError()const { for(auto& msg : this->mMessages) { if(eError == msg.type) return true; } return false; } void ErrorReceiver::print(uint32_t flag) { for(auto& msg : this->mMessages) { if(msg.type & flag) { cerr << msg.message << endl; } } } std::string ErrorReceiver::attachMessageTypePrefix( const std::string& str, MessageType type, size_t line)const { std::string lineStr = "(line:" + std::to_string(line) + ") "; switch(type) { case eError: return lineStr + "!!error!! " + str; case eWarnning: return lineStr + "!!warnning!! " + str; default: return lineStr + "!!implement miss!! " + str; } } }
fdcd787dca59c5ef7f605c797ae7ab2c5784dc1a
a6ae3b2ec8dae0dd1aac9b4cab0bd774960f27e4
/ExampleGame/Header Files/GameClasses/GameNetworking.h
a8db5ba9a2c9702ecd0bf6673a02aaaf05e693c6
[]
no_license
AnthonyBeacock/KodeboldsEngineMK2
6490aa4554c1e9f424897c5166c8e36dbf93e724
79090d5a47f7700dfe47b34b1c5c4022fd77e078
refs/heads/master
2020-05-23T02:31:18.974031
2019-06-02T10:13:34
2019-06-02T10:13:34
169,144,544
1
0
null
2019-03-28T17:11:01
2019-02-04T20:28:44
C++
UTF-8
C++
false
false
320
h
GameNetworking.h
#pragma once #include "NetworkManager.h" #include "ECSManager.h" class GameNetworking { private: std::shared_ptr<ECSManager> mEcsManager = ECSManager::Instance(); std::shared_ptr<NetworkManager> mNetworkManager = NetworkManager::Instance(); public: GameNetworking(); ~GameNetworking(); void ProcessMessages(); };
09c24b9ac4ff788b88613e952839bcd99c7ca6b1
f0755c0ca52a0a278d75b76ee5d9b547d9668c0e
/atcoder.jp/abc150/abc150_d/Main.cpp
ad80443153f7ff345b926f34258a59d6b2001846
[]
no_license
nasama/procon
7b70c9a67732d7d92775c40535fd54c0a5e91e25
cd012065162650b8a5250a30a7acb1c853955b90
refs/heads/master
2022-07-28T12:37:21.113636
2020-05-19T14:11:30
2020-05-19T14:11:30
263,695,345
0
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
Main.cpp
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) #define rep2(i,n) for (int i = 1; i < (n); ++i) using namespace std; typedef long long ll; ll gcd(ll a, ll b) { int v0 = a, v1 = b, v2 = a % b; while (v2 != 0) { v0 = v1; v1 = v2; v2 = v0 % v1; }; return v1; } ll lcm(ll a, ll b) { return a * b / gcd(a, b); } int main() { ll N, M; cin >> N >> M; vector<ll> a(N+2); rep(i,N) { cin >> a[i]; a[i]/=2; } ll ans = 1; for (ll i = 0; i < N; i++) ans = lcm(ans, a[i]); ll b = 0; for(ll i = 1; ; i+=2){ if(ans*i > M) break; b++; } rep(i, N) { if(ans/a[i]%2==0) { b = 0; break; } } cout << b << endl; return 0; }
d40cddc143c79621537b7edc21552e2b8feb43d6
e410f3831a7132e4c8a12c0b02bee93a840e5bef
/loopFor.cpp
6a6bf27aa1000fb886ca6aa425a6b99bddfe6dc6
[]
no_license
Brian-wKicheu/Summarry-of-cpp-basics
87e245a0887b4578692fbfa1346a6b2f7b7116de
f7b77610a91bfca74e253e65bcc17236626468e3
refs/heads/main
2023-04-23T06:37:02.866001
2021-05-04T08:54:37
2021-05-04T08:54:37
364,195,155
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
loopFor.cpp
#include <iostream> using namespace std; int main() { /* When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. */ for (int i = 0; i < 5; i++) { cout << i << "\n"; } return 0; }
c9d9f5c46c3e07ca1df73c6917d9110c2fa99e1a
714ba40913184bc5a65a527bf30667c83e26ae30
/CppCli-WPF-App/Display/Display.h
79c40fb197eda95ec9db72c85fd42300c9bfd6a0
[]
no_license
Isira/Remote-Code-Management-Facility
8366782b77c38cb49b0e821802a9c87948cac9dc
7fa15889c667f1902dd6108d68f57a82ff878e86
refs/heads/master
2016-09-06T09:19:12.823711
2015-06-25T19:31:52
2015-06-25T19:31:52
38,068,687
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,481
h
Display.h
#ifndef DISPLAY_H #define DISPLAY_H ////////////////////////////////////////////////////////////////////////////// // ServiceMessage.h - Display results on the standard output // // ver 1.0 // // -------------------------------------------------------------------------// // copyright © Isira Samarasekera, 2015 // // All rights granted provided that this notice is retained // // -------------------------------------------------------------------------// // Language: Visual C++, Visual Studio Ultimate 2013 // // Platform: Mac Book Pro, Core i5, Windows 8.1 // // Application: Project #3 – Message Passing Communication,2015 // // Author: Isira Samarasekera, Syracuse University // // issamara@syr.edu // ////////////////////////////////////////////////////////////////////////////// /* * Module Operations: * ================== * Display results on the standard output * * Public Interface: * ================= * Display display; * display.showString("Hello World"); * display.RequirementHeader("123"); * std::vector<std::string> header = { "srcIp:localhost", "srcPort:1234", "dstIp:localhost", "3333" }; * ServiceMessage msg = ServiceMessage::interpret(header); * Display::setShowMessage(true); * display.showMessageReceived(msg); * display.showMessageSent(msg); * Display::setShowMessage(false); * * Required Files: * =============== * Display.h Display.cpp * * Build Command: * ============== * cl /EHa /DTEST_DISPLAY Display.cpp * * Maintenance History: * ==================== * ver 1.0 : 12 April 15 * - first release */ #include <string> #include <iostream> #include <sstream> #include <mutex> class ServiceMessage; class Display { private: static bool _showMessage; static void showMessage(ServiceMessage& msg); static bool showState_; public: Display(bool showState = false); void static show(const std::string& msg, bool always = false); void RequirementHeader(const std::string& num); void showString(const std::string& str); static void showMessageReceived(ServiceMessage& msg); static void showMessageSent(ServiceMessage& msg); static void setShowMessage(bool value); static void title(const std::string& msg, char underline = '-'); static void putLine(const std::string& msg = ""); static std::mutex mtx; }; template<typename T> std::string toString(T t) { std::ostringstream out; out << t; return out.str(); } extern const bool always; #endif
a3e3c11df3f694826fdfa0951dfb7daa62524327
3c088469730cadd36de8592708f75d7b6f4dad75
/atmosstakev2.cpp
2ae89b9eac00b1d8bbe2637ca99d6bcd516ad9a9
[]
no_license
Novusphere/atmosstakev2
f4d35d2751e69b3de10c1dff19a371c3ebbe8a26
db00574c0d4a01330ebf94eba69e24b3b4c88d1c
refs/heads/master
2023-08-19T18:29:38.718192
2021-09-09T23:56:42
2021-09-09T23:56:42
317,768,852
0
0
null
null
null
null
UTF-8
C++
false
false
14,783
cpp
atmosstakev2.cpp
// // Created by xia256 on behalf of the Novusphere Foundation // #include "atmosstakev2.hpp" // // Checks sanity of all data associated with the contract // ACTION atmosstakev2::sanity() { // check public key sanity eosio::public_key pk = eosio::public_key_from_string("EOS82g6zVgPDNb1XDQBc6knEBusvPonq7KBhgCq3qkYWYt4kjm4JX"); string pks = eosio::public_key_to_string(pk); eosio::checkf(pks == "EOS82g6zVgPDNb1XDQBc6knEBusvPonq7KBhgCq3qkYWYt4kjm4JX", "Unexpected key: %s != EOS82g6zVgPDNb1XDQBc6knEBusvPonq7KBhgCq3qkYWYt4kjm4JX", pks.c_str()); // stats: total_weight, total_supply stats stats_table(_self, _self.value); for (auto it = stats_table.begin(); it != stats_table.end(); it++) { stakes stakes_table(_self, it->token_symbol.raw()); accounts accounts_table(_self, it->token_symbol.raw()); int64_t total_weight = 0; eosio::asset total_supply = eosio::asset(0, it->token_symbol); for (auto stake = stakes_table.begin(); stake != stakes_table.end(); stake++) { total_weight += stake->weight; total_supply += stake->balance; } eosio::checkf(total_weight == it->total_weight, "stat->total_weight=%s, [stakes_table]->total_weight=%s", to_string(it->total_weight).c_str(), to_string(total_weight).c_str()); eosio::checkf(total_supply == it->total_supply, "stat->total_supply=%s, [stakes_table]->total_supply=%s", it->total_supply.to_string().c_str(), total_supply.to_string().c_str()); total_weight = 0; total_supply = eosio::asset(0, it->token_symbol); for (auto acc = accounts_table.begin(); acc != accounts_table.end(); acc++) { total_weight += acc->total_weight; total_supply += acc->total_balance; } eosio::checkf(total_weight == it->total_weight, "stat->total_weight=%s, [stakes_table]->total_weight=%s", to_string(it->total_weight).c_str(), to_string(total_weight).c_str()); eosio::checkf(total_supply == it->total_supply, "stat->total_supply=%s, [stakes_table]->total_supply=%s", it->total_supply.to_string().c_str(), total_supply.to_string().c_str()); } eosio::check(false, "Sanity is OK"); } // // Destroys all data associated with the contract // WARNING: should only be called upon termination or migration // ACTION atmosstakev2::destroy() { eosio::require_auth(_self); stats stats_table(_self, _self.value); for (auto it = stats_table.begin(); it != stats_table.end(); it++) { stakes stakes_table(_self, it->token_symbol.raw()); accounts accounts_table(_self, it->token_symbol.raw()); eosio::clear_table(stakes_table); eosio::clear_table(accounts_table); } eosio::clear_table(stats_table); } // // Creates or updates a stakable token // ACTION atmosstakev2::create( eosio::name token_contract, eosio::symbol token_symbol, eosio::asset round_subsidy, int64_t min_claim_secs, int64_t min_stake_secs, int64_t max_stake_secs, eosio::asset min_stake) { eosio::require_auth(_self); eosio::check(token_symbol.is_valid(), "invalid token symbol name"); eosio::check(round_subsidy.is_valid() && round_subsidy.amount > 0 && round_subsidy.symbol == token_symbol, "invalid round subsidy"); eosio::check(min_stake.is_valid() && min_stake.amount > 0 && min_stake.symbol == token_symbol, "invalid min stake"); eosio::check(min_claim_secs > 0, "min claim secs must be greater than zero"); eosio::check(min_stake_secs > 0, "min stake secs must be greater than zero"); eosio::check(max_stake_secs >= min_stake_secs, "max stake secs must be greater than or equal to min stake secs"); stats stats_table(_self, _self.value); auto stat = stats_table.find(token_symbol.raw()); if (stat == stats_table.end()) { // // Creating a new stakable token // stats_table.emplace(_self, [&](auto &a) { a.total_weight = 0; a.total_supply = eosio::asset(0, token_symbol); a.subsidy_supply = eosio::asset(0, token_symbol); a.round_subsidy = round_subsidy; a.token_contract = token_contract; a.token_symbol = token_symbol; a.last_claim = eosio::current_time_point_sec(); a.min_claim_secs = min_claim_secs; a.min_stake_secs = min_stake_secs; a.max_stake_secs = max_stake_secs; a.min_stake = min_stake; }); } else { // // Updating an existing token // stats_table.modify(stat, _self, [&](auto &a) { eosio::check(a.token_contract == token_contract, "token contract for symbol is not as expected"); a.round_subsidy = round_subsidy; a.min_claim_secs = min_claim_secs; a.min_stake_secs = min_stake_secs; a.max_stake_secs = max_stake_secs; a.min_stake = min_stake; }); } } // // Can only be called by contract itself, used as an emergency exit of all stakes // ACTION atmosstakev2::fexitstakes(eosio::symbol token_symbol, eosio::name stakes_to, eosio::name supply_to) { eosio::require_auth(_self); stats stats_table(_self, _self.value); auto stat = stats_table.find(token_symbol.raw()); stakes stakes_table(_self, token_symbol.raw()); accounts accounts_table(_self, token_symbol.raw()); // eject the stakes for (auto it = stakes_table.begin(); it != stakes_table.end(); it++) { eosio::action( permission_level{_self, name("active")}, stat->token_contract, name("transfer"), std::make_tuple(_self, stakes_to, it->balance, eosio::public_key_to_string(it->public_key))) .send(); } eosio::clear_table(stakes_table); eosio::clear_table(accounts_table); // eject the subsidy supply if (supply_to != _self && stat->subsidy_supply.amount > 0) { eosio::action( permission_level{_self, name("active")}, stat->token_contract, name("transfer"), std::make_tuple(_self, supply_to, stat->subsidy_supply, "fexitstakes"s)) .send(); } stats_table.modify(stat, same_payer, [&](auto &a) { a.total_supply = eosio::asset(0, token_symbol); a.subsidy_supply = eosio::asset(0, token_symbol); a.total_weight = 0; }); } // // Called by a user to exit a stake from the system // The message below should be signed for the [sig] parameter: // `atmosstakev2 unstake:${key} ${to} ${memo}` // ACTION atmosstakev2::exitstake(uint64_t key, eosio::symbol token_symbol, eosio::name to, string memo, eosio::signature sig) { eosio::check(to != _self, "cannot exit to self"); eosio::check(token_symbol.is_valid(), "invalid token symbol"); stakes stakes_table(_self, token_symbol.raw()); stats stats_table(_self, _self.value); accounts accounts_table(_self, token_symbol.raw()); auto accounts_index = accounts_table.get_index<by_public_key>(); auto now = eosio::current_time_point_sec(); auto stake = stakes_table.find(key); eosio::check(stake != stakes_table.end(), "stake not found"); eosio::check(now >= stake->expires, "stake is not yet expired"); string msg = eosio::format_string("atmosstakev2 unstake:%s %s %s", to_string(key).c_str(), to.to_string().c_str(), memo.c_str()); eosio::checksum256 digest = eosio::sha256(msg.c_str(), msg.length()); eosio::assert_recover_key(digest, sig, stake->public_key); auto stat = stats_table.find(stake->balance.symbol.raw()); eosio::check(stat != stats_table.end(), "stat not found"); eosio::check(stat->total_supply >= stake->balance, "insufficient supply"); auto account = accounts_index.find(eosio::public_key_to_fixed_bytes(stake->public_key)); eosio::check(account != accounts_index.end(), "account not found"); stakes_table.erase(stake); stats_table.modify(stat, same_payer, [&](auto &a) { a.total_supply -= stake->balance; a.total_weight -= stake->weight; }); if (stake->balance.amount == account->total_balance.amount) { accounts_index.erase(account); } else { accounts_index.modify(account, same_payer, [&](auto &a) { a.total_balance -= stake->balance; a.total_weight -= stake->weight; }); } eosio::action( permission_level{_self, name("active")}, stat->token_contract, name("transfer"), std::make_tuple(_self, to, stake->balance, memo)) .send(); } // // Admin function for resetting the claim period // ACTION atmosstakev2::resetclaim(eosio::symbol token_symbol) { eosio::require_auth(_self); stats stats_table(_self, _self.value); auto stat = stats_table.find(token_symbol.raw()); stats_table.modify(stat, same_payer, [&](auto &a) { a.last_claim -= stat->min_claim_secs; }); } // // Can be called by anyone // Cycles through all staked amounts for [token_symbol] and awards stake accordingly // [relay] receives 1% of the [round_subsidy] where as the reminaing 99% is split among stakers // ACTION atmosstakev2::claim(eosio::symbol token_symbol, eosio::name relay, string memo) { eosio::check(relay != _self, "self cannot relay"); eosio::check(token_symbol.is_valid(), "invalid token symbol"); stakes stakes_table(_self, token_symbol.raw()); stats stats_table(_self, _self.value); accounts accounts_table(_self, token_symbol.raw()); auto accounts_index = accounts_table.get_index<by_public_key>(); auto now = eosio::current_time_point_sec(); auto stat = stats_table.find(token_symbol.raw()); eosio::check(stat != stats_table.end(), "token not found"); auto time_delta = eosio::time_diff_secs(now, stat->last_claim); eosio::checkf(time_delta >= stat->min_claim_secs, "it has not been a sufficient amount of time since the last claim() call, remaining secs: %d", (stat->min_claim_secs - time_delta)); eosio::check(stat->subsidy_supply >= stat->round_subsidy, "insufficient subsidy"); eosio::asset subsidy(stat->round_subsidy.amount * 99 / 100, token_symbol); eosio::check(subsidy.is_valid() && stat->round_subsidy > subsidy, "invalid subsidy"); eosio::asset relay_subsidy(stat->round_subsidy.amount * 1 / 100, token_symbol); eosio::check(relay_subsidy.is_valid(), "invalid relay subsidy"); eosio::check(relay_subsidy.amount > 0, "relay subsidy must be greater than zero, increase relay subsidy by recalling create"); for (auto stake = stakes_table.begin(); stake != stakes_table.end(); stake++) { eosio::asset reward(subsidy.amount * (stake->weight) / (stat->total_weight), token_symbol); if (reward.amount <= 0 || !reward.is_valid()) continue; // ignore, insufficient amount auto account = accounts_index.find(eosio::public_key_to_fixed_bytes(stake->public_key)); eosio::check(account != accounts_index.end(), "account not found"); stakes_table.modify(stake, same_payer, [&](auto &a) { a.balance += reward; }); accounts_index.modify(account, same_payer, [&](auto &a) { a.total_balance += reward; }); } stats_table.modify(stat, same_payer, [&](auto &a) { a.subsidy_supply -= stat->round_subsidy; a.total_supply += subsidy; a.last_claim = now; }); eosio::action( permission_level{_self, "active"_n}, stat->token_contract, "transfer"_n, std::make_tuple(_self, relay, relay_subsidy, memo)) .send(); } // // Inline called when receiving a transfer to purpose it to be staked // void atmosstakev2::stake(eosio::public_key public_key, eosio::asset balance, eosio::time_point_sec expires) { accounts accounts_table(_self, balance.symbol.raw()); stakes stakes_table(_self, balance.symbol.raw()); stats stats_table(_self, _self.value); auto stat = stats_table.find(balance.symbol.raw()); eosio::check(stat != stats_table.end(), "token not found"); eosio::check(balance >= stat->min_stake, "amount does not meet the minimum stake requirement"); auto now = eosio::current_time_point_sec(); eosio::check(expires >= (now + stat->min_stake_secs), "the staking period is too short"); eosio::check(expires <= (now + stat->max_stake_secs), "the staking period is too long"); int64_t weight = (balance.amount / 10000) * (eosio::time_diff_secs(expires, now) / 60); eosio::check(weight > 0, "weight must be greater than zero"); stats_table.modify(stat, same_payer, [&](auto &a) { a.total_supply += balance; a.total_weight += weight; }); stakes_table.emplace(_self, [&](auto &a) { a.key = stakes_table.available_primary_key(); a.weight = weight; a.public_key = public_key; a.initial_balance = balance; a.balance = balance; a.expires = expires; }); auto accounts_index = accounts_table.get_index<by_public_key>(); auto account = accounts_index.find(eosio::public_key_to_fixed_bytes(public_key)); if (account == accounts_index.end()) { accounts_table.emplace(_self, [&](auto &a) { a.key = accounts_table.available_primary_key(); a.public_key = public_key; a.total_balance = balance; a.total_weight = weight; }); } else { accounts_index.modify(account, same_payer, [&](auto &a) { a.total_balance += balance; a.total_weight += weight; }); } } // // Inline called when receiving a transfer which is a subsidy // void atmosstakev2::addsubsidy(eosio::asset balance) { stats stats_table(_self, _self.value); auto stat = stats_table.find(balance.symbol.raw()); eosio::check(stat != stats_table.end(), "token not found"); stats_table.modify(stat, same_payer, [&](auto &a) { a.subsidy_supply += balance; }); } // // Called on an incoming transfer // void atmosstakev2::transfer(eosio::name from, eosio::name to, eosio::asset quantity, string memo) { if (from == _self) return; eosio::check(to == _self, "stop trying to hack the contract"); eosio::check(quantity.is_valid(), "invalid quantity"); eosio::check(quantity.amount > 0, "must be positive quantity"); auto arguments = eosio::split_string(memo, " "); eosio::check(arguments.size() > 0, "expected at least one argument"); stats stats_table(_self, _self.value); auto stat = stats_table.find(quantity.symbol.raw()); eosio::check(stat != stats_table.end(), "token is not supported"); string method = arguments[0]; if (method == "stake") { eosio::check(arguments.size() == 3, "expected exactly 3 arguments"); auto public_key = eosio::public_key_from_string(arguments[1]); auto expires = eosio::current_time_point_sec() + stoi(arguments[2]); this->stake(public_key, quantity, expires); } else if (method == "addsubsidy") { eosio::check(arguments.size() == 1, "expected exactly 1 argument"); this->addsubsidy(quantity); } else { eosio::check(false, "unknown method"); } } // // Dispatcher // extern "C" { [[eosio::wasm_entry]] void apply(uint64_t receiver, uint64_t code, uint64_t action) { auto _self = eosio::name(receiver); if (code == _self.value) { // // Self dispatched actions (callable contract methods) // switch (action) { EOSIO_DISPATCH_HELPER(atmosstakev2, (destroy)(create)(sanity)(exitstake)(fexitstakes)(claim)(resetclaim)) } } else { // // If we receive a call from an external contract we care about // atmosstakev2::stats stats_table(_self, _self.value); for (auto it = stats_table.begin(); it != stats_table.end(); it++) { if (code == it->token_contract.value) { switch (action) { EOSIO_DISPATCH_HELPER(atmosstakev2, (transfer)) } break; } } } } }
17488ec68afcd311495e7c349e470070a8446fe8
a17d860d97ba51c384a591eb8e4d9c009822613b
/Project1/1312727/ScreenNote/ScreenNote/ScreenNote.cpp
2d8d6b61afbaace17b7ba6fd9c4647cd59c8c08d
[]
no_license
yadzhang/Winprogramming
54f0804b7fbfb8d2e6a369c6ca141caf869994fe
ef535f8e70b93af42207b5edef712805adcb583d
refs/heads/master
2021-01-22T16:56:44.302635
2016-02-01T13:28:26
2016-02-01T13:28:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,044
cpp
ScreenNote.cpp
// ScreenNote.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "ScreenNote.h" #define MAX_LOADSTRING 100 // Global Variables: // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK DlgShape(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); void setHook(); void showAllWindow(UINT type); void unHook(); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_SCREENNOTE, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SCREENNOTE)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SCREENNOTE)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_SCREENNOTE); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } //ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: { HWND temp = CreateDialog(hInst, MAKEINTRESOURCE(IDD_CHOOSESHAPE), hWnd, About); RECT t; GetClientRect(temp, &t); SetWindowLong(temp, GWL_STYLE, 0); ShowWindow(temp, SW_SHOW); //DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; } case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_CREATE: { // Pointer not needed. /// //ShowWindow(hWnd, SW_HIDE); mainWindow = hWnd; myDrawWindow::MyRegisterClass(hInst); myTextWindow::MyRegisterClass(hInst); TCHAR s[1111]; // wsprintf(s, L"\n\tĐây là cửa sổ note graphics.\n\tCho phép vẽ note đồ họa (dùng mouse)."); drawWindowHandle = CreateWindow(L"DRAW_WINDOW", L"", WS_OVERLAPPED, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL); // wsprintf(s, L"\n\tĐây là cửa sổ note dạng text.\n\tCho phép gõ các note văn bản."); textWindowHandle = CreateWindow(L"TEXT_WINDOW", L"", WS_OVERLAPPED, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL); SetWindowLong(drawWindowHandle, GWL_STYLE, 0); SetWindowLong(textWindowHandle, GWL_STYLE, 0); shapeDlgHandle = CreateDialog(hInst, MAKEINTRESOURCE(IDD_CHOOSESHAPE), hWnd, DlgShape); setHook(); showAllWindow(SWP_SHOWWINDOW); break; } case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: unHook(); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } INT_PTR CALLBACK DlgShape(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: { switch (LOWORD(wParam)) { case IDC_RECTANGLE: { int *cshape = (int*)GetWindowLong(drawWindowHandle, 8); *cshape = 0; break; } case IDC_ELLIPSE: { int *cshape = (int*)GetWindowLong(drawWindowHandle, 8); *cshape = 1; break; } case IDC_LINE: { int *cshape = (int*)GetWindowLong(drawWindowHandle, 8); *cshape = 2; break; } case IDC_PIXEL: { int *cshape = (int*)GetWindowLong(drawWindowHandle, 8); *cshape = 3; break; } } break; } } return (INT_PTR)FALSE; } void setHook() { HINSTANCE hlib = LoadLibrary(L"DLL_SHOW"); typedef void(*setHook)(HWND mainWin, HWND textWin, HWND drawWin, HWND dlgshape); if (hlib != NULL) { setHook func; func = (setHook) GetProcAddress(hlib, "setHook"); func(mainWindow, textWindowHandle, drawWindowHandle, shapeDlgHandle); } } void unHook() { HINSTANCE hlib = LoadLibrary(L"DLL_SHOW"); typedef void(*unHook)(); if (hlib != NULL) { unHook func; func = (unHook)GetProcAddress(hlib, "unHook"); func(); } } void showAllWindow(UINT type) { HINSTANCE hlib = LoadLibrary(L"DLL_SHOW"); typedef void (*showAllWindow)(UINT type); if (hlib != NULL) { showAllWindow func; func = (showAllWindow)GetProcAddress(hlib, "showAllWindow"); func(type); } }
4cc629ee8adc41e7f54c4fba4485bee349628da7
b81424733ba7aa22971017a2b723cebdb79e2ff9
/B13547/B13547.cpp
0366ff1f0919d0e84694a6993814e275756f1ecb
[]
no_license
tongnamuu/Algorithm-PS
1d8ee70c60da9bafdae7c820872e685fdf2b28fa
464b68c34bb07f9e1e00e4b5475c6f0240cd20d4
refs/heads/master
2022-06-04T01:57:29.432141
2022-04-08T11:52:01
2022-04-08T11:52:01
164,219,701
0
1
null
2019-03-28T03:43:13
2019-01-05T13:58:05
C++
UTF-8
C++
false
false
1,796
cpp
B13547.cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; #define N 1000001 struct Node { int val = 0; Node *l, *r; }; Node nodePool[5 * N]; int nodeCnt; Node* newNode() { return &nodePool[nodeCnt++]; } void init(Node* cur, int s, int e) { if (s == e) return; cur->l = newNode(); cur->r = newNode(); int m = s + e >> 1; init(cur->l, s, m); init(cur->r, m+1,e); } void update(Node* prev, Node* cur, int s, int e, int idx, int val) { if (s == e) { cur->val = prev->val + val; return; } int m = s + e >> 1; if (idx <= m) { cur->l = newNode(); cur->r = prev->r; update(prev->l, cur->l, s, m, idx, val); } else { cur->r = newNode(); cur->l = prev->l; update(prev->r, cur->r, m + 1, e, idx, val); } cur->val = cur->l->val + cur->r->val; } int query(Node* prev, Node* cur, int s, int e, int i, int j) { if (e<i || s>j) return 0; if (i <= s && e <= j) return cur->val - prev->val; int m = s + e >> 1; return query(prev->l, cur->l, s, m, i, j) + query(prev->r, cur->r, m + 1, e, i, j); } vector<Node*>roots; bool used[N] ; int pos[N]; int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); Node* dummy = newNode(); dummy->l = dummy->r = dummy; roots.push_back(dummy); int n; cin >> n; for (int i = 1; i <= n; ++i) { int x; cin >> x; if (!used[x]) { used[x] = true; pos[x] = i; Node* root = newNode(); update(roots.back(), root, 1, N - 1, i, 1); roots.push_back(root); } else { Node* temp = newNode(); update(roots.back(), temp, 1, N - 1, pos[x], -1); pos[x] = i; Node* root = newNode(); update(temp, root, 1, N - 1, i, 1); roots.push_back(root); } } int Q; cin >> Q; while (Q--) { int s, e; cin >> s >> e; cout << query(roots[s - 1], roots[e], 1, N - 1, s, e) << '\n'; } }
be31fc642bd54d8ad0c01182efb34c673ca3a2b4
387549ab27d89668e656771a19c09637612d57ed
/DRGLib UE project/Source/FSD/Private/EnemyPawn.cpp
3b8d8f8d37c2ddea84526d41de56a1b7c2a18bba
[ "MIT" ]
permissive
SamsDRGMods/DRGLib
3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a
76f17bc76dd376f0d0aa09400ac8cb4daad34ade
refs/heads/main
2023-07-03T10:37:47.196444
2023-04-07T23:18:54
2023-04-07T23:18:54
383,509,787
16
5
MIT
2023-04-07T23:18:55
2021-07-06T15:08:14
C++
UTF-8
C++
false
false
807
cpp
EnemyPawn.cpp
#include "EnemyPawn.h" #include "EnemyComponent.h" #include "EnemyHealthComponent.h" #include "EnemyPawnAfflictionComponent.h" #include "Net/UnrealNetwork.h" #include "PawnStatsComponent.h" void AEnemyPawn::OnRep_QueuedMontage() { } void AEnemyPawn::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AEnemyPawn, QueuedMontage); } AEnemyPawn::AEnemyPawn() { this->Health = CreateDefaultSubobject<UEnemyHealthComponent>(TEXT("Health")); this->Stats = CreateDefaultSubobject<UPawnStatsComponent>(TEXT("Stats")); this->Affliction = CreateDefaultSubobject<UEnemyPawnAfflictionComponent>(TEXT("Affliction")); this->enemy = CreateDefaultSubobject<UEnemyComponent>(TEXT("enemy")); }
701619d9636d2c3753ad40cdb52a1591311658c2
11d335b447ea5389f93165dd21e7514737259ced
/transport/Transcendence/TransData/main.cpp
e05f56864cf5a345b88b64523625a4fd346dddb0
[]
no_license
bennbollay/Transport
bcac9dbd1449561f2a7126b354efc29ba3857d20
5585baa68fc1f56310bcd79a09bbfdccfaa61ed7
refs/heads/master
2021-05-27T03:30:57.746841
2012-04-12T04:31:22
2012-04-12T04:31:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,871
cpp
main.cpp
// TransData // // TransData is used to report information out of a Transcendence // datafile #include <stdio.h> #include <windows.h> #include <ddraw.h> #include "Alchemy.h" #include "XMLUtil.h" #include "TransData.h" #define NOARGS CONSTLIT("noArgs") #define QUESTION_MARK_SWITCH CONSTLIT("?") #define HELP_SWITCH CONSTLIT("help") #define H_SWITCH CONSTLIT("h") #define NO_LOGO_SWITCH CONSTLIT("nologo") #define ARMOR_TABLE_SWITCH CONSTLIT("armortable") #define DECOMPILE_SWITCH CONSTLIT("decompile") #define ENCOUNTER_TABLE_SWITCH CONSTLIT("encountertable") #define ENTITIES_SWITCH CONSTLIT("entities") #define SHIP_TABLE_SWITCH CONSTLIT("shiptable") #define SHIP_IMAGES_SWITCH CONSTLIT("shipimages") #define STATS_SWITCH CONSTLIT("stats") #define RANDOM_ITEMS_SWITCH CONSTLIT("randomitems") #define RANDOM_NUMBER_TEST CONSTLIT("randomnumbertest") #define SHIELD_TEST_SWITCH CONSTLIT("shieldtest") #define SIM_TABLES_SWITCH CONSTLIT("simTables") #define STATION_FREQUENCY_SWITCH CONSTLIT("stationfrequency") #define SYSTEM_LABELS_SWITCH CONSTLIT("systemlabels") #define SYSTEM_TEST_SWITCH CONSTLIT("systemtest") #define TOPOLOGY_SWITCH CONSTLIT("topology") #define ITEM_FREQUENCY_SWITCH CONSTLIT("itemsim") #define ITEM_TABLE_SWITCH CONSTLIT("itemtable") #define WORD_LIST_SWITCH CONSTLIT("wordlist") void AlchemyMain (CXMLElement *pCmdLine); int main (int argc, char *argv[ ], char *envp[ ]) // main // // main entry-point { if (!kernelInit()) { printf("ERROR: Unable to initialize Alchemy kernel.\n"); return 1; } // Do it { ALERROR error; CXMLElement *pCmdLine; if (error = CreateXMLElementFromCommandLine(argc, argv, &pCmdLine)) { printf("ERROR: Unable to parse command line.\n"); return 1; } AlchemyMain(pCmdLine); delete pCmdLine; } // Done kernelCleanUp(); return 0; } void AlchemyMain (CXMLElement *pCmdLine) // AlchemyMain // // Main entry-point after kernel initialization { ALERROR error; bool bLogo = !pCmdLine->GetAttributeBool(NO_LOGO_SWITCH); if (bLogo) { printf("TransData v1.6\n"); printf("Copyright (c) 2001-2008 by George Moromisato. All Rights Reserved.\n\n"); } if (pCmdLine->GetAttributeBool(NOARGS) || pCmdLine->GetAttributeBool(QUESTION_MARK_SWITCH) || pCmdLine->GetAttributeBool(HELP_SWITCH) || pCmdLine->GetAttributeBool(H_SWITCH)) { ShowHelp(pCmdLine); return; } // Figure out the data file that we're working on CString sDataFile = CONSTLIT("Transcendence"); // See if we are doing a command that does not require parsing if (pCmdLine->GetAttributeBool(WORD_LIST_SWITCH)) { GenerateWordList(sDataFile, pCmdLine); return; } else if (pCmdLine->GetAttributeBool(ENTITIES_SWITCH)) { GenerateEntitiesTable(sDataFile, pCmdLine); return; } else if (pCmdLine->GetAttributeBool(DECOMPILE_SWITCH)) { Decompile(sDataFile, pCmdLine); return; } // See if we need to load images DWORD dwInitFlags = 0; if (pCmdLine->GetAttributeBool(SHIP_IMAGES_SWITCH)) ; else dwInitFlags |= flagNoResources; // We don't need a version check dwInitFlags |= flagNoVersionCheck; // Open the universe if (bLogo) printf("Loading..."); CUniverse Universe; CString sError; if (error = Universe.Init(sDataFile, &sError, dwInitFlags)) { printf("\n%s\n", sError.GetASCIIZPointer()); return; } if (error = Universe.InitAdventure(DEFAULT_ADVENTURE_UNID, &sError)) { printf("\n%s\n", sError.GetASCIIZPointer()); return; } if (bLogo) printf("done.\n"); // Mark everything as known MarkItemsKnown(Universe); // Figure out what to do if (pCmdLine->GetAttributeBool(ARMOR_TABLE_SWITCH)) GenerateArmorTable(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(ENCOUNTER_TABLE_SWITCH)) GenerateEncounterTable(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(SHIP_TABLE_SWITCH)) GenerateShipTable(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(SHIP_IMAGES_SWITCH)) GenerateShipImages(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(RANDOM_ITEMS_SWITCH)) GenerateRandomItemTables(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(STATS_SWITCH)) GenerateStats(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(STATION_FREQUENCY_SWITCH)) GenerateStationFrequencyTable(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(SYSTEM_LABELS_SWITCH)) GenerateSystemLabelCount(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(SYSTEM_TEST_SWITCH)) GenerateSystemTest(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(SHIELD_TEST_SWITCH)) GenerateShieldStats(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(ITEM_TABLE_SWITCH)) GenerateItemTable(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(ITEM_FREQUENCY_SWITCH)) GenerateItemFrequencyTable(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(SIM_TABLES_SWITCH)) GenerateSimTables(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(TOPOLOGY_SWITCH)) GenerateTopology(Universe, pCmdLine); else if (pCmdLine->GetAttributeBool(RANDOM_NUMBER_TEST)) { int i; int Results[100]; for (i = 0; i < 100; i++) Results[i] = 0; for (i = 0; i < 1000000; i++) Results[mathRandom(1, 100)-1]++; for (i = 0; i < 100; i++) printf("%d: %d\n", i, Results[i]); } else GenerateStats(Universe, pCmdLine); // Done } void MarkItemsKnown (CUniverse &Universe) { int i; for (i = 0; i < Universe.GetItemTypeCount(); i++) { CItemType *pItem = Universe.GetItemType(i); pItem->SetKnown(); pItem->SetShowReference(); } }
8bb4175350d9995cc382ce35f14b74a21202543a
c088f377ca789474f2f66caab3bbdfd592bba5a5
/pipelinelib/incl/ConstNode.hpp
e2fdd170e626338dd047b403fc2670da36f0ea90
[]
no_license
mfep/pipeline
c4312d6167dae7ee31ebc9b616d098f83b7cee84
c4544eeb7639a828fe4b9e878a7b0dd4e7527717
refs/heads/master
2020-03-26T19:54:17.852175
2018-08-19T10:19:46
2018-08-19T10:19:46
145,292,463
0
0
null
null
null
null
UTF-8
C++
false
false
564
hpp
ConstNode.hpp
#pragma once #include "NodeStructure.hpp" namespace mfep { namespace Pipeline { template<typename T> class ConstNode : public Node<tuple<>, tuple<T>> { public: ConstNode() : m_data() { } explicit ConstNode(T&& data) : m_data(data) { } tuple<unique_ptr<T>> process(const tuple<>& inData) const override { return tuple<unique_ptr<T>>{ std::make_unique<T>(m_data) }; } const T& getData() const { return m_data; } void setData(const T& data) { m_data = data; } private: T m_data; }; } }
c4151925b5375ceb14abbd29ef0dc5da2712cb6e
1ed1ed934e4175bb20024311a007d60ae784b046
/COMMAND/COMMAND.cpp
4f49c94c28ef7954bab30ea0cf1de5e651d65835
[]
no_license
kkkcoder/Code_in_thptchuyen.ntucoder.net
f568cddc01b641c9a6a3c033a4b48ca59bb6435e
c4c0e19ea56a6560014cbb6e4d7489fb16e8aad7
refs/heads/master
2023-07-16T16:15:39.421817
2021-08-29T15:56:35
2021-08-29T15:56:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,502
cpp
COMMAND.cpp
// Cho mảng a chứa n số nguyên. // Ban đầu tất cả các phần tử trong mảng đều bằng 0. // Ta viết m câu lệnh vào 1 mảnh giấy. Các câu lệnh được đánh số từ 1 đến m. // Những lệnh này có thể là một trong hai loại sau: //  l r (1 ≤ l ≤ r ≤ n) - tăng tất cả các phần tử của mảng có chỉ số thuộc đoạn [l, r] // lên 1 đơn vị //  l r (1 ≤ l ≤ r ≤ m) - thực hiện tất cả các câu lệnh có chỉ số thuộc đoạn [l, r]. // Dữ liệu đảm bảo rằng r nhỏ hơn chỉ số của câu lệnh hiện tại // Yêu cầu: tìm giá trị của mảng a sau khi thực hiện tất cả các câu lệnh // Input: //  Dòng đầu tiên của mỗi test chứa số nguyên n và m. //  m dòng tiếp theo chứa các câu lệnh theo mẫu, miêu tả bằng t, l, r, với t là // loại câu lệnh (1 hoặc 2) // Output: //  Với mỗi test in ra các phần tử của mảng a sau khi thực hiện tất cả các câu // lệnh trên một dòng. Các số cách nhau bởi dấu cách. //  Do giá trị có thể rất lớn nên chỉ cần in ra phần dư của nó cho 109 + 7 // Ràng buộc: 1 ≤ n, m ≤ 105 // Subtask: //  Subtask 1 (20%): 1 ≤ n, m ≤ 10 //  Subtask 2 (30%): 1 ≤ n, m ≤ 1000 //  Subtask 3 (50%): Ràng buộc gốc #include <bits/stdc++.h> #define ll long long #define fo(i, a, b) for (int i = a; i <= b; ++i) #define ii pair<ll, ll> #define fi first #define se second #define nmax 100005 #define oo 1e18 using namespace std; const int mod = 1e9 + 7; struct com { ll t, l, r; }; ll n, m, ans[nmax], st[4 * nmax], laz[4 * nmax]; com a[nmax]; void down(int id, int l, int r) { int mid = l + r >> 1; st[2 * id] = (st[2 * id] + laz[id] * (mid - l + 1)) % mod; st[2 * id + 1] = (st[2 * id + 1] + laz[id] * (r - mid)) % mod; laz[2 * id] = (laz[2 * id] + laz[id]) % mod; laz[2 * id + 1] = (laz[2 * id + 1] + laz[id]) % mod; laz[id] = 0; } void update(int id, int l, int r, int u, int v, ll val) { if (r < u || v < l) return; if (u <= l && r <= v) { st[id] = (st[id] + (r - l + 1) * val) % mod; laz[id] = (laz[id] + val) % mod; return; } int mid = l + r >> 1; down(id, l, r); update(2 * id, l, mid, u, v, val); update(2 * id + 1, mid + 1, r, u, v, val); st[id] = (st[2 * id] + st[2 * id + 1]) % mod; } ll get(int id, int l, int r, int u, int v) { if (r < u || v < l) return 0; if (u <= l && r <= v) return st[id]; int mid = l + r >> 1; down(id, l, r); return (get(2 * id, l, mid, u, v) + get(2 * id + 1, mid + 1, r, u, v)) % mod; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; fo(i, 1, m) cin >> a[i].t >> a[i].l >> a[i].r; update(1, 1, m, 1, m, 1); for (int i = m; i >= 1; i--) if (a[i].t == 2) { ll res = get(1, 1, m, i, i); update(1, 1, m, a[i].l, a[i].r, res); update(1, 1, m, i, i, -res); } fo(i, 1, m) if (a[i].t == 1) { ll res = get(1, 1, m, i, i); ans[a[i].l] = ((ans[a[i].l] + res) % mod + mod) % mod; ans[a[i].r + 1] = ((ans[a[i].r + 1] - res) % mod + mod) % mod; } fo(i, 1, n) ans[i] = ((ans[i] + ans[i - 1]) % mod + mod) % mod; fo(i, 1, n) cout << ans[i] << ' '; }
c19aee44393afe27de9aa34103d1f83a85763316
91d2db4211ad47f0a40e62f2a47194893ab79a3b
/5/ISpringWord/Storage.h
de43cd85233ecc6fbf4f222e6dd4cad6b29b4f9d
[]
no_license
iglar14/ood
1170b90eb5ddb62503d2b2917564aa534d10e0f1
5724e2b73993def5d62c3117da6739873e892e08
refs/heads/master
2021-01-25T14:32:32.597519
2019-01-19T21:44:24
2019-01-19T21:44:24
123,703,146
0
0
null
null
null
null
UTF-8
C++
false
false
342
h
Storage.h
#pragma once #include "IStorage.h" class CStorage : public IStorage { public: CStorage(); ~CStorage() override; std::unique_ptr<IWorkCopy> AddFile(const std::filesystem::path& path) override; private: std::filesystem::path GetNextFileName(const std::filesystem::path& ext); std::filesystem::path m_tempDir; size_t m_counter = 0; };
550746f0bddad499812820a5b4e12d348a46ba25
696678289f66ea0f4aed0d03d809ebe86e686411
/ComputerGraphicsProject/model/car.cpp
cf79a1ce7642f704e2f14f915262c2191d8cd725
[]
no_license
adinowi/ComputerGraphicsProject
6c0fad0417a7d1b24d9588e54b8d4be4f2cd0e46
c3643a1267cc117bfd6a57e6065483ea889f93e4
refs/heads/master
2020-12-05T11:08:09.970045
2020-01-07T22:09:17
2020-01-07T22:09:17
232,090,846
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
car.cpp
#include <stdlib.h> #include <stdio.h> // Include GLEW #include <GL\glew.h> #include <GL\GLU.h> // Include GLFW #include <GLFW\glfw3.h> // Include GLM #include <glm\glm.hpp> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\constants.hpp> #include "..\renderer\model.h" #include "car.hpp" using namespace model; Car::Car() { mPosition = glm::vec3(0, 0, 0); mRotation = 0.0f; } Car::Car(glm::vec3 tPosition, float tRotation) { mPosition = tPosition; mRotation = tRotation; }; Car::Car(glm::vec3 tPosition) { mPosition = tPosition; mRotation = 0.0f; };
18e66c18c3474b23acea5bc50c2a6cf080922236
61c1f2ee1fe9985c02863d7d99798ba94385da47
/src/RLDOCK_CASE.cpp
89b7df6d363d7f8e8654de163d07ababa5db7842
[]
no_license
EtienneReboul/RLDOCK
335687b6c365f1e5b5713e6f94c2d058a74d444e
fb55141bd5c99f0bdd4e70259ac3df6904a0f823
refs/heads/master
2023-06-06T22:52:05.285045
2021-07-08T19:49:55
2021-07-08T19:49:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,319
cpp
RLDOCK_CASE.cpp
#include "RLDOCK_CASE.h" void CASE::Move_to_Center_Easy() { this->center = this->noH; xcen=0,ycen=0,zcen=0; for(auto&a:this->noH){xcen+=a.x;ycen+=a.y;zcen+=a.z;} xcen/=1.0*this->noH.size(); ycen/=1.0*this->noH.size(); zcen/=1.0*this->noH.size(); for(auto&a:this->center){a.x-=xcen;a.y-=ycen;a.z-=zcen;} } void CASE::Find_Max_and_Min() { xmax=-1000000.0; for(auto&a:this->noH){if(xmax<a.x)xmax=a.x;} ymax=-1000000.0; for(auto&a:this->noH){if(ymax<a.y)ymax=a.y;} zmax=-1000000.0; for(auto&a:this->noH){if(zmax<a.z)zmax=a.z;} xmin=1000000.0; for(auto&a:this->noH){if(xmin>a.x)xmin=a.x;} ymin=1000000.0; for(auto&a:this->noH){if(ymin>a.y)ymin=a.y;} zmin=1000000.0; for(auto&a:this->noH){if(zmin>a.z)zmin=a.z;} } void CASE::cal_distance() { this->distance.resize(this->noH.size(),vector<double>(this->noH.size(),0.0)); this->distance_square.resize(this->noH.size(),vector<double>(this->noH.size(),0.0)); for(int ilig=0;ilig!=this->noH.size();ilig++) { for(int jlig=0;jlig!=this->noH.size();jlig++) { if(ilig!=jlig) { this->distance[ilig][jlig]=this->noH[ilig].dis(this->noH[jlig]); this->distance_square[ilig][jlig] = this->distance[ilig][jlig]*this->distance[ilig][jlig]; } } } } void CASE::get_rb0_and_cal_pol(const PARAMETER& P) { for(int ir = 0; ir !=this->noH.size(); ir++) { double intb=0., radi = this->noH[ir].rrr; for(int jr = 0; jr !=this->noH.size(); jr++) { if(jr!=ir) { double dis=(this->noH[ir].x - this->noH[jr].x)*(this->noH[ir].x - this->noH[jr].x); dis += (this->noH[ir].y - this->noH[jr].y)*(this->noH[ir].y - this->noH[jr].y); dis += (this->noH[ir].z - this->noH[jr].z)*(this->noH[ir].z - this->noH[jr].z); dis = sqrt(dis); double radj = noH[jr].rrr; double radj_sb = noH[jr].sb*noH[jr].rrr; double radc = dis+radj_sb; double Lij,Uij; if(radi>=radc){Lij=0;Lij=0;} else{ if(radi>(dis-radj_sb)){Lij=radi;} else{Lij=dis-radj_sb;} Uij=dis+radj_sb; } intb += 0.5*((1./Lij-1./Uij)+(radj_sb*radj_sb/(4.*dis)-dis/4.)*(1./(Lij*Lij)-1./(Uij*Uij))+(1./(2.*dis))*log(Lij/Uij)); } } this->noH[ir].rb0 = 1./(1./radi-intb); } this->pol=0; for(int il = 0; il != this->noH.size(); il++) { for(int jl = 0; jl != il; jl++) { double rr_square = this->noH[il].rb0*this->noH[jl].rb0; this->pol+=P.pol_par * this->noH[il].q * this->noH[jl].q/sqrt(this->distance_square[il][jl]+rr_square*exp(-this->distance_square[il][jl]/4./rr_square)); } } } void CASE::cal_internal_lj(const FORCEFIELD& F, const PARAMETER& P) { this->internal_lj=0; for(int ilig =0; ilig!=this->noH.size();ilig++) for(int jlig =0; jlig!=ilig;jlig++) { vector<int>::iterator it = find(this->noH[ilig].bonded_atom.begin(),this->noH[ilig].bonded_atom.end(),jlig); if(it==this->noH[ilig].bonded_atom.end() && ilig!=jlig) { int dis_idx = distance[ilig][jlig]/F.eql_lj[this->noH[ilig].type_idx][this->noH[jlig].type_idx]*P.LJstep; if(dis_idx<P.LJstep)this->internal_lj += F.LJ_potential[this->noH[ilig].type_idx][this->noH[jlig].type_idx][dis_idx]; } } } void CASE::set_rw_position(const PARAMETER & P) { this->radius_rw.resize(this->noH.size()); for(int ir=0;ir!=this->noH.size();ir++) { double rrr_rw=this->noH[ir].rrr+P.r_water; double dsita=P.step_SASA/rrr_rw; int jmax=P.pi/dsita; this->radius_rw[ir].resize(jmax); for(int j=1;j<=jmax;j++) { double sita=j*dsita; double dphi=dsita*sin(sita); int kmax=2.*P.pi/dphi+1; this->radius_rw[ir][j-1].resize(kmax); for(int k=1;k<=kmax;k++) { double phi=k*dphi; this->radius_rw[ir][j-1][k-1].x=rrr_rw*sin(sita)*cos(phi)+this->noH[ir].x; this->radius_rw[ir][j-1][k-1].y=rrr_rw*sin(sita)*sin(phi)+this->noH[ir].y; this->radius_rw[ir][j-1][k-1].z=rrr_rw*cos(sita)+this->noH[ir].z; } } } } void COMPLEX::Mol2_Info_Get(string lig_file_name) { for(int i=1;i!=this->conformers.size();i++) { if(this->conformers[i].noH.size()!=this->conformers[0].noH.size()) { cout<<"The number of heavy atoms of the "<<i+1<<"th conformer is different from that of first conformer."<<endl; cout<<"The "<<i+1<<"th conformer has "<<this->conformers[i].noH.size()<<" heavy atoms."<<endl; cout<<"The first conformer has "<<this->conformers[0].noH.size()<<" heavy atoms."<<endl; exit(3); } } this->lig_atom_num = this->conformers[0].noH.size(); this->rec_atom_num = this->rec[0].noH.size(); this->conformers_num = this->conformers.size(); ifstream infile(lig_file_name.c_str()); string sline; while (getline(infile,sline)) { if(sline.find("@<TRIPOS>MOLECULE")!=std::string::npos) { if(this->lig_mol2.atom_num != 0)break; CASE tmp_mol; int num_atom,num_bond,num_sub,num_feat,num_sets; infile>>this->lig_mol2.mol_name; infile>>num_atom; infile>>num_bond; infile>>num_sub; infile>>num_feat; infile>>num_sets; getline(infile,sline); getline(infile,sline); getline(infile,sline); this->lig_mol2.charge_type=sline; std::map<int,int> idx_update; while(getline(infile,sline)) { if(sline.find("@<TRIPOS>ATOM")!=std::string::npos) { for (int ia=0,iheavy=1;ia!=num_atom;ia++) { getline(infile,sline); ATOM a; a.mol2_input(sline); if(a.element != "H" && a.element != "h") { idx_update[ia+1]=iheavy; iheavy++; this->lig_mol2.atoms.push_back(a); } else { idx_update[ia+1]=0; } } this->lig_mol2.atom_num = this->lig_mol2.atoms.size(); } if(sline.find("@<TRIPOS>BOND")!=std::string::npos) { for(int ib=0,ib_real=1;ib!=num_bond;ib++) { getline(infile,sline); BOND b; b.mol2_input(sline); int new_left = idx_update[b.left_id]; int new_right = idx_update[b.right_id]; if(new_left!=0 && new_right != 0) { b.index=ib_real; b.update(ib_real,new_left,new_right); this->lig_mol2.bonds.push_back(b); ib_real++; } } this->lig_mol2.bond_num = this->lig_mol2.bonds.size(); break; // if(sline.find("@<TRIPOS>SUBSTRUCTURE")!=std::string::npos) // { // for(int is=0;is!=num_sub;is++) // { // getline(infile,sline); // SUBSTRUCTURE s; // s.mol2_input(sline); // s.root_atom = idx_update[s.root_atom]; // this->lig_mol2.subs.push_back(s); // } // this->lig_mol2.sub_num = this->lig_mol2.subs.size(); // break; // } } } } } infile.close(); } void COMPLEX::Initialization(const PARAMETER& P, const FORCEFIELD& F) { for(auto&arec:this->rec) { arec.Find_Max_and_Min(); arec.cal_distance(); arec.get_rb0_and_cal_pol(P); arec.set_rw_position(P); } for(auto&alig:this->conformers) { alig.cal_distance(); alig.get_rb0_and_cal_pol(P); alig.Move_to_Center_Easy(); alig.cal_internal_lj(F,P); alig.usepose.resize(this->lig_atom_num); } } void READFILE(const PARAMETER P, vector<CASE>& in_mol, string filename) { ifstream infile(filename.c_str()); string sline; int ii=0; while (getline(infile,sline)) { if(sline.find("@<TRIPOS>MOLECULE")!=std::string::npos) { CASE tmp_mol; int num_atom,num_bond; getline(infile,sline); infile>>sline;num_atom=stoi(sline); infile>>sline;num_bond=stoi(sline); while(getline(infile,sline)) { if(sline.find("@<TRIPOS>ATOM")!=std::string::npos) { int index_noH=0, index_HH=0; for (int ia=0;ia!=num_atom;ia++) { getline(infile,sline); std::istringstream ss(sline); std::string buf; std::vector<std::string> token; while(ss >> buf) token.push_back(buf); ATOM a; a.index_original = stoi(token[0]); a.name = token[1]; a.x = stod(token[2]); a.y = stod(token[3]); a.z = stod(token[4]); a.type = token[5]; a.resi_index = stoi(token[6]); a.resi_name = token[7]; a.q = stod(token[8]); if(a.type.find(".")!=std::string::npos) { string::size_type position; position = a.type.find("."); a.element = a.type.substr(0,position); } else { a.element = a.type; } if(a.element == "H" || a.element == "h") { a.rrr = P.radius_H; a.sb = P.born_scale_H; a.type_idx = 0; } else if(a.element == "C" || a.element == "c") { a.rrr = P.radius_C; a.sb = P.born_scale_C; a.type_idx = 1; } else if(a.element == "N" || a.element == "n") { a.rrr = P.radius_N; a.sb = P.born_scale_N; a.type_idx = 2; } else if(a.element == "O" || a.element == "o") { a.rrr = P.radius_O; a.sb = P.born_scale_O; a.type_idx = 3; } else if(a.element == "P" || a.element == "p") { a.rrr = P.radius_P; a.sb = P.born_scale_P; a.type_idx = 4; } else if(a.element == "S" || a.element == "s") { a.rrr = P.radius_S; a.sb = P.born_scale_S; a.type_idx = 5; } else { a.rrr = P.radius_C; a.sb = P.born_scale_C; a.type_idx = 6; } if(a.element != "H" && a.element != "h") { a.index = index_noH; index_noH++; tmp_mol.noH.push_back(a); tmp_mol.wH.push_back(a); } else { a.index = index_HH; index_HH++; tmp_mol.HH.push_back(a); tmp_mol.wH.push_back(a); } } } if(sline.find("@<TRIPOS>BOND")!=std::string::npos) { for(int ib=0;ib!=num_bond;ib++) { getline(infile,sline); std::istringstream ss(sline); std::string buf; std::vector<std::string> token; while(ss >> buf) token.push_back(buf); int left_idx = stoi(token[1])-1; int left_actual_index = tmp_mol.wH[left_idx].index; int right_idx = stoi(token[2])-1;int right_actual_index = tmp_mol.wH[right_idx].index; tmp_mol.wH[left_idx].bonded_atom.push_back(right_idx); tmp_mol.wH[right_idx].bonded_atom.push_back(left_idx); if( !tmp_mol.wH[left_idx].if_H() && !tmp_mol.wH[right_idx].if_H()) //both not hydrogen { tmp_mol.noH[left_actual_index].bonded_atom.push_back(right_actual_index); tmp_mol.noH[right_actual_index].bonded_atom.push_back(left_actual_index); } else if(tmp_mol.wH[left_idx].if_H() && !tmp_mol.wH[right_idx].if_H()) //left hydrogen, right not H { tmp_mol.noH[right_actual_index].carryH = true; tmp_mol.noH[right_actual_index].q += tmp_mol.wH[left_idx].q; } else if(!tmp_mol.wH[left_idx].if_H() && tmp_mol.wH[right_idx].if_H()) //left not hydrogen,right hydrogen { tmp_mol.noH[left_actual_index].carryH = true; tmp_mol.noH[left_actual_index].q += tmp_mol.wH[right_idx].q; } } in_mol.push_back(tmp_mol); break; } } } } infile.close(); }
c3b91fa07b262733e8edc051636e9a6adc42d6cb
cb114e954a0c8d5e29285a9f89d45b428c73ebfb
/ObjLoader.h
f5f683b2e5eb384a10b2b4690c0e41739750d003
[]
no_license
AlexAngelosky/Diplomna
930962b6733d934705c713a2f3b5a8ac2134f3ab
8bce29b2feb1e4e8a7f581c506c68d5da52d162b
refs/heads/master
2021-01-23T13:22:22.611797
2015-06-03T05:31:43
2015-06-03T05:31:43
36,781,684
0
0
null
null
null
null
UTF-8
C++
false
false
3,322
h
ObjLoader.h
#ifndef OBJ_LOADER #define OBJ_LOADER #include<vector> #include<string> #include <d3d9.h> #include <d3dx9.h> using namespace std; //struktura koqto loadera she polzva za zapazvane na vertexite struct v{ double x,y,z,w; v() { w = 1; } }; //struktura koqto loadera she polzva za zapazvane na texture vectorite struct vt{ double u,v,w; vt() { w = 0; } }; //struktura koqto loadera she polzva za zapazvane na vruzkite mejdu vertexite, texturite i normalnite vectori //face-a ne pazi samiq vertex ili normalen vector a pazi poredniq mu nomer vuv faila (nqkakuv index) struct face{ int* vertices;//ukazatel kum masiv ot vertexi za daden face(vruzkata mejdu trite neshta) int number_of_vertices;//kolko sa vertexite int* textures;//ukazatel kum masiv ot texturi za daden face int number_of_textures;//kolko sa texturite int* normals;//ukazatel kum masiv ot normalni vektori za daden face int number_of_normals;//kolko sa normalnite vektori face()//konstruktor { number_of_vertices = 3;//poneje napravih nabliudenieto che nay chesto edin face se definira ot tri vertexa tova e default stoinostta vertices = new int[number_of_vertices];//zadelqme pamet za masiva //sushtoto kato gore number_of_textures = 3; textures = new int[number_of_textures]; number_of_normals = 3; normals = new int[number_of_normals]; } ~face()//destruktor { delete[] vertices;//osvobojdavane pametta zadelena za zapazvane na vertexite delete[] textures; delete[] normals; } }; class ObjLoader{//class za loadvane na obekti ot .obj fail private: vector<v*> vv;//vector ot ukazateli kum vertexi vector<vt*> vvt;//vector ot ukazateli kum texture vectori vector<face*> faces;//vector ot ukazateli kum face-ove vector<D3DVECTOR*> normals;//vector ot normalni vectori void load_vv(char**, int);//loadva po daden dvumeren masiv na vseki red na koito ima po edin red ot textoviq fail vertexite void load_vvt(char**, int);//loadva po daden dvumeren masiv na vseki red na koito ima po edin red ot textoviq fail texture vectorite void load_faces(char**, int);//loadva po daden dvumeren masiv na vseki red na koito ima po edin red ot textoviq fail face-ovete void load_normals(char**, int);//loadva po daden dvumeren masiv na vseki red na koito ima po edin red ot textoviq fail normalnite vectori char* trim_whitespace(char*);//premahva whitespaceovete i tabulaciite v nachaloto i v kraq na daden simvolen niz int rows;//pazi broq na prochetenite ot .obj fail redove char** result;//pazi prochetenoto sudurjanie ot .obj faila public: ObjLoader();//konstruktor void read_file(char*, char**&, int& );//prochita faila i zapazva vsicko procheteno v dvumeren masiv vseki red na koito e red ot faila void split(char*, char**&, int&, char);//razdelq daden simvolen niz na mnojestvo ot simvolni nizove po daden simvol void load_model(char*);//loadva model ot fail vector<v*> get_vv();//vrushta vectora ot vertexi vector<vt*> get_vvt();//vrushta vectora ot texture vectori vector<face*> get_faces();//vrushta vectora ot faceove vector<D3DVECTOR*> get_normals();//vrushta vectora ot normalni vectori }; #endif // OBJ_LOADER
b4a4dc1328481574dff5e2202708a159c6e4a91a
00e9b8471bd2e81ceb667fc82e49240babbb113e
/Class8/main/src/logindialog.h
6a1c6c5bfb7f589365e943fc54ffac66b3e7ae97
[]
no_license
Xershoo/BM-Client
4a6df1e4465d806bca6718391fc2f5c46ab1d2b4
2d1b8d26d63bb54b1ac296341353a6e07809b2d6
refs/heads/master
2020-03-29T05:01:00.564762
2019-03-06T01:46:35
2019-03-06T01:46:35
149,561,359
5
1
null
null
null
null
UTF-8
C++
false
false
1,475
h
logindialog.h
#ifndef LOGINDIALOG_H #define LOGINDIALOG_H #include "src/control/c8commonwindow.h" #include "ui_logindialog.h" #include <QListWidget> #include "BizCallBack.h" #include "login/Login.h" class AccountItem; class LoginDialog : public C8CommonWindow { Q_OBJECT public: LoginDialog(QWidget *parent = 0); ~LoginDialog(); void loginByTokenUid(QString acc, QString token, __int64 uid); signals: void showcoursepage(__int64 nUserID); protected: virtual void setTitleBarRect() override; void showHistoryAccount(); bool eventFilter(QObject *, QEvent *); protected slots: void showMinimized(); void close(); void doForgetPwd(QString); void linkHovered(QString); void checkAuto(); void checkKeeppwd(); void doLogin(); void doSelectUser(QString strUser); void doChangeUser(const QString &strUser); void doChangePwd(const QString &strPwd); void removeAccountItem(AccountItem* item); void accountListItemChanged(AccountItem* item, int row); void DoLoginOK(LoginInfo info); void DoLoginError(int nErrorCode); void DoLogOut(__int64 nUserId); void DoLogKickOut(__int64 nUserId); void onConnectServerError(ServerErrorInfo errInfo); private: void addItemToAccountListWidget(); void setControlState(bool bISEnble); protected: //xiewb 2018.11.26 void doDeviceDetect(); private: Ui::LoginDialog ui; QListWidget *m_accountListWidget; CLogin m_login; }; #endif // LOGINDIALOG_H
baa2536d4afb9744e3465fe7238f7f9f26e45615
c9042c65d6c7a632cfd903a56e52a42903464467
/utils/Mutex.h
84cba8a5e669e2c1e2cf46f86cd16136e41b5f32
[]
no_license
cnsuhao/myown
4048a2a878b744636a88a2090739e39698904964
50dab74b9ab32cba8b0eb6cf23cf9f95a5d7f3e4
refs/heads/master
2021-09-10T23:48:25.187878
2018-04-04T09:33:30
2018-04-04T09:33:30
140,817,274
2
2
null
null
null
null
GB18030
C++
false
false
2,707
h
Mutex.h
//-------------------------------------------------------------------- // 文件名: Mutex.h // 内 容: // 说 明: // 创建日期: 2006年8月23日 // 创建人: 陆利民 // 版权所有: 苏州蜗牛电子有限公司 //-------------------------------------------------------------------- #ifndef _UTILS_MUTEX_H #define _UTILS_MUTEX_H #include "../public/Macros.h" #ifdef FX_SYSTEM_WINDOWS #include "../system/WinMutex.h" #endif // FX_SYSTEM_WINDOWS #ifdef FX_SYSTEM_LINUX #include "../system/LinuxMutex.h" #endif // FX_SYSTEM_LINUX /* #include <windows.h> #include <string.h> // 进程互斥锁 class CWinMutex { public: static bool Exists(const char* name) { HANDLE mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, name); if (NULL == mutex) { return false; } CloseHandle(mutex); return true; } public: CWinMutex() { m_pName = NULL; m_hMutex = NULL; } ~CWinMutex() { Destroy(); } // 获得名字 const char* GetName() const { if (NULL == m_pName) { return ""; } return m_pName; } // 是否有效 bool IsValid() const { return (m_hMutex != NULL); } // 创建或获得锁 bool Create(const char* name, bool* exists = NULL) { Assert(name != NULL); size_t name_size = strlen(name) + 1; char* pName = NEW char[name_size]; memcpy(pName, name, name_size); if (m_pName) { delete[] m_pName; } m_pName = pName; if (exists) { *exists = false; } m_hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, name); if (NULL == m_hMutex) { m_hMutex = CreateMutex(NULL, FALSE, name); if (NULL == m_hMutex) { return false; } if (exists) { if (GetLastError() == ERROR_ALREADY_EXISTS) { *exists = true; } } } else { if (exists) { *exists = true; } } return true; } // 删除锁 bool Destroy() { if (!CloseHandle(m_hMutex)) { return false; } m_hMutex = NULL; if (m_pName) { delete[] m_pName; m_pName = NULL; } return true; } // 加锁 void Lock() { Assert(m_hMutex != NULL); WaitForSingleObject(m_hMutex, INFINITE); } // 解锁 void Unlock() { Assert(m_hMutex != NULL); ReleaseMutex(m_hMutex); } private: CWinMutex(const CWinMutex&); CWinMutex& operator=(const CWinMutex&); private: char* m_pName; HANDLE m_hMutex; }; */ // 自动加解锁 class CAutoMutex { public: explicit CAutoMutex(CMutex& mutex): m_Mutex(mutex) { Assert(mutex.IsValid()); m_Mutex.Lock(); } ~CAutoMutex() { m_Mutex.Unlock(); } private: CAutoMutex(); CAutoMutex(const CAutoMutex&); CAutoMutex& operator=(const CAutoMutex&); private: CMutex& m_Mutex; }; #endif // _UTILS_MUTEX_H
24680e142b04ae890b0b650b6a5ff51404abdf7b
fd3f8e4383292c15194a97cfa251a3de0882ac3c
/src/replica/duplication/test/duplication_test_base.h
fb0c7ea4f981f35a41dae85ebf3a3cece8f8087f
[ "Apache-2.0", "Zlib", "MIT", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
apache/incubator-pegasus
417ea26a150c3bfd6c7f6a0a2148de7770dd291b
be9119e75f27b9f0563acaf33f5c96edf0051307
refs/heads/master
2023-08-29T00:35:34.152285
2023-08-28T06:45:00
2023-08-28T06:45:00
41,712,332
663
97
Apache-2.0
2023-09-14T08:03:29
2015-09-01T02:29:37
C++
UTF-8
C++
false
false
3,574
h
duplication_test_base.h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #pragma once #include "replica/mutation_log_utils.h" #include "replica/test/replica_test_base.h" #include "replica/duplication/replica_duplicator.h" #include "replica/duplication/replica_duplicator_manager.h" #include "replica/duplication/duplication_sync_timer.h" namespace dsn { namespace replication { DEFINE_STORAGE_WRITE_RPC_CODE(RPC_DUPLICATION_IDEMPOTENT_WRITE, NOT_ALLOW_BATCH, IS_IDEMPOTENT) DEFINE_STORAGE_WRITE_RPC_CODE(RPC_DUPLICATION_NON_IDEMPOTENT_WRITE, NOT_ALLOW_BATCH, NOT_IDEMPOTENT) class duplication_test_base : public replica_test_base { public: duplication_test_base() { mutation_duplicator::creator = [](replica_base *r, dsn::string_view, dsn::string_view) { return std::make_unique<mock_mutation_duplicator>(r); }; stub->_duplication_sync_timer = std::make_unique<duplication_sync_timer>(stub.get()); } void add_dup(mock_replica *r, replica_duplicator_u_ptr dup) { r->get_replica_duplicator_manager()._duplications[dup->id()] = std::move(dup); } replica_duplicator *find_dup(mock_replica *r, dupid_t dupid) { auto &dup_entities = r->get_replica_duplicator_manager()._duplications; if (dup_entities.find(dupid) == dup_entities.end()) { return nullptr; } return dup_entities[dupid].get(); } std::unique_ptr<replica_duplicator> create_test_duplicator(decree confirmed = invalid_decree, decree start = invalid_decree) { duplication_entry dup_ent; dup_ent.dupid = 1; dup_ent.remote = "remote_address"; dup_ent.status = duplication_status::DS_PAUSE; dup_ent.progress[_replica->get_gpid().get_partition_index()] = confirmed; auto duplicator = std::make_unique<replica_duplicator>(dup_ent, _replica.get()); duplicator->_start_point_decree = start; return duplicator; } std::map<int, log_file_ptr> open_log_file_map(const std::string &log_dir) { std::map<int, log_file_ptr> log_file_map; error_s err = log_utils::open_log_file_map(log_dir, log_file_map); EXPECT_EQ(err, error_s::ok()); return log_file_map; } mutation_ptr create_test_mutation(int64_t decree, const std::string &data) override { auto mut = replica_test_base::create_test_mutation(decree, data); mut->data.updates[0].code = RPC_DUPLICATION_IDEMPOTENT_WRITE; // must be idempotent write return mut; } void wait_all(const std::unique_ptr<replica_duplicator> &dup) { dup->tracker()->wait_outstanding_tasks(); dup->_replica->tracker()->wait_outstanding_tasks(); } }; } // namespace replication } // namespace dsn
9009c8ac4a4a1d5579be6c881650786dd87ae249
c7a3050ca21824a341c46f9f93aedd0a0ee6b9b9
/origin/core/concepts.test/movable.cpp
06be07825e2a9bcf3052843a0c1510aed0661557
[]
no_license
jeb2239/origin
39c65caca90190c8730d6f93cd41d27af26c1b69
96956aeb88bcd1e2ca08d20d52e2d098e8ff254c
refs/heads/master
2020-12-11T07:26:09.768048
2015-03-24T14:40:53
2015-03-24T14:40:53
33,154,097
2
0
null
2015-03-30T23:38:41
2015-03-30T23:38:40
null
UTF-8
C++
false
false
282
cpp
movable.cpp
// This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #include <origin/core/concepts.hpp> static_assert(origin::Movable<int>(), ""); int main() { return 0; }
68abb78397061e6f7fe3124a2a8e99abfa9e1928
463e532c2addb431c967d7d8baea03f792c7b8e6
/StudyOwFuture/File.h
16a77a6bb7a693dfb5c3f270e7614dfde0c7441f
[]
no_license
threelamb/StudyDemo
5c04e8320ed007dd76aa3d2b3d0301f08e214222
005856642d97de42c05f32af8623e9b4f3499a1e
refs/heads/master
2021-01-10T02:35:02.051709
2016-02-02T18:42:46
2016-02-02T18:42:46
50,525,673
0
1
null
null
null
null
UTF-8
C++
false
false
65
h
File.h
#pragma once class File { public: File(); ~File(); };
2c94a3ec53562b903478c6d65f442e306327bef1
0bb208821c77c189be4af368ae6a89d56aec9bac
/game/src/Block.cpp
7cee9d4321577be2147a6faad10fae68bd104854
[]
no_license
aanddrew/lolcraft
10601982bbc0a4164bd4f58d49284d5c3895c136
70a2661ae953f0df83c26a274405dab289f1d281
refs/heads/master
2022-08-27T21:08:57.994560
2019-08-02T10:11:50
2019-08-02T10:11:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,854
cpp
Block.cpp
#include "../include/Block.h" #include <iostream> //init static members //these must be vectors of pointers because c++ does not like //overwriting the objects after their default constructors have been called //I think it has to do with the shitty default cube code in the mesh class std::vector<s3::Texture*> Block::blockTextures = std::vector<s3::Texture*>(); //we only have 1 mesh s3::Mesh* Block::blockMesh = new s3::Mesh("game/res/blocks/mesh/cube_full.obj"); int Block::NUM_TEX_IDS = AIR; // Block::Block() // { // this->ID = AIR; // static bool initialized = false; // if (!initialized) // { // init(); // } // } // Block::Block(unsigned char ID) // { // this->ID = ID; // static bool initialized = false; // if (!initialized) // { // init(); // } // } void Block::init() { blockTextures.reserve(NUM_TEX_IDS); //creating textures blockTextures[DIRT] = new s3::Texture("game/res/blocks/tex/dirt.png"); blockTextures[GRASS] = new s3::Texture("game/res/blocks/tex/grass.png"); blockTextures[STONE] = new s3::Texture("game/res/blocks/tex/stone.png"); blockTextures[COBBLE] = new s3::Texture("game/res/blocks/tex/cobble.png"); blockTextures[LOG] = new s3::Texture("game/res/blocks/tex/log.png"); blockTextures[LEAF] = new s3::Texture("game/res/blocks/tex/leaf.png"); blockTextures[PLANK] = new s3::Texture("game/res/blocks/tex/plank.png"); //loading them for(int i = 0; i < NUM_TEX_IDS; i++) { blockTextures[i]->load(); } //load mesh blockMesh->load(); } void Block::cleanUp() { for(int i = 0; i < NUM_TEX_IDS; i++) { if (blockTextures[i] != nullptr) delete blockTextures[i]; } if (blockMesh != nullptr) delete blockMesh; } void Block::draw(unsigned char ID, s3::Shader& shader) { if (ID == AIR) return; shader.bind(); blockTextures[ID]->bind(); blockMesh->bind(); blockMesh->draw(); }
9640708e2c48c2d8a39a64231606cee8d2bb22f2
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/ui/app_list/app_list_model.h
8dbdc5986ea261c01842906524a7ebb9d363da40
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
3,946
h
app_list_model.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_APP_LIST_APP_LIST_MODEL_H_ #define UI_APP_LIST_APP_LIST_MODEL_H_ #include <string> #include <vector> #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "ui/app_list/app_list_export.h" #include "ui/app_list/app_list_item_list.h" #include "ui/app_list/app_list_item_list_observer.h" #include "ui/app_list/search_result.h" #include "ui/base/models/list_model.h" namespace app_list { class AppListFolderItem; class AppListItem; class AppListItemList; class AppListModelObserver; class SearchBoxModel; class APP_LIST_EXPORT AppListModel : public AppListItemListObserver { public: enum Status { STATUS_NORMAL, STATUS_SYNCING, }; typedef ui::ListModel<SearchResult> SearchResults; AppListModel(); virtual ~AppListModel(); void AddObserver(AppListModelObserver* observer); void RemoveObserver(AppListModelObserver* observer); void SetStatus(Status status); AppListItem* FindItem(const std::string& id); AppListFolderItem* FindFolderItem(const std::string& id); AppListItem* AddItem(scoped_ptr<AppListItem> item); AppListItem* AddItemToFolder(scoped_ptr<AppListItem> item, const std::string& folder_id); const std::string MergeItems(const std::string& target_item_id, const std::string& source_item_id); void MoveItemToFolder(AppListItem* item, const std::string& folder_id); bool MoveItemToFolderAt(AppListItem* item, const std::string& folder_id, syncer::StringOrdinal position); void SetItemPosition(AppListItem* item, const syncer::StringOrdinal& new_position); void SetItemName(AppListItem* item, const std::string& name); void SetItemNameAndShortName(AppListItem* item, const std::string& name, const std::string& short_name); void DeleteItem(const std::string& id); void NotifyExtensionPreferenceChanged(); void SetFoldersEnabled(bool folders_enabled); static std::vector<SearchResult*> FilterSearchResultsByDisplayType( SearchResults* results, SearchResult::DisplayType display_type, size_t max_results); AppListItemList* top_level_item_list() { return top_level_item_list_.get(); } SearchBoxModel* search_box() { return search_box_.get(); } SearchResults* results() { return results_.get(); } Status status() const { return status_; } bool folders_enabled() const { return folders_enabled_; } private: virtual void OnListItemMoved(size_t from_index, size_t to_index, AppListItem* item) OVERRIDE; AppListFolderItem* FindOrCreateFolderItem(const std::string& folder_id); AppListItem* AddItemToItemListAndNotify( scoped_ptr<AppListItem> item_ptr); AppListItem* AddItemToItemListAndNotifyUpdate( scoped_ptr<AppListItem> item_ptr); AppListItem* AddItemToFolderItemAndNotify(AppListFolderItem* folder, scoped_ptr<AppListItem> item_ptr); scoped_ptr<AppListItem> RemoveItem(AppListItem* item); scoped_ptr<AppListItem> RemoveItemFromFolder(AppListFolderItem* folder, AppListItem* item); scoped_ptr<AppListItemList> top_level_item_list_; scoped_ptr<SearchBoxModel> search_box_; scoped_ptr<SearchResults> results_; Status status_; ObserverList<AppListModelObserver, true> observers_; bool folders_enabled_; DISALLOW_COPY_AND_ASSIGN(AppListModel); }; } #endif
41cb3b9eb19b367e0a08fa2ba5c8adf6979f9407
67f605c2a17ef15a7efe0e272e621df6e28a0940
/EstacionMeteorologica/SlaveL/SlaveNetworking.h
0f7f7cc85b7859b371f64fc3d52e8b68d57ad181
[]
no_license
sivulich/EstacionMeteorlogica
b8c142c4d3f5f6b41ccc2e75aece16da47fba7b2
d93123c6f72a909189c0d4fb91d914572b9e4e73
refs/heads/master
2021-01-12T21:54:08.004806
2017-08-02T01:38:40
2017-08-02T01:38:40
81,754,331
0
0
null
null
null
null
UTF-8
C++
false
false
604
h
SlaveNetworking.h
#pragma once #include "Sensor.h" #include "Event.h" #include "mosquitto.hpp" #define BROKER "192.168.1.33" class SlaveNetworking { public: SlaveNetworking(); ~SlaveNetworking(); bool hayEvento(); Event getEvent(); void sendStatus(const vector<Sensor*>& mySensors, uint8_t battery, bool busy); void sendData(const vector<Sensor*>& mySensors); void getUpdate(); void sendSensorList(const vector<Sensor*>& mySensors); bool publish(const string& subTopic, const vector<uint8_t>& message, bool persitence); void ping(); private: Event ev; uint32_t serverIp; Mosquitto mosq; string serial; };
0875910730535984588072eacb025c4986d92576
cc453b1b93bb3fc5556d5effab4cdb217799b2ae
/Medium/139-WordBreak.cpp
fac4b4049bdba475e117ffa1a91d7118e0203e26
[]
no_license
prasadnallani/LeetCodeProblems
7615d1f3a10e8d1800e322f6fbfa0a5feb55117f
33472bc788a2e54294fdb59cf26438f92f322493
refs/heads/master
2023-06-30T15:51:57.943254
2021-07-27T16:56:25
2021-07-27T16:56:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,351
cpp
139-WordBreak.cpp
/* * Author: Raghavendra Mallela */ /* * LeetCode 139: Word Break * * Given a string s and a dictionary of strings wordDict, return true if s can be segmented * into a space-separated sequence of one or more dictionary words. * * Note that the same word in the dictionary may be reused multiple times in the segmentation. * * Example 1: * Input: s = "leetcode", wordDict = ["leet","code"] * Output: true * Explanation: Return true because "leetcode" can be segmented as "leet code". * * Example 2: * Input: s = "applepenapple", wordDict = ["apple","pen"] * Output: true * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". * Note that you are allowed to reuse a dictionary word. * * Example 3: * Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] * Output: false * * Constraints: * 1 <= s.length <= 300 * 1 <= wordDict.length <= 1000 * 1 <= wordDict[i].length <= 20 * s and wordDict[i] consist of only lowercase English letters. * All the strings of wordDict are unique. */ /* * TopDown Approach or Recursive Solution * * As the solution is to find whether the input string is segmented into * words in the dictionary. * Loop through each word in the dictionary and check if a word in * dictionary is found in s * . If found, remove the word from s and do a recursive call to find * remaining string in dictionary * . If it is not found, move onto next word in dictionary * * If all words is not matched, then return false. If incase, any of the * recursive calls return true, then solution is also true * * Base case is that if string is empty, then return true, empty string is * always true */ bool wordBreak(string s, vector<string>& wordDict) { if (s.empty()) { return true; } // string is not empty, loop all words in dictionary for (string word : wordDict) { string left = s.substr(0, word.size()); if (left == word && wordBreak(s.substr(word.size()), wordDict)) { return true; } } return false; } /* * TopDown Approach or Recursive Solution with Memoization * * There will be many duplicate subproblems if the input * string has many continous duplicate letters, * * For eg: s = "aaaaaaaa" wordDict = ["a", "aa", "aaa", "aaaa"] * In order for not to evaluate the duplicate sub problems, * the intermediate results are stored in the dp, so the time * complexity can be reduced from O(2^n) to O(n^2) */ std::unordered_map<string, bool> dp1; bool wordBreak_memo(string s, vector<string>& wordDict) { if (s.empty()) { // String is empty, return true return true; } // Check if this subproblem is evaluated if (dp1.count(s) == 1) { // The subproblem is already evaluated, returning previous // calculated solution return dp1[s]; } // string is not empty, loop all words in dictionary for (string word : wordDict) { string left = s.substr(0, word.size()); if (left == word && wordBreak(s.substr(word.size()), wordDict)) { return dp1[left] = true; } } return dp1[s] = false; } /* * Bottom Up Solution * * Similar to Memoization but will be an iterative not recursive. * * The DP array holds whether the substring from 0 is present in dictionary or not * The length of dp array is n + 1 where n = length of i/p string, +1 to accomidate * for empty string */ bool wordBreak_BU(string s, vector<string>& wordDict) { // DP array to hold whether the substring till that point are available in // Dictionary or not. vector<bool> dp(s.size() + 1, false); // Empty string is always true dp[0] = true; // Try to fill the dp array, concpet is 2 index solution where the first // idx runs from 1... dp.size() and the other idx runs from first idx -1 // till >= 0 // first idx holds the length of substr // second idx is starting idx of substr in input S for (int i = 1; i < dp.size(); i++) { for (int j = i - 1; j >= 0; j--) { if (dp[j] && std::find(wordDict.begin(), wordDict.end(), s.substr(j, i - j)) != wordDict.end()) { dp[i] = true; break; } } } return dp.back(); }
bfd666b17e54581d0cecd0870fdcc3e19e86d7e2
b926843b474946a424568ef2b035cd907ff3136f
/algorighm_4th/Ex_1_2_01/Ex_1_2_01/TestPoint2DDlg.cpp
6a971f57231e18b781e90317a400058f77c120d9
[]
no_license
tom1232289/Algorithm_learn
f2e93302f13dc0a2c17a5f537af884218f794ee6
c0677c3a0f20bf3141e5cae548f9590676eb1395
refs/heads/master
2020-04-22T20:58:00.647753
2019-11-18T13:02:08
2019-11-18T13:02:08
170,646,106
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
TestPoint2DDlg.cpp
#include "TestPoint2DDlg.h" #include <random> CTestPoint2DDlg::CTestPoint2DDlg(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); } void CTestPoint2DDlg::paintEvent(QPaintEvent * event) { QPainter painter(this); painter.setPen(QPen(Qt::blue, 2)); m_PointCoordinate.clear(); CreateRandomPoint(); for (auto c : m_PointCoordinate) { painter.drawPoint(c.rx(), c.ry()); } } void CTestPoint2DDlg::CreateRandomPoint() { random_device rd; mt19937_64 generator(rd()); uniform_int_distribution<int> distribution(100, 600); const int N = 100; for (int i = 0; i < N; ++i) { int x = distribution(generator); int y = distribution(generator); m_PointCoordinate.push_back(QPoint(x, y)); } double min = numeric_limits<double>::max(); double trueLength = 0.0; for (auto i = m_PointCoordinate.begin(); i != m_PointCoordinate.end(); ++i) { for (auto j = i + 1; j != m_PointCoordinate.end(); ++j) { auto temp1 = pow((*j).rx() - (*i).rx(), 2); auto temp2 = pow((*j).ry() - (*i).ry(), 2); trueLength = sqrt(pow((*j).rx() - (*i).rx(), 2) + pow((*j).ry() - (*i).ry(), 2)); if (trueLength < min) min = trueLength; } } ui.label->setText(QString::number(min)); }
bba6537ed18944ecf377e5ca9ce935ca24535fe4
35baa4a4648003fdd85732850897d043b830761e
/iblinkedlistmerge2list.cpp
caef898630dd790c5f3a7c3f61a9d3dab7dc224d
[]
no_license
deepanshuoct12/interviewbit-solution
0c091e7ddab2d1be3cc207a70b5c9498c23b33d2
87254a250233c571611cc70b91749574d0544b5a
refs/heads/master
2023-01-03T11:46:16.244384
2020-11-02T21:29:57
2020-11-02T21:29:57
279,698,381
0
0
null
null
null
null
UTF-8
C++
false
false
1,114
cpp
iblinkedlistmerge2list.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) { ListNode* newlist=NULL,*h=NULL; ListNode *pt1=A,*pt2=B; while(pt1!=NULL && pt2!=NULL) { if(pt1->val<pt2->val) { if(newlist==NULL) { newlist=pt1; h=pt1; } else { h->next=pt1; h=pt1; } pt1=pt1->next; } else { if(newlist==NULL) { newlist=pt2; h=pt2; } else { h->next=pt2; h=pt2; } pt2=pt2->next; } } while(pt1!=NULL){ h->next=pt1; h=pt1; pt1=pt1->next; } while(pt2!=NULL){ h->next=pt2; h=pt2; pt2=pt2->next; } ListNode*curr=newlist; return newlist; }
5e4b35dd2da213b4e705616d67fff7f5357b6f1b
72910f28ab9acea94c21204431b14828497c693e
/lua_serial/LuaScript.cpp
e8c0ee2c131dc72e24152a9b3b3b69d420502769
[]
no_license
PeachChen/test
3e5a8757deeac644b368889a25564554cb85833a
a939b7c7d6dc5eefba33d29d266f378af0ef87b5
refs/heads/master
2021-04-09T11:32:56.326967
2017-04-21T01:38:06
2017-04-21T01:38:06
61,102,362
0
0
null
null
null
null
UTF-8
C++
false
false
9,495
cpp
LuaScript.cpp
#include "LuaScript.h" #include "util/MyStream.h" #include <string> using namespace std; CLuaScript::CLuaScript() { Init(); } CLuaScript::~CLuaScript() { if(L) { lua_close(L); L=NULL; } } void CLuaScript::Init() { L=luaL_newstate(); luaL_openlibs(L); REG_LUA_FUNCTION(LoadTable); REG_LUA_FUNCTION(SaveTable); } void CLuaScript::RegisterFunction(const char* funcName,lua_CFunction func) { if(funcName==NULL) { return; } lua_register(L,funcName,func); } bool CLuaScript::LoadFile(const char *path) { int ret=luaL_loadfile(L,path); if(ret!=0) { return false; } ret=lua_pcall(L,0,0,0); if(ret!=0) { return false; } return true; } int CLuaScript::L_LoadTable(lua_State* L) { if(!lua_istable(L,1)) return 0; const char* fileName=lua_tostring(L,2); if(fileName==0) { return 0; } string file=fileName; lua_pop(L,1); if(!lua_istable(L,1)) return 0; int result=0; FILE *pf=::fopen(file.c_str(),"rb"); if(pf!=0) { long bufferSize=0; fseek(pf,0,SEEK_END); bufferSize=ftell(pf); fseek(pf,0,SEEK_SET); uint8* buffer=new uint8[bufferSize+1]; buffer[0]=0; buffer[bufferSize]=0; if(fread(buffer,bufferSize,1,pf)!=1) { ::fclose(pf); delete [] buffer; return 0; } ::fclose(pf); if(LoadTableFromData(L,buffer,bufferSize)) { result=1; } delete [] buffer; } else { return 0; } lua_pushboolean(L,result); return 1; } bool CLuaScript::LoadTableFromData(lua_State*L,uint8 *data,uint dataSize) { int oldStackPos=lua_gettop(L); Stream reader(data,dataSize); bool iskey=true; bool loadOK=false; while(reader.GetSpace()>0) { if(!LoadValue(L,lua_gettop(L),reader,iskey,loadOK)) { lua_settop(L,oldStackPos); return false; } if(loadOK) break; } if(lua_gettop(L)!=oldStackPos) { lua_settop(L,oldStackPos); return false; } return true; } bool CLuaScript::LoadValue(lua_State* L, int idx, BaseStream& reader, bool& isKey, bool& loadOk) { if (reader.GetSpace() < 1) return true; uint8 type = 0; reader >> type; switch (type) { case EScriptStreamType_number: { double doubleValue; reader >> doubleValue; lua_pushnumber(L, doubleValue); //如果上一层不是table就一定是key //-1 number value //-2 key //-3 table if (!isKey&&lua_istable(L, -3)) { if (lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING) lua_settable(L, -3); } isKey = !isKey; } break; case EScriptStreamType_string: { string strValue; reader >> strValue; lua_pushstring(L, strValue.c_str()); //-1 string value //-2 key //-3 table if (!isKey&&lua_istable(L, -3)) { if (lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING) lua_settable(L, -3); } isKey = !isKey; } break; case EScriptStreamType_bool: { uint8 b = 0; reader >> b; lua_pushboolean(L, b); //-1 string value //-2 key //-3 table if (!isKey&&lua_istable(L, -3)) { if (lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING) lua_settable(L, -3); } isKey = !isKey; } break; case EScriptStreamType_table: { uint8 flagValue = 0; reader >> flagValue; if (flagValue == EScriptStreamType_end)//整个数据块的结束标记 { loadOk = true; return isKey; } else if (flagValue == EScriptStreamTableFlag_Begin)//table 开始标记 { lua_newtable(L); //-1 sub table //-2 key //-3 parent table Assert(lua_istable(L, -3)); Assert(lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING); Assert(!isKey); if (!isKey && lua_istable(L, -3)) { Assert(lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING); } isKey = !isKey; bool loadOk2 = false; //加载子表 if (!LoadValue(L, lua_gettop(L), reader, isKey, loadOk2)) return false; } else if (flagValue == EScriptStreamTableFlag_End) { //现在最上面一层一定是table //-1 sub table //-2 key //-3 parent table Assert(lua_istable(L, -1) && lua_istable(L, -3)); if (lua_istable(L, -1)) { Assert(lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING); if (lua_type(L, -2) == LUA_TNUMBER || lua_type(L, -2) == LUA_TSTRING) lua_settable(L, -3); } } else { Assert(false); return false; } } break; case EScriptStreamType_end: { Assert(isKey); loadOk = true; return isKey; } break; default: Assert(false); return false; } return true; } int CLuaScript::L_SaveTable(lua_State* L) { if (lua_gettop(L) != 2) return 0; if (!lua_istable(L, 1)) return 0; const char* fileName = lua_tostring(L, 2); if (fileName == 0) return 0; string file = fileName; lua_pop(L, 1); if (!lua_istable(L, -1)) return 0; int oldStackPos = lua_gettop(L); int saveTableSize = 0; if (!GetSaveTableSize(L, lua_gettop(L), saveTableSize, true)) { lua_settop(L, oldStackPos); return 0; } uint8* saveBuffer = new uint8[saveTableSize]; uint writeSize = 0; if (!SaveTableToData(L, saveBuffer, saveTableSize, writeSize)) { SAFE_DELETE_ARRAY(saveBuffer); return 0; } //流数据保存到文件 //如果文件存在会被清空 FILE* pf = ::fopen(file.c_str(), "wb+"); if (pf != 0) { if (writeSize > 0) { ::fwrite(saveBuffer, 1, writeSize, pf); } ::fclose(pf); SAFE_DELETE_ARRAY(saveBuffer); lua_pushnumber(L, writeSize); return 1; } else { SAFE_DELETE_ARRAY(saveBuffer); } return 0; } bool CLuaScript::GetSaveTableSize(lua_State* L, int idx, int& saveSize, bool writeEndFlag) { int oldStackPos = lua_gettop(L); lua_pushnil(L); while (lua_next(L,idx)) { int keyType = lua_type(L, -2); int valueType = lua_type(L, -1); if (keyType == LUA_TBOOLEAN || keyType == LUA_TNUMBER || keyType == LUA_TSTRING) { if (valueType == LUA_TBOOLEAN || valueType == LUA_TNUMBER || valueType == LUA_TSTRING || valueType == LUA_TTABLE) { if (!GetSaveValueSize(L, -2,saveSize)) return false; if (!GetSaveValueSize(L, -1, saveSize)) return false; //子表 if (lua_istable(L, -1)) { if (!GetSaveTableSize(L, lua_gettop(L), saveSize, false)) { lua_settop(L, oldStackPos); return false; } saveSize += 2; } } } lua_pop(L, 1);//因为lua_next是pop1个,push2个所以这儿只需要pop1个就可以了 } if (lua_gettop(L) != oldStackPos) { return false; } if (writeEndFlag) ++saveSize; return true; } bool CLuaScript::GetSaveValueSize(lua_State* L, int idx, int& saveSize) { int type = lua_type(L, idx); switch (type) { case LUA_TSTRING: { const char* s = lua_tostring(L, idx); if (!s) { return false; } uint size = (uint)::strlen(s); saveSize += (1 + sizeof(uint)+size); } break; case LUA_TNUMBER: { saveSize += (1 + sizeof(lua_Number)); } break; case LUA_TBOOLEAN: saveSize += 2; break; case LUA_TTABLE: { Assert(idx == -1);//table只能是value 绝不可能是key if (idx != -1) return false; saveSize+=2; } break; default: break; } return true; } bool CLuaScript::SaveTableToData(lua_State* L, uint8* data, uint dataSize, uint& writeSize) { int oldStackPos = lua_gettop(L); Stream writer(data, dataSize); if (!SaveTable(L, lua_gettop(L), writer, true)) { lua_settop(L,oldStackPos); return false; } if (lua_gettop(L) != oldStackPos) { return lua_settop(L, oldStackPos), false; } writeSize = (uint)writer.GetOffset(); return true; } bool CLuaScript::SaveTable(lua_State* L, int idx, BaseStream& writer, bool writeEndFlag) { int oldStackPos = lua_gettop(L); lua_pushnil(L); while (lua_next(L,idx)) { int keyType = lua_type(L, -2); int valueType = lua_type(L, -1); if (keyType == LUA_TBOOLEAN || keyType == LUA_TNUMBER || keyType == LUA_TSTRING) { if (valueType == LUA_TBOOLEAN || valueType == LUA_TNUMBER || valueType == LUA_TSTRING || valueType == LUA_TTABLE) { if (!SaveValue(L, -2, writer)) return false; if (!SaveValue(L, -1, writer)) return false; //子表 if (lua_istable(L, -1)) { if (!SaveTable(L, lua_gettop(L), writer, false)) { lua_settop(L, oldStackPos); return false; } writer << ((uint8)EScriptStreamType_table); writer << ((uint8)EScriptStreamTableFlag_End); } } } lua_pop(L, 1);//因为lua_next是pop1个,push2个所以这儿只需要pop1个就可以了 } if (lua_gettop(L) != oldStackPos) { lua_settop(L, oldStackPos); return false; } if (writeEndFlag) writer << ((uint8)EScriptStreamTableFlag_End); return true; } bool CLuaScript::SaveValue(lua_State* L, int idx, BaseStream& writer) { int type = lua_type(L, idx); switch (type) { case LUA_TSTRING: { const char* s = lua_tostring(L, idx); Assert(s); if (!s) { return false; } writer << ((uint8)EScriptStreamType_string); writer << (s); } break; case LUA_TNUMBER: { writer<<((uint8)EScriptStreamType_number); writer << (lua_tonumber(L, idx)); } break; case LUA_TBOOLEAN: { writer<< ((uint8)EScriptStreamType_bool); writer << (lua_toboolean(L, idx) == 0 ? false : true); } break; case LUA_TTABLE: { Assert(idx == -1);//table只能是value 绝不可能是key if (idx != -1) return false; writer << ((uint8)EScriptStreamType_table); writer << ((uint8)EScriptStreamTableFlag_Begin); } break; default: break; } return true; }
6f71d52dc4ef3e1927c6ef5c22f755c778b0f697
8f34911e697ef220d7cf76d44fa9b560be4ba7f0
/Engine/Source/Game/Floppy/S_Floppy.cpp
b69050a7f3c2193040e36bc8e9b8b8e11fad9e16
[ "MIT" ]
permissive
RaMaaT-MunTu/OOM-Engine
3d85d6bef34d55b4061dc5f87d74d411e66ec93a
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
refs/heads/master
2022-01-23T07:17:14.483120
2018-08-20T11:19:31
2018-08-20T11:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,082
cpp
S_Floppy.cpp
/// \file S_Floppy.cpp /// \date 08/08/2018 /// \project OOM-Engine /// \package Built-in/Script /// \author Vincent STEHLY--CALISTO #include "Game/Floppy/S_Floppy.hpp" /*virtual */ void S_Floppy::Awake() { m_limit_size = 1440; m_current_size = 0; mp_text = nullptr; mp_floppy_text = nullptr; mp_floppy_sprite = nullptr; mp_source_floppy = nullptr; } /*virtual */ void S_Floppy::Start() { mp_floppy_text = Sdk::GameObject::CreateUIText (); mp_floppy_sprite = Sdk::GameObject::CreateUISprite(); mp_text = mp_floppy_text->GetComponent <S_Text>(); auto* p_material = mp_floppy_sprite->GetComponent<CMaterial>(); auto* p_renderer = mp_floppy_sprite->GetComponent<CUISpriteRenderer>(); mp_source_floppy = GetGameObject()->AddComponent<CAudioSource3D>(); p_renderer->SetSortingLayer(0); p_material->SetTexture(Sdk::Import::ImportTexture("Resources/Texture/T_Floppy_UI.png")); mp_floppy_sprite->GetTransform().SetScale(0.8f, 0.8f, 0.8f); mp_floppy_sprite->GetTransform().SetPosition(0.96f, 0.06f, 0.0f); mp_text->SetText("0 / 1440 KB"); mp_floppy_text->GetTransform().SetScale(0.4f, 0.4f, 0.4f); mp_floppy_text->GetTransform().SetPosition(0.75f, 0.04f, 0.0f); // Audio m_audio_buffer_floppy.LoadFromFile("Resources/Sound/sound_floppy_filling.ogg"); mp_source_floppy->SetAudioBuffer(&m_audio_buffer_floppy); mp_source_floppy->SetMinDistance(15.0f); mp_source_floppy->SetMaxDistance(30.0f); // Moving away this anoying floppy GetTransform()->Translate(-20.0f, 0.0f, 0.0f); } /*virtual */ void S_Floppy::Update() { GetTransform()->Rotate(0.0f, 0.0f, 1.0f * CTime::delta_time); } /*virtual */ void S_Floppy::OnDestroy() { // None } void S_Floppy::AddKiloByte(uint32_t kilo_bytes) { m_current_size += kilo_bytes; char text_buffer[32] = { '\0' }; sprintf(text_buffer, "%d / 1440 KB", m_current_size); mp_text->SetText(text_buffer); mp_source_floppy->Play(); } uint32_t S_Floppy::GetLimitSize() const { return m_limit_size; } uint32_t S_Floppy::GetCurrentSize() const { return m_current_size; }
b55f8ae24559efd206a970a4bbde8904c84077d8
74a0bd5552e2ffc94162ea9a2ffba3b46120d60d
/Deitel/10.9_IntegerSet/main.cpp
bfe2571d8cf7ff744c00e1630fad19b9a2e8b6ae
[]
no_license
dmytrofrolov/Cpp
9103f5979e710061d8bf03465fc87b7fc3ff7bc9
a216cadd3903c1e73381bf6d12a394af472cfc93
refs/heads/master
2016-09-09T22:08:01.471867
2015-05-04T19:06:49
2015-05-04T19:06:49
25,148,597
0
1
null
null
null
null
UTF-8
C++
false
false
602
cpp
main.cpp
#include <iostream> #include "IntegerSet.h" using std::cout; using std::endl; int main() { int initialArray1[] = {1, 2, 3, 6, 5, 4}; IntegerSet set1(initialArray1, 6); set1.printIt(); cout << endl; int initialArray2[] = {5, 8, 12, 6, 23, 4}; IntegerSet set2(initialArray2, 6); set2.printIt(); cout << endl; IntegerSet set3; set3.printIt(); cout << endl; set3 = IntegerSet::unionOfSet(set1, set2); set3.printIt(); cout << endl; IntegerSet set4(initialArray1, 6); cout << IntegerSet::isEqual(set1, set4) << endl; return 0; }
d4281c3ac47576c455b09d1bc781d1fe583cb9b8
f445fd75299ad7d9e238326360d1fe2b8c4bccf9
/Exercise-9a.cpp
baf156ebcb2e67754176f46421791f2225fc1b12
[]
no_license
neverkas/learning-cpp
d8a9bfa9e23ac9b55aabb6a251fc069ff17f080a
10851eea7009412fb390a50539ce36e5a4cf3765
refs/heads/master
2020-03-12T10:17:54.367867
2018-05-27T00:04:19
2018-05-27T00:04:19
130,570,223
0
0
null
null
null
null
UTF-8
C++
false
false
1,801
cpp
Exercise-9a.cpp
/* * Exercise 9: * * Dados un mes y el año correspondiente, informar cuantos dias tiene el mes. * ****** * Solucion en Proposicion logica * p=es divisible por 4, r=es divisible por 400, ¬q=es divisible por 100 * p y (¬q o r)r ****** * Solucion en Pseudo codigo: * 1. Datos de Entrada m=3, anio=2018 * 2. Si el anio es divisible por 4 y 400, pero no por 100 * 2.1 es anio bisiesto, entonces febrero tiene 29 dias * 2.1 sino febrero tiene 28 dias * 3. Segun el numero de mes mostrar x cantidad de dias * */ #include <iostream> using namespace std; int main(){ // Definir variables int dia, anio, mes; bool es_anio_bisiesto; // Texto informativo cout << "Averigua cuantos dias tiene tal mes, a partir del mes y anio" << endl; // Entrada de datos cout << "Ingrese el mes en formato (mm): "; cin >> mes; cout << "Ingrese el anio en formato (aaaa): "; cin >> anio; // Verificar si es anio bisiesto // Si el anio es divisible por 4 y por 400 o no es divisible por 100 // entonces es Anio Bisiesto es_anio_bisiesto = ((anio % 4 == 0) && (anio % 400 == 0 || anio % 100 != 0)); /* * Meses con 31 dias: * Enero(1), Marzo(3), Mayo(5), Julio(7), Agosto(8), Octubre(10), Diciembre(12) * * Meses con 30 dias: * Abril(4), Junio(6), Septiembre(9), Noviembre(11) * * Meses con 28-29 dias: * Febrero(2) */ // Segun el mes elegido, mostrar x cantidad de dias switch(mes){ case 2: dia = (es_anio_bisiesto) ? 29 : 28; break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: dia = 31; break; case 4: case 6: case 9: case 11: dia = 30; break; } // Salida de datos cout << "El mes " << mes << " del anio " << anio; cout << " tiene " << dia << "dias" << endl; return 0; }
943cfc32724db027526da0f318bba982d18625b5
94bbf67e9834d662b3f777b96fd8366321a4d56d
/Assignments/Assignment 4/GradeBook.cpp
e861844fe5744f27c8d90ece9b5a5684df616939
[]
no_license
CristianCortez/CS-301-05-DataStructures
fc11774fef15ce8f614dc5cc73db4f0af524f110
488ce3cd08ea5047eaba8aeb44696de105b2cd3e
refs/heads/master
2020-07-25T02:08:20.092988
2019-12-03T01:26:28
2019-12-03T01:26:28
208,126,917
0
1
null
null
null
null
UTF-8
C++
false
false
6,138
cpp
GradeBook.cpp
#include "GradeBook.h" Semester::Semester() { //cout << "obj built."; } void Semester::setNumP(int num) { numPrograms = num; } void Semester::setNumT(int num) { numTest = num; } void Semester::setNumF(int num) { numFinal = num; } void Semester::setWeigths(int num, int idx) { weights[idx] = num; } int Semester::getNumP() { return numPrograms; } int Semester::getNumT() { return numTest; } int Semester::getNumF() { return numFinal; } int Semester::getWeights(int idx) { return weights[idx]; } GradeBook::GradeBook() { headPtr = nullptr; } GradeBook::~GradeBook() { if (headPtr) { while (headPtr) { Students* tmp = headPtr; headPtr = headPtr->next; delete[] tmp->saddness.prg; delete[] tmp->saddness.tst; delete[] tmp->saddness.fnl; tmp->saddness.prg = nullptr; tmp->saddness.tst = nullptr; tmp->saddness.fnl = nullptr; delete tmp; } } } void GradeBook::addStudent(string lName, string fName, int id, int pNum, int tNum, int fNum) { int i; Students* newStu = new Students; Students* head = headPtr; newStu->lastName = lName; newStu->firstName = fName; newStu->ID = id; newStu->pGrd = 0; newStu->tfGrd = 0; newStu->saddness.prg = new int[pNum]; newStu->saddness.tst = new int[tNum]; newStu->saddness.fnl = new int[fNum]; for (i = 0; i < pNum; i++) newStu->saddness.prg[i] = -1; for (i = 0; i < tNum; i++) newStu->saddness.tst[i] = -1; for (i = 0; i < fNum; i++) newStu->saddness.fnl[i] = -1; newStu->next = NULL; alphaMe(newStu); } void GradeBook::addGrade(string name, char ptf, int grd, int idx) { Students* tmp = headPtr; while (tmp) { if (tmp->lastName == name) { switch (ptf) { case 'P': tmp->saddness.prg[idx] = grd; break; case 'T': tmp->saddness.tst[idx] = grd; break; case 'F': tmp->saddness.fnl[idx] = grd; break; } tmp = NULL; } else tmp = tmp->next; } } void GradeBook::alphaMe(Students* newStu) { Students* tmpHead = headPtr; Students* previous = tmpHead; int i = 0; if (headPtr == NULL || headPtr->lastName[0] > newStu->lastName[0]) { newStu->next = headPtr; headPtr = newStu; } else { do { previous = tmpHead; if (tmpHead->lastName[i] == newStu->lastName[i]) { i++; } else { i = 0; tmpHead = tmpHead->next; } } while (tmpHead && tmpHead->lastName[i] <= newStu->lastName[i]); if (previous->lastName.compare(newStu->lastName) == 0) { if (previous->ID > newStu->ID) { newStu->next = previous; previous = newStu; } else { newStu->next = previous->next; previous->next = newStu; } } else { newStu->next = previous->next; previous->next = newStu; } } } void GradeBook::changeGrade(int id, int grd, char ptf, int idx) { Students* tmp = headPtr; if (tmp) { while (tmp) { if (tmp->ID == id) { switch (ptf) { case 'P': tmp->saddness.prg[idx] = grd; break; case 'T': tmp->saddness.tst[idx] = grd; break; case 'F': tmp->saddness.fnl[idx] = grd; break; } tmp = NULL; } else { tmp = tmp->next; } } } } string GradeBook::printStuds(bool out, int pNum, int tNum, int fNum) { ostringstream prtList; Students* tmp = headPtr; int i; if (tmp) { while (tmp) { prtList << "\nName: " << tmp->lastName << ", " << tmp->firstName << "\nID#: " << tmp->ID << "\nAverage Prgrogram Grade: " << tmp->pGrd << "\nAverage Test Grade: " << tmp->tfGrd; if (out) { prtList << "\n\nGrades: \n\tPrograms: "; for (i = 0; i < pNum; i++) { if (tmp->saddness.prg[i] != -1) { prtList << "\n\t\tProgram #" << i + 1 << ": " << tmp->saddness.prg[i]; } } prtList << "\n\tTests: "; for (i = 0; i < tNum; i++) { if (tmp->saddness.tst[i] != -1) { prtList << "\n\t\tTest #" << i + 1 << ": " << tmp->saddness.tst[i]; } } prtList << "\n\tFinal: "; for (i = 0; i < fNum; i++) { if (tmp->saddness.fnl[i] != -1) { prtList << "\n\t\tFinal #" << i + 1 << ": " << tmp->saddness.fnl[i]; } } } tmp = tmp->next; } } return prtList.str(); } int GradeBook::getLength() { Students* currentNodeAddr = headPtr; int classSize = 0; if (currentNodeAddr) { do { classSize++; currentNodeAddr = currentNodeAddr->next; } while (currentNodeAddr); } return classSize; } void GradeBook::setAssgG(int indx) { Students* tmp = headPtr; int grade; if (tmp) { while (tmp) { cout << "\n\tName: " << tmp->lastName << ", " << tmp->firstName << "\n\tProgramming Assingment #" << indx << ": " << "\n\t\t:Grade: "; cin >> grade; tmp->saddness.prg[indx] = grade; tmp = tmp->next; } } } void GradeBook::setTestG(int indx) { Students* tmp = headPtr; int grade; if (tmp) { while (tmp) { cout << "\n\tName: " << tmp->lastName << ", " << tmp->firstName << "\n\tTest #" << indx <<": " << "\n\t\t:Grade: "; cin >> grade; tmp->saddness.tst[indx] = grade; tmp = tmp->next; } } } void GradeBook::setFinalG(int indx) { Students* tmp = headPtr; int grade; if (tmp) { while (tmp) { cout << "\n\tName: " << tmp->lastName << ", " << tmp->firstName << "\n\tFinal #" << indx << ": " << "\n\t\t:Grade: "; cin >> grade; tmp->saddness.fnl[indx] = grade; tmp = tmp->next; } } } void GradeBook::calcGrade(int pNum, int tNum, int fNum) { Students* tmp = headPtr; int pAvg = 0, tfAvg = 0; int counter = 0, i; if (tmp) { while (tmp) { for (i = 0; i < pNum; i++) { pAvg += tmp->saddness.prg[i]; } tmp->pGrd = pAvg / i; for (i = 0; i < tNum; i++) { tfAvg += tmp->saddness.tst[i]; counter++; } for (i = 0; i < fNum; i++) { tfAvg += tmp->saddness.fnl[i]; counter++; } tmp->tfGrd = tfAvg / counter; tmp = tmp->next; } cout << "\nGrade Calulated."; } }
0c14209db7af3725df59b6578cf1af56402cb094
0f6b033575bf8bec80f08d26db28a7e8f5c7d226
/client/SWGModelFactory.h
a137d1ff810bd48937222ec8d352ad055f51b3b4
[ "MIT" ]
permissive
gantony/corkdev-questions-qml
cbdad68be5406575ef314388324bc6edecea4086
b20a1e0cbfa4ca5e189a3615b5ef0f17a1e67c87
refs/heads/master
2021-08-12T02:02:53.144834
2017-11-14T08:10:27
2017-11-14T09:43:48
108,461,337
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
h
SWGModelFactory.h
/** * Simple API to gather and rank questions during talks * This is a simple API * * OpenAPI spec version: 1.0.0 * Contact: antony.guinard@gmail.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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 ModelFactory_H_ #define ModelFactory_H_ #include "SWGQuestion.h" namespace Swagger { inline void* create(QString type) { if(QString("SWGQuestion").compare(type) == 0) { return new SWGQuestion(); } return nullptr; } inline void* create(QString json, QString type) { void* val = create(type); if(val != nullptr) { SWGObject* obj = static_cast<SWGObject*>(val); return obj->fromJson(json); } if(type.startsWith("QString")) { return new QString(); } return nullptr; } } /* namespace Swagger */ #endif /* ModelFactory_H_ */
6a8289e4a1fad274ee254410a0ee7060a9afece9
a6a208018266e93d2d4306bbdf600d2fcd5145f5
/TAfin.~h
4be5b113ee3af1e315a1202ce76f6f132a3b28d3
[]
no_license
alvaropascualcrespo/Camara
872e4e8946f7d599a63324430fd5ece3497e18d7
ca1b156f4a3d01d1cbf6f44991763efebbfd30f7
refs/heads/master
2020-06-08T19:10:06.012431
2014-05-01T11:10:41
2014-05-01T11:10:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
730
TAfin.~h
//--------------------------------------------------------------------------- #ifndef TAfinH #define TAfinH #include <gl\gl.h> //--------------------------------------------------------------------------- class TAfin{ private: GLfloat* m; public: TAfin(); GLfloat* getMatrix(){return m;}; void traslacion(GLfloat x, GLfloat y, GLfloat z); void escalacion(GLfloat x, GLfloat y, GLfloat z); void rotacion(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); void postMultiplica(GLfloat matr[16]); void setPosicion(int posicion, GLfloat numero){m[posicion] = numero;}; }; #endif
85f57d7979a678a4f60c5a7800832bb7a688dc1f
993a8cf2a4e060a8ddea9653611276a72cd93ed9
/Cone_t.h
e872d985986e071cf4a68941698707c06849b310
[]
no_license
vvanirudh/raytracer
77cdc54880089f4fe1fd5d9f66dc3bf670907a7d
f0b46b4ecab84e08fa7b40f3ba4cdc22cf5888f5
refs/heads/master
2020-12-30T20:05:43.993355
2014-02-10T17:23:02
2014-02-10T17:23:02
16,253,088
0
0
null
null
null
null
UTF-8
C++
false
false
379
h
Cone_t.h
#ifndef CONE_T_H #define CONE_T_H #include "Object_t.h" class Cone_t : public virtual Object_t { public: Point_t baseCenter; double baseRadius; double height; Vector_t axis; Cylinder_t(Point_t, double, double, Vector_t); bool intersect(Ray_t, double*, Point_t*); Vector_t getNormal(Point_t); /* http://tog.acm.org/resources/GraphicsGems/gemsiv/ray_cyl.c */ }; #endif
d6a1cd4f7b2c316b831de81f85fed812345020eb
7fa7be5bf3d68d5c24accb912408c4260f63835d
/Game/code/Image.h
a676cecfc2ba3177cc47f8a38f5792c2d5885261
[]
no_license
ssveta7ak/Asteroids
7e8aec2400fccf9ec115fa736babf6a175e60c1d
5b42417475428f6d5c56f27221231ba2af62b115
refs/heads/master
2023-05-26T23:09:09.540789
2021-06-12T19:28:47
2021-06-12T19:28:47
344,226,874
0
0
null
null
null
null
UTF-8
C++
false
false
961
h
Image.h
#pragma once #include "SDL.h" #include "SDL_image.h" #include <SDL_ttf.h> #include <cassert> #include <string> #include <windows.h> class Image { public: Image(); ~Image(); int width() const { return mWidth; } int height() const { return mHeight; } bool createTexture(const char* path, SDL_Renderer* renderer); void drawTexture(SDL_Renderer* renderer, const SDL_Rect& dest_rect); SDL_Texture* getTexture() const; void render(SDL_Renderer* renderer, const SDL_Rect& dest_rect, SDL_RendererFlip flip = SDL_FLIP_NONE, float angle = 0.0, SDL_Point* center = nullptr); // Creates image from font string bool createFromRenderedText(const char* textureText, SDL_Color textColor, int textSize, SDL_Renderer* renderer); private: SDL_Surface* mImage = nullptr; SDL_Texture* mTexture = nullptr; // Image dimensions int mWidth; int mHeight; };
d9735c4548c8ee147b1acf1fe94bb28012f9ece6
0e899957b663584c03e2a0cdc7ed7f2cf22f3d2a
/src/AirfoilViewer.cpp
3baed78a1bf386c66355ebbad7d0270c1b4d97c1
[ "MIT" ]
permissive
maxweis/FoilAnalyzer
69108a31bcf8de50e450a7c53cbc8c3ff61e3b63
1e519ea4334f690f285a78ff23f8749a46e402fd
refs/heads/master
2020-08-07T01:59:26.248351
2019-10-06T21:21:43
2019-10-06T21:21:43
213,251,404
0
0
MIT
2019-10-06T22:08:19
2019-10-06T22:08:19
null
UTF-8
C++
false
false
3,002
cpp
AirfoilViewer.cpp
#include "AirfoilViewer.h" ViewerPanel::ViewerPanel(wxWindow* parent) : wxPanel(parent, -1, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE){ // Sizer that controls the overall layout of the airfoil viewer avTopSizer = new wxBoxSizer(wxVERTICAL); // Drawing area for the airfoil plot avDrawArea = avTopSizer->Add(new wxPanel(this,7), wxEXPAND); // List to hold loaded airfoils wxListBox* airfoilListBox = new wxListBox(this, -1); avTopSizer->Add(airfoilListBox, 0, wxEXPAND); wxBoxSizer* buttonBox = new wxBoxSizer(wxHORIZONTAL); buttonBox->Add(new wxButton(this, BACK_ID, "Main Menu"), wxSizerFlags().Left()); avTopSizer->Add(buttonBox); this->SetSizer(avTopSizer); // Black Background SetBackgroundColour(wxColour(*wxBLACK)); // ------ Bind button events to functions ------ // Main Menu Button Connect(BACK_ID, wxEVT_BUTTON, wxCommandEventHandler(ViewerPanel::onViewerBackButton)); Connect(GetId(), wxEVT_PAINT, wxPaintEventHandler(ViewerPanel::onPaintEvent)); } wxBoxSizer* ViewerPanel::getTopSizer() { return avTopSizer; } enum { axesHORIZ = 0, axesVERT = 1 }; void ViewerPanel::onPaintEvent(wxPaintEvent& event) { wxPaintDC pdc(this); drawAxes(pdc); } void ViewerPanel::drawAxes(wxPaintDC& dc) { int w = avTopSizer->GetSize().GetWidth(); int h = avDrawArea->GetRect().GetHeight(); wxPoint top(60, 50); wxPoint bottom(60, h - 50); wxPoint left(20, h / 2); wxPoint right(w - 20, h / 2); wxPoint origin(60, h / 2); dc.SetPen(wxPen(*wxWHITE, 2)); dc.DrawLine(top,bottom); dc.DrawLine(left,right); drawTicks(dc, origin, top, bottom, axesVERT, 15); drawTicks(dc, origin, left, right, axesHORIZ, 23); } void ViewerPanel::drawTicks(wxDC& dc, wxPoint& origin, wxPoint& beg, wxPoint& end, int dir, int n){ dc.SetPen(wxPen(*wxWHITE, 1)); if (n < 1) return; int l = 0; int h = 0; if (dir == axesHORIZ) { l = end.x - beg.x; h = origin.x - beg.x; } else { l = end.y - beg.y; h = origin.y - beg.y; } if (l < 1) return; int a = l / n; for (int i = 0; i < n; i++) { if (dir == axesHORIZ) { int pos = beg.x + i * a + h; if (pos > beg.x + l) { pos -= l; } drawTick(dc, wxPoint(pos, beg.y), dir); } else { int pos = beg.y + i * a + h; if (pos > beg.y + l) { pos -= l; } drawTick(dc, wxPoint(beg.x, pos), dir); } } } void ViewerPanel::drawTick(wxDC& dc, wxPoint pos, int dir) { if (dir == axesHORIZ) { dc.DrawLine(pos.x, pos.y - 7, pos.x, pos.y + 7); } else dc.DrawLine(pos.x - 7, pos.y, pos.x + 7, pos.y); } AirfoilViewer::AirfoilViewer(wxWindow* parent) { initializeProgram(parent); } wxPanel* AirfoilViewer::getTopPanel() { return viewerPanel; } bool AirfoilViewer::initializeProgram(wxWindow* parent) { viewerPanel = new ViewerPanel(parent); if (viewerPanel) { show(false); return true; } return false; } void AirfoilViewer::show(bool show) { if (viewerPanel) { viewerPanel->Show(show); viewerPanel->Enable(show); } else return; // Add error reporting here }
ef09cb9c4a17b4dc939431400814d961c0c81506
8146d07d399d91774ab79c07de35fe1420f3fe99
/Csci 191 - Projects/Project/Project/src/GLInputs.cpp
4b6b1ac1663adb9e95ef11d5d640d1175d458c84
[]
no_license
ChaiseAllegra/SnackBoys
fda68c143d80ad177f871787b62044e11fee7c52
e302bca119ba578c5cf50e83b3d44d54effa0668
refs/heads/master
2021-04-12T11:02:50.628662
2018-03-27T00:26:01
2018-03-27T00:26:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,784
cpp
GLInputs.cpp
#include "GLInputs.h" #include <player.h> #include<GLModel.h> #include<collision.h> #include<box.h> Inputs::Inputs() { //ctor prev_Mouse_X =0; prev_Mouse_Y =0; Mouse_Translate=0; Mouse_Roatate=0; } bool leftPRESSED = FALSE; bool rightPRESSED = FALSE; Inputs::~Inputs() { //dtor } void Inputs::keyEnv(parallax* plx, float speed) { switch(wParam) { case VK_LEFT: //plx->Xmin -=speed; // plx->Xmax -=speed; break; case VK_RIGHT: // plx->Xmin +=speed; // plx->Xmax +=speed; break; case VK_UP: // plx->Ymin -=speed; // plx->Ymax -=speed; break; case VK_DOWN: // plx->Ymin +=speed; // plx->Ymax +=speed; break; } } void Inputs::keyPressed(Model* Mdl) { switch(wParam) { case VK_LEFT: Mdl->RotateX +=1.0; break; case VK_RIGHT: Mdl->RotateX -=1.0; break; case VK_DOWN: Mdl->RotateY -=1.0; break; case VK_UP: Mdl->RotateY +=1.0; break; case VK_ADD: Mdl->Zoom +=1.0; break; case VK_SUBTRACT: Mdl->Zoom -=1.0; break; } } void Inputs::keyUp(player* ply) { ply->actionTrigger =1; switch(wParam) { default:break; } } void Inputs::keyPressed(player* ply) { cout<<"jack "<<endl; return; } void Inputs::keyPressed(player* ply, Model* wallL,Model* wallR,Model* wallT) { box tmp1; tmp1.x = ply->playerHBox.x - 0.2; tmp1.y = ply->playerHBox.y - 0.2; tmp1.width = ply->playerHBox.width; tmp1.height = ply->playerHBox.height; if(wParam==VK_LEFT) { ply->actionTrigger =0; ply->verticies[0].x-=0.2; ply->verticies[1].x-=0.2; ply->verticies[2].x-=0.2; ply->verticies[3].x-=0.2; ply->playerUpdateHbox(); } if(wParam==VK_RIGHT) if(box_collision(ply->playerHBox,wallR->wallHBox)==false) { ply->actionTrigger =1; ply->verticies[0].x+=0.2; ply->verticies[1].x+=0.2; ply->verticies[2].x+=0.2; ply->verticies[3].x+=0.2; ply->playerUpdateHbox(); } else{ ply->actionTrigger =0; } /* switch(wParam) { case VK_LEFT: if(box_collision(tmp1,wallL->wallHBox)==false) { ply->actionTrigger = 1; if(!leftPRESSED) { float temp1, temp2, temp3, temp4; temp1 = ply->verticies[0].x; ply->verticies[0].x = ply->verticies[1].x; ply->verticies[1].x = temp1; temp2 = ply->verticies[0].y; ply->verticies[0].y = ply->verticies[1].y; ply->verticies[1].y = temp1; temp3 = ply->verticies[2].x; ply->verticies[2].x = ply->verticies[3].x; ply->verticies[3].x = temp3; temp4 = ply->verticies[2].y; ply->verticies[2].y = ply->verticies[3].y; ply->verticies[3].y = temp4; leftPRESSED = TRUE; rightPRESSED = FALSE; } ply->verticies[0].x -= 0.2; ply->verticies[1].x -= 0.2; ply->verticies[2].x -= 0.2; ply->verticies[3].x -= 0.2; ply->playerUpdateHbox(); } break; case VK_RIGHT: if(box_collision(ply->playerHBox,wallR->wallHBox)==false) { ply->actionTrigger = 1; if(!rightPRESSED){ float temp1, temp2, temp3, temp4; temp1 = ply->verticies[0].x; ply->verticies[0].x = ply->verticies[1].x; ply->verticies[1].x = temp1; temp2 = ply->verticies[0].y; ply->verticies[0].y = ply->verticies[1].y; ply->verticies[1].y = temp1; temp3 = ply->verticies[2].x; ply->verticies[2].x = ply->verticies[3].x; ply->verticies[3].x = temp3; temp4 = ply->verticies[2].y; ply->verticies[2].y = ply->verticies[3].y; ply->verticies[3].y = temp4; leftPRESSED = FALSE; rightPRESSED = TRUE; } ply->verticies[0].x += 0.2; ply->verticies[1].x += 0.2; ply->verticies[2].x += 0.2; ply->verticies[3].x += 0.2; ply->playerUpdateHbox(); } break; case VK_DOWN: break; case VK_UP: break; case VK_ADD: break; case VK_SUBTRACT: break; } */ } void Inputs::keyUP() { switch (wParam) { default: break; } } void Inputs::mouseEventDown(Model *Model, double x,double y) { prev_Mouse_X =x; prev_Mouse_Y =y; switch (wParam) { case MK_LBUTTON: Mouse_Roatate = true; break; case MK_RBUTTON: Mouse_Translate =true; break; case MK_MBUTTON: break; default: break; } } void Inputs::mouseEventUp() { Mouse_Translate =false; Mouse_Roatate =false; } void Inputs::mouseWheel(Model *Model,double Delta) { Model->Zoom += Delta/100; } void Inputs::mouseMove(Model *Model,double x,double y) { if(Mouse_Translate) { Model->Xpos += (x-prev_Mouse_X)/100; Model->Ypos -= (y-prev_Mouse_Y)/100; prev_Mouse_X =x; prev_Mouse_Y =y; } if(Mouse_Roatate) { Model->RotateY += (x-prev_Mouse_X)/3; Model->RotateX += (y-prev_Mouse_Y)/3; prev_Mouse_X =x; prev_Mouse_Y =y; } }
7af8693c34548d12250b26a9a34fc44e696f9076
045ad86b79d87f501cfd8252ecd8cc3c1ac960dd
/RxActor/SupervisorPolicy.h
b892dac2e9398bf5ddda456fc8b352d97e8ff518
[ "MIT" ]
permissive
intact-software-systems/cpp-software-patterns
9513e4d988342d88c100e4d85a0e58a3dbd9909e
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
refs/heads/master
2020-04-08T08:22:25.073672
2018-11-26T14:19:49
2018-11-26T14:19:49
159,176,259
1
0
null
null
null
null
UTF-8
C++
false
false
258
h
SupervisorPolicy.h
#pragma once #include "CommonDefines.h" namespace RxActor { struct SupervisorPolicy { SupervisorPolicy() { } SupervisorStrategy strategy_ = SupervisorStrategy::AllForOne; Policy::Criterion criterion_ = Policy::Criterion::All(); }; }
969d059f9eedfd2ae7a88e9ea52afa10d1eb05f5
9ff0eacffe2aef18a080386ccf886ed5f6ff1389
/jolly_banker.h
304fa806d6c62269b01d944c1c589e71594ba26d
[]
no_license
michzelinger/Program5
7aa48e6372b650d7d927341b0b74ef12b81ebcb7
2aecd9963f551b30ed9f1be3e1c8d35029cbe36d
refs/heads/master
2023-01-24T13:56:58.872497
2020-12-07T20:07:44
2020-12-07T20:07:44
319,430,601
0
0
null
null
null
null
UTF-8
C++
false
false
402
h
jolly_banker.h
#pragma once #include <queue> #include "binary_search_tree.h" #include "transaction.h" #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> class JollyBanker { public: JollyBanker(); ~JollyBanker(); bool ReadTransactions(); void ExecuteTransactions(); void Display(); private: queue<Transaction> transaction_list_; BinarySearchTree account_list_; };
ca2c5d7dd68538920ab00d4b29dac22487048223
1f24fe23bdc4ebfe7e588d5e962e16ec9fc99327
/Pow(x,n)/main.cpp
c42440693ddbd1b9ce39ffacbcb18569b1e59ac2
[]
no_license
AotY/Play_Interview
40a9efd3dbe9e16a2490ed98d1277df941efd6e7
868029e3cb195ccf254ab964eb73224719e38230
refs/heads/master
2020-03-22T11:05:48.926563
2018-10-14T07:37:51
2018-10-14T07:37:51
139,946,339
6
0
null
null
null
null
UTF-8
C++
false
false
251
cpp
main.cpp
#include <iostream> #include <cmath> class Solution { public: double myPow(double x, int n) { double res; res = pow(x, n); return res; } }; int main() { std::cout << "Hello, World!" << std::endl; return 0; }
65bdc7a6d5a7014c0fe4c2f8c29055fcb2e730de
201c2251a68337ba09c9b993fe1989d595125eb9
/leetcode/Remove All Adjacent Duplicates in String II.cpp
ab23fe5cec5e7c235221906363c917d6469eed17
[]
no_license
AhmedKhaledAK/problem-solving-training
92a928ca383d37abe493145d306e52cb08d5b4ef
54dd37aef981ab1a8d55e46cf9f57ab1426f6353
refs/heads/master
2022-03-16T07:42:28.785189
2022-02-12T19:54:54
2022-02-12T19:54:54
191,613,437
4
0
null
null
null
null
UTF-8
C++
false
false
445
cpp
Remove All Adjacent Duplicates in String II.cpp
class Solution { public: string removeDuplicates(string S, int k) { stack<int> st; for (int i = 0; i < S.size(); i++) { if (i == 0 || S[i] != S[i - 1]) { st.push(1); } else { if (++st.top() == k) { st.pop(); S.erase(i - k + 1, k); i -= k; } } } return S; } };
f71b4811ee071a6094a3bb4a20b5ea94bb93d8e7
2998093876315b60079a152e48c19bdd3834e893
/src/jaspinteg/src/last_error.cpp
2875f5f4f147dfa28f49580e97b87bb508b40973
[]
no_license
lorjnr/php-jasper-integration
0ea4b4615176c2b7847abbee32367bb132c6b337
652eeff11b3e418ee0f74e4579c2a316cd3db548
refs/heads/master
2021-01-10T22:00:15.383582
2010-03-08T23:26:51
2010-03-08T23:26:51
33,122,914
0
0
null
null
null
null
UTF-8
C++
false
false
5,751
cpp
last_error.cpp
#include "last_error.h" //-----------------------------------------------------------------------------------------------// //-- Globals ------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// CountedSp<LastErrorManager> ERROR_MNGR(new LastErrorManager()); //-----------------------------------------------------------------------------------------------// //-- Functions ----------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// void setLastError_I(const RETURN_CODE& error) { ERROR_MNGR->setLastError(error, pthread_self()); } //-----------------------------------------------------------------------------------------------// RETURN_CODE getLastError_I() { return ERROR_MNGR->getLastError(pthread_self()); } //-----------------------------------------------------------------------------------------------// //-- LastErrorItem ------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// LastErrorItem::LastErrorItem(const RETURN_CODE& code, const pthread_t& thread_id) : m_code(code), m_thread_id(thread_id) { } //-----------------------------------------------------------------------------------------------// LastErrorItem::~LastErrorItem() { } //-----------------------------------------------------------------------------------------------// RETURN_CODE LastErrorItem::getCode() const { return m_code; } //-----------------------------------------------------------------------------------------------// pthread_t LastErrorItem::getThreadId() const { return m_thread_id; } //-----------------------------------------------------------------------------------------------// void LastErrorItem::setCode(const RETURN_CODE& code) { m_code = code; } //-----------------------------------------------------------------------------------------------// //-- LastErrorItems -----------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// LastErrorItems::LastErrorItems() : m_items() { } //-----------------------------------------------------------------------------------------------// LastErrorItems::~LastErrorItems() { } //-----------------------------------------------------------------------------------------------// void LastErrorItems::add(LastErrorItem* item) { m_items.push_back(LastErrorItem_Sp(item)); } //-----------------------------------------------------------------------------------------------// bool LastErrorItems::sameThreadId(const int& threadId, const LastErrorItem_Sp& item) const { return ( threadId == item->getThreadId() ); } //-----------------------------------------------------------------------------------------------// const LastErrorItem_Sp& LastErrorItems::getByThreadId(const pthread_t& thread_id) const { LastErrorItemList::const_iterator it; for (it=m_items.begin(); it<m_items.end(); it++) { const LastErrorItem_Sp& item = *it; if ( sameThreadId(thread_id, item) ) { return item; } } throw JaspItemNotFoundExc(); } //-----------------------------------------------------------------------------------------------// LastErrorItem_Sp& LastErrorItems::getByThreadId(const pthread_t& thread_id) { LastErrorItemList::iterator it; for (it=m_items.begin(); it<m_items.end(); it++) { LastErrorItem_Sp& item = *it; if ( sameThreadId(thread_id, item) ) { return item; } } throw JaspItemNotFoundExc(); } //-----------------------------------------------------------------------------------------------// //-- LastErrorManager ---------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// LastErrorManager::LastErrorManager() : m_errors() { } //-----------------------------------------------------------------------------------------------// LastErrorManager::~LastErrorManager() { } //-----------------------------------------------------------------------------------------------// void LastErrorManager::setLastError(const RETURN_CODE& error, const pthread_t& thread_id) { LastErrorItem_Sp* pEi = 0; try { LastErrorItem_Sp& rEi = m_errors.getByThreadId(thread_id); pEi = &rEi; } catch ( JaspItemNotFoundExc ) { pEi = 0; } if (pEi == 0) { m_errors.add(new LastErrorItem(error, thread_id)); } else { LastErrorItem_Sp& rEi = *pEi; rEi->setCode(error); } } //-----------------------------------------------------------------------------------------------// RETURN_CODE LastErrorManager::getLastError(const pthread_t& thread_id) const { const LastErrorItem_Sp* pEi = 0; try { const LastErrorItem_Sp& rEi = m_errors.getByThreadId(thread_id); pEi = &m_errors.getByThreadId(thread_id); } catch ( JaspItemNotFoundExc ) { pEi = 0; } if (pEi == 0) { return JPI_NO_ERROR; } else { const LastErrorItem_Sp& rEi = *pEi; return rEi->getCode(); } }
e031904ef186a0dffeff7163829568dc1226e479
2bde780c6756eac2a4bab093796755db943675d4
/C++/class/friend_point_fun.cpp
49bc317a616f271ebc155432f103ca17beb50a2f
[]
no_license
boyuandong/C-Practice
d3399dea2b3623076bb8624656f78b2dfe13100f
5320f5382af102b6556d8c5124bcdb60dac4450d
refs/heads/main
2023-06-02T01:12:02.995508
2021-06-18T11:34:00
2021-06-18T11:34:00
358,832,654
0
0
null
null
null
null
UTF-8
C++
false
false
944
cpp
friend_point_fun.cpp
/* Friend Function Calculating the distance between two points by using the friend function */ #include<iostream> #include<cmath> using namespace std; class Point { private: double X, Y; public: Point(double xi, double yi) {X = xi; Y = yi;} double GetX() {return X;} double GetY() {return Y;} friend double Distance(Point &a, Point &b); }; double Distance(Point &a, Point &b) { double dx = a.X - b.X; double dy = a.Y - b.Y; return sqrt(dx * dy + dx * dy); } double Distance2(Point &a, Point &b) { double dx = a.GetX() - b.GetX(); double dy = a.GetY() - b.GetY(); return sqrt(dx * dx - dy * dy); } int main() { Point p1(3.0, 5.0), p2(4.0, 6.0); double d = Distance(p1, p2); // Call by friend function cout<<"This distance is "<<d<<endl; double d2 = Distance2(p1, p2); // Call by Getters in class cout<<"This distance is "<<d2<<endl; // can not get the private data }
3b1131cb883dc300349a72c9d89ec37b404e2525
02d9ea3dddc1b14b69d06c67f5973b98772fbcdc
/Legolas/BlockMatrix/IterationControler.hxx
5be8e66cc7a114ba8d8b81acf74815f73be5ad1d
[ "MIT" ]
permissive
LaurentPlagne/Legolas
6c656e4e7dd478a77a62fc76f7c1c9101f48f61c
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
refs/heads/master
2023-03-05T07:19:43.167114
2020-01-26T13:44:05
2020-01-26T13:44:05
338,055,388
0
1
null
null
null
null
UTF-8
C++
false
false
3,020
hxx
IterationControler.hxx
#ifndef __LEGOLAS_ITERATION_CONTROLER_HXX__ #define __LEGOLAS_ITERATION_CONTROLER_HXX__ #include "Legolas/Vector/Vector.hxx" namespace Legolas{ class IterationControler{ VirtualVector * XoldPtr_; int iterationNumber_; int maxIteration_; mutable double epsilon_; bool fixedIterationNumber_; double relativeDifference_; public: inline int iterationNumber( void ) const { return iterationNumber_ ; } inline int & getIterationNumber( void ) { return iterationNumber_ ; } inline double relativeDifference( void ) const { return relativeDifference_;} const int & maxIteration( void ) const {return maxIteration_;} int & maxIteration( void ) {return maxIteration_;} const double & epsilon( void ) const {return epsilon_;} double & epsilon( void ) {return epsilon_;} void modifyEpsilon( double epsilon ) const { epsilon_=epsilon ;} const bool & fixedIterationNumber( void ) const {return fixedIterationNumber_;} bool & fixedIterationNumber( void ) {return fixedIterationNumber_;} inline IterationControler( void ):XoldPtr_(0), iterationNumber_(0), maxIteration_(100), epsilon_(1.e-12), fixedIterationNumber_(false), relativeDifference_(-1.0) { } inline IterationControler(const IterationControler & ic):XoldPtr_(ic.XoldPtr_->clone()), iterationNumber_(ic.iterationNumber_), maxIteration_(ic.maxIteration_), epsilon_(ic.epsilon_), fixedIterationNumber_(ic.fixedIterationNumber_), relativeDifference_(ic.relativeDifference_) { } inline ~IterationControler( void ){ if (XoldPtr_){ delete XoldPtr_; XoldPtr_=0; } } template <class MATRIX> inline void initialize(const MATRIX & A, const VirtualVector & Xold){ iterationNumber_=0; maxIteration_=A.maxIteration(); epsilon_=A.epsilon(); fixedIterationNumber_=A.fixedIterationNumber(); if (maxIteration_<=1) fixedIterationNumber_=true; if (!fixedIterationNumber_){ //Ensure Xold_ ==Xold if (!XoldPtr_){ XoldPtr_=Xold.clone(); } else{ if (!XoldPtr_->sameShape(Xold)){ INFOS("TEMPORARY RESIZE..."); delete XoldPtr_; XoldPtr_=Xold.clone(); } else{ XoldPtr_->copy(Xold); } } } } inline bool end(const VirtualVector & X){ bool result=false; iterationNumber_++; if (iterationNumber_>=maxIteration_){ result=true; // INFOS("iterationNumber>=maxIteration"<< maxIteration_); } else{ if (!fixedIterationNumber_){ //returns relativeDiff=||X-Xold|| and Copy Xold=X relativeDifference_=XoldPtr_->relativeDiffAndCopy(X); if (relativeDifference_<epsilon_){ result=true; // INFOS("relativeDifference="<<relativeDifference_<<" (iterationNumber="<<iterationNumber_<<")"); } } } return result; } }; } #endif
8bf1fb6fba76aafb2f5c2f93396f6b27edea33a0
e10a6d844a286db26ef56469e31dc8488a8c6f0e
/fully_dynamic_submodular_maximization/dynamic_submodular_main.cc
932c14646d5199d73c56623b99f2b32296fc7e1f
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
Jimmy-INL/google-research
54ad5551f97977f01297abddbfc8a99a7900b791
5573d9c5822f4e866b6692769963ae819cb3f10d
refs/heads/master
2023-04-07T19:43:54.483068
2023-03-24T16:27:28
2023-03-24T16:32:17
282,682,170
1
0
Apache-2.0
2020-07-26T15:50:32
2020-07-26T15:50:31
null
UTF-8
C++
false
false
6,943
cc
dynamic_submodular_main.cc
// Copyright 2020 The Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The main file for running experiments // // compile this as C++14 (or later) #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <fstream> #include <iostream> #include <map> #include <memory> #include <random> #include <unordered_map> #include <unordered_set> #include <vector> #include "dynamic_submodular_algorithm.h" #include "graph.h" #include "graph_utility.h" #include "greedy_algorithm.h" #include "sieve_streaming_algorithm.h" #include "simple_greedy.h" #include "submodular_function.h" #include "utilities.h" using std::ifstream; using std::ostream; using std::pair; using std::unordered_set; using std::vector; template <class T> ostream& operator<<(ostream& s, const vector<T>& t) { for (const auto& x : t) s << x << " "; return s; } template <class T> ostream& operator<<(ostream& s, const unordered_set<T>& t) { for (const auto& x : t) s << x << " "; return s; } template <class T, class R> ostream& operator<<(ostream& s, const pair<T, R>& p) { return s << p.first << ' ' << p.second; } // // Experiments // // An experiment is a function that takes parameters: // - Submodular function // - Algorithm // - Any number of other parameters // And returns the (average) objective function value. // Window experiment: // Process elements one by one (in the universe-order), // at all times maintaining a window of size at most windowSize // return the average objective value. double windowExperiment(SubmodularFunction& sub_func_f, Algorithm& alg, int windowSize) { vector<double> values; windowSize = std::min(windowSize, static_cast<int>(sub_func_f.GetUniverse().size())); for (int i = 0; i < static_cast<int>(sub_func_f.GetUniverse().size()) + windowSize; ++i) { // There are more elements to insert. if (i < static_cast<int>(sub_func_f.GetUniverse().size())) { alg.Insert(sub_func_f.GetUniverse()[i]); } // We should start deleting elements when the window reaches them. if (i >= windowSize) { alg.Erase(sub_func_f.GetUniverse()[i - windowSize]); } values.push_back(alg.GetSolutionValue()); } // Returns average. return accumulate(values.begin(), values.end(), 0.0) / static_cast<double>(values.size()); } // An experiment where we first insert elements as they come in the universe, // then remove them largest-to-smallest and return the average objective value. double insertInOrderThenDeleteLargeToSmall(SubmodularFunction& sub_func_f, Algorithm& alg) { // Sort elements from largest marginal value to smallest vector<pair<double, int>> sorter; for (int e : sub_func_f.GetUniverse()) { sorter.emplace_back(sub_func_f.DeltaAndIncreaseOracleCall(e), e); SubmodularFunction::oracle_calls_--; } sort(sorter.begin(), sorter.end()); reverse(sorter.begin(), sorter.end()); vector<double> values; // First insert elements in arbitrary order (the order they come in the // universe). for (int e : sub_func_f.GetUniverse()) { alg.Insert(e); const double val = alg.GetSolutionValue(); values.push_back(val); } // Then delete elements in the order from largest to smallest. for (auto it : sorter) { alg.Erase(it.second); const double val = alg.GetSolutionValue(); values.push_back(val); } // Return average. return accumulate(values.begin(), values.end(), 0.0) / static_cast<double>(values.size()); } // Helper function that runs an experiment on a given submodular function, // a set of algorithms, and a set of k-values. template <typename Function, typename... Args> void runExperimentForAlgorithms( const Function& experiment, SubmodularFunction& sub_func_f, const vector<std::reference_wrapper<Algorithm>>& algs, const vector<int>& cardinality_ks, Args... args) { std::cout << "submodular function: " << sub_func_f.GetName() << "\n"; for (Algorithm& alg : algs) { std::cout << "now running " << alg.GetAlgorithmName() << "...\n"; vector<double> valuesPerK; vector<int64_t> oracleCallsPerK; for (int cardinality_k : cardinality_ks) { std::cerr << "running k = " << cardinality_k << std::endl; // Reseed reproducible randomness. RandomHandler::generator_.seed(); alg.Init(sub_func_f, cardinality_k); const int64_t oracleCallsAtStart = SubmodularFunction::oracle_calls_; double value = experiment(sub_func_f, alg, args...); // We could also pass k, but none of our experiments needs it // (that is, k was only needed to init the algorithm). valuesPerK.push_back(value); oracleCallsPerK.push_back(SubmodularFunction::oracle_calls_ - oracleCallsAtStart); // Simple trick, just to reduce memory usage. alg.Init(sub_func_f, cardinality_k); } std::cout << "k f\n"; for (int i = 0; i < static_cast<int>(cardinality_ks.size()); ++i) { std::cout << cardinality_ks[i] << " " << valuesPerK[i] << "\n"; } std::cout << std::endl; std::cout << "k OC\n"; for (int i = 0; i < static_cast<int>(cardinality_ks.size()); ++i) { std::cout << cardinality_ks[i] << " " << oracleCallsPerK[i] << "\n"; } std::cout << std::endl; } } int main() { RandomHandler::CheckRandomNumberGenerator(); SieveStreaming sieveStreaming; SimpleGreedy simpleGreedy; Greedy greedy; OurSimpleAlgorithm ourSimpleAlgorithmEps00(0.0); OurSimpleAlgorithm ourSimpleAlgorithmEps02(0.2); GraphUtility f_pokec("pokec"); // Potential values of cardinality constraint that can be used. const vector<int> from10to200 = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200}; // Potential values of cardinality constraint that can be used. const vector<int> from20to200 = {20, 40, 60, 80, 100, 120, 140, 160, 180, 200}; std::cout << "window experiment\n"; for (int windowSize : {2000000, 1300000}) { std::cout << "window size = " << windowSize << std::endl; runExperimentForAlgorithms( windowExperiment, f_pokec, {ourSimpleAlgorithmEps00, ourSimpleAlgorithmEps02, sieveStreaming}, from10to200, windowSize); } }
c181a5b275d9ca8488b7b03736fe3b8dc5231455
d6125fb9313bd89b40de90d3bbe1a17dcb452c1e
/src/Messages/StartDATCMsg.h
7674335a0510a58a21ee695356ab19a4cc271b02
[]
no_license
alejandroguillen/testbed_final
011d3820784026978b5047d9cec91c4b0fdaf304
354660ae99e99a7615c30f2709bc2817bab7e036
refs/heads/master
2021-01-19T21:28:39.538813
2015-05-06T08:13:30
2015-05-06T08:13:30
35,144,996
0
0
null
null
null
null
UTF-8
C++
false
false
1,496
h
StartDATCMsg.h
#ifndef START_DATC_MSG_H #define START_DATC_MSG_H #include "Message.h" class StartDATCMsg : public Message{ private: StartDATCMessage_t* internal_msg; public: ~StartDATCMsg(); StartDATCMsg(int fps, DetectorTypes_t det, double det_thr, DescriptorTypes_t desc, int desc_length, int max_feat, bool rotation_invariant, CodingChoices_t coding, bool transfer_kpt, bool transfer_scale, bool transfer_orientation, int num_feat_per_block, int num_cooperators); StartDATCMsg(StartDATCMessage_t* internal_message); void setFramesPerSecond(int fps); void setDetectorType(DetectorTypes_t det); void setDetectorThreshold(double det_thr); void setDescriptorType(DescriptorTypes_t desc); void setDescriptorLength(int desc_length); void setMaxNumFeat(int max_feat); void setRotationInvariant(bool rotation_invariant); void setCoding(CodingChoices_t coding); void setTransferKpt(bool transfer_kpt); void setTransferScale(bool transfer_scale); void setTransferOrientation(bool transfer_orientation); void setNumFeatPerBlocks(int n); // new void setNumCooperators(int n); int getFramesPerSecond(); DetectorTypes_t getDetectorType(); double getDetectorThreshold(); DescriptorTypes_t getDescriptorType(); int getDescriptorLength(); int getMaxNumFeat(); CodingChoices_t getCoding(); bool getTransferKpt(); bool getTransferScale(); bool getTransferOrientation(); int getNumFeatPerBlock(); int getNumCooperators(); int getBitStream(vector<uchar>& bitstream); }; #endif
700e506d7b8b84e545b444b2bed437216028d083
e7d2392115c82912cdcb80f5de518ad49934a08d
/lonk.cpp
f018ef2f4306bd00aafa877ffde4b3b329385be7
[]
no_license
JamirLeal/POO
d124177f80ce786de927451e66714110568817de
292552aa685dc6978f88871a97a404cece093a74
refs/heads/master
2020-04-22T02:59:33.003005
2019-02-13T15:31:07
2019-02-13T15:31:07
170,070,147
0
0
null
null
null
null
UTF-8
C++
false
false
9,539
cpp
lonk.cpp
// Jamir Leal Cota A00826275 #include <iostream> #include <fstream> #include <string> #include <stdlib.h> // /Users/jamirleal/Desktop/dar.txt // /Users/jamirleal/Desktop/dar2.txt using namespace std; // despliega el contenido del archivo en terminal void cat(string nombreArchivo){ ifstream archivo; string texto; //cout << "Escriba el nombre del archivo" << endl; //getline(cin, nombreArchivo); archivo.open(nombreArchivo.c_str(), ios::in); // ABRIMOS EL ARCHIVO if(archivo.fail()){ cout << "No se pudo abrir el archivo" << endl; // MENSAJE DE QUE NO SE PUDO ABRIR exit(1); // SALIDA DEL PROGRAMA } while(!archivo.eof()){ // COPIAMOS Y MOSTRAMOS CASA UNA DE LAS LINEAS EN PANTALLA getline(archivo, texto); cout << texto << endl; } archivo.close(); // CERRAMOS EL ARCHIVO } // void wc(string nombreArchivo){ int longitud = 0; ifstream archivo; string texto; // STRING DONDE SE GUARDARA EL CONTENIDO //cout << "Escriba el nombre del archivo" << endl; //getline(cin, nombreArchivo); archivo.open(nombreArchivo.c_str(), ios::in); // ABRIMOS EL ARCHIVO if(archivo.fail()){ cout << "No se pudo abrir el archivo" << endl; // SI NO SE ABRE NOS MANDARA ERROR exit(1); } getline(archivo, texto, '\0'); longitud = texto.length(); // OBTENEMOS LA LONGITUD DE CARACTERES cout << longitud << " caracteres" << endl; // MOSTRAMOS archivo.close(); // CERRAMOS EL ARCHIVO } void tail(string n, string nombreArchivo){ ifstream archivo; string texto; //cout << "Escriba el nombre del archivo" << endl; //getline(cin, nombreArchivo); archivo.open(nombreArchivo.c_str(), ios::in); if(archivo.fail()){ cout << "No se pudo abrir el archivo" << endl; exit(1); } getline(archivo, texto, '\0'); // PASAMOS TODO EL CONTENIDO A UNA STRING int j = 0; int *arr; for(int i = 0; i < texto.length(); i++){ // OBTENEMOS CUANTOS RENGLONES TIENE ('\n') if(texto[i] == '\n'){ j++; } } arr = new int [j]; // LE DAMOS ESE TAMAÑO AL ARREGLO DE LAS POSICIONES j=0; for(int i = 0; i < texto.length(); i++){ if(texto[i] == '\n'){ arr[j] = i; j++; } } int num = 0; for (int i = 0; i < n.length(); i++){ num = n[i] - 48;} //cout << "Introduzca la linea n" << endl; cout << texto.substr(arr[j-num]) << endl; } void cp(string nombreArchivo, string nombreArchivo2){ ifstream archivo; string texto; //cout << "Escriba el nombre del archivo" << endl; //getline(cin, nombreArchivo); archivo.open(nombreArchivo.c_str(), ios::in); if(archivo.fail()){ cout << "No se pudo abrir el archivo" << endl; exit(1); } getline(archivo, texto, '\0'); archivo.close(); // CIERRE ARCHIVO ofstream archivo2; //cout << "Escriba el nombre del archivo" << endl; //getline(cin, nombreArchivo2); archivo2.open(nombreArchivo2.c_str(), ios::in); if(archivo2.fail()){ cout << "No se pudo abrir el archivo" << endl; exit(1); } archivo2 << texto; // COPIAMOS LA INFO DEL STRING AL ARCHIVO archivo2.close(); // CIERRE ARCHIVO 2 } void grep(string nombreArchivo, string cadena){ ifstream archivo; // DECLARACION DE ARCHIVO string texto; //cout << "Introduzca el nombre del archivo" << endl; //getline(cin, nombreArchivo); // NOMBRE DEL ARCHIVO archivo.open(nombreArchivo.c_str(), ios::in); // ABRIMOS EL ARCHIVO if(archivo.fail()){ cout << "No se pudo abrir el archivo" << endl; exit(1); } getline(archivo, texto, '\0'); // LO COPIAMOS A UNA CADENA //cout << "Introduzca la cadena" << endl; //getline(cin, cadena); // INTRODUCIMOS LA CADENA int j = 0; int *arr; for(int i = 0; i <= texto.length(); i++){ if((texto[i] == '\n')||(texto[i]== '\0')){ j++; } } arr = new int [j]; // ARRAY DEL TAMAÑO CON LAS POSICIONES DE LOS RENGLONES ('\0') j=0; for(int i = 0; i <= texto.length(); i++){ // FOR QUE ASIGNA LAS POSICIONES DE CADA FINAL DEL RENGLON Y FINAL TOTAL if((texto[i] == '\n')||(texto[i]== '\0')){ arr[j] = i; j++; } } string renglon; // PARA UN SOLO RENGLON int n = 0; for(int contR = 0; contR < j; contR++){ // FOR QUE VA CONTANDO CADA RENGLON renglon = texto.substr(n, arr[contR] - n); if (renglon.find(cadena) != std::string::npos) { // SI SE REPITE LA PALABRA EN UN RENGLON cout << renglon << endl; } n = arr[contR] + 1; // ASIGNAMOS N AL SIGUIENTE INICIO DE RENGLON renglon = ""; // BORRAMOS EL CONTENIDO DE LA STRING } archivo.close(); } void diff(string nombreArchivo, string nombreArchivo2){ // despliega las líneas en donde los archivos son diferentes ifstream archivo; // DECLARACION DE ARCHIVO string texto; //cout << "Introduzca el nombre del archivo" << endl; //getline(cin, nombreArchivo); // NOMBRE DEL ARCHIVO archivo.open(nombreArchivo.c_str(), ios::in); // ABRIMOS EL ARCHIVO if(archivo.fail()){ cout << "No se pudo abrir el archivo" << endl; exit(1); } getline(archivo, texto, '\0'); // LO COPIAMOS A UNA CADENA ifstream archivo2; // DECLARACION DE ARCHIVO string texto2; //cout << "Introduzca el nombre del archivo 2" << endl; //getline(cin, nombreArchivo2); // NOMBRE DEL ARCHIVO archivo2.open(nombreArchivo2.c_str(), ios::in); // ABRIMOS EL ARCHIVO if(archivo2.fail()){ cout << "No se pudo abrir el archivo 2" << endl; exit(1); } getline(archivo2, texto2, '\0'); // LO COPIAMOS A UNA CADENA int j = 0; int *arr; for(int i = 0; i <= texto.length(); i++){ if((texto[i] == '\n')||(texto[i]== '\0')){ j++; } } arr = new int [j]; // ARRAY DEL TAMAÑO CON LAS POSICIONES DE LOS RENGLONES ('\0') j=0; for(int i = 0; i <= texto.length(); i++){ // FOR QUE ASIGNA LAS POSICIONES DE CADA FINAL DEL RENGLON Y FINAL TOTAL if((texto[i] == '\n')||(texto[i]== '\0')){ arr[j] = i; j++; } } int k = 0; int *arr2; for(int i = 0; i <= texto2.length(); i++){ if((texto2[i] == '\n')||(texto2[i]== '\0')){ k++; } } arr2 = new int [k]; // ARRAY DEL TAMAÑO CON LAS POSICIONES DE LOS RENGLONES ('\0') k=0; for(int i = 0; i <= texto2.length(); i++){ // FOR QUE ASIGNA LAS POSICIONES DE CADA FINAL DEL RENGLON Y FINAL TOTAL if((texto2[i] == '\n')||(texto2[i]== '\0')){ arr2[k] = i; k++; } } string renglon, renglon2; // PARA UN SOLO RENGLON int n = 0, n2 = 0; for(int contR = 0; contR < j; contR++){ // FOR QUE VA CONTANDO CADA RENGLON renglon = texto.substr(n, arr[contR] - n); renglon2 = texto2.substr(n2, arr2[contR] - n2); if (renglon != renglon2) { // SI SE REPITE LA PALABRA EN UN RENGLON cout << "linea " << contR << " archivo1 = " << renglon << "|" << " archivo2 = " << renglon2 << endl; } n = arr[contR] + 1; n2 = arr2[contR] + 1;// ASIGNAMOS N AL SIGUIENTE INICIO DE RENGLON renglon = ""; renglon2 = "";// BORRAMOS EL CONTENIDO DE LA STRING } archivo.close(); // CERRAMOS LOS ARCHIVOS archivo2.close(); } int main(int argc, const char* argv[]) { for(int i = 0; i < argc; i++) // EL NUMERO DE PARAMETROS QUE LEERA LA CONSOLA { cout << argv[i] << endl; } string utilidad = argv[1]; // LA FUNCION QUE QUEREMOS LLAMAR if(utilidad == "cat"){ //cout << "Escriba el nombre del archivo" << endl; string nombreDelArchivo = argv[2]; cat(nombreDelArchivo); } else if(utilidad == "wc"){ //cout << "Escriba el nombre del archivo" << endl; string nombreDelArchivo = argv[2]; wc(nombreDelArchivo); } else if(utilidad == "tail"){ //cout << "Escriba las ultimas lineas a mostrar" << endl; string n = argv[2]; //cout << "Escriba el nombre del archivo" << endl; string nombreDelArchivo = argv[3]; tail(n, nombreDelArchivo); } else if(utilidad == "cp"){ //cout << "Escriba el nombre del archivo" << endl; string nombreDelArchivo = argv[2]; //cout << "Escriba el nombre del archivo 2" << endl; string nombreDelArchivo2 = argv[3]; cp(nombreDelArchivo, nombreDelArchivo2); } else if(utilidad == "grep"){ //cout << "Escriba el nombre del archivo" << endl; string nombreDelArchivo = argv[2]; //cout << "Escriba la cadena" << endl; string cadena = argv[3]; grep(nombreDelArchivo, cadena); } else if(utilidad == "diff"){ //cout << "Escriba el nombre del archivo" << endl; string nombreDelArchivo = argv[2]; //cout << "Escriba el nombre del archivo 2" << endl; string nombreDelArchivo2 = argv[3]; diff(nombreDelArchivo, nombreDelArchivo2); } return 0; }
31483cba0ff1a665d0ff286e59b9980e28fedcd3
6926361d32b07133eee7b84f7a2049f925b39199
/src/SignalR/clients/cpp/test/signalrclient-e2e-tests/hub_connection_tests.cpp
89d1fade27dfee73e25623390faa632a637e8350
[ "Apache-2.0" ]
permissive
lyqcoder/AspNetCore
d0ed82460adfaf94dd9d656443cdf45ad7fe6fa2
6a6a870f0847d347e72443eda843969d0b46da94
refs/heads/master
2020-05-04T06:17:27.579794
2019-04-01T23:01:26
2019-04-02T04:43:30
179,002,699
1
1
Apache-2.0
2019-04-02T05:06:27
2019-04-02T05:06:25
null
UTF-8
C++
false
false
10,946
cpp
hub_connection_tests.cpp
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #pragma once #include "stdafx.h" #include <string> #include "cpprest/details/basic_types.h" #include "cpprest/json.h" #include "signalrclient/connection.h" #include "signalrclient/hub_connection.h" #include "signalrclient/signalr_exception.h" #include "../signalrclienttests/test_utils.h" extern std::string url; TEST(hub_connection_tests, connection_status_start_stop_start) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto weak_hub_conn = std::weak_ptr<signalr::hub_connection>(hub_conn); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(hub_conn->get_connection_state(), signalr::connection_state::connected); hub_conn->stop([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(hub_conn->get_connection_state(), signalr::connection_state::disconnected); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(hub_conn->get_connection_state(), signalr::connection_state::connected); } TEST(hub_connection_tests, send_message) { auto hub_conn = std::make_shared<signalr::hub_connection>(url + "custom", signalr::trace_level::all, nullptr); auto message = std::make_shared<std::string>(); auto received_event = std::make_shared<signalr::event>(); hub_conn->on("sendString", [message, received_event](const web::json::value& arguments) { *message = utility::conversions::to_utf8string(arguments.serialize()); received_event->set(); }); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); web::json::value obj{}; obj[0] = web::json::value(U("test")); hub_conn->send("invokeWithString", obj, [&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(received_event->wait(2000)); ASSERT_EQ(*message, "[\"Send: test\"]"); } TEST(hub_connection_tests, send_message_return) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto mre = manual_reset_event<web::json::value>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); web::json::value obj{}; obj[0] = web::json::value(U("test")); hub_conn->invoke("returnString", obj, [&mre](const web::json::value & value, std::exception_ptr exception) { if (exception) { mre.set(exception); } else { mre.set(value); } }); auto test = mre.get(); ASSERT_EQ(test.serialize(), U("\"test\"")); } TEST(hub_connection_tests, send_message_after_connection_restart) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto message = std::make_shared<std::string>(); auto received_event = std::make_shared<signalr::event>(); hub_conn->on("sendString", [message, received_event](const web::json::value& arguments) { *message = utility::conversions::to_utf8string(arguments.serialize()); received_event->set(); }); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); hub_conn->stop([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); web::json::value obj{}; obj[0] = web::json::value(U("test")); hub_conn->send("invokeWithString", obj, [&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(received_event->wait(2000)); ASSERT_EQ(*message, "[\"Send: test\"]"); } TEST(hub_connection_tests, send_message_empty_param) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto message = std::make_shared<std::string>(); auto received_event = std::make_shared<signalr::event>(); hub_conn->on("sendString", [message, received_event](const web::json::value& arguments) { *message = utility::conversions::to_utf8string(arguments.serialize()); received_event->set(); }); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); hub_conn->invoke("invokeWithEmptyParam", web::json::value::array(), [&mre](const web::json::value &, std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(received_event->wait(2000)); ASSERT_EQ(*message, "[\"Send\"]"); } TEST(hub_connection_tests, send_message_primitive_params) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto message = std::make_shared<std::string>(); auto received_event = std::make_shared<signalr::event>(); hub_conn->on("sendPrimitiveParams", [message, received_event](const web::json::value& arguments) { *message = utility::conversions::to_utf8string(arguments.serialize()); received_event->set(); }); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); web::json::value obj{}; obj[0] = web::json::value(5); obj[1] = web::json::value(21.05); obj[2] = web::json::value(8.999999999); obj[3] = web::json::value(true); obj[4] = web::json::value('a'); hub_conn->send("invokeWithPrimitiveParams", obj, [&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(received_event->wait(2000)); obj[0] = web::json::value(6); obj[1] = web::json::value(22.05); obj[2] = web::json::value(9.999999999); obj[3] = web::json::value(true); obj[4] = web::json::value::string(U("a")); ASSERT_EQ(*message, utility::conversions::to_utf8string(obj.serialize())); } TEST(hub_connection_tests, send_message_complex_type) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto message = std::make_shared<std::string>(); auto received_event = std::make_shared<signalr::event>(); hub_conn->on("sendComplexType", [message, received_event](const web::json::value& arguments) { *message = utility::conversions::to_utf8string(arguments.serialize()); received_event->set(); }); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); web::json::value obj{}; web::json::value person; web::json::value address; address[U("street")] = web::json::value::string(U("main st")); address[U("zip")] = web::json::value::string(U("98052")); person[U("address")] = address; person[U("name")] = web::json::value::string(U("test")); person[U("age")] = web::json::value::number(15); obj[0] = person; hub_conn->send("invokeWithComplexType", obj, [&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(received_event->wait(2000)); ASSERT_EQ(*message, "[{\"Address\":{\"Street\":\"main st\",\"Zip\":\"98052\"},\"Age\":15,\"Name\":\"test\"}]"); } TEST(hub_connection_tests, send_message_complex_type_return) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto mre = manual_reset_event<web::json::value>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); web::json::value obj{}; web::json::value person; web::json::value address; address[U("street")] = web::json::value::string(U("main st")); address[U("zip")] = web::json::value::string(U("98052")); person[U("address")] = address; person[U("name")] = web::json::value::string(U("test")); person[U("age")] = web::json::value::number(15); obj[0] = person; hub_conn->invoke("returnComplexType", obj, [&mre](const web::json::value & value, std::exception_ptr exception) { if (exception) { mre.set(exception); } else { mre.set(value); } }); auto test = mre.get(); ASSERT_EQ(test.serialize(), U("{\"Address\":{\"Street\":\"main st\",\"Zip\":\"98052\"},\"Age\":15,\"Name\":\"test\"}")); } TEST(hub_connection_tests, connection_id_start_stop_start) { auto hub_conn = std::make_shared<signalr::hub_connection>(url); auto weak_hub_conn = std::weak_ptr<signalr::hub_connection>(hub_conn); std::string connection_id; ASSERT_EQ(u8"", hub_conn->get_connection_id()); auto mre = manual_reset_event<void>(); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection_id = hub_conn->get_connection_id(); ASSERT_NE(connection_id, u8""); hub_conn->stop([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(hub_conn->get_connection_id(), connection_id); hub_conn->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_NE(hub_conn->get_connection_id(), u8""); ASSERT_NE(hub_conn->get_connection_id(), connection_id); connection_id = hub_conn->get_connection_id(); } //TEST(hub_connection_tests, mirror_header) //{ // auto hub_conn = std::make_shared<signalr::hub_connection>(url); // // signalr::signalr_client_config signalr_client_config{}; // auto headers = signalr_client_config.get_http_headers(); // headers[U("x-mirror")] = U("MirrorThis"); // signalr_client_config.set_http_headers(headers); // hub_conn->set_client_config(signalr_client_config); // // { // auto mirrored_header_value = hub_conn->start().then([&hub_conn]() // { // return hub_conn->invoke(U("mirrorHeader")); // }).get(); // ASSERT_EQ(U("MirrorThis"), mirrored_header_value.as_string()); // } // // hub_conn->stop().wait(); // // headers[U("x-mirror")] = U("MirrorThat"); // signalr_client_config.set_http_headers(headers); // hub_conn->set_client_config(signalr_client_config); // // { // auto mirrored_header_value = hub_conn->start().then([&hub_conn]() // { // return hub_conn->invoke(U("mirrorHeader")); // }).get(); // ASSERT_EQ(U("MirrorThat"), mirrored_header_value.as_string()); // } //}
c142c5dfad0e9c36d34413ef38c9ba2b6c3395e4
868c42a1c50be49af42f392769a4474d3e53f611
/OpenOVR/Reimpl/BaseSettings.cpp
954a38541e4ddb7a25899d4a8815b71daac3369d
[]
no_license
GXiaoyang/qrvr
1458efbc979cf4d56ac5e19e29876d14f99b2d94
902b9c79d834d3df6b43417f93c2f79acacc893b
refs/heads/master
2023-05-09T22:17:41.834044
2020-06-14T18:28:43
2020-06-14T18:28:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,732
cpp
BaseSettings.cpp
#include "stdafx.h" #define BASE_IMPL #include "BaseSettings.h" // #include "OpenVR/interfaces/IVRSettings_001.h" // #include "OpenVR/interfaces/IVRSettings_002.h" #include "Misc/Config.h" #include "BaseSystem.h" #include <string> #include <codecvt> // #include "OVR_CAPI_Audio.h" using namespace std; // namespace kk1 = vr::IVRSettings_001; // namespace kk = vr::IVRSettings_002; const char * BaseSettings::GetSettingsErrorNameFromEnum(EVRSettingsError eError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::GetSettingsErrorNameFromEnum" << std::endl; }); return g_pvrsettings->GetSettingsErrorNameFromEnum(eError); } bool BaseSettings::Sync(bool bForce, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::Sync" << std::endl; }); return g_pvrsettings->Sync(bForce, peError); } void BaseSettings::SetBool(const char * pchSection, const char * pchSettingsKey, bool bValue, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::SetBool" << std::endl; }); return g_pvrsettings->SetBool(pchSection, pchSettingsKey, bValue, peError); } void BaseSettings::SetInt32(const char * pchSection, const char * pchSettingsKey, int32_t nValue, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::SetInt32" << std::endl; }); return g_pvrsettings->SetInt32(pchSection, pchSettingsKey, nValue, peError); } void BaseSettings::SetFloat(const char * pchSection, const char * pchSettingsKey, float flValue, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::SetFloat" << std::endl; }); return g_pvrsettings->SetFloat(pchSection, pchSettingsKey, flValue, peError); } void BaseSettings::SetString(const char * pchSection, const char * pchSettingsKey, const char * pchValue, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::SetString" << std::endl; }); return g_pvrsettings->SetString(pchSection, pchSettingsKey, pchValue, peError); } bool BaseSettings::GetBool(const char * pchSection, const char * pchSettingsKey, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::GetBool" << std::endl; }); return g_pvrsettings->GetBool(pchSection, pchSettingsKey, peError); } int32_t BaseSettings::GetInt32(const char * pchSection, const char * pchSettingsKey, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::GetInt32" << std::endl; }); return g_pvrsettings->GetInt32(pchSection, pchSettingsKey, peError); } float BaseSettings::GetFloat(const char * pchSection, const char * pchSettingsKey, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::GetFloat" << std::endl; }); return g_pvrsettings->GetFloat(pchSection, pchSettingsKey, peError); } void BaseSettings::GetString(const char * pchSection, const char * pchSettingsKey, VR_OUT_STRING() char * pchValue, uint32_t unValueLen, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::GetString" << std::endl; }); return g_pvrsettings->GetString(pchSection, pchSettingsKey, pchValue, unValueLen, peError); } void BaseSettings::RemoveSection(const char * pchSection, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::RemoveSection" << std::endl; }); return g_pvrsettings->RemoveSection(pchSection, peError); } void BaseSettings::RemoveKeyInSection(const char * pchSection, const char * pchSettingsKey, EVRSettingsError * peError) { TRACE("BaseSettings", []() { getOut() << "BaseSettings::RemoveKeyInSection" << std::endl; }); return g_pvrsettings->RemoveKeyInSection(pchSection, pchSettingsKey, peError); }
167dbd2d7c22c53207cf904b28cd4c8ffa1eb55a
d41b90545b1d5a417cef4510e530a4b392e9f247
/source/src/eth32.cpp
11ff54499ee271cc8823a82b4d0b8e4e591c73cd
[]
no_license
annihil-com/eth32nix_resurrection
d36d47c85ea2cbcff04f03b8826864852e2f8eb6
b45c8e29cc60bcf778ef0420f9951d157706f9d0
refs/heads/master
2022-10-10T00:00:26.118732
2020-06-07T14:51:52
2020-06-07T14:51:52
268,081,021
1
0
null
null
null
null
UTF-8
C++
false
false
3,229
cpp
eth32.cpp
// ETH32 - an Enemy Territory cheat for windows // Copyright (c) 2007 eth32 team // www.cheatersutopia.com & www.nixcoders.org // lib constructor/destructor, various linux chores #include "eth32.h" #include <dlfcn.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> #include <strings.h> CDebug Debug; eth32_t eth32; #ifdef ETH32_PRELIM_OFFSETS bool offset_pmext = false; bool offset_cginit = false; #endif uint32 key_state[256]; void __attribute__ ((constructor)) eth32Main() { // fetch program name char link[PATH_MAX]; memset(link, 0, sizeof(link)); if (readlink("/proc/self/exe", link, sizeof(link)) <= 0) exit(1); // if exe crc32 matches known version of ET, go forward int i; Tools.initCrc32(); memset(&key_state, 0, sizeof(key_state)); #ifdef ETH32_DEBUG Debug.Init(); Debug.SetLogFile("/tmp/eth32.log"); #endif if ((i = Hook.isGameSupported(link)) >= 0) Tools.Init(i); } // a hack to prevent ET from swallowing core dumps __attribute__ ((visibility ("default"))) __sighandler_t signal(int __sig, __sighandler_t __handler) { typedef __sighandler_t (*signal_t)(int __sig, __sighandler_t __handler); static signal_t orig_signal = NULL; if (!orig_signal) orig_signal = (signal_t)dlsym(RTLD_NEXT, "signal"); return orig_signal(__sig, __handler); } #ifdef ETH32_PRELIM_OFFSETS __attribute__ ((visibility ("default"))) void *memset(void *s, int c, size_t n) { typedef void *(*memset_t)(void *s, int c, size_t n); static memset_t orig_memset = NULL; if (!orig_memset) orig_memset = (memset_t)dlsym(RTLD_NEXT, "memset"); if (offset_cginit){ uint32 offset = (uint32)s-(uint32)eth32.cg.module; if (n > 0x1c0000 && n < 0x2e8000) { Debug.Log("memset: possible 1024-sized cent found: 0x%x size=0x%x (0x%x)\n", offset, n, n/0x400); } if (n > 0x380000 && n < 0x5d0000) { Debug.Log("memset: possible 2048-sized cent found: %0x%x size=0x%x (0x%x)\n", offset, n, n/0x800); } } if (offset_pmext){ uint32 offset = (uint32)s-(uint32)eth32.cg.module; Debug.Log("memset: possible cg.pmext found: 0x%x size=0x%x", offset, n); } return orig_memset(s,c,n); } #endif void __attribute__ ((destructor)) eth32End(void) { Tools.Shutdown(); } typedef struct { uint32 Xkey; uint32 Vkey; } keyTable_t; keyTable_t key_table[] = { {XK_Escape, 0}, {XK_F5, 1}, {XK_F6, 2}, {XK_F7, 3}, {XK_F8, 4}, {XK_F9, 5}, {XK_F10, 6}, {XK_F11, 7}, {XK_F12, 8}, {XK_Left, 9}, {XK_Right, 10}, {XK_Insert, 11}, {0xffffff, 0} }; void UpdateKeyTable(uint32 key, int down) { int i; for(i=0; i<256; i++) { if (key_table[i].Xkey == key) { key_state[key_table[i].Vkey] = down; return; } if (key_table[i].Xkey == 0xffffff) return; } } uint32 GetAsyncKeyState(int key) { int i; for(i=0; i<256; i++) { if (key_table[i].Xkey == key){ int state = key_state[key_table[i].Vkey]; if (state) key_state[key_table[i].Vkey] = 0; return state; } if (key_table[i].Xkey == 0xffffff) return 0; } } // pv: shortcut for printing vec3_t's to precision 'n' char *pv(float *x, int n) { char buf[32]; sprintf(buf, "{%c.%if, %c.%if, %c.%if}", '%', n, '%', n, '%', n); sprintf(___buffer, buf, x[0], x[1], x[2]); return ___buffer; }
94208471d975b334866662c95c1f25fac53d5436
56ee04007eac69701f0bb4421046eb558b24f6d6
/0templates/fastio.cpp
66385eac9a708ba0b098ed31480cdd22d47b93a6
[]
no_license
tsuba3/atcoder
e5789515d96079a386843f744f0cf594ec663a24
d397e98686cae982b431c098ec288d2994c33152
refs/heads/master
2021-07-01T21:31:45.429120
2021-02-20T13:40:24
2021-02-20T13:40:24
224,573,527
0
0
null
null
null
null
UTF-8
C++
false
false
4,698
cpp
fastio.cpp
// begin fast io template <typename IStream = decltype(cin), typename OStream = decltype(cout)> struct FastIO { char *buf, *OUT, *out; OStream& os; FastIO(size_t input_size = 1e7, size_t output_size = 1e7): os(cout) { buf = new char[input_size]; OUT = new char[output_size]; out = OUT; ios::sync_with_stdio(false); cin.tie(nullptr); cin.read(buf, input_size); } FastIO(IStream& in, OStream& out, size_t input_size = 1e7, size_t output_size = 1e7): os(out) { buf = new char[input_size]; OUT = new char[output_size]; this-> out = OUT; in.read(buf, input_size); } ~FastIO() { os.write(OUT, out - OUT); } char readc() { return *buf++; } template<typename T> void readui(T &n) { n = 0; char c = readc(); for (; '0' <= c && c <= '9'; c = readc()) n = 10 * n + c - '0'; } template<typename T> void readi(T &n) { bool negative = false; if (*buf == '-') negative = true, buf++; readui(n); if (negative) n = -n; } template<typename T> void readuf(T &x) { x = 0; T y = 0; int z = 0; char c = readc(); for (; '0' <= c && c <= '9'; c = readc()) x = 10 * x + c - '0'; if (buf[-1] == '.') for (; '0' <= c && c <= '9'; c = readc(), ++z) y = 10 * y + c - '0'; x += y / pow(10, z); } template<typename T> void readf(T &x) { bool negative = false; if (*buf == '-') negative = true, buf++; readuf(x); if (negative) x = -x; } string_view reads() { const char *begin = buf; char c; while (c = readc(), c >= '!') {} return string_view(begin, buf - begin - 1); } string_view readline() { const char *begin = buf; while (readc() != '\n') {} return string_view(begin, buf - begin - 1); } void writec(const char c) { *out++ = c; } void writes(const string& s) { memcpy(out, s.c_str(), s.size()); out += s.size(); } void writes(const string_view& s) { memcpy(out, s.data(), s.size()); out += s.size(); } constexpr static char digit_pairs[] = { "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899" }; template<typename T> void writeui(T n) { if (n == 0) { writec('0'); return; } int size; if (n >= 1e12) { if (n >= 1e16) { if (n >= 1e18) { if (n >= 1e19) size = 20; else size = 19; } else { if (n >= 1e17) size = 18; else size = 17; } } else { if (n >= 1e14) { if (n >= 1e15) size = 16; else size = 15; } else { if (n >= 1e13) size = 14; else size = 13; } } } else if (n >= 1e4) { if (n >= 1e8) { if (n >= 1e10) { if (n >= 1e11) size = 12; else size = 11; } else { if (n >= 1e9) size = 10; else size = 9; } } else { if (n >= 1e6) { if (n >= 1e7) size = 8; else size = 7; } else { if (n >= 1e5) size = 6; else size = 5; } } } else { if (n >= 1e2) { if (n >= 1e3) size = 4; else size = 3; } else { if (n >= 1e1) size = 2; else size = 1; } } char *c = out + size; out += size; while (n >= 100) { int x = n % 100; n /= 100; *--c = digit_pairs[2 * x + 1]; *--c = digit_pairs[2 * x]; } while (n > 0) { *--c = '0' + (n % 10); n /= 10; } } template<typename T> void writei(T n) { if (n < 0) { writec('-'); writeui(-n); } else { writeui(n); } } }; // end fast io
4f6c60a8efe22fdb22b6f3f4ac936c606231bae1
9eb2eb4de471b6c522ecb6e11bd1d10ee3bf1c29
/src/gigablast/TopTree.h
02e08ce007c930758168185487e064a41c10df7d
[ "Apache-2.0" ]
permissive
fossabot/kblast
6df5a5c6d4ae708a6813963f0dac990d94710a91
37b89fd6ba5ce429be5a69e2c6160da8a6aa21e6
refs/heads/main
2023-07-25T04:06:20.527449
2021-09-08T04:15:07
2021-09-08T04:15:07
404,208,031
1
0
Apache-2.0
2021-09-08T04:15:02
2021-09-08T04:15:01
null
UTF-8
C++
false
false
4,814
h
TopTree.h
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2000-2014 Matt Wells // Copyright 2004-2013 Gigablast, Inc. // Copyright 2013 Web Research Properties, LLC // // 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. // . class used to hold the top scoring search results // . filled by IndexTable.cpp // . used by Msg38 to get cluster info for each TopNode // . used by Msg39 to serialize into a reply #ifndef _TOPTREE_H_ #define _TOPTREE_H_ #include "Clusterdb.h" // SAMPLE_VECTOR_SIZE, 48 bytes for now //#include "IndexTable2.h" // score_t definition #include "RdbTree.h" class TopNode { public: //unsigned char m_bscore ; // bit #6(0x40) is on if has all explicitly // do not allow a higher-tiered node to outrank a lower that has // bit #6 set, under any circumstance char m_depth ; // Msg39 now looks up the cluster recs so we can do clustering // really quick on each machine, assuming we have a full split and the // entire clusterdb is in our local disk page cache. char m_clusterLevel; key_t m_clusterRec; // no longer needed, Msg3a does not need, it has already //unsigned char m_tier ; float m_score ; long long m_docId; // option for using int scores long m_intScore; // clustering info //long m_kid ; // result from our same site below us //unsigned long m_siteHash ; //unsigned long m_contentHash ; //long m_rank ; // the lower 64 bits of the cluster rec, used by Msg51, the new // class for doing site clustering //uint64_t m_clusterRec; // . for getting similarity between titleRecs // . this is so big only include if we need it //long m_vector [ VECTOR_SIZE ]; // tree info, indexes into m_nodes array long m_parent; long m_left; // kid long m_right; // kid //long long getDocId ( ); //long long getDocIdForMsg3a ( ); }; class TopTree { public: TopTree(); ~TopTree(); // free mem void reset(); // pre-allocate memory bool setNumNodes ( long docsWanted , bool doSiteClustering ); // . add a node // . get an empty first, fill it in and call addNode(t) long getEmptyNode ( ) { return m_emptyNode; }; // . you can add a new node // . it will NOT overwrite a node with same bscore/score/docid // . it will NOT add if bscore/score/docid < m_tail node // otherwise it will remove m_tail node if // m_numNodes == m_numUsedNodes bool addNode ( TopNode *t , long tnn ); long getLowNode ( ) { return m_lowNode ; }; // . this is computed and stored on demand // . WARNING: only call after all nodes have been added! long getHighNode ( ) ; float getMinScore ( ) { if ( m_lowNode < 0 ) return -1.0; return m_nodes[m_lowNode].m_score; } long getPrev ( long i ); long getNext ( long i ); bool checkTree ( bool printMsgs ) ; long computeDepth ( long i ) ; void deleteNodes ( ); bool hasDocId ( long long d ); TopNode *getNode ( long i ) { return &m_nodes[i]; } // ptr to the mem block TopNode *m_nodes; long m_allocSize; // optional dedup vectors... very big, VECTOR_REC_SIZE-12 bytes each // (512) so we make this an option //long *m_sampleVectors; //bool m_useSampleVectors; // which is next to be used, after m_nextPtr long m_numUsedNodes; // total count long m_numNodes; // the top of the tree long m_headNode; // . always keep track of the high and low nodes // . IndexTable.cpp likes to replace the low-scoring tail often // . Msg39.cpp likes to print out starting at the high-scorer // . these are indices into m_nodes[] array long m_lowNode; long m_highNode; // use this to set "t" in call to addNode(t) long m_emptyNode; bool m_pickRight; float m_vcount ; long m_cap ; float m_partial ; bool m_doSiteClustering; bool m_useIntScores; long m_docsWanted; long m_ridiculousMax; char m_kickedOutDocIds; //long long m_lastKickedOutDocId; long m_domCount[256]; // the node with the minimum "score" for that domHash long m_domMinNode[256]; // an embedded RdbTree for limiting the storing of keys to X // keys per domHash, where X is usually "m_ridiculousMax" RdbTree m_t2; private: void deleteNode ( long i , uint8_t domHash ) ; void setDepths ( long i ) ; long rotateLeft ( long i ) ; long rotateRight ( long i ) ; }; #endif
4bab7928a09fd9c6f1b7cffe12f84943e1d6ab76
c3f2ed9a8cd963041fd62161336d3dd0eb352ee7
/HelloDll/src/main.cpp
382ebc86dbb1846d9ce23fec777b1ea78a5cdb2f
[]
no_license
etheaven/CMake_HelloDll
1c40ae0ddf424e32a40ea81a413e567e4b148eb5
a9399913c7cde6b66cdf5d9f1db0f37c359b0e47
refs/heads/master
2021-01-21T01:25:47.844182
2017-08-31T18:53:58
2017-08-31T18:53:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
main.cpp
#include <cstdio> #include <iostream> #include <Windows.h> extern "C" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: MessageBox(NULL, "Abcd", "Test", 0); break; } return TRUE; }
852a77ff38e314607d563fe0273a1daebfed60c8
2b0ff7f7529350a00a34de9050d3404be6d588a0
/056_選單與工具列/01_Menu控制/方法3/選單切換與Title完全修改外加控制選單內選項是否可以執行/kkkkDoc.cpp
4c6e9005bbcae04bad8a40a0c4c46944eb86ca26
[]
no_license
isliulin/jashliao_VC
6b234b427469fb191884df2def0b47c4948b3187
5310f52b1276379b267acab4b609a9467f43d8cb
refs/heads/master
2023-05-13T09:28:49.756293
2021-06-08T13:40:23
2021-06-08T13:40:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,702
cpp
kkkkDoc.cpp
// kkkkDoc.cpp : implementation of the CKkkkDoc class // #include "stdafx.h" #include "kkkk.h" #include "kkkkDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CKkkkDoc IMPLEMENT_DYNCREATE(CKkkkDoc, CDocument) BEGIN_MESSAGE_MAP(CKkkkDoc, CDocument) //{{AFX_MSG_MAP(CKkkkDoc) ON_COMMAND(ID_test, Ontest) ON_COMMAND(ID_t, Ont) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CKkkkDoc construction/destruction CKkkkDoc::CKkkkDoc() { // TODO: add one-time construction code here } CKkkkDoc::~CKkkkDoc() { } BOOL CKkkkDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) SetTitle("test"); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CKkkkDoc serialization void CKkkkDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CKkkkDoc diagnostics #ifdef _DEBUG void CKkkkDoc::AssertValid() const { CDocument::AssertValid(); } void CKkkkDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CKkkkDoc commands void CKkkkDoc::Ontest() { // TODO: Add your command handler code here } void CKkkkDoc::Ont() { // TODO: Add your command handler code here }
541630395f54b3edf1a6236345683cc9f9500d7e
5b4795642fd09154c10d343836b0a1aa61f77ae8
/libraries/TINAH/src/TINAH_Servo.h
c142fcbf3cd05877b603b26d7373b0f4e14289e3
[]
no_license
ENPH253/arduino-tinah
162abb066d06d54438097515bb068288951adfb6
ef2dafec935b3a46038f67ac32dd3e228bb6190c
refs/heads/master
2020-03-17T04:45:59.180646
2018-07-31T07:24:30
2018-07-31T07:32:51
133,288,174
1
0
null
null
null
null
UTF-8
C++
false
false
1,641
h
TINAH_Servo.h
#ifndef TINAH_SERVO_H #define TINAH_SERVO_H #include <avr/interrupt.h> #include <Arduino.h> #define MAX_SERVO_CHANNELS (8U) /* don't change! */ #define MAX_SERVO_ANGLE (180U) namespace TINAH { class Servo { public: /** * @brief constructs a servo object that is not yet attached to the pin * * @param pin If provided, the object will automatically attach to this pin * on the first use. */ Servo(uint8_t pin = 0xFF); /** * @brief Enables the servo signal output on the given pin. * * @param pin The Arduino pin number to use. * * @returns true if the pin is valid and attaching was successful. */ uint8_t attach(uint8_t pin); /** * @brief Enables the servo signal output. * * Uses the most recently used pin, or the one specified in the constructor * if attach(pin) has never been used. * * @returns true if the pin is valid and attaching was successful. */ uint8_t attach(void); /** * @brief Disables the servo signal output, should make the servo go "limp". */ void detach(void); /** * @brief Returns true if the servo signal is currently enabled. */ bool attached(void); /** * @brief Sets the servo output to the given angle * * Attaches the servo object if it was not already attached. * * Using this doesn't always correspond to the proper value in degrees * if you are using a servo with a more limited range, or one with * different pulse timing specifications. * * @param angle in degrees */ void write(uint16_t angle); private: uint8_t pin; uint8_t channel; static uint8_t timerRunning; static uint8_t channelsUsed; }; } #endif
bc16e4545eafbb47ea3d9a052874a7274bcb5985
9c6cd28abbe3bddbf48fa56526be6d07f0b254b0
/pingkv/src/server/kv_worker.h
184dfe48d97f49fffa61cad95626dfca36e91f57
[]
no_license
liusheng1985/pingkv
eeea108a5bcd21b0652a41733f78cb96af588fd2
a8186dfc30829d359e4567ed970eaf5979302e02
refs/heads/master
2021-01-19T00:37:06.955740
2016-11-07T13:28:36
2016-11-07T13:28:36
73,080,042
2
0
null
null
null
null
UTF-8
C++
false
false
1,169
h
kv_worker.h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: kv_worker.h * Author: liusheng * * Created on 2016年7月12日, 下午2:02 */ #ifndef KV_WORKER_H #define KV_WORKER_H #include "../tool/kv_base.h" #include "../index/kv_index.h" #include "kv_work_queue.h" using std::cout; using std::endl; namespace pingkv { class kv_worker: public kv_base { private: int _file_id; std::string _db_name; std::string _data_file_name; kv_work_queue* _req_buf; kv_work_queue* _res_buf; kv_index* _idx; kv_work* _err_result(const string& err); kv_work* _make_result(const int flag, char* const field1, const int len1, char* const field2, const int len2); int _get_work(kv_work** w); void _put_res(int fd, kv_work* w); public: kv_worker(const std::string& db_name, int file_id, const std::string& data_file_name, bool create, kv_work_queue* request_buf, kv_work_queue* resault_buf); virtual ~kv_worker(); void work(); }; } #endif /* KV_WORKER_H */
7b57af4dac1267f80e889f73bc16fec1e5f2decc
c39862dcbc5b9ad65f582752bcfd0c5eb9be463e
/dev/external/wxWidgets-3.1.0/include/wx/univ/statusbr.h
fe39b05f38b3deb41d79e06cfc4f69c11fd53b94
[ "MIT" ]
permissive
rexdex/recompiler
5f1138adf5d02a052c8b37c290296d5cf5faadc2
7cd1d5a33d6c02a13f972c6564550ea816fc8b5b
refs/heads/master
2023-08-16T16:24:37.810517
2022-02-12T21:20:21
2022-02-12T21:20:21
81,953,901
1,714
120
MIT
2022-02-12T21:20:22
2017-02-14T14:32:17
C++
UTF-8
C++
false
false
3,211
h
statusbr.h
/////////////////////////////////////////////////////////////////////////////// // Name: wx/univ/statusbr.h // Purpose: wxStatusBarUniv: wxStatusBar for wxUniversal declaration // Author: Vadim Zeitlin // Modified by: // Created: 14.10.01 // Copyright: (c) 2001 SciTech Software, Inc. (www.scitechsoft.com) // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_UNIV_STATUSBR_H_ #define _WX_UNIV_STATUSBR_H_ #include "wx/univ/inpcons.h" #include "wx/arrstr.h" // ---------------------------------------------------------------------------- // wxStatusBarUniv: a window near the bottom of the frame used for status info // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxStatusBarUniv : public wxStatusBarBase { public: wxStatusBarUniv() { Init(); } wxStatusBarUniv(wxWindow *parent, wxWindowID id = wxID_ANY, long style = wxSTB_DEFAULT_STYLE, const wxString& name = wxPanelNameStr) { Init(); (void)Create(parent, id, style, name); } bool Create(wxWindow *parent, wxWindowID id = wxID_ANY, long style = wxSTB_DEFAULT_STYLE, const wxString& name = wxPanelNameStr); // implement base class methods virtual void SetFieldsCount(int number = 1, const int *widths = NULL) wxOVERRIDE; virtual void SetStatusWidths(int n, const int widths[]) wxOVERRIDE; virtual bool GetFieldRect(int i, wxRect& rect) const wxOVERRIDE; virtual void SetMinHeight(int height) wxOVERRIDE; virtual int GetBorderX() const wxOVERRIDE; virtual int GetBorderY() const wxOVERRIDE; // wxInputConsumer pure virtual virtual wxWindow *GetInputWindow() const wxOVERRIDE { return const_cast<wxStatusBar*>(this); } protected: virtual void DoUpdateStatusText(int i) wxOVERRIDE; // recalculate the field widths void OnSize(wxSizeEvent& event); // draw the statusbar virtual void DoDraw(wxControlRenderer *renderer) wxOVERRIDE; // tell them about our preferred height virtual wxSize DoGetBestSize() const wxOVERRIDE; // override DoSetSize() to prevent the status bar height from changing virtual void DoSetSize(int x, int y, int width, int height, int sizeFlags = wxSIZE_AUTO) wxOVERRIDE; // get the (fixed) status bar height wxCoord GetHeight() const; // get the rectangle containing all the fields and the border between them // // also updates m_widthsAbs if necessary wxRect GetTotalFieldRect(wxCoord *borderBetweenFields); // get the rect for this field without ani side effects (see code) wxRect DoGetFieldRect(int n) const; // common part of all ctors void Init(); private: // the current status fields strings //wxArrayString m_statusText; // the absolute status fields widths wxArrayInt m_widthsAbs; wxDECLARE_DYNAMIC_CLASS(wxStatusBarUniv); wxDECLARE_EVENT_TABLE(); WX_DECLARE_INPUT_CONSUMER() }; #endif // _WX_UNIV_STATUSBR_H_
9b524cbbbdd0bd46d3ed36960f34f897f41c036f
4b5a631af6e3215424a26764b7b6c9d5366b68d5
/AI/evaluate.hpp
9281804a5df61bd88f489b53b262bfeb7450e756
[]
no_license
adidvar/Chess-app
a02370428c121c99d124593ef9b37f6e838a8425
e136ed2edbdb5226b34b99875d9d18d6e306ef87
refs/heads/master
2023-08-08T19:29:24.320021
2023-08-01T12:21:08
2023-08-01T12:21:08
208,478,893
0
0
null
null
null
null
UTF-8
C++
false
false
872
hpp
evaluate.hpp
#ifndef EVALUATE_HPP #define EVALUATE_HPP #include <string> #include "bitboard.hpp" class Evaluate { using ScoreType = int; public: Evaluate(); Evaluate(ScoreType value); bool operator<(const Evaluate value) const; bool operator>(const Evaluate value) const; bool operator<=(const Evaluate value) const; bool operator>=(const Evaluate value) const; bool operator==(const Evaluate value) const; bool operator!=(const Evaluate value) const; Evaluate operator-() const; Evaluate operator-(const Evaluate value) const; static Evaluate Win(int depth); static Evaluate Lose(int depth); static Evaluate Tie(); static Evaluate Value(const BitBoard &board, Color color); static Evaluate Max(); static Evaluate Min(); static ScoreType FigurePrice(Figure figure); std::string ToString() const; private: ScoreType value_; }; #endif
133b0314e25a3ec2deb817e6dbec389d4f3ea6d5
624a1c8acca88c746af2d14d93205599b28e73d7
/source/thsolver.cpp
6db5d9dcd91242c7df90899982ad50671685d486
[ "MIT" ]
permissive
danolivo/avd
107630bc177c37bd7607addcd1b902f3b862b8d1
223e65cc98c4250856e17e14dff5607277010ed4
refs/heads/master
2020-03-19T03:34:22.994924
2018-06-04T17:37:49
2018-06-04T17:37:49
135,740,506
0
0
null
null
null
null
UTF-8
C++
false
false
7,585
cpp
thsolver.cpp
#include <tdma.h> #include <thsolver.h> #include <boundary.h> #include <cstring> #define NEED_SMALLER_STEP (1) #define TIMESTEP_MIN_CALCS (2) CTHSolver::CTHSolver(thm_t* thm) { assert(thm != 0); this->thm = thm; this->TIMESTEP_MIN = STD_TIMESTEP_MIN; this->TIMESTEP_MAX = STD_TIMESTEP_MAX; this->T[0] = thm->T[thm->fcnum]; for (int i=1; i< CELLS_MAX_NUM; i++) { T[i] = -1.; l[i] = -1.; c[i] = -1.; r[i] = -1.; qv[i] = 0.; } } CTHSolver::~CTHSolver() { } solve_result_t CTHSolver::Solve(double time) { sres.QLconv = 0.; sres.QLrad = 0.; sres.QRconv = 0.; sres.QRrad = 0.; sres.dHeatQty = 0.; double dHeatQty = 0.; double residual = 0.; int counter = 0; double dt = time - thm->CURRENT_TIME; Prepare(); double TIMESTEP = time - thm->CURRENT_TIME; bool isPrintWTmin = false; assert(time - thm->CURRENT_TIME > 0.); while (thm->CURRENT_TIME < time) { double HeatQty_Pre = Pre(thm->CURRENT_TIME); double twlk = Twl(); double twrk = Twr(); int res = DoIteration(TIMESTEP); if (res == NEED_SMALLER_STEP) { Prepare(); if (TIMESTEP > TIMESTEP_MIN) TIMESTEP = TIMESTEP/2.; continue; } else if ((res == SUCCESS) || (res == TIMESTEP_MIN_CALCS)) { thm->CURRENT_TIME += TIMESTEP; counter++; dHeatQty = Post(thm->CURRENT_TIME)-HeatQty_Pre; /* Calculate heat quantity at boundaries */ double ql; if (thm->LBC->type() != 1) { // Second-order left BC BC_t bc = thm->LBC->GetBC(thm->CURRENT_TIME-TIMESTEP); double qlconv, qlrad; qlconv = bc.acp*(bc.Ie-bc.Iw); sres.QLconv+= qlconv*TIMESTEP; qlrad = (-bc.eps*5.67E-08*(pow(twlk, 4.)+4*pow(twlk, 3.)*(Twl()-twlk))); sres.QLrad += qlrad*TIMESTEP; ql = qlconv+qlrad; } else ql = 2*(twlk-T[1])*l[1]/w[1]; double qr; if (thm->RBC->type() != 1) { // Second-order left BC BC_t bc = thm->RBC->GetBC(thm->CURRENT_TIME-TIMESTEP); double qrconv, qrrad; qrconv = bc.acp*(bc.Ie-bc.Iw); sres.QRconv+= qrconv*TIMESTEP; qrrad = (-bc.eps*5.67E-08*(pow(twrk, 4.)+4*TIMESTEP*pow(twrk, 3.)*(Twr()-twrk)/TIMESTEP)); sres.QRrad += qrrad*TIMESTEP; qr = qrconv+qrrad; } else qr = 2*(twrk-T[SIZE-2])*l[SIZE-2]/w[SIZE-2]; sres.dHeatQty += (ql+qr)*TIMESTEP-dHeatQty; } else assert(0 || !printf("[EE]: Unknown result value: %d\n", res)); TIMESTEP = min(TIMESTEP*1.1, TIMESTEP_MAX); TIMESTEP = min(TIMESTEP, time-thm->CURRENT_TIME); } sres.dHeatQty/=(sres.QLconv+sres.QLrad); sres.LAST_TIMESTEP = max(dt/counter, STD_TIMESTEP_MIN); TIMESTEP_MIN = sres.LAST_TIMESTEP; return sres; } void CTHSolver::Prepare() { assert(thm->lcnum < CELLS_MAX_NUM+2); assert(thm->fcnum >= 0); SIZE = thm->lcnum-thm->fcnum+3; w[0]= thm->PrimaryLeftCellSize/100.; w[SIZE-1]= thm->PrimaryRightCellSize/100.; T[0]= thm->TWL; T[SIZE-1]= thm->TWR; /* Make a internal copy of thermal model */ memcpy(&(T[1]), &(thm->T[thm->fcnum]), (SIZE-2)*sizeof(double)); memcpy(&(w[1]), &(thm->width[thm->fcnum]), (SIZE-2)*sizeof(double)); } double CTHSolver::Pre(double time) { // printf("PRE:\n"); /* Update thermal properties */ for (int j=1; j<SIZE-1; j++) { int i = j+thm->fcnum-1; l[j] = thm->m[i]->l(T[j]); c[j] = thm->m[i]->c(T[j]); r[j] = thm->m[i]->r(T[j]); } /* Update boundaries */ setBoundaries(thm->LBC, thm->RBC, time); /** Calculate heat quantity */ return currentHeatQty(); } double CTHSolver::Post(double time) { memcpy(&(thm->T[thm->fcnum]), &(T[1]), (SIZE-2)*sizeof(double)); thm->TWL = Twl(); if (thm->TWL <= 0.) { printf("T0=%lf T1=%lf T2=%lf w0=%E w1=%lf w2=%lf qv0=%lf\n", T[0], T[1], T[2], w[0], w[1], w[2], qv[0]); print(); } assert(thm->TWL > 0.); thm->TWR = Twr(); return currentHeatQty(); } int CTHSolver::DoIteration(double TIMESTEP) { double tempT0 = T[0]; CalculateTDMA(T, w, qv, l, r, c, eps, TIMESTEP, SIZE); if (TIMESTEP <= TIMESTEP_MIN) return TIMESTEP_MIN_CALCS; if (T[0] <= 0.) { print(); thm->print(); printf("[EE]: cell %d has T=%lf! Previous T=%lf TIMESTEP=%lf\n", 0, T[0], thm->T[1], TIMESTEP); fflush(NULL); } if ((fabs(T[0]-tempT0) > DT_MAX) && (DT_MAX > 0.)) return NEED_SMALLER_STEP; sres.CURRENT_DT_MAX = fabs(T[0] - tempT0); for (int i=1; i<SIZE-2; i++) { int j=thm->fcnum+i-1; if (T[i] <= 0.) { printf("i=%d T[i]=%lf\n", i, T[i]); print(); thm->print(); } assert(T[i] >= 0.); double DT = fabs(T[i]-thm->T[j]); if (DT > sres.CURRENT_DT_MAX) sres.CURRENT_DT_MAX = DT; if ((DT > DT_MAX) && (DT_MAX > 0.)) return NEED_SMALLER_STEP; if (T[i] < 0.) { print(); thm->print(); printf("[EE]: cell %d has T=%lf! Previous T=%lf TIMESTEP=%lf\n", i, T[i], thm->T[j], TIMESTEP); fflush(NULL); } assert((T[i] >= 0.)); } return SUCCESS; } void CTHSolver::setBoundaries(CBoundary *lbc, CBoundary *rbc, double time) { setLeftBoundary(lbc, time); setRightBoundary(rbc, time); } void CTHSolver::setLeftBoundary(CBoundary *cbc, double time) { BC_t bc = cbc->GetBC(time); if (cbc->type() == 1) { /* First kind type boundary */ l[0] = 1.0E+15*l[1]; c[0] = 1.0E+03*c[1]; r[0] = 1.0E+03*r[1]; assert(bc.Tw >= 0.); T[0] = bc.Tw; qv[0] = 0.; eps[0] = 0.; } else { assert(bc.Ie >= 0.); assert(bc.eps >= 0.); double q = bc.acp*(bc.Ie-bc.Iw); T[0] = thm->TWL; c[0] = c[1]; r[0] = r[1]; l[0] = l[1]; qv[0] = q/w[0]; eps[0] = bc.eps; // assert(bc.eps == 0); } } void CTHSolver::setRightBoundary(CBoundary *cbc, double time) { BC_t bc = cbc->GetBC(time); if (cbc->type() == 1) { /* First kind type boundary */ l[SIZE-1] = 1.0E+15*l[SIZE-2]; c[SIZE-1] = 1.0E+03*c[SIZE-2]; r[SIZE-1] = 1.0E+03*r[SIZE-2]; assert(bc.Tw >= 0.); T[SIZE-1] = bc.Tw; qv[SIZE-1] = 0.; eps[1] = 0.; } else { l[SIZE-1] = l[SIZE-2]; c[SIZE-1] =c[SIZE-2]; r[SIZE-1] = r[SIZE-2]; assert(bc.acp >= 0.); assert(bc.Ie >= 0.); assert(bc.eps >= 0.); double q = bc.acp*(bc.Ie-bc.Iw); qv[SIZE-1] = q/w[SIZE-1]; T[SIZE-1] = thm->TWR; eps[1] = bc.eps; } } thm_t* CTHSolver::getTHM() { return thm; } void CTHSolver::setPrefs(double TIMESTEP_MIN, double TIMESTEP_MAX, double DT_MAX) { this->TIMESTEP_MIN = TIMESTEP_MIN; this->TIMESTEP_MAX = TIMESTEP_MAX; this->DT_MAX = DT_MAX; } void CTHSolver::printPreferences() { printf("SOLVER PREFERENCES:\n"); printf("CURRENT_TIME=%lf\n", thm->CURRENT_TIME); printf("TIMESTEP_MIN=%E\n", TIMESTEP_MIN); printf("TIMESTEP_MAX=%E\n", TIMESTEP_MAX); } double CTHSolver::Twl() { return T[0]; } double CTHSolver::Twr() { return T[SIZE-1]; } double CTHSolver::currentHeatQty() { double sum = w[0]*thm->m[thm->fcnum]->heatQuantity(T[0]); for (int i=1; i<SIZE-1; i++) sum += w[i]*thm->m[thm->fcnum+i-1]->heatQuantity(T[i]); sum += w[SIZE-1]*thm->m[thm->lcnum]->heatQuantity(T[SIZE-1]); return sum; } void CTHSolver::print(FILE* out) { fprintf(out, "T= "); for (int i=0; i<SIZE-1; i++) fprintf(out, "%10.4lf ", T[i]); fprintf(out, "\n"); fprintf(out, "w= "); for (int i=0; i<SIZE-1; i++) fprintf(out, "%5.3E ", w[i]); fprintf(out, "\n"); fprintf(out, "l= "); for (int i=0; i<SIZE-1; i++) fprintf(out, "%5.3E ", l[i]); fprintf(out, "\n"); fprintf(out, "c= "); for (int i=0; i<SIZE-1; i++) fprintf(out, "%5.3E ", c[i]); fprintf(out, "\n"); fprintf(out, "r= "); for (int i=0; i<SIZE-1; i++) fprintf(out, "%5.3E ", r[i]); fprintf(out, "\n"); }
45409fd72ef97983d9f65ab83857950cb8f2dc51
d822ffd937fae821fdc1f96369c26b8b31c0cda6
/luogu/p2426.cpp
34100114a2971d083145327a047139dd3a5c4307
[ "MIT" ]
permissive
freedomDR/coding
f8bb5b43951f49cc1018132cc5c53e756a782740
408f0fd8d7e5dd986842746d27d4d26a8dc9896c
refs/heads/master
2023-03-30T03:01:01.837043
2023-03-28T12:36:53
2023-03-28T12:36:53
183,414,292
1
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
p2426.cpp
#include<bits/stdc++.h> using namespace std; const int maxn = 1005; long long dp[maxn], n, a[maxn]; int main() { cin >> n; for(int i = 1; i <= n; i++) cin >> a[i]; for(int i = 1; i <= n; i++) { dp[i] = dp[i-1]+a[i]; for(int j = i-1; j >= 1; j--) dp[i] = max(1ll*dp[i], dp[j-1]+abs(a[i]-a[j])*(i-j+1)); } cout << dp[n] << endl; return 0; }
362d482ff8922d1123665e85b1e8da2147fea04e
03429cdeba6002028e60d12e49620678364a0599
/Src/Library/EnPacket.h
5df30c7345ba07745472dd9b89f1d0d3a9f0f93f
[]
no_license
zhangf911/mir_server
d5b29a38406b9049179ccbc6e5fda629b3cd2498
35167d0dee453f1b31c20f66dd41ef08b7e28f4f
refs/heads/master
2021-01-10T01:44:45.771574
2015-08-12T11:33:00
2015-08-12T11:33:00
36,706,465
1
0
null
null
null
null
GB18030
C++
false
false
2,675
h
EnPacket.h
#ifndef LIBRARY_BASE_ENPACKET_H #define LIBRARY_BASE_ENPACKET_H #include "Type.h" class EnPacket { private: /** 二进制数据 **/ string m_data; /** 写入位置 **/ UInt32 m_pos; public: EnPacket(); EnPacket(const EnPacket& INinstance); EnPacket(EnPacket&& INright); ~EnPacket(); public: EnPacket& operator = (const EnPacket& INinstance); EnPacket& operator = (EnPacket&& INright); public: /** * @brief 压入一个布尔值 **/ void PushBool(bool INvalue); /** * @brief 压入一个字符值 **/ void PushChar(char INvalue); /** * @brief 压入一个无符号字符值 **/ void PushUChar(unsigned char INvalue); /** * @brief 压入一个短整型值 **/ void PushShort(short INvalue); /** * @brief 压入一个无符号短整型值 **/ void PushUShort(unsigned short INvalue); /** * @brief 压入一个位整型值 **/ void PushInt(int INvalue); /** * @brief 压入一个无符号整型值 **/ void PushUInt(unsigned int INvalue); /** * @brief 压入一个长整型值 **/ void PushLong(long INvalue); /** * @brief 压入一个无符号长整型值 **/ void PushULong(unsigned long INvalue); /** * @brief 压入一个64位有符号整型值 **/ #ifdef WIN32 void PushInt64(__int64 INvalue); #else void PushInt64(long long INvalue); #endif /** * @brief 压入一个64位无符号整型值 **/ #ifdef WIN32 void PushUInt64(unsigned __int64 INvalue); #else void PushUInt64(unsigned long long INvalue); #endif /** * @brief 压入一个单精度浮点值 **/ void PushFloat(float INvalue); /** * @brief 压入一个双精度浮点值 **/ void PushDouble(double INvalue); /** * @brief 压入一个字符串 **/ void PushString(const char* INdata, UInt32 INdataSize); /** * @brief 压入一个字符串 **/ void PushString(const string& INdata); /** * @brief 压入一个字符串,压入格式为第一个字段是UInt16的字符串长度,第二个字段为string **/ void PushUInt16String(const string& INdata); /** * @brief 定位 * @param INpos : 位置 * @exception * @note INpos超过数据大小,则处理为数据尾端 **/ void Seekg(UInt32 INpos); /** * @brief 获取包数据 **/ const string& GetString() { return m_data; }; /** * @brief 获取包数据, 可修改 **/ string& GetStringData() { return m_data; }; /** * @brief 获取包大小 **/ inline UInt32 GetLength() { return static_cast<UInt32>(m_data.size()); }; /** * @brief 清理包数据 **/ void Clear() { m_data.clear(); m_pos = 0; }; private: template <typename DataType> void PushData(DataType* INdata, UInt32 INdataSize = sizeof(DataType)); }; #endif
17cb77b085a5546b6345222ca8ac98401b4911ce
d4042c55c865ab21ed8de27cbe4b6f0c76b20aa8
/Maschinen/ContainedController.h
e98b25f8fa5dd35d500d1f01b2105c8357bc0e18
[]
no_license
LeonColt/skripsi
a1f207622a3c4aabab0f951e4f08767f3d085ba2
141af593ec65cd7adaedf7a90fc4cd7cde5cc602
refs/heads/master
2020-08-02T11:40:06.134151
2019-09-27T14:33:27
2019-09-27T14:33:27
211,331,309
0
0
null
null
null
null
UTF-8
C++
false
false
1,167
h
ContainedController.h
#pragma once #include "VisibleController.h" #include "Layout.h" namespace maschinen { namespace layout { class Layout; } class MASCHINEN_API ContainedController : public maschinen::VisibleController { protected: bool on_init = true; maschinen::layout::Layout* wlayout = nullptr; virtual void onCreate() = 0; virtual void onInit() = 0; virtual void onHide() = 0; virtual void onShow() = 0; virtual void onSize( WPARAM wparam, LPARAM lparam ) = 0; virtual void onPaint( HDC hdc ); virtual void onDestroy() = 0; public: ContainedController(); ContainedController(UINT id, ContainedController* parent); virtual void create() = 0; HWND getWindowHandler(); inline ContainedController* getParent() const noexcept { return dynamic_cast< ContainedController* >( parent ); } ContainedController* getWindowParent() noexcept; void setParentAndId(maschinen::ContainedController* parent, UINT id); void setParent(maschinen::ContainedController* parent); void setLayout( maschinen::layout::Layout* layout ) noexcept; maschinen::layout::Layout* getLayout() const noexcept; ~ContainedController(); }; }
17f5f5e122250952d9a241c90bdbf9d631dcf2f6
f7a3a1a0bd6ac5d51af73e5d53ba5f50c2847690
/Benchmark/Jacobian/JacobianTests.cpp
f34bd2d44d3b90023914ee175eee8d3a54d92b86
[]
no_license
ana-GT/Lucy
890d60876aca028c051b928bd49bf93092151058
819d2c7210c920ea0d0c1f549bb7df022260bb3f
refs/heads/master
2021-01-22T05:28:22.021489
2011-12-12T23:18:45
2011-12-12T23:18:45
2,887,317
0
0
null
null
null
null
UTF-8
C++
false
false
15,846
cpp
JacobianTests.cpp
/* * Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Humanoid Robotics Lab Georgia Institute of Technology * Director: Mike Stilman http://www.golems.org */ #include "JacobianTests.h" #include <wx/wx.h> #include <GUI/Viewer.h> #include <GUI/GUI.h> #include <GUI/GRIPSlider.h> #include <GUI/GRIPFrame.h> #include <Tabs/GRIPTab.h> #include <iostream> #include <Tabs/AllTabs.h> #include <GRIPApp.h> using namespace std; /* Quick intro to adding tabs: * 1- Copy template cpp and header files and replace with new class name * 2- include classname.h in AllTabs.h, and use the ADD_TAB macro to create it */ // Control IDs (used for event handling - be sure to start with a non-conflicted id) enum JacobianTestsEvents { button_SetStartConf = 50, button_ShowStartConf, button_Plot1, button_Plot2, button_Plot3, button_Plan, button_Stop, button_UpdateTime, button_ExportSequence, button_ShowPath, slider_Time, checkbox_FixXYZ, checkbox_FixOrient }; enum SliderNames{ SLIDER_NULLSPACE = 1000, }; // sizer for whole tab wxBoxSizer* sizerFull; //Add a handler for any events that can be generated by the widgets you add here (sliders, radio, checkbox, etc) BEGIN_EVENT_TABLE( JacobianTests, wxPanel ) EVT_COMMAND ( wxID_ANY, wxEVT_GRIP_SLIDER_CHANGE, JacobianTests::OnSlider ) EVT_COMMAND ( wxID_ANY, wxEVT_COMMAND_BUTTON_CLICKED, JacobianTests::OnButton ) EVT_COMMAND ( wxID_ANY, wxEVT_COMMAND_CHECKBOX_CLICKED, JacobianTests::OnCheckBox ) EVT_COMMAND( wxID_ANY, wxEVT_COMMAND_RADIOBOX_SELECTED, JacobianTests::OnRadio ) END_EVENT_TABLE() // Class constructor for the tab: Each tab will be a subclass of RSTTab IMPLEMENT_DYNAMIC_CLASS( JacobianTests, GRIPTab ) /** * @function JacobianTests * @brief Constructor */ JacobianTests::JacobianTests( wxWindow *parent, const wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : GRIPTab(parent, id, pos, size, style ) { startConf.resize(0); targetConf.resize(0); targetPose.resize(0); robotId = 0; links.resize(0); sizerFull = new wxBoxSizer( wxHORIZONTAL ); // ** Create left static box for configuring the planner ** // Create StaticBox container for all items wxStaticBox* configureBox = new wxStaticBox(this, -1, wxT("Configure")); // Create sizer for this box with horizontal layout wxStaticBoxSizer* configureBoxSizer = new wxStaticBoxSizer(configureBox, wxHORIZONTAL); // Create sizer for start buttons in 1st column wxBoxSizer *col1Sizer = new wxBoxSizer(wxVERTICAL); col1Sizer->Add( new wxButton(this, button_SetStartConf, wxT("Set &Start Conf")), 0, // make horizontally unstretchable wxALL, // make border all around (implicit top alignment) 1 ); // set border width to 1, so start buttons are close together col1Sizer->Add( new wxButton(this, button_ShowStartConf, wxT("Show S&tart Conf")), 0, // make horizontally unstretchable wxALL, // make border all around (implicit top alignment) 1 ); // set border width to 1, so start buttons are close together wxBoxSizer *miniSizer1 = new wxBoxSizer(wxVERTICAL); miniSizer1->Add( new wxCheckBox(this, checkbox_FixXYZ, _T("Fix XYZ")), 1, // vertical stretch evenly wxALIGN_NOT, 0); miniSizer1->Add( new wxCheckBox(this, checkbox_FixOrient, _T("Fix Orient")), 1, // vertical stretch evenly wxALIGN_NOT, 0 ); col1Sizer->Add( miniSizer1, 1, wxALIGN_NOT, 0 ); mSlider_Nullspace = new GRIPSlider("Ang",-3,3,500,0,100,500,this, SLIDER_NULLSPACE ); col1Sizer->Add( mSlider_Nullspace, 1, wxEXPAND | wxALL, 6 ); // Add col1Sizer to the configuration box configureBoxSizer->Add( col1Sizer, 1, // takes half the space of the configure box wxALIGN_NOT ); // no border and center horizontally // Create sizer for planner buttons in 4th column wxBoxSizer *col4Sizer = new wxBoxSizer(wxVERTICAL); col4Sizer->Add( new wxButton(this, button_Plot1, wxT("Plot 1")), 0, // make horizontally unstretchable wxALL, // make border all around (implicit top alignment) 1 ); // set border width to 1, so start buttons are close together col4Sizer->Add( new wxButton(this, button_Plot2, wxT("Plot 2")), 0, // make horizontally unstretchable wxALL, // make border all around (implicit top alignment) 1 ); // set border width to 1, so start buttons are close together col4Sizer->Add( new wxButton(this, button_Plot3, wxT("Plot 3")), 0, // make horizontally unstretchable wxALL, // make border all around (implicit top alignment) 1 ); // set border width to 1, so start buttons are close together // Add col2Sizer to the configuration box configureBoxSizer->Add( col4Sizer, 1, // size evenly with radio box and checkboxes wxALIGN_NOT ); // no border and center horizontally // Add this box to parent sizer sizerFull->Add( configureBoxSizer, 4, // 4-to-1 ratio with execute sizer, since it has 4 buttons wxEXPAND | wxALL, 6 ); // ** Create right static box for running the planner ** wxStaticBox* executeBox = new wxStaticBox(this, -1, wxT("Execute Planner")); // Create sizer for this box wxStaticBoxSizer* executeBoxSizer = new wxStaticBoxSizer(executeBox, wxVERTICAL); // Add buttons for "plan", "save movie", and "show path" executeBoxSizer->Add( new wxButton(this, button_Plan, wxT("&Run")), 1, // stretch to fit horizontally wxGROW ); // let it hog all the space in it's column executeBoxSizer->Add( new wxButton(this, button_Stop, wxT("&Stop")), 1, // stretch to fit horizontally wxGROW ); wxBoxSizer *timeSizer = new wxBoxSizer(wxHORIZONTAL); timeText = new wxTextCtrl(this,1008,wxT("5.0"),wxDefaultPosition,wxSize(40,20),wxTE_RIGHT);//,wxTE_PROCESS_ENTER | wxTE_RIGHT); timeSizer->Add(timeText,2,wxALL,1); timeSizer->Add(new wxButton(this, button_UpdateTime, wxT("Set T(s)")),2,wxALL,1); executeBoxSizer->Add(timeSizer,1,wxALL,2); executeBoxSizer->Add( new wxButton(this, button_ShowPath, wxT("&Print")), 1, // stretch to fit horizontally wxGROW ); sizerFull->Add(executeBoxSizer, 1, wxEXPAND | wxALL, 6); SetSizer(sizerFull); } /** * @function getLeftArmIds * @brief Get DOF's IDs for ROBINA's left arm */ Eigen::VectorXi JacobianTests::GetLeftArmIds() { string LINK_NAMES[7] = {"LJ0", "LJ1", "LJ2", "LJ3", "LJ4", "LJ5", "LJ6" }; Eigen::VectorXi linksAll = mWorld->mRobots[robotId]->getQuickDofsIndices(); Eigen::VectorXi linksLeftArm(7); for( unsigned int i = 0; i < 7; i++ ) { for( unsigned int j = 0; j < linksAll.size(); j++ ) { if( mWorld->mRobots[robotId]->getDof( linksAll[j] )->getJoint()->getChildNode()->getName() == LINK_NAMES[i] ) { linksLeftArm[i] = linksAll[j]; break; } } } return linksLeftArm; } /** * @function setTimeLine * @brief */ void JacobianTests::SetTimeline( std::list<Eigen::VectorXd> _path ) { if( mWorld == NULL || _path.size() == 0 ) { std::cout << "--(!) Must create a valid plan before updating its duration (!)--" << std::endl; return; } double T; timeText->GetValue().ToDouble(&T); int numsteps = _path.size(); double increment = T/(double)numsteps; cout << "-->(+) Updating Timeline - Increment: " << increment << " Total T: " << T << " Steps: " << numsteps << endl; frame->InitTimer( string("RRT_Plan"),increment ); Eigen::VectorXd vals( links.size() ); for( std::list<Eigen::VectorXd>::iterator it = _path.begin(); it != _path.end(); it++ ) { mWorld->mRobots[robotId]->setDofs( *it, links ); mWorld->mRobots[robotId]->update(); frame->AddWorld( mWorld ); } } /** * @function OnButton * @brief Handle Button Events */ void JacobianTests::OnButton(wxCommandEvent &evt) { int button_num = evt.GetId(); links = GetLeftArmIds(); switch (button_num) { /** Set Start Configuration */ case button_SetStartConf: if ( mWorld != NULL ) { if( mWorld->mRobots.size() < 1) { cout << "--(!) Must have a world with a robot to set a Start state (!)--" << endl; break; } std::cout << "--(i) Setting Start state for " << mWorld->mRobots[robotId]->getName() << ":" << std::endl; startConf = mWorld->mRobots[robotId]->getDofs( links ); for( unsigned int i = 0; i < startConf.size(); i++ ) { std::cout << startConf(i) << " "; } std::cout << endl; } else { std::cout << "--(!) Must have a world loaded to set a Start state.(!)--" << std::endl; } break; /** Show Start */ case button_ShowStartConf: if( startConf.size() < 1 ) { std::cout << "--(x) First, set a start configuration (x)--" << std::endl; break; } mWorld->mRobots[robotId]->setDofs( startConf, links ); for( unsigned int i = 0; i< startConf.size(); i++ ) { cout << startConf(i) << " "; } std::cout << std::endl; mWorld->mRobots[robotId]->update(); viewer->UpdateCamera(); break; /** Execute Plan */ case button_Plan: { printf("Here we don't plan yet \n"); } break; /** Plot 1 */ case button_Plot1: { } break; /** Plot 2 */ case button_Plot2: { } break; /** Plot 3 */ case button_Plot3: { } break; /** UpdateTime (?) */ case button_UpdateTime: { /// Update the time span of the movie timeline //SetTimeline(); } break; /** Show Path */ case button_ShowPath: if( mWorld == NULL ) { cout << "--(!) Must create a valid plan before printing. (!)--" << endl; return; } else { printf("--(i) Printing (i)-- \n"); } break; } // end of switch } /** * @function NullspaceTest */ double JacobianTests::NullspaceTest( double _ang ) { kinematics::BodyNode *mEENode; int mEEId; mEENode = mWorld->mRobots[robotId]->getNode( "LJ6" ); mEEId = mEENode->getSkelIndex(); // Set to start configuration mWorld->mRobots[robotId]->setDofs( startConf, links ); mWorld->mRobots[robotId]->update(); // Get current XYZ position Eigen::MatrixXd transStart = mEENode->getWorldTransform(); Eigen::Vector3d ts; ts << transStart(0,3), transStart(1,3), transStart(2,3); Eigen::MatrixXd Jaclin; Jaclin = mEENode->getJacobianLinear().topRightCorner( 3, links.size() ); // Projecting in nullspace Eigen::MatrixXd Id( links.size(), links.size() ); Id.setIdentity(); Eigen::VectorXd alpha( links.size() ); for( int i = 0; i < alpha.size(); i++ ) { alpha[i] = _ang; } Eigen::VectorXd dq( links.size() ); dq = ( Id - Jaclin.transpose()*(Jaclin*Jaclin.transpose()).inverse()*Jaclin )*alpha; std::cout << "dq: " << dq.transpose() << std::endl; Eigen::VectorXd newConfig = startConf + dq; mWorld->mRobots[robotId]->setDofs( newConfig, links ); mWorld->mRobots[robotId]->update(); // Get current XYZ position Eigen::MatrixXd transEnd = mEENode->getWorldTransform(); Eigen::Vector3d te; te << transEnd(0,3), transEnd(1,3), transEnd(2,3); viewer->UpdateCamera(); printf("Alpha element: %f \n", _ang); return (ts-te).norm(); } /** * @function OnSlider * @brief Handle slider changes */ void JacobianTests::OnSlider(wxCommandEvent &evt) { /* if ( selectedTreeNode == NULL ) { return; } */ /// Do I need this now? - AHQ: Dec 6th, 2012 int slnum = evt.GetId(); double pos = *(double*) evt.GetClientData(); char numBuf[1000]; switch (slnum) { case slider_Time: sprintf(numBuf, "X Change: %7.4f", pos); std::cout << "-->(i) Timeline slider output: " << numBuf << std::endl; //handleTimeSlider(); // uses slider position to query plan state break; case SLIDER_NULLSPACE: { double diff3D = NullspaceTest( pos ); printf("3D error: %f \n", diff3D ); } break; default: return; } //world->updateCollision(o); //viewer->UpdateCamera(); if (frame != NULL) frame->SetStatusText(wxString(numBuf, wxConvUTF8)); } /** * @function OnRadio */ void JacobianTests::OnRadio( wxCommandEvent &evt ) { } /** * @function OnCheckBox */ void JacobianTests::OnCheckBox( wxCommandEvent &evt ) { int checkbox_num = evt.GetId(); switch ( checkbox_num ) { case checkbox_FixXYZ: mFixXYZ = (bool)evt.GetSelection(); std::cout << "--> Fixing XYZ Position: "<< mFixXYZ << std::endl; break; case checkbox_FixOrient: mFixOrient = (bool)evt.GetSelection(); std::cout << "--> Fixing Orientation: "<< mFixOrient << std::endl; break; } } /** * @function GRIPStateChange -- Keep using this name as it is a virtual function * @brief This function is called when an object is selected in the Tree View or other * global changes to the RST world. Use this to capture events from outside the tab. */ void JacobianTests::GRIPStateChange() { if ( selectedTreeNode == NULL ) { return; } string statusBuf; string buf, buf2; switch (selectedTreeNode->dType) { case Return_Type_Object: selectedObject = (planning::Object*) ( selectedTreeNode->data ); statusBuf = " Selected Object: " + selectedObject->getName(); buf = "You clicked on object: " + selectedObject->getName(); // Enter action for object select events here: break; case Return_Type_Robot: selectedRobot = (planning::Robot*) ( selectedTreeNode->data ); statusBuf = " Selected Robot: " + selectedRobot->getName(); buf = " You clicked on robot: " + selectedRobot->getName(); // Enter action for Robot select events here: break; case Return_Type_Node: selectedNode = (kinematics::BodyNode*) ( selectedTreeNode->data ); statusBuf = " Selected Body Node: " + string(selectedNode->getName()) + " of Robot: " + ( (planning::Robot*) selectedNode->getSkel() )->getName(); buf = " Node: " + string(selectedNode->getName()) + " of Robot: " + ( (planning::Robot*) selectedNode->getSkel() )->getName(); // Enter action for link select events here: break; default: fprintf(stderr, "--( :D ) Someone else's problem!\n"); assert(0); exit(1); } //cout << buf << endl; frame->SetStatusText(wxString(statusBuf.c_str(), wxConvUTF8)); sizerFull->Layout(); }
d77a37e9e7ac7495a1888f2391ba41a3fa3fca5d
ab15206fb8b2b469195ed553ff43a079fa32454e
/lab1/lab2_2.cpp
a08abb06ae744bff71f7532e659f4c084598ecf7
[ "MIT" ]
permissive
galek/MPEI_ParallelProgramming_MPI_LAB1
b5ea4940a6925039c8a454dd1cbd6730a9c8a241
661ee2d5a1eee4530a86ca62e2d36abd58a0b29a
refs/heads/master
2021-11-05T02:16:52.031247
2021-10-31T02:42:15
2021-10-31T02:42:15
95,285,015
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,215
cpp
lab2_2.cpp
// lab1.cpp: определяет точку входа для консольного приложения. // //#include "stdafx.h" #include "mpi.h" #include <stdio.h> #include <stdlib.h> //#include <sys/time.h> #include <time.h> //#include <iostream> #define NUMBER_REPS 1000 #if _MSC_VER #pragma comment(lib, "msmpi.lib") //#pragma comment(lib, "Ws2_32.lib") #endif #define SAFE_DELETE_ARRAY(x) if(x) delete[]x; #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif /* 2. Сравнить производительность функций MPI_Bcast и MPI_Send/MPI_Recv при разном количестве задействованных узлов. */ namespace Benchmarking_1 { void Task1(int reps, double &SumTimeDelta, int size, int rank, MPI_Status& status, double&BCastTimeDelta, bool _compare) { for (auto i = 0; i < reps; i++) { if (rank == 0) { for (auto j = 1; j < size; j++) { auto _startTime = MPI_Wtime(); /* start time */ /* send message to worker - message tag set to 1. */ /* If return code indicates error quit */ int rc = MPI_Send(NULL, 0, MPI_BYTE, j, 1, MPI_COMM_WORLD); if (rc != MPI_SUCCESS) { printf("Send error in task 0!\n"); MPI_Abort(MPI_COMM_WORLD, rc); exit(1); } auto _endTime = MPI_Wtime(); /* end time */ /* calculate round trip time and print */ auto deltaT = _endTime - _startTime; SumTimeDelta += deltaT; } } else { /* Now wait to receive the echo reply from the worker */ auto rc = MPI_Recv(NULL, 0, MPI_BYTE, 0, 1, MPI_COMM_WORLD, &status); if (rc != MPI_SUCCESS) { printf("Receive error in task 0!\n"); MPI_Abort(MPI_COMM_WORLD, rc); exit(1); } } } { if ((rank == 0) && (_compare)) { auto _startTime = MPI_Wtime(); /* start time */ for (int i = 0; i < reps; i++) { MPI_Bcast(NULL, 0, MPI_BYTE, 0, MPI_COMM_WORLD); } auto _endTime = MPI_Wtime(); /* end time */ /* calculate round trip time and print */ auto deltaT = _endTime - _startTime; BCastTimeDelta += deltaT; } } } inline void BenchmarkBcastAndSendRecv(int _count, double&SumTimeDelta, double&BCastTimeDelta, int size, int rank, MPI_Status& status) { Task1(_count, SumTimeDelta, size, rank, status, BCastTimeDelta, true); } inline void RunTask1(int _count, double&SumTimeDelta, double&BCastTimeDelta, int size, int rank, MPI_Status& status) { Task1(_count, SumTimeDelta, size, rank, status, BCastTimeDelta, false); } } namespace Benchmarking_2 { } int main(int argc, char*argv[]) { int tag, /* MPI message tag parameter */ size, /* number of MPI tasks */ rank, /* my MPI task number */ dest, source, /* send/receive task designators */ avgT, /* average time per rep in microseconds */ rc, /* return code */ n; double T1, T2, /* start/end times per rep */ sumT, /* sum of all reps times */ deltaT; /* time for one rep */ char* msg; /* buffer containing 1 byte message */ MPI_Status status; /* MPI receive routine parameter */ MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Расчеты MPI_Barrier(MPI_COMM_WORLD); sumT = 0; tag = 1; double SumTimeDelta = 0; double BCastTimeDelta = 0; //printf("Capacity checking Started \n"); /*Количество измерений*/ int Count = 10; { using namespace Benchmarking_1; BenchmarkBcastAndSendRecv(Count, SumTimeDelta, BCastTimeDelta, size, rank, status); } if (rank == 0) { printf("Send/Recv time %f ms for operations %i Performance %f operations for per-ms \n", SumTimeDelta*(1000000 / CLOCKS_PER_SEC), Count, SumTimeDelta*(1000000 / CLOCKS_PER_SEC) / Count); printf("BCast time %f ms for operations %i Performance %f operations for per-ms \n", BCastTimeDelta*(1000000 / CLOCKS_PER_SEC), Count, SumTimeDelta *(1000000 / CLOCKS_PER_SEC) / Count); } MPI_Finalize(); exit(0); return 0; }
ce70d5fc124413d9855bcc18145bf9fb11317a60
43efeeab2f43449ec6f0ba71d9755cf6043aa3aa
/qtProjet/paramdialog.cpp
a4b1261fd75ded4dc4ac03dbf3e5aa6dbd381931
[]
no_license
prm1108a/ElbezFisliPerreuSLA
98b4b10a7a18e66e402835aa3df23e30a616b324
b9c56c9cff435d52b39df16a518462223ea172de
refs/heads/master
2021-01-24T03:03:14.707318
2018-02-25T20:07:08
2018-02-25T20:07:08
122,871,570
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
cpp
paramdialog.cpp
#include "paramdialog.h" ParamDialog::ParamDialog() { verticalLayout = new QVBoxLayout; horizontalLayout1 = new QHBoxLayout; horizontalLayout2 = new QHBoxLayout; nbAnnees = new QSpinBox; QLabel *labelAnnees = new QLabel; labelAnnees->setText("Nombre d'années : "); horizontalLayout1->addWidget(labelAnnees); horizontalLayout1->addWidget(nbAnnees); nbHuits = new QSpinBox; QLabel *labelHuits = new QLabel; labelHuits->setText("Nombre de 8h : "); horizontalLayout2->addWidget(labelHuits); horizontalLayout2->addWidget(nbHuits); verticalLayout->addLayout(horizontalLayout1); verticalLayout->addLayout(horizontalLayout2); setLayout(verticalLayout); setWindowTitle("Paramètres"); move(250, 60); } void ParamDialog::setNbAnnees(int n) { Nb_Annees = n; nbAnnees->setValue(Nb_Annees); } void ParamDialog::setNbHuits(int n) { Nb_Huits = n; nbHuits->setValue(Nb_Huits); } int ParamDialog::getNbAnnees() { return nbAnnees->value(); } int ParamDialog::getNbHuits() { return nbHuits->value(); } void ParamDialog::addButtonToLayout(QPushButton * b) { verticalLayout->addWidget(b); }
59e47d681f33ae6bbe12343fb35346a3fe307632
ee4f2821521c41a8d48e526cea2106dbf165644d
/src/TenantCharacter.h
a5f6421a98f6d76835d42aa378d0665b69b018ff
[]
no_license
legionarius/landlord
90c840706ab113dc1e2e398786a43569e67e2db7
e2dabc8264bec1323a0a0e7c7a0f33c1b22a2028
refs/heads/master
2023-05-27T21:50:33.081680
2021-06-14T07:23:22
2021-06-14T07:23:22
376,736,444
0
0
null
null
null
null
UTF-8
C++
false
false
938
h
TenantCharacter.h
// // Created by acroquelois on 07/04/2021. // #ifndef MUNDANE_JAM_TENANTCHARACTER_H #define MUNDANE_JAM_TENANTCHARACTER_H #include <AnimationPlayer.hpp> #include <Godot.hpp> #include <KinematicBody2D.hpp> #include <Node2D.hpp> #include <RandomNumberGenerator.hpp> #include <Timer.hpp> #include <sstream> namespace godot { class TenantCharacter : public KinematicBody2D { GODOT_CLASS(TenantCharacter, KinematicBody2D); Node2D *characterShape; AnimationPlayer *characterAnimation; RandomNumberGenerator *rng; Timer *characterTimer; bool tenantSlideLeft = false; bool tenantIsIdle = false; float tenantSpeed = 10.0f; real_t pourcentageOfChanceToIdle = 40; public: static void _register_methods(); void _init(); void _ready(); void _process(float delta); void _reverse_shape(); void _init_idle_timer(); void launch_tenant_animation(); }; } #endif //MUNDANE_JAM_TENANTCHARACTER_H
4c94d99971c2cf9d341eb41ad1649cec0a1f6243
1fbf30ee65f4d26fefd7679c00c733e9aa05daec
/Lame/TextureCache.cpp
ad7c0656eb27a1b90473eb4646ac7d3ae8f1ed20
[]
no_license
elamitie/learning-opengl
b94e2fd33c6b1837b826101fdd188ee168161262
eee10db6ac672f5a0525ab47a9f72b71bd22a01f
refs/heads/master
2021-05-29T14:42:55.056438
2015-09-19T05:35:03
2015-09-19T05:35:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
457
cpp
TextureCache.cpp
#include "TextureCache.h" #include "ImageLoader.h" namespace lame { TextureCache::TextureCache() { } TextureCache::~TextureCache() { } Texture TextureCache::getTexture(const std::string& filepath) { auto iterator = m_textureMap.find(filepath); if (iterator == m_textureMap.end()) { Texture tex = ImageLoader::loadPNG(filepath); m_textureMap.insert(std::make_pair(filepath, tex)); return tex; } return iterator->second; } }
3c3ef1d2d94c540a823a7f466b3d6487ae50d90d
0fdb6565a31358a7021c30bbfd0e95a1a9d39e25
/tests/morganaFile/resumeHDF5Test8.cpp
b01088fc8e2d155a019c345803291facf3f2f0ae
[]
no_license
feof81/morganaPublic
b8b61a08d222a2ade3484cbdfc80c9790c0e5508
540cdbcdcf56e5cd13c0dc98c04f724543025bce
refs/heads/master
2023-01-28T01:12:51.711178
2023-01-11T16:56:37
2023-01-11T16:56:37
216,569,123
3
2
null
null
null
null
UTF-8
C++
false
false
3,400
cpp
resumeHDF5Test8.cpp
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This file is part of Morgana. Author: Andrea Villa, andrea.villa81@fastwebnet.it Morgana is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Morgana 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 Morgana. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "pMapItem.h" #include "pMapItemShare.h" #include "pGraph.hpp" #include "geoShapes.h" #include "resumeHDF5.h" using namespace std; using namespace boost::mpi; using namespace Teuchos; int main(int argc, char *argv[]) { typedef geoElement<linearTetra> GEOELEMENT; typedef pMapItemShare ELMAP; typedef pMapItem NODEMAP; environment env(argc,argv); communicator world; assert(world.size() == 2); mesh3d<linearTetra,ELMAP,NODEMAP> grid3d, rGrid; if(world.rank() == 0) { //Nodes pVect<point3d,NODEMAP> nodes; nodes.reserve(5); nodes.push_back(point3d(0.0, 0.0, 0.0),pMapItem(1,1,0)); nodes.push_back(point3d(1.0, 0.0, 0.0),pMapItem(2,2,0)); nodes.push_back(point3d(1.0, 1.0, 0.0),pMapItem(3,3,0)); nodes.push_back(point3d(0.0, 1.0, 0.0),pMapItem(4,4,0)); nodes.push_back(point3d(0.5, 0.5, 1.0),pMapItem(5,5,0)); nodes.updateFinder(); //Elements GEOELEMENT tet(true); pGraph<GEOELEMENT,ELMAP,NODEMAP> elList; elList.reserve(2); tet.setGeoId(1); tet(1) = 1; tet(2) = 2; tet(3) = 3; tet(4) = 5; elList.push_back(tet, pMapItemShare(1,1,true,true)); tet.setGeoId(1); tet(1) = 1; tet(2) = 3; tet(3) = 4; tet(4) = 5; elList.push_back(tet, pMapItemShare(2,2,true,false)); //The grid3d grid3d.setNodes(nodes); grid3d.setElements(elList); } else { //Nodes pVect<point3d,NODEMAP> nodes; nodes.reserve(5); nodes.push_back(point3d(0.0, 0.0, 0.0),pMapItem(1,1,1)); nodes.push_back(point3d(1.0, 0.0, 0.0),pMapItem(2,2,1)); nodes.push_back(point3d(1.0, 1.0, 0.0),pMapItem(3,3,1)); nodes.push_back(point3d(0.0, 1.0, 0.0),pMapItem(4,4,1)); nodes.push_back(point3d(0.5, 0.5, 1.0),pMapItem(5,5,1)); nodes.updateFinder(); //Elements GEOELEMENT tet(true); pGraph<GEOELEMENT,ELMAP,NODEMAP> elList; elList.reserve(2); tet.setGeoId(1); tet(1) = 1; tet(2) = 2; tet(3) = 3; tet(4) = 5; elList.push_back(tet, pMapItemShare(1,1,true,false)); tet.setGeoId(1); tet(1) = 1; tet(2) = 3; tet(3) = 4; tet(4) = 5; elList.push_back(tet, pMapItemShare(2,2,true,true)); //The grid3d grid3d.setNodes(nodes); grid3d.setElements(elList); } resumeHDF5 resumer(world); resumer.printToFile("mesh3d",grid3d); resumer.loadFromFile("mesh3d", rGrid); if(world.rank() == 1) { cout << rGrid.getElements() << endl; } }
5036ab7ab3740e7325f0cc722e451d2597891e66
e8042f76e2a32d1d03e253de217c01e211843d2c
/ProjectEve/RGBImage.cpp
abcee70b17a6ea98066e6a9a78aafa79f437fc00
[]
no_license
gomyk/Project_Eve_MFC
03262cab29ab404766d2ccb487bdf4bb4a43ae2f
49c3d115a73c98cdae886fcbd1ed6d68fbbeeca7
refs/heads/master
2020-05-25T03:17:23.885372
2017-03-14T04:26:27
2017-03-14T04:26:27
84,905,224
0
0
null
null
null
null
UTF-8
C++
false
false
3,181
cpp
RGBImage.cpp
#include "stdafx.h" #include "RGBImage.h" RGBImage::RGBImage() { } RGBImage::RGBImage(int width, int height) { this->width = width; this->height = height; } RGBImage::~RGBImage() { delete[] buffer.Rdata; delete[] buffer.Gdata; delete[] buffer.Bdata; delete[] buffer.Ydata; } bool RGBImage::isGood() { if (width > 0) { return true; } else { return false; } } void RGBImage::copyFrame(AVFrame* frame) { width = frame->width; height = frame->height; int H = frame->height; int W = frame->linesize[0]; buffer.Rdata = new u_char[W*H]; buffer.Gdata = new u_char[W*H]; buffer.Bdata = new u_char[W*H]; buffer.Ydata = new u_char[W*H]; int Y, U, V; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { Y = frame->data[0][i*W + j]; U = frame->data[1][((i / 2)*(W / 2) + j / 2)]; V = frame->data[2][((i / 2)*(W / 2) + j / 2)]; int R, G, B; //Rdata[i*W + j] = frame->data[0][i*W + j] + (1.370705 * (frame->data[2][((i / 2)*(W / 2) + j / 2)] - 128)); //Gdata[i*W + j] = frame->data[0][i*W + j] - (0.698001 * (frame->data[2][((i / 2)*(W / 2) + j / 2)] - 128)) - (0.337633 * (frame->data[1][((i / 2)*(W / 2) + j / 2)] - 128)); //Bdata[i*W + j] = frame->data[0][i*W + j] + (1.732446 * frame->data[1][((i / 2)*(W / 2) + j / 2)]); R = (int)(1.164*(Y - 16) + 1.596*(V - 128)); G = (int)(1.164*(Y - 16) - 0.813*(V - 128) - 0.391*(U - 128)); B = (int)(1.164*(Y - 16) + 2.018*(U - 128)); if (R < 0) { R = 0; } else if (R > 255) { R = 255; } if (G < 0) { G = 0; } else if (G > 255) { G = 255; } if (B < 0) { B = 0; } else if (B > 255) { B= 255; } buffer.Rdata[i*W + j] = R; buffer.Gdata[i*W + j] = G; buffer.Bdata[i*W + j] = B; buffer.Ydata[i*W + j] = Y; //Rdata[i*W + j] =(int) frame->data[0][i*W + j] + 1.402*frame->data[2][((i / 2)*(W / 2) + j / 2)]; //Gdata[i*W + j] = frame->data[0][i*W + j] - 0.344*frame->data[1][((i / 2)*(W / 2) + j / 2)] - 0.714*frame->data[2][((i / 2)*(W / 2) + j / 2)]; // Bdata[i*W + j] = frame->data[0][i*W + j] + 1.772*frame->data[1][((i / 2)*(W / 2) + j / 2)]; } } } bool RGBImage::checkPixelWhite(int index) { if (buffer.Rdata[index] > 250 && buffer.Gdata[index] > 250 && buffer.Bdata[index] > 250 ) return true; return false; } void RGBImage::getPixelColor(u_char& R, u_char& G, u_char& B, int index) { R = buffer.Rdata[index]; G = buffer.Gdata[index]; B = buffer.Bdata[index]; } u_char RGBImage::getYdata(int index) { return buffer.Ydata[index]; } void RGBImage::setPixelColor(u_char R, u_char G, u_char B, int index) { buffer.Rdata[index] = R; buffer.Gdata[index] = G; buffer.Bdata[index] = B; } void RGBImage::RGB2YUV(AVFrame& frame) { int H = height; int W = frame.linesize[0]; int R, G, B; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { R = buffer.Rdata[i*W + j]; G = buffer.Gdata[i*W + j]; B = buffer.Bdata[i*W + j]; frame.data[0][i*W + j] = (0.257* R) + (0.504*G) + (0.098*B) + 16; frame.data[1][((i / 2)*(W / 2) + j / 2)] = -(0.148*R) - (0.291*G) + (0.439*B) + 128; frame.data[2][((i / 2)*(W / 2) + j / 2)] = (0.439*R) - (0.368*G) - (0.071*B) + 128; } } }
978f4a8078c19bca160158e0410068f42062d5b9
c1a56d1d086fcef47c7b171e8862d69eb3889c45
/Practice Problems/Issue 4/FormatPrint.cpp
61b14172e005247855d6bc8c84e5ec4303b92a9e
[]
no_license
avanti534/CPP_Programming
9a3ef66cdef6103d82d04ae9eb1ee21069c757cf
04ba652a9912898376bb286bdb5d2830e0a39ecf
refs/heads/master
2020-03-28T09:23:24.963204
2018-11-23T16:43:33
2018-11-23T16:43:33
148,033,012
1
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
FormatPrint.cpp
#include <iostream> #include <stdio.h> int main() { double a, b; std::cin >> a >> b; printf("%.2f\n", a/b); }
7c42303386c9298d72f8e88eca80fac06b6a2956
4e5c394c33f0a8adf0152742f01aebb5755c4581
/code/sunlight/API.h
08f098b15554b7721e49274c5a69711214ac20d1
[]
no_license
dennistimmermann/iot-sunlight
f13ddcdd8e8f4020219feb0b19088491580068ec
78380c1213bea326bfebce8c9d1ee61d1aa73e06
refs/heads/master
2021-01-01T05:11:36.027448
2016-05-30T10:04:42
2016-05-30T10:04:42
59,310,198
3
0
null
null
null
null
UTF-8
C++
false
false
378
h
API.h
#ifndef H_API #define H_API #include "Arduino.h" #include <TimeLib.h> #include <WiFiClient.h> #include <ESP8266HTTPClient.h> class API { public: size_t parseTime(String t); int getTimezone(String t); void fetchAPI(String lat, String lon); void fetchTime(); int timeOffset = 0; size_t sunrise = 0; size_t sunset = 1; private: }; #endif H_API
38abb75e117fc64246b3d242d9a1bf51f51494d4
b04a0c0cd5e5023f06e7667ca92e0fc0fcf78d73
/src/ground.h
af91156e19343857bb29893e8b2c1454fff21d0c
[ "MIT" ]
permissive
felipefr/MBS
55a206046561fc136f73fd511cc16f5279821e81
6731d2c8334bbbc74b5408ffb771b6b4b53ed12b
refs/heads/main
2023-07-13T02:51:56.404688
2021-08-24T20:57:57
2021-08-24T20:57:57
399,600,102
0
0
null
null
null
null
UTF-8
C++
false
false
526
h
ground.h
// Classe de fixacao, herda a classe de Restricoes class Ground: public Constraint { public: Vetor c; // posicao relativa do corpo fixo ao SC global // construtor Ground(int label,Body &bd, double c1, double c2, double c3); // atualizacoes void C_upd(Vetor& C) { C[slice(l1,3,1)]=b1->q-c; } void Cq_upd(Matriz& Cq) {Cq[l1][l1]=1.0; Cq[l1+1][l1+1]=1.0; Cq[l1+2][l1+2]=1.0;} }; Ground::Ground(int label,Body &bd, double c1, double c2, double c3): Constraint(label,bd) { c=Vetor(3); c[0]=c1; c[1]=c2; c[2]=c3; }
ad2143c855e85c48aa11f9c2b349b6f6234d082c
7b8774d7027bcc4beae45ad729c32cdda34defe8
/minimum-spanning-tree/DisjointSetUnion.cpp
b53e95f9f8ae34ed39eccf425b88324e92f28859
[]
no_license
AnnaGudkova/combinatorial-algorithms
a31d13b8974766825f2f023d11a6134f4b70e331
46127fbbeb7fb545f5f1fe782580aed0a70a9c81
refs/heads/master
2021-01-18T15:19:43.669008
2012-12-21T09:02:31
2012-12-21T09:02:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
946
cpp
DisjointSetUnion.cpp
#include "DisjointSetUnion.hpp" #define START_PARENT_NUMBER 10 DisjointSetUnion::DisjointSetUnion() { this->parent.resize(START_PARENT_NUMBER, -1); } DisjointSetUnion::~DisjointSetUnion() {} void DisjointSetUnion::makeSet(int vertex) { while ((unsigned int) vertex >= this->parent.size()) this->parent.resize(2 * this->parent.size(), -1); this->parent[vertex] = vertex; } void DisjointSetUnion::unionSet(int vertex_one, int vertex_two) { vertex_one = this->findSet(vertex_one); vertex_two = this->findSet(vertex_two); if (vertex_one != vertex_two) { this->parent[vertex_one] = vertex_two; } } // Применена эвристика сжатия пути int DisjointSetUnion::findSet(int vertex) { if (this->parent[vertex] == -1) return -1; if (this->parent[vertex] == vertex) return vertex; return this->parent[vertex] = this->findSet( this->parent[vertex] ); }
50986658b7a4e742e64e1ddfbf6702ca9b210e6b
1202233d05402df9ed808ec023355541bdb24aac
/twitPick/src/EncodedUrl.h
698a67ac6546f5c1c3dcdba2c477767cbbc94c59
[ "Apache-2.0" ]
permissive
rlunaro/twitPick
f814a43e33f11258d5f94884767e994236e43e60
91a8be4dde7bbca1bbe39f7fe8e36cf90e88338f
refs/heads/master
2020-04-13T18:51:51.809778
2019-01-20T17:33:13
2019-01-20T17:33:13
163,312,140
0
0
null
null
null
null
UTF-8
C++
false
false
965
h
EncodedUrl.h
/* * Copyright 2018 Raul Luna * * 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. * */ /* * EncodedUrl.h * * rluna * Jul 20, 2018 * */ #ifndef ENCODEDURL_H_ #define ENCODEDURL_H_ #include <string> #include <curl/curl.h> class EncodedUrl { char *escapedUrl; public: EncodedUrl( CURL *curlHandle, std::string url ); EncodedUrl( CURL *curlHandle, char *url, size_t size ); ~EncodedUrl(); char *getUrlEncoded(); }; #endif /* ENCODEDURL_H_ */
5d981b2241fa3eec21071483a7e4e8cde42195f1
4adace3b69868884f9f160bc019f91050219513f
/cplusplus/深浅拷贝.cpp
c58f306389abd0c8680b75209812ea696e20ae0d
[]
no_license
Dawn-K/Andy
f14e23d1b1317e2ad078b63756dd67b60ed6f4ce
98845bb46312d5195987bc08d9a957a45cf33d45
refs/heads/master
2021-09-20T08:35:03.989167
2018-08-07T02:45:26
2018-08-07T02:45:26
null
0
0
null
null
null
null
GB18030
C++
false
false
2,139
cpp
深浅拷贝.cpp
//深浅拷贝的展示 //浅拷贝指的是将值直接地拷贝给另一个变量 //深拷贝指的是指向两块不同的内存,然后只对应相等 //深拷贝:新建一个堆, //然后就通过循环的方法把堆中的一个一个的数据拷过去。 //这样就可以避免在修改拷贝对象的数据时, //同时改变了被拷贝对象的数据 #include<iostream> using namespace std; //定义类 Array class Array { public: Array(int _count) { m_iCount =_count; m_pArr = new int [m_iCount]; //在实例化的同时申请内存 for(int i=0;i<m_iCount;i++) m_pArr[i]=i; //然后逐个填入数据 cout<<"Array()"<<endl; } // Array(const Array& arr) // { // cout<<"Array(const Array& arr)"<<endl; // m_pArr =arr.m_pArr; // m_iCount=arr.m_iCount; // } Array(const Array& arr) { m_iCount=arr.m_iCount; m_pArr =new int [m_iCount]; for(int i=0;i<m_iCount;i++) m_pArr[i]= arr.m_pArr[i]; } ~Array() { //销毁对象,避免内存泄漏 delete []m_pArr; m_pArr=NULL; cout<<"~Array()"<<endl; } void setCount(int _count) { m_iCount=_count; } int getCount(void) { return m_iCount; } void printAddr() { cout<<"地址是: "<<m_pArr<<endl; } void printArr() { for(int i=0;i<m_iCount;i++) cout<<m_pArr[i]<<" "; cout<<endl; } private: int m_iCount; int *m_pArr; }; int main() { Array arr1(5); arr1.printAddr(); arr1.printArr(); Array arr2(arr1); arr2.printAddr(); arr2.printArr(); return 0; } /*浅拷贝输出结果 Array() 地址是: 0xc0c98 Array(const Array& arr) 地址是: 0xc0c98 ~Array() ~Array() 可见,浅拷贝会使得两个指针指向同一块内存 这在执行析构函数的时候,会报错(同一块内存释放了两次) */ /*深拷贝输出结果 Array() 地址是: 0x2b00c98 地址是: 0x2b00cb8 ~Array() ~Array() 可见,深拷贝是不同的地址 */
773f54a24343ac14aee3ecefd6f10071be0583a2
adf99a0b01b3753de452a2736ce5c55f48ffc4f6
/X-Drive/ROBOT_CONFIG__javelinbot2.hpp
8ad7d0ae9c0b84c992bdcb706345736d8418ded9
[]
no_license
rasheeddo/mbedCode
ef1906bc0a82b39a79a375eef06c56404495e1bf
e74721df277cfc3007b7fc2db9b5f39585481e5e
refs/heads/master
2022-04-24T07:14:53.624590
2019-10-07T07:48:39
2019-10-07T07:48:39
198,154,243
0
1
null
2019-10-07T07:48:40
2019-07-22T05:36:07
Makefile
UTF-8
C++
false
false
432
hpp
ROBOT_CONFIG__javelinbot2.hpp
#ifndef __ROBOT__CONFIG__HPP #define __ROBOT__CONFIG__HPP // Javelinbot #2 (the one with the larger payload) #define _MOAB_IP_ADDRESS "192.168.53.202" #define _NETMASK "255.255.255.0" #define _DEFUALT_GATEWAY "192.168.53.1" #define _BROADCAST_IP_ADDRESS "192.168.53.255" #define _AUTOPILOT_IP_ADDRESS "192.168.53.212" #define _STEERING_PW_CENTER 0.001426 #define _STEERING_PW_RANGE 0.000350 #endif // __ROBOT__CONFIG__HPP
cdca8805904cb0f3adaa3e2d8b63e555b0e102bf
f057d8c2184cd7dab6ef64da1b4a37e514801933
/DHT_lib/DHT.cpp
80683d1f009cb4082bb00400a7ef2cddb16cd545
[]
no_license
fotopretty/SimArduino-framework
30fb63f17840e9a5ff1baf3ebf3da059ec159f5b
f68492276970cd364d95593c891b435378ae86ac
refs/heads/master
2021-06-09T19:10:14.217934
2016-10-05T16:52:58
2016-10-05T16:52:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
DHT.cpp
// #define DEBUG_Lib // #define DEBUG_OUTPUT Serial #include "DHT.h" DHT::DHT() { } bool DHT::read(int pin, int type) { pinMode(pin, OUTPUT); digitalWrite(pin, LOW); delay(20); digitalWrite(pin, HIGH); delayMicroseconds(20); pinMode(pin, INPUT_PULLUP); int timeCount=0; while(digitalRead(pin) == HIGH && timeCount<255) { timeCount++; delayMicroseconds(1); } if (timeCount<255) { for (int i=0;i<41;i++) { timeCount=0; while(digitalRead(pin) == LOW) ; while(digitalRead(pin) != LOW && timeCount < 255) { timeCount++; delayMicroseconds(1); } if (timeCount >= 255) break; if (i>0 && i<42) { tmpData[(i-1) / 8] <<= 1; tmpData[(i-1) / 8] |= (timeCount>40 ? 1 : 0); } } } #ifdef DEBUG_Lib printf("timeCount: %d\r\n", timeCount); printf("tmpData[0]: 0x%x\r\n", tmpData[0]); printf("tmpData[1]: 0x%x\r\n", tmpData[1]); printf("tmpData[2]: 0x%x\r\n", tmpData[2]); printf("tmpData[3]: 0x%x\r\n", tmpData[3]); printf("tmpData[4]: 0x%x\r\n", tmpData[4]); printf("\r\n"); #endif if (timeCount >= 255 || (tmpData[4] != ((tmpData[0] + tmpData[1] + tmpData[2] + tmpData[3])&0xFF))) { tempC = tempF = humidity = 0; return false; } switch (type) { case TYPE_DHT11: case TYPE_DHT12: humidity = tmpData[0]; tempC = tmpData[2]; break; case TYPE_DHT22: case TYPE_DHT21: humidity = tmpData[0]; humidity *= 256; humidity += tmpData[1]; humidity *= 0.1; tempC = tmpData[2] & 0x7F; tempC *= 256; tempC += tmpData[3]; tempC *= 0.1; if (tmpData[2] & 0x80) tempC *= -1; } tempF = tempC * 9.0 / 5.0 + 32.0; return true; }
880e98e8309f50341cc222a88271139683ca6759
dd949f215d968f2ee69bf85571fd63e4f085a869
/subarchitectures/vision.sa/branches/stable-0/src/c++/vision/components/ObjectTracker2/src/Resources.cpp
3d1b91e79b7787f415c20c86d19fa56f525133e3
[]
no_license
marc-hanheide/cogx
a3fd395805f1b0ad7d713a05b9256312757b37a9
cb9a9c9cdfeba02afac6a83d03b7c6bb778edb95
refs/heads/master
2022-03-16T23:36:21.951317
2013-12-10T23:49:07
2013-12-10T23:49:07
219,460,352
1
2
null
null
null
null
UTF-8
C++
false
false
11,139
cpp
Resources.cpp
#include "Resources.h" #include "Messages.h" // *** PRIVATE *** int Resources::SearchName(NameList* list, const char* filename){ // parse through name list int i = 0; NameList::iterator it_name = list->begin(); while(it_name != list->end()){ if(!strcmp((*it_name),filename)) return i; it_name++; i++; } // not found return -1; } // *** PUBLIC *** Resources::Resources(){ m_capture = 0; m_image = 0; m_screen = 0; m_ip = 0; m_ortho_search = 0; m_frustum = 0; m_showlog = false; } Resources::~Resources(){ ReleaseModel(); ReleaseTexture(); ReleaseShader(); ReleaseCamera(); ReleaseImageProcessor(); ReleaseOrthoSearch(); ReleaseFrustum(); ReleaseScreen(); ReleaseCapture(); if(m_showlog) g_Messages->log("Resources released", "Resources::~Resources()"); } // *** Initialisation *** IplImage* Resources::InitCapture(float width, float height, int camID){ m_capture = cvCreateCameraCapture(camID); if(!m_capture) { printf( "[Resources::InitCapture] Error could not initialise camera\n" ); return 0; } cvSetCaptureProperty(m_capture, CV_CAP_PROP_FRAME_WIDTH, width ); cvSetCaptureProperty(m_capture, CV_CAP_PROP_FRAME_HEIGHT, height ); float w = cvGetCaptureProperty( m_capture, CV_CAP_PROP_FRAME_WIDTH ); float h = cvGetCaptureProperty( m_capture, CV_CAP_PROP_FRAME_HEIGHT ); if(m_showlog) printf("Camera settings: %.1f x %.1f\n", w, h); m_image = cvQueryFrame(m_capture); cvConvertImage(m_image, m_image, CV_CVTIMG_FLIP | CV_CVTIMG_SWAP_RB); //cvFlip(m_image, m_image, 1); return m_image; } SDL_Surface* Resources::InitScreen(int width, int height){ if(!m_screen){ if((SDL_Init(SDL_INIT_VIDEO)==-1)) { printf("[Resources::GetScreen] Error could not initialize SDL: %s\n", SDL_GetError()); return 0; } // Set mode for video output (width, height, resolution) SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); // activate alpha channel //glPixelStorei(GL_PACK_ALIGNMENT, 8); // supposed to be faster //glPixelStorei(GL_UNPACK_ALIGNMENT, 8); // supposed to be faster m_screen = SDL_SetVideoMode( width, height, 0, SDL_OPENGL ); if ( !m_screen) { printf( "[Resources::GetScreen] Error setting video mode: %s\n", SDL_GetError( ) ); SDL_Quit(); return 0; } }else{ printf( "[Resources::GetScreen] Warning SDL allready initialised\n" ); } return m_screen; } ImageProcessor* Resources::InitImageProcessor(int width, int height, Camera* cam){ if(width==0||height==0){ printf("[Resources::GetImageProcessor] Error ImageProcessor needs width and height for initialisation\n"); return 0; } if(!m_ip) m_ip = new(ImageProcessor); else printf("[Resources::GetImageProcessor] Warning re-initialising ImageProcessor\n"); if( !(m_ip->init(width, height, cam)) ){ printf("[Resources::GetImageProcessor] Error could not initialise ImageProcessor\n"); delete(m_ip); m_ip = 0; return 0; } return m_ip; } OrthoSearch* Resources::InitOrthoSearch(float width, float height){ if(!m_ortho_search) m_ortho_search = new OrthoSearch(width, height); return m_ortho_search; } Frustum* Resources::InitFrustum(){ if(!m_frustum) m_frustum = new Frustum(); return m_frustum; } // *** Release-functions *** void Resources::ReleaseCapture(){ if(m_capture) cvReleaseCapture(&m_capture); m_capture = 0; } void Resources::ReleaseScreen(){ SDL_Quit(); m_screen = 0; } void Resources::ReleaseImageProcessor(){ if(m_ip) delete(m_ip); m_ip = 0; } void Resources::ReleaseOrthoSearch(){ if(m_ortho_search) delete(m_ortho_search); m_ortho_search = 0; } void Resources::ReleaseFrustum(){ if(m_frustum) delete(m_frustum); m_frustum = 0; } // *** Get-functions *** IplImage* Resources::GetNewImage(){ if(!m_capture){ printf("[Resources::GetNewImage] Error camera not initialised\n" ); return 0; } m_image = cvQueryFrame(m_capture); cvConvertImage(m_image, m_image, CV_CVTIMG_SWAP_RB); //cvFlip(m_image, m_image, 1); return m_image; } IplImage* Resources::GetImage(){ if(!m_image){ return GetNewImage(); } return m_image; } SDL_Surface* Resources::GetScreen(){ if(!m_screen){ printf("[Resources::GetScreen] Error SDL not initialised\n" ); return 0; } return m_screen; } ImageProcessor* Resources::GetImageProcessor(){ if(!m_ip){ printf("[Resources::GetImageProcessor] Error ImageProcessor not initialised\n" ); return 0; } return m_ip; } OrthoSearch* Resources::GetOrthoSearch(){ if(!m_ortho_search){ printf("[Resources::GetOrthoSearch] Error OrthoSearch not initialised\n" ); return 0; } return m_ortho_search; } Frustum* Resources::GetFrustum(){ if(!m_frustum){ printf("[Resources::GetFrustum] Warning Frustum not initialised\n" ); return 0; } return m_frustum; } // *** Add-functions *** int Resources::AddModel(Model* model, const char* name){ // check if texture allready loaded before by comparing filename int modelID = SearchModelName(name); if(modelID != -1){ printf("[Resources::AddModel] Warning model allready exists: '%s'", name); return modelID; // return existing texture ID } char* tmp_name = new char[FN_LEN]; strcpy(tmp_name, name); // put model into texture list m_modelNameList.push_back(tmp_name); m_modelList.push_back(model); modelID = m_modelList.size()-1; if(m_showlog) printf("Model %i loaded: %s\n", modelID, name); return modelID; } int Resources::AddPlyModel(const char* filename){ bool loaded = false; // check if texture allready loaded before by comparing filename int modelID = SearchModelName(filename); if(modelID != -1) return modelID; // return existing texture ID // texture doesn't exist and needs to be loaded char fullname[FN_LEN]; sprintf(fullname, "%s%s", m_modelPath, filename); PlyModel* model = new PlyModel(); loaded = model->load(fullname); if(!loaded){ printf("[Resources::AddModel] Error failed to load model %s\n", fullname); delete(model); return -1; } char* name = new char[FN_LEN]; strcpy(name, filename); // put model into texture list m_modelNameList.push_back(name); m_modelList.push_back(model); modelID = m_modelList.size()-1; if(m_showlog) printf("Model %i loaded: %s\n", modelID, name); return modelID; } int Resources::AddTexture(const char* filename, const char* texturename){ bool loaded = false; int texID; if(!filename && !texturename){ printf("[Resources::AddTexture] Error no filename nor texturename given\n"); return -1; } // check if texture allready loaded before by comparing filename if(filename) texID = SearchTextureName(filename); else texID = SearchTextureName(texturename); if(texID != -1) return texID; // return existing texture ID // texture doesn't exist and needs to be loaded char fullname[FN_LEN]; sprintf(fullname, "%s%s", m_texturePath, filename); Texture* texture = new Texture(); if(filename) loaded = texture->load(fullname); else loaded = true; if(!loaded){ printf("[Resources::AddTexture] Error failed to load texture %s\n", fullname); delete(texture); return -1; } char* name = new char[FN_LEN]; if(filename) strcpy(name, filename); else if(texturename) strcpy(name, texturename); // put model into texture list m_textureNameList.push_back(name); m_textureList.push_back(texture); texID = m_textureList.size()-1; if(m_showlog) printf("Texture %i loaded: %s\n", texID, name); return texID; } int Resources::AddShader( const char* shadername, const char* vertex_file, const char* fragment_file, const char* header) { // check if texture allready loaded before by comparing filename int shaderID = SearchShaderName(shadername); if(shaderID != -1) return shaderID; // return existing texture ID // texture doesn't exist and needs to be loaded char vertex_fullname[FN_LEN]; char fragment_fullname[FN_LEN]; char header_fullname[FN_LEN]; sprintf(vertex_fullname, "%s%s", m_shaderPath, vertex_file); sprintf(fragment_fullname, "%s%s", m_shaderPath, fragment_file); sprintf(header_fullname, "%s%s", m_shaderPath, header); if(vertex_file) vertex_file = &vertex_fullname[0]; if(fragment_file) fragment_file = &fragment_fullname[0]; if(header) header = &header_fullname[0]; Shader* shader = new Shader(vertex_file, fragment_file, header); if(!shader->getStatus()){ printf("[Resources::AddShader] Error failed to load shader %s\n", shadername); delete(shader); return -1; } char* name = new char[FN_LEN]; strcpy(name, shadername); // put model into texture list m_shaderNameList.push_back(name); m_shaderList.push_back(shader); shaderID = m_shaderList.size()-1; if(m_showlog) printf("Shader %i loaded: %s\n", shaderID, name); return shaderID; } int Resources::AddCamera(const char* camname){ int camID = SearchCameraName(camname); if(camID != -1) return camID; Camera* camera = new Camera(); char* name = new char[FN_LEN]; strcpy(name, camname); m_cameraNameList.push_back(name); m_cameraList.push_back(camera); camID = m_cameraList.size()-1; if(m_showlog) printf("Camera %i loaded: %s\n", camID, name); return camID; } // *** Release void Resources::ReleaseModel(){ // release Models ModelList::iterator it_model = m_modelList.begin(); while(it_model != m_modelList.end()){ delete(*it_model); it_model++; } // release Modelnames NameList::iterator it_name = m_modelNameList.begin(); while(it_name != m_modelNameList.end()){ delete(*it_name); it_name++; } } void Resources::ReleaseTexture(){ // release Textures TextureList::iterator it_texture = m_textureList.begin(); while(it_texture != m_textureList.end()){ delete(*it_texture); it_texture++; } // release Texturenames NameList::iterator it_name = m_textureNameList.begin(); while(it_name != m_textureNameList.end()){ delete(*it_name); it_name++; } } void Resources::ReleaseShader(){ // release Shader ShaderList::iterator it_shader = m_shaderList.begin(); while(it_shader != m_shaderList.end()){ delete(*it_shader); it_shader++; } // release Shadernames NameList::iterator it_name = m_shaderNameList.begin(); while(it_name != m_shaderNameList.end()){ delete(*it_name); it_name++; } } void Resources::ReleaseCamera(){ // release Camera CameraList::iterator it_camera = m_cameraList.begin(); while(it_camera != m_cameraList.end()){ delete(*it_camera); it_camera++; } // release Cameranames NameList::iterator it_name = m_cameraNameList.begin(); while(it_name != m_cameraNameList.end()){ delete(*it_name); it_name++; } } // *** Search-functions *** int Resources::SearchModelName(const char* filename){ SearchName(&m_modelNameList, filename); } int Resources::SearchTextureName(const char* filename){ SearchName(&m_textureNameList, filename); } int Resources::SearchShaderName(const char* filename){ SearchName(&m_shaderNameList, filename); } int Resources::SearchCameraName(const char* name){ SearchName(&m_cameraNameList, name); }
d416adf932b81d06cd43be1cd000c5af4c8cbd06
54320ef64dd0548a5b5016feed14c606a5fd1e76
/Vagharsh_Hakobyan/Homework/C/20151031/k_n_2zero.cpp
c3a64c53f45e937b80f8eb77f38f0e9c4aa00f82
[]
no_license
ITC-Vanadzor/ITC-7
9859ebbd0d824d3a480ea281bbdb14edbb6a374e
d2bfcdc3a1faea4cdc1d7e555404445ac8768c66
refs/heads/master
2021-01-17T15:43:29.646485
2019-02-17T19:07:36
2019-02-17T19:07:36
44,699,731
0
4
null
2017-04-13T18:45:36
2015-10-21T19:38:34
JavaScript
UTF-8
C++
false
false
1,342
cpp
k_n_2zero.cpp
//number of 2 zero's combination #include <iostream> #include <cmath> using namespace std; int InputNumber(int limit, char name) { int n1 = limit; while (n1 <= limit){ cout << "Ներմուծել " << limit << "֊ից մեծ " << name << " բնական թիվ՝ " << endl; cin >> n1; } return n1; } void Zero(int *a, int b) { for(int i = 0; i < b; ++i) { a[i] = 0; } } int main() { int k = InputNumber(1,'k'), n = InputNumber(1,'n'); int *number; number = new int [n]; int max_demical=pow(k,n); int counter=0; int counter1=0; for (int i=0; i<max_demical;++i) { Zero(number,n); int c=i; int j=0; while (c>0) { number[j]=c%k; if (number[n-1]!=0) { counter1=counter1+1; } j=j+1; c=c/k; } j=0; while (j<(n-1)) { if (number[j]==0 && number[j+1]==0 && number[n-1]) { counter=counter+1; j=n; } j=j+1; } } delete number; cout << k <<"-ական համակարգի " << n << "-անիշ թվերի քանակն է՝ " << counter1 << endl; cout << "Երկու և ավելի անընդմեջ զրոներով թվերի քանակն է՝ " << counter << endl; cout << "Առանց երկու անընդմեջ զրոների թվերի քանակն է՝ " << counter1-counter << endl; return 0; }
b4a85fb8dd67a6ed302ae3e3549da06b73524440
921c689451ff3b6e472cc6ae6a34774c4f57e68b
/llvm-2.8/tools/clang/lib/Checker/CFRefCount.cpp
6fa48b2923fe17575bcab0f6fda43ca51c95e4af
[ "NCSA" ]
permissive
xpic-toolchain/xpic_toolchain
36cae905bbf675d26481bee19b420283eff90a79
9e6d4276cc8145a934c31b0d3292a382fc2e5e92
refs/heads/master
2021-01-21T04:37:18.963215
2016-05-19T12:34:11
2016-05-19T12:34:11
29,474,690
4
0
null
null
null
null
UTF-8
C++
false
false
120,445
cpp
CFRefCount.cpp
// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the methods for CFRefCount, which implements // a reference count checker for Core Foundation (Mac OS X). // //===----------------------------------------------------------------------===// #include "clang/AST/DeclObjC.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Checker/BugReporter/BugType.h" #include "clang/Checker/BugReporter/PathDiagnostic.h" #include "clang/Checker/Checkers/LocalCheckers.h" #include "clang/Checker/DomainSpecific/CocoaConventions.h" #include "clang/Checker/PathSensitive/CheckerVisitor.h" #include "clang/Checker/PathSensitive/GRExprEngineBuilders.h" #include "clang/Checker/PathSensitive/GRStateTrait.h" #include "clang/Checker/PathSensitive/GRTransferFuncs.h" #include "clang/Checker/PathSensitive/SymbolManager.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableList.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include <stdarg.h> using namespace clang; using llvm::StringRef; using llvm::StrInStrNoCase; namespace { class InstanceReceiver { const ObjCMessageExpr *ME; const LocationContext *LC; public: InstanceReceiver(const ObjCMessageExpr *me = 0, const LocationContext *lc = 0) : ME(me), LC(lc) {} bool isValid() const { return ME && ME->isInstanceMessage(); } operator bool() const { return isValid(); } SVal getSValAsScalarOrLoc(const GRState *state) { assert(isValid()); // We have an expression for the receiver? Fetch the value // of that expression. if (const Expr *Ex = ME->getInstanceReceiver()) return state->getSValAsScalarOrLoc(Ex); // Otherwise we are sending a message to super. In this case the // object reference is the same as 'self'. if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl()) return state->getSVal(state->getRegion(SelfDecl, LC)); return UnknownVal(); } SourceRange getSourceRange() const { assert(isValid()); if (const Expr *Ex = ME->getInstanceReceiver()) return Ex->getSourceRange(); // Otherwise we are sending a message to super. SourceLocation L = ME->getSuperLoc(); assert(L.isValid()); return SourceRange(L, L); } }; } static const ObjCMethodDecl* ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) { const ObjCInterfaceDecl *ID = MD->getClassInterface(); return MD->isInstanceMethod() ? ID->lookupInstanceMethod(MD->getSelector()) : ID->lookupClassMethod(MD->getSelector()); } namespace { class GenericNodeBuilder { GRStmtNodeBuilder *SNB; const Stmt *S; const void *tag; GREndPathNodeBuilder *ENB; public: GenericNodeBuilder(GRStmtNodeBuilder &snb, const Stmt *s, const void *t) : SNB(&snb), S(s), tag(t), ENB(0) {} GenericNodeBuilder(GREndPathNodeBuilder &enb) : SNB(0), S(0), tag(0), ENB(&enb) {} ExplodedNode *MakeNode(const GRState *state, ExplodedNode *Pred) { if (SNB) return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag), state, Pred); assert(ENB); return ENB->generateNode(state, Pred); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Primitives used for constructing summaries for function/method calls. //===----------------------------------------------------------------------===// /// ArgEffect is used to summarize a function/method call's effect on a /// particular argument. enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing, DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape, NewAutoreleasePool, SelfOwn, StopTracking }; namespace llvm { template <> struct FoldingSetTrait<ArgEffect> { static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) { ID.AddInteger((unsigned) X); } }; } // end llvm namespace /// ArgEffects summarizes the effects of a function/method call on all of /// its arguments. typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects; namespace { /// RetEffect is used to summarize a function/method call's behavior with /// respect to its return value. class RetEffect { public: enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol, NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias, OwnedWhenTrackedReceiver }; enum ObjKind { CF, ObjC, AnyObj }; private: Kind K; ObjKind O; unsigned index; RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {} RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {} public: Kind getKind() const { return K; } ObjKind getObjKind() const { return O; } unsigned getIndex() const { assert(getKind() == Alias); return index; } bool isOwned() const { return K == OwnedSymbol || K == OwnedAllocatedSymbol || K == OwnedWhenTrackedReceiver; } static RetEffect MakeOwnedWhenTrackedReceiver() { return RetEffect(OwnedWhenTrackedReceiver, ObjC); } static RetEffect MakeAlias(unsigned Idx) { return RetEffect(Alias, Idx); } static RetEffect MakeReceiverAlias() { return RetEffect(ReceiverAlias); } static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) { return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o); } static RetEffect MakeNotOwned(ObjKind o) { return RetEffect(NotOwnedSymbol, o); } static RetEffect MakeGCNotOwned() { return RetEffect(GCNotOwnedSymbol, ObjC); } static RetEffect MakeNoRet() { return RetEffect(NoRet); } }; //===----------------------------------------------------------------------===// // Reference-counting logic (typestate + counts). //===----------------------------------------------------------------------===// class RefVal { public: enum Kind { Owned = 0, // Owning reference. NotOwned, // Reference is not owned by still valid (not freed). Released, // Object has been released. ReturnedOwned, // Returned object passes ownership to caller. ReturnedNotOwned, // Return object does not pass ownership to caller. ERROR_START, ErrorDeallocNotOwned, // -dealloc called on non-owned object. ErrorDeallocGC, // Calling -dealloc with GC enabled. ErrorUseAfterRelease, // Object used after released. ErrorReleaseNotOwned, // Release of an object that was not owned. ERROR_LEAK_START, ErrorLeak, // A memory leak due to excessive reference counts. ErrorLeakReturned, // A memory leak due to the returning method not having // the correct naming conventions. ErrorGCLeakReturned, ErrorOverAutorelease, ErrorReturnedNotOwned }; private: Kind kind; RetEffect::ObjKind okind; unsigned Cnt; unsigned ACnt; QualType T; RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t) : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {} public: Kind getKind() const { return kind; } RetEffect::ObjKind getObjKind() const { return okind; } unsigned getCount() const { return Cnt; } unsigned getAutoreleaseCount() const { return ACnt; } unsigned getCombinedCounts() const { return Cnt + ACnt; } void clearCounts() { Cnt = 0; ACnt = 0; } void setCount(unsigned i) { Cnt = i; } void setAutoreleaseCount(unsigned i) { ACnt = i; } QualType getType() const { return T; } bool isOwned() const { return getKind() == Owned; } bool isNotOwned() const { return getKind() == NotOwned; } bool isReturnedOwned() const { return getKind() == ReturnedOwned; } bool isReturnedNotOwned() const { return getKind() == ReturnedNotOwned; } static RefVal makeOwned(RetEffect::ObjKind o, QualType t, unsigned Count = 1) { return RefVal(Owned, o, Count, 0, t); } static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t, unsigned Count = 0) { return RefVal(NotOwned, o, Count, 0, t); } // Comparison, profiling, and pretty-printing. bool operator==(const RefVal& X) const { return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt; } RefVal operator-(size_t i) const { return RefVal(getKind(), getObjKind(), getCount() - i, getAutoreleaseCount(), getType()); } RefVal operator+(size_t i) const { return RefVal(getKind(), getObjKind(), getCount() + i, getAutoreleaseCount(), getType()); } RefVal operator^(Kind k) const { return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(), getType()); } RefVal autorelease() const { return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1, getType()); } void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned) kind); ID.AddInteger(Cnt); ID.AddInteger(ACnt); ID.Add(T); } void print(llvm::raw_ostream& Out) const; }; void RefVal::print(llvm::raw_ostream& Out) const { if (!T.isNull()) Out << "Tracked Type:" << T.getAsString() << '\n'; switch (getKind()) { default: assert(false); case Owned: { Out << "Owned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case NotOwned: { Out << "NotOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case ReturnedOwned: { Out << "ReturnedOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case ReturnedNotOwned: { Out << "ReturnedNotOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case Released: Out << "Released"; break; case ErrorDeallocGC: Out << "-dealloc (GC)"; break; case ErrorDeallocNotOwned: Out << "-dealloc (not-owned)"; break; case ErrorLeak: Out << "Leaked"; break; case ErrorLeakReturned: Out << "Leaked (Bad naming)"; break; case ErrorGCLeakReturned: Out << "Leaked (GC-ed at return)"; break; case ErrorUseAfterRelease: Out << "Use-After-Release [ERROR]"; break; case ErrorReleaseNotOwned: Out << "Release of Not-Owned [ERROR]"; break; case RefVal::ErrorOverAutorelease: Out << "Over autoreleased"; break; case RefVal::ErrorReturnedNotOwned: Out << "Non-owned object returned instead of owned"; break; } if (ACnt) { Out << " [ARC +" << ACnt << ']'; } } } //end anonymous namespace //===----------------------------------------------------------------------===// // RefBindings - State used to track object reference counts. //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings; namespace clang { template<> struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> { static void* GDMIndex() { static int RefBIndex = 0; return &RefBIndex; } }; } //===----------------------------------------------------------------------===// // Summaries //===----------------------------------------------------------------------===// namespace { class RetainSummary { /// Args - an ordered vector of (index, ArgEffect) pairs, where index /// specifies the argument (starting from 0). This can be sparsely /// populated; arguments with no entry in Args use 'DefaultArgEffect'. ArgEffects Args; /// DefaultArgEffect - The default ArgEffect to apply to arguments that /// do not have an entry in Args. ArgEffect DefaultArgEffect; /// Receiver - If this summary applies to an Objective-C message expression, /// this is the effect applied to the state of the receiver. ArgEffect Receiver; /// Ret - The effect on the return value. Used to indicate if the /// function/method call returns a new tracked symbol, returns an /// alias of one of the arguments in the call, and so on. RetEffect Ret; /// EndPath - Indicates that execution of this method/function should /// terminate the simulation of a path. bool EndPath; public: RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff, ArgEffect ReceiverEff, bool endpath = false) : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R), EndPath(endpath) {} /// getArg - Return the argument effect on the argument specified by /// idx (starting from 0). ArgEffect getArg(unsigned idx) const { if (const ArgEffect *AE = Args.lookup(idx)) return *AE; return DefaultArgEffect; } /// setDefaultArgEffect - Set the default argument effect. void setDefaultArgEffect(ArgEffect E) { DefaultArgEffect = E; } /// getRetEffect - Returns the effect on the return value of the call. RetEffect getRetEffect() const { return Ret; } /// setRetEffect - Set the effect of the return value of the call. void setRetEffect(RetEffect E) { Ret = E; } /// isEndPath - Returns true if executing the given method/function should /// terminate the path. bool isEndPath() const { return EndPath; } /// getReceiverEffect - Returns the effect on the receiver of the call. /// This is only meaningful if the summary applies to an ObjCMessageExpr*. ArgEffect getReceiverEffect() const { return Receiver; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Data structures for constructing summaries. //===----------------------------------------------------------------------===// namespace { class ObjCSummaryKey { IdentifierInfo* II; Selector S; public: ObjCSummaryKey(IdentifierInfo* ii, Selector s) : II(ii), S(s) {} ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s) : II(d ? d->getIdentifier() : 0), S(s) {} ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s) : II(d ? d->getIdentifier() : ii), S(s) {} ObjCSummaryKey(Selector s) : II(0), S(s) {} IdentifierInfo* getIdentifier() const { return II; } Selector getSelector() const { return S; } }; } namespace llvm { template <> struct DenseMapInfo<ObjCSummaryKey> { static inline ObjCSummaryKey getEmptyKey() { return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(), DenseMapInfo<Selector>::getEmptyKey()); } static inline ObjCSummaryKey getTombstoneKey() { return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(), DenseMapInfo<Selector>::getTombstoneKey()); } static unsigned getHashValue(const ObjCSummaryKey &V) { return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier()) & 0x88888888) | (DenseMapInfo<Selector>::getHashValue(V.getSelector()) & 0x55555555); } static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) { return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(), RHS.getIdentifier()) && DenseMapInfo<Selector>::isEqual(LHS.getSelector(), RHS.getSelector()); } }; template <> struct isPodLike<ObjCSummaryKey> { static const bool value = true; }; } // end llvm namespace namespace { class ObjCSummaryCache { typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy; MapTy M; public: ObjCSummaryCache() {} RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName, Selector S) { // Lookup the method using the decl for the class @interface. If we // have no decl, lookup using the class name. return D ? find(D, S) : find(ClsName, S); } RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) { // Do a lookup with the (D,S) pair. If we find a match return // the iterator. ObjCSummaryKey K(D, S); MapTy::iterator I = M.find(K); if (I != M.end() || !D) return I->second; // Walk the super chain. If we find a hit with a parent, we'll end // up returning that summary. We actually allow that key (null,S), as // we cache summaries for the null ObjCInterfaceDecl* to allow us to // generate initial summaries without having to worry about NSObject // being declared. // FIXME: We may change this at some point. for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) { if ((I = M.find(ObjCSummaryKey(C, S))) != M.end()) break; if (!C) return NULL; } // Cache the summary with original key to make the next lookup faster // and return the iterator. RetainSummary *Summ = I->second; M[K] = Summ; return Summ; } RetainSummary* find(IdentifierInfo* II, Selector S) { // FIXME: Class method lookup. Right now we dont' have a good way // of going between IdentifierInfo* and the class hierarchy. MapTy::iterator I = M.find(ObjCSummaryKey(II, S)); if (I == M.end()) I = M.find(ObjCSummaryKey(S)); return I == M.end() ? NULL : I->second; } RetainSummary*& operator[](ObjCSummaryKey K) { return M[K]; } RetainSummary*& operator[](Selector S) { return M[ ObjCSummaryKey(S) ]; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Data structures for managing collections of summaries. //===----------------------------------------------------------------------===// namespace { class RetainSummaryManager { //==-----------------------------------------------------------------==// // Typedefs. //==-----------------------------------------------------------------==// typedef llvm::DenseMap<const FunctionDecl*, RetainSummary*> FuncSummariesTy; typedef ObjCSummaryCache ObjCMethodSummariesTy; //==-----------------------------------------------------------------==// // Data. //==-----------------------------------------------------------------==// /// Ctx - The ASTContext object for the analyzed ASTs. ASTContext& Ctx; /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier /// "CFDictionaryCreate". IdentifierInfo* CFDictionaryCreateII; /// GCEnabled - Records whether or not the analyzed code runs in GC mode. const bool GCEnabled; /// FuncSummaries - A map from FunctionDecls to summaries. FuncSummariesTy FuncSummaries; /// ObjCClassMethodSummaries - A map from selectors (for instance methods) /// to summaries. ObjCMethodSummariesTy ObjCClassMethodSummaries; /// ObjCMethodSummaries - A map from selectors to summaries. ObjCMethodSummariesTy ObjCMethodSummaries; /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects, /// and all other data used by the checker. llvm::BumpPtrAllocator BPAlloc; /// AF - A factory for ArgEffects objects. ArgEffects::Factory AF; /// ScratchArgs - A holding buffer for construct ArgEffects. ArgEffects ScratchArgs; /// ObjCAllocRetE - Default return effect for methods returning Objective-C /// objects. RetEffect ObjCAllocRetE; /// ObjCInitRetE - Default return effect for init methods returning /// Objective-C objects. RetEffect ObjCInitRetE; RetainSummary DefaultSummary; RetainSummary* StopSummary; //==-----------------------------------------------------------------==// // Methods. //==-----------------------------------------------------------------==// /// getArgEffects - Returns a persistent ArgEffects object based on the /// data in ScratchArgs. ArgEffects getArgEffects(); enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable }; public: RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; } RetainSummary *getDefaultSummary() { RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>(); return new (Summ) RetainSummary(DefaultSummary); } RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func); RetainSummary* getCFSummaryCreateRule(const FunctionDecl* FD); RetainSummary* getCFSummaryGetRule(const FunctionDecl* FD); RetainSummary* getCFCreateGetRuleSummary(const FunctionDecl* FD, StringRef FName); RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff, ArgEffect ReceiverEff = DoNothing, ArgEffect DefaultEff = MayEscape, bool isEndPath = false); RetainSummary* getPersistentSummary(RetEffect RE, ArgEffect ReceiverEff = DoNothing, ArgEffect DefaultEff = MayEscape) { return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff); } RetainSummary *getPersistentStopSummary() { if (StopSummary) return StopSummary; StopSummary = getPersistentSummary(RetEffect::MakeNoRet(), StopTracking, StopTracking); return StopSummary; } RetainSummary *getInitMethodSummary(QualType RetTy); void InitializeClassMethodSummaries(); void InitializeMethodSummaries(); private: void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) { ObjCClassMethodSummaries[S] = Summ; } void addNSObjectMethSummary(Selector S, RetainSummary *Summ) { ObjCMethodSummaries[S] = Summ; } void addClassMethSummary(const char* Cls, const char* nullaryName, RetainSummary *Summ) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); Selector S = GetNullarySelector(nullaryName, Ctx); ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addInstMethSummary(const char* Cls, const char* nullaryName, RetainSummary *Summ) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); Selector S = GetNullarySelector(nullaryName, Ctx); ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } Selector generateSelector(va_list argp) { llvm::SmallVector<IdentifierInfo*, 10> II; while (const char* s = va_arg(argp, const char*)) II.push_back(&Ctx.Idents.get(s)); return Ctx.Selectors.getSelector(II.size(), &II[0]); } void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries, RetainSummary* Summ, va_list argp) { Selector S = generateSelector(argp); Summaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); va_end(argp); } void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp); va_end(argp); } void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp); va_end(argp); } void addPanicSummary(const char* Cls, ...) { RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(), RetEffect::MakeNoRet(), DoNothing, DoNothing, true); va_list argp; va_start (argp, Cls); addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); va_end(argp); } public: RetainSummaryManager(ASTContext& ctx, bool gcenabled) : Ctx(ctx), CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")), GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()), ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned() : RetEffect::MakeOwned(RetEffect::ObjC, true)), ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned() : RetEffect::MakeOwnedWhenTrackedReceiver()), DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */, RetEffect::MakeNoRet() /* return effect */, MayEscape, /* default argument effect */ DoNothing /* receiver effect */), StopSummary(0) { InitializeClassMethodSummaries(); InitializeMethodSummaries(); } ~RetainSummaryManager(); RetainSummary* getSummary(const FunctionDecl* FD); RetainSummary *getInstanceMethodSummary(const ObjCMessageExpr *ME, const GRState *state, const LocationContext *LC); RetainSummary* getInstanceMethodSummary(const ObjCMessageExpr* ME, const ObjCInterfaceDecl* ID) { return getInstanceMethodSummary(ME->getSelector(), 0, ID, ME->getMethodDecl(), ME->getType()); } RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName, const ObjCInterfaceDecl* ID, const ObjCMethodDecl *MD, QualType RetTy); RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName, const ObjCInterfaceDecl *ID, const ObjCMethodDecl *MD, QualType RetTy); RetainSummary *getClassMethodSummary(const ObjCMessageExpr *ME) { ObjCInterfaceDecl *Class = 0; switch (ME->getReceiverKind()) { case ObjCMessageExpr::Class: case ObjCMessageExpr::SuperClass: Class = ME->getReceiverInterface(); break; case ObjCMessageExpr::Instance: case ObjCMessageExpr::SuperInstance: break; } return getClassMethodSummary(ME->getSelector(), Class? Class->getIdentifier() : 0, Class, ME->getMethodDecl(), ME->getType()); } /// getMethodSummary - This version of getMethodSummary is used to query /// the summary for the current method being analyzed. RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) { // FIXME: Eventually this should be unneeded. const ObjCInterfaceDecl *ID = MD->getClassInterface(); Selector S = MD->getSelector(); IdentifierInfo *ClsName = ID->getIdentifier(); QualType ResultTy = MD->getResultType(); // Resolve the method decl last. if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD)) MD = InterfaceMD; if (MD->isInstanceMethod()) return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy); else return getClassMethodSummary(S, ClsName, ID, MD, ResultTy); } RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD, Selector S, QualType RetTy); void updateSummaryFromAnnotations(RetainSummary &Summ, const ObjCMethodDecl *MD); void updateSummaryFromAnnotations(RetainSummary &Summ, const FunctionDecl *FD); bool isGCEnabled() const { return GCEnabled; } RetainSummary *copySummary(RetainSummary *OldSumm) { RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>(); new (Summ) RetainSummary(*OldSumm); return Summ; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Implementation of checker data structures. //===----------------------------------------------------------------------===// RetainSummaryManager::~RetainSummaryManager() {} ArgEffects RetainSummaryManager::getArgEffects() { ArgEffects AE = ScratchArgs; ScratchArgs = AF.GetEmptyMap(); return AE; } RetainSummary* RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff, ArgEffect ReceiverEff, ArgEffect DefaultEff, bool isEndPath) { // Create the summary and return it. RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>(); new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath); return Summ; } //===----------------------------------------------------------------------===// // Summary creation for functions (largely uses of Core Foundation). //===----------------------------------------------------------------------===// static bool isRetain(const FunctionDecl* FD, StringRef FName) { return FName.endswith("Retain"); } static bool isRelease(const FunctionDecl* FD, StringRef FName) { return FName.endswith("Release"); } RetainSummary* RetainSummaryManager::getSummary(const FunctionDecl* FD) { // Look up a summary in our cache of FunctionDecls -> Summaries. FuncSummariesTy::iterator I = FuncSummaries.find(FD); if (I != FuncSummaries.end()) return I->second; // No summary? Generate one. RetainSummary *S = 0; do { // We generate "stop" summaries for implicitly defined functions. if (FD->isImplicit()) { S = getPersistentStopSummary(); break; } // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the // function's type. const FunctionType* FT = FD->getType()->getAs<FunctionType>(); const IdentifierInfo *II = FD->getIdentifier(); if (!II) break; StringRef FName = II->getName(); // Strip away preceding '_'. Doing this here will effect all the checks // down below. FName = FName.substr(FName.find_first_not_of('_')); // Inspect the result type. QualType RetTy = FT->getResultType(); // FIXME: This should all be refactored into a chain of "summary lookup" // filters. assert(ScratchArgs.isEmpty()); if (FName == "pthread_create") { // Part of: <rdar://problem/7299394>. This will be addressed // better with IPA. S = getPersistentStopSummary(); } else if (FName == "NSMakeCollectable") { // Handle: id NSMakeCollectable(CFTypeRef) S = (RetTy->isObjCIdType()) ? getUnarySummary(FT, cfmakecollectable) : getPersistentStopSummary(); } else if (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" || FName == "IOServiceNameMatching" || FName == "IORegistryEntryIDMatching" || FName == "IOOpenFirmwarePathMatching") { // Part of <rdar://problem/6961230>. (IOKit) // This should be addressed using a API table. S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), DoNothing, DoNothing); } else if (FName == "IOServiceGetMatchingService" || FName == "IOServiceGetMatchingServices") { // FIXES: <rdar://problem/6326900> // This should be addressed using a API table. This strcmp is also // a little gross, but there is no need to super optimize here. ScratchArgs = AF.Add(ScratchArgs, 1, DecRef); S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } else if (FName == "IOServiceAddNotification" || FName == "IOServiceAddMatchingNotification") { // Part of <rdar://problem/6961230>. (IOKit) // This should be addressed using a API table. ScratchArgs = AF.Add(ScratchArgs, 2, DecRef); S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } else if (FName == "CVPixelBufferCreateWithBytes") { // FIXES: <rdar://problem/7283567> // Eventually this can be improved by recognizing that the pixel // buffer passed to CVPixelBufferCreateWithBytes is released via // a callback and doing full IPA to make sure this is done correctly. // FIXME: This function has an out parameter that returns an // allocated object. ScratchArgs = AF.Add(ScratchArgs, 7, StopTracking); S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } else if (FName == "CGBitmapContextCreateWithData") { // FIXES: <rdar://problem/7358899> // Eventually this can be improved by recognizing that 'releaseInfo' // passed to CGBitmapContextCreateWithData is released via // a callback and doing full IPA to make sure this is done correctly. ScratchArgs = AF.Add(ScratchArgs, 8, StopTracking); S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), DoNothing, DoNothing); } else if (FName == "CVPixelBufferCreateWithPlanarBytes") { // FIXES: <rdar://problem/7283567> // Eventually this can be improved by recognizing that the pixel // buffer passed to CVPixelBufferCreateWithPlanarBytes is released // via a callback and doing full IPA to make sure this is done // correctly. ScratchArgs = AF.Add(ScratchArgs, 12, StopTracking); S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } // Did we get a summary? if (S) break; // Enable this code once the semantics of NSDeallocateObject are resolved // for GC. <rdar://problem/6619988> #if 0 // Handle: NSDeallocateObject(id anObject); // This method does allow 'nil' (although we don't check it now). if (strcmp(FName, "NSDeallocateObject") == 0) { return RetTy == Ctx.VoidTy ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc) : getPersistentStopSummary(); } #endif if (RetTy->isPointerType()) { // For CoreFoundation ('CF') types. if (cocoa::isRefType(RetTy, "CF", FName)) { if (isRetain(FD, FName)) S = getUnarySummary(FT, cfretain); else if (FName.find("MakeCollectable") != StringRef::npos) S = getUnarySummary(FT, cfmakecollectable); else S = getCFCreateGetRuleSummary(FD, FName); break; } // For CoreGraphics ('CG') types. if (cocoa::isRefType(RetTy, "CG", FName)) { if (isRetain(FD, FName)) S = getUnarySummary(FT, cfretain); else S = getCFCreateGetRuleSummary(FD, FName); break; } // For the Disk Arbitration API (DiskArbitration/DADisk.h) if (cocoa::isRefType(RetTy, "DADisk") || cocoa::isRefType(RetTy, "DADissenter") || cocoa::isRefType(RetTy, "DASessionRef")) { S = getCFCreateGetRuleSummary(FD, FName); break; } break; } // Check for release functions, the only kind of functions that we care // about that don't return a pointer type. if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) { // Test for 'CGCF'. FName = FName.substr(FName.startswith("CGCF") ? 4 : 2); if (isRelease(FD, FName)) S = getUnarySummary(FT, cfrelease); else { assert (ScratchArgs.isEmpty()); // Remaining CoreFoundation and CoreGraphics functions. // We use to assume that they all strictly followed the ownership idiom // and that ownership cannot be transferred. While this is technically // correct, many methods allow a tracked object to escape. For example: // // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); // CFDictionaryAddValue(y, key, x); // CFRelease(x); // ... it is okay to use 'x' since 'y' has a reference to it // // We handle this and similar cases with the follow heuristic. If the // function name contains "InsertValue", "SetValue", "AddValue", // "AppendValue", or "SetAttribute", then we assume that arguments may // "escape." This means that something else holds on to the object, // allowing it be used even after its local retain count drops to 0. ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos|| StrInStrNoCase(FName, "AddValue") != StringRef::npos || StrInStrNoCase(FName, "SetValue") != StringRef::npos || StrInStrNoCase(FName, "AppendValue") != StringRef::npos|| StrInStrNoCase(FName, "SetAttribute") != StringRef::npos) ? MayEscape : DoNothing; S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E); } } } while (0); if (!S) S = getDefaultSummary(); // Annotations override defaults. assert(S); updateSummaryFromAnnotations(*S, FD); FuncSummaries[FD] = S; return S; } RetainSummary* RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl* FD, StringRef FName) { if (FName.find("Create") != StringRef::npos || FName.find("Copy") != StringRef::npos) return getCFSummaryCreateRule(FD); if (FName.find("Get") != StringRef::npos) return getCFSummaryGetRule(FD); return getDefaultSummary(); } RetainSummary* RetainSummaryManager::getUnarySummary(const FunctionType* FT, UnaryFuncKind func) { // Sanity check that this is *really* a unary function. This can // happen if people do weird things. const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT); if (!FTP || FTP->getNumArgs() != 1) return getPersistentStopSummary(); assert (ScratchArgs.isEmpty()); switch (func) { case cfretain: { ScratchArgs = AF.Add(ScratchArgs, 0, IncRef); return getPersistentSummary(RetEffect::MakeAlias(0), DoNothing, DoNothing); } case cfrelease: { ScratchArgs = AF.Add(ScratchArgs, 0, DecRef); return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } case cfmakecollectable: { ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable); return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing); } default: assert (false && "Not a supported unary function."); return getDefaultSummary(); } } RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl* FD) { assert (ScratchArgs.isEmpty()); if (FD->getIdentifier() == CFDictionaryCreateII) { ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef); ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef); } return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); } RetainSummary* RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl* FD) { assert (ScratchArgs.isEmpty()); return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), DoNothing, DoNothing); } //===----------------------------------------------------------------------===// // Summary creation for Selectors. //===----------------------------------------------------------------------===// RetainSummary* RetainSummaryManager::getInitMethodSummary(QualType RetTy) { assert(ScratchArgs.isEmpty()); // 'init' methods conceptually return a newly allocated object and claim // the receiver. if (cocoa::isCocoaObjectRef(RetTy) || cocoa::isCFObjectRef(RetTy)) return getPersistentSummary(ObjCInitRetE, DecRefMsg); return getDefaultSummary(); } void RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ, const FunctionDecl *FD) { if (!FD) return; QualType RetTy = FD->getResultType(); // Determine if there is a special return effect for this method. if (cocoa::isCocoaObjectRef(RetTy)) { if (FD->getAttr<NSReturnsRetainedAttr>()) { Summ.setRetEffect(ObjCAllocRetE); } else if (FD->getAttr<CFReturnsRetainedAttr>()) { Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); } else if (FD->getAttr<NSReturnsNotRetainedAttr>()) { Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC)); } else if (FD->getAttr<CFReturnsNotRetainedAttr>()) { Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); } } else if (RetTy->getAs<PointerType>()) { if (FD->getAttr<CFReturnsRetainedAttr>()) { Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); } } } void RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ, const ObjCMethodDecl *MD) { if (!MD) return; bool isTrackedLoc = false; // Determine if there is a special return effect for this method. if (cocoa::isCocoaObjectRef(MD->getResultType())) { if (MD->getAttr<NSReturnsRetainedAttr>()) { Summ.setRetEffect(ObjCAllocRetE); return; } if (MD->getAttr<NSReturnsNotRetainedAttr>()) { Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC)); return; } isTrackedLoc = true; } if (!isTrackedLoc) isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL; if (isTrackedLoc) { if (MD->getAttr<CFReturnsRetainedAttr>()) Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); else if (MD->getAttr<CFReturnsNotRetainedAttr>()) Summ.setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); } } RetainSummary* RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD, Selector S, QualType RetTy) { if (MD) { // Scan the method decl for 'void*' arguments. These should be treated // as 'StopTracking' because they are often used with delegates. // Delegates are a frequent form of false positives with the retain // count checker. unsigned i = 0; for (ObjCMethodDecl::param_iterator I = MD->param_begin(), E = MD->param_end(); I != E; ++I, ++i) if (ParmVarDecl *PD = *I) { QualType Ty = Ctx.getCanonicalType(PD->getType()); if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy) ScratchArgs = AF.Add(ScratchArgs, i, StopTracking); } } // Any special effect for the receiver? ArgEffect ReceiverEff = DoNothing; // If one of the arguments in the selector has the keyword 'delegate' we // should stop tracking the reference count for the receiver. This is // because the reference count is quite possibly handled by a delegate // method. if (S.isKeywordSelector()) { const std::string &str = S.getAsString(); assert(!str.empty()); if (StrInStrNoCase(str, "delegate:") != StringRef::npos) ReceiverEff = StopTracking; } // Look for methods that return an owned object. if (cocoa::isCocoaObjectRef(RetTy)) { // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned // by instance methods. RetEffect E = cocoa::followsFundamentalRule(S) ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC); return getPersistentSummary(E, ReceiverEff, MayEscape); } // Look for methods that return an owned core foundation object. if (cocoa::isCFObjectRef(RetTy)) { RetEffect E = cocoa::followsFundamentalRule(S) ? RetEffect::MakeOwned(RetEffect::CF, true) : RetEffect::MakeNotOwned(RetEffect::CF); return getPersistentSummary(E, ReceiverEff, MayEscape); } if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing) return getDefaultSummary(); return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape); } RetainSummary* RetainSummaryManager::getInstanceMethodSummary(const ObjCMessageExpr *ME, const GRState *state, const LocationContext *LC) { // We need the type-information of the tracked receiver object // Retrieve it from the state. const Expr *Receiver = ME->getInstanceReceiver(); const ObjCInterfaceDecl* ID = 0; // FIXME: Is this really working as expected? There are cases where // we just use the 'ID' from the message expression. SVal receiverV; if (Receiver) { receiverV = state->getSValAsScalarOrLoc(Receiver); // FIXME: Eventually replace the use of state->get<RefBindings> with // a generic API for reasoning about the Objective-C types of symbolic // objects. if (SymbolRef Sym = receiverV.getAsLocSymbol()) if (const RefVal *T = state->get<RefBindings>(Sym)) if (const ObjCObjectPointerType* PT = T->getType()->getAs<ObjCObjectPointerType>()) ID = PT->getInterfaceDecl(); // FIXME: this is a hack. This may or may not be the actual method // that is called. if (!ID) { if (const ObjCObjectPointerType *PT = Receiver->getType()->getAs<ObjCObjectPointerType>()) ID = PT->getInterfaceDecl(); } } else { // FIXME: Hack for 'super'. ID = ME->getReceiverInterface(); } // FIXME: The receiver could be a reference to a class, meaning that // we should use the class method. RetainSummary *Summ = getInstanceMethodSummary(ME, ID); // Special-case: are we sending a mesage to "self"? // This is a hack. When we have full-IP this should be removed. if (isa<ObjCMethodDecl>(LC->getDecl()) && Receiver) { if (const loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&receiverV)) { // Get the region associated with 'self'. if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl()) { SVal SelfVal = state->getSVal(state->getRegion(SelfDecl, LC)); if (L->StripCasts() == SelfVal.getAsRegion()) { // Update the summary to make the default argument effect // 'StopTracking'. Summ = copySummary(Summ); Summ->setDefaultArgEffect(StopTracking); } } } } return Summ ? Summ : getDefaultSummary(); } RetainSummary* RetainSummaryManager::getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName, const ObjCInterfaceDecl* ID, const ObjCMethodDecl *MD, QualType RetTy) { // Look up a summary in our summary cache. RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S); if (!Summ) { assert(ScratchArgs.isEmpty()); // "initXXX": pass-through for receiver. if (cocoa::deriveNamingConvention(S) == cocoa::InitRule) Summ = getInitMethodSummary(RetTy); else Summ = getCommonMethodSummary(MD, S, RetTy); // Annotations override defaults. updateSummaryFromAnnotations(*Summ, MD); // Memoize the summary. ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ; } return Summ; } RetainSummary* RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName, const ObjCInterfaceDecl *ID, const ObjCMethodDecl *MD, QualType RetTy) { assert(ClsName && "Class name must be specified."); RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S); if (!Summ) { Summ = getCommonMethodSummary(MD, S, RetTy); // Annotations override defaults. updateSummaryFromAnnotations(*Summ, MD); // Memoize the summary. ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ; } return Summ; } void RetainSummaryManager::InitializeClassMethodSummaries() { assert(ScratchArgs.isEmpty()); RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE); // Create the summaries for "alloc", "new", and "allocWithZone:" for // NSObject and its derivatives. addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ); addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ); addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ); // Create the [NSAssertionHandler currentHander] summary. addClassMethSummary("NSAssertionHandler", "currentHandler", getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC))); // Create the [NSAutoreleasePool addObject:] summary. ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease); addClassMethSummary("NSAutoreleasePool", "addObject", getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Autorelease)); // Create a summary for [NSCursor dragCopyCursor]. addClassMethSummary("NSCursor", "dragCopyCursor", getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing)); // Create the summaries for [NSObject performSelector...]. We treat // these as 'stop tracking' for the arguments because they are often // used for delegates that can release the object. When we have better // inter-procedural analysis we can potentially do something better. This // workaround is to remove false positives. Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking); IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject"); addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject", "afterDelay", NULL); addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject", "afterDelay", "inModes", NULL); addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread", "withObject", "waitUntilDone", NULL); addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread", "withObject", "waitUntilDone", "modes", NULL); addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread", "withObject", "waitUntilDone", NULL); addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread", "withObject", "waitUntilDone", "modes", NULL); addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground", "withObject", NULL); // Specially handle NSData. RetainSummary *dataWithBytesNoCopySumm = getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing, DoNothing); addClsMethSummary("NSData", dataWithBytesNoCopySumm, "dataWithBytesNoCopy", "length", NULL); addClsMethSummary("NSData", dataWithBytesNoCopySumm, "dataWithBytesNoCopy", "length", "freeWhenDone", NULL); } void RetainSummaryManager::InitializeMethodSummaries() { assert (ScratchArgs.isEmpty()); // Create the "init" selector. It just acts as a pass-through for the // receiver. RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg); addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); // awakeAfterUsingCoder: behaves basically like an 'init' method. It // claims the receiver and returns a retained object. addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx), InitSumm); // The next methods are allocators. RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE); RetainSummary *CFAllocSumm = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); // Create the "copy" selector. addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm); // Create the "mutableCopy" selector. addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm); // Create the "retain" selector. RetEffect E = RetEffect::MakeReceiverAlias(); RetainSummary *Summ = getPersistentSummary(E, IncRefMsg); addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); // Create the "release" selector. Summ = getPersistentSummary(E, DecRefMsg); addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); // Create the "drain" selector. Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef); addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ); // Create the -dealloc summary. Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc); addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); // Create the "autorelease" selector. Summ = getPersistentSummary(E, Autorelease); addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); // Specially handle NSAutoreleasePool. addInstMethSummary("NSAutoreleasePool", "init", getPersistentSummary(RetEffect::MakeReceiverAlias(), NewAutoreleasePool)); // For NSWindow, allocated objects are (initially) self-owned. // FIXME: For now we opt for false negatives with NSWindow, as these objects // self-own themselves. However, they only do this once they are displayed. // Thus, we need to track an NSWindow's display status. // This is tracked in <rdar://problem/6062711>. // See also http://llvm.org/bugs/show_bug.cgi?id=3714. RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(), StopTracking, StopTracking); addClassMethSummary("NSWindow", "alloc", NoTrackYet); #if 0 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", NULL); addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", "screen", NULL); #endif // For NSPanel (which subclasses NSWindow), allocated objects are not // self-owned. // FIXME: For now we don't track NSPanels. object for the same reason // as for NSWindow objects. addClassMethSummary("NSPanel", "alloc", NoTrackYet); #if 0 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", NULL); addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", "styleMask", "backing", "defer", "screen", NULL); #endif // Don't track allocated autorelease pools yet, as it is okay to prematurely // exit a method. addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet); // Create NSAssertionHandler summaries. addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file", "lineNumber", "description", NULL); addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object", "file", "lineNumber", "description", NULL); // Create summaries QCRenderer/QCView -createSnapShotImageOfType: addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType", NULL); addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType", NULL); // Create summaries for CIContext, 'createCGImage' and // 'createCGLayerWithSize'. These objects are CF objects, and are not // automatically garbage collected. addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect", NULL); addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect", "format", "colorSpace", NULL); addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info", NULL); } //===----------------------------------------------------------------------===// // AutoreleaseBindings - State used to track objects in autorelease pools. //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts; typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents; typedef llvm::ImmutableList<SymbolRef> ARStack; static int AutoRCIndex = 0; static int AutoRBIndex = 0; namespace { class AutoreleasePoolContents {}; } namespace { class AutoreleaseStack {}; } namespace clang { template<> struct GRStateTrait<AutoreleaseStack> : public GRStatePartialTrait<ARStack> { static inline void* GDMIndex() { return &AutoRBIndex; } }; template<> struct GRStateTrait<AutoreleasePoolContents> : public GRStatePartialTrait<ARPoolContents> { static inline void* GDMIndex() { return &AutoRCIndex; } }; } // end clang namespace static SymbolRef GetCurrentAutoreleasePool(const GRState* state) { ARStack stack = state->get<AutoreleaseStack>(); return stack.isEmpty() ? SymbolRef() : stack.getHead(); } static const GRState * SendAutorelease(const GRState *state, ARCounts::Factory &F, SymbolRef sym) { SymbolRef pool = GetCurrentAutoreleasePool(state); const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool); ARCounts newCnts(0); if (cnts) { const unsigned *cnt = (*cnts).lookup(sym); newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1); } else newCnts = F.Add(F.GetEmptyMap(), sym, 1); return state->set<AutoreleasePoolContents>(pool, newCnts); } //===----------------------------------------------------------------------===// // Transfer functions. //===----------------------------------------------------------------------===// namespace { class CFRefCount : public GRTransferFuncs { public: class BindingsPrinter : public GRState::Printer { public: virtual void Print(llvm::raw_ostream& Out, const GRState* state, const char* nl, const char* sep); }; private: typedef llvm::DenseMap<const ExplodedNode*, const RetainSummary*> SummaryLogTy; RetainSummaryManager Summaries; SummaryLogTy SummaryLog; const LangOptions& LOpts; ARCounts::Factory ARCountFactory; BugType *useAfterRelease, *releaseNotOwned; BugType *deallocGC, *deallocNotOwned; BugType *leakWithinFunction, *leakAtReturn; BugType *overAutorelease; BugType *returnNotOwnedForOwned; BugReporter *BR; const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind& hasErr); void ProcessNonLeakError(ExplodedNodeSet& Dst, GRStmtNodeBuilder& Builder, const Expr* NodeExpr, SourceRange ErrorRange, ExplodedNode* Pred, const GRState* St, RefVal::Kind hasErr, SymbolRef Sym); const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V, llvm::SmallVectorImpl<SymbolRef> &Leaked); ExplodedNode* ProcessLeaks(const GRState * state, llvm::SmallVectorImpl<SymbolRef> &Leaked, GenericNodeBuilder &Builder, GRExprEngine &Eng, ExplodedNode *Pred = 0); public: CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts) : Summaries(Ctx, gcenabled), LOpts(lopts), useAfterRelease(0), releaseNotOwned(0), deallocGC(0), deallocNotOwned(0), leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), returnNotOwnedForOwned(0), BR(0) {} virtual ~CFRefCount() {} void RegisterChecks(GRExprEngine &Eng); virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) { Printers.push_back(new BindingsPrinter()); } bool isGCEnabled() const { return Summaries.isGCEnabled(); } const LangOptions& getLangOptions() const { return LOpts; } const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const { SummaryLogTy::const_iterator I = SummaryLog.find(N); return I == SummaryLog.end() ? 0 : I->second; } // Calls. void EvalSummary(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, const Expr* Ex, InstanceReceiver Receiver, const RetainSummary& Summ, const MemRegion *Callee, ConstExprIterator arg_beg, ConstExprIterator arg_end, ExplodedNode* Pred, const GRState *state); virtual void EvalCall(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, const CallExpr* CE, SVal L, ExplodedNode* Pred); virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, const ObjCMessageExpr* ME, ExplodedNode* Pred, const GRState *state); // Stores. virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val); // End-of-path. virtual void EvalEndPath(GRExprEngine& Engine, GREndPathNodeBuilder& Builder); virtual void EvalDeadSymbols(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, ExplodedNode* Pred, const GRState* state, SymbolReaper& SymReaper); std::pair<ExplodedNode*, const GRState *> HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd, ExplodedNode* Pred, GRExprEngine &Eng, SymbolRef Sym, RefVal V, bool &stop); // Return statements. virtual void EvalReturn(ExplodedNodeSet& Dst, GRExprEngine& Engine, GRStmtNodeBuilder& Builder, const ReturnStmt* S, ExplodedNode* Pred); // Assumptions. virtual const GRState *EvalAssume(const GRState* state, SVal condition, bool assumption); }; } // end anonymous namespace static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym, const GRState *state) { Out << ' '; if (Sym) Out << Sym->getSymbolID(); else Out << "<pool>"; Out << ":{"; // Get the contents of the pool. if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym)) for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J) Out << '(' << J.getKey() << ',' << J.getData() << ')'; Out << '}'; } void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out, const GRState* state, const char* nl, const char* sep) { RefBindings B = state->get<RefBindings>(); if (!B.isEmpty()) Out << sep << nl; for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { Out << (*I).first << " : "; (*I).second.print(Out); Out << nl; } // Print the autorelease stack. Out << sep << nl << "AR pool stack:"; ARStack stack = state->get<AutoreleaseStack>(); PrintPool(Out, SymbolRef(), state); // Print the caller's pool. for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I) PrintPool(Out, *I, state); Out << nl; } //===----------------------------------------------------------------------===// // Error reporting. //===----------------------------------------------------------------------===// namespace { //===-------------===// // Bug Descriptions. // //===-------------===// class CFRefBug : public BugType { protected: CFRefCount& TF; CFRefBug(CFRefCount* tf, llvm::StringRef name) : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {} public: CFRefCount& getTF() { return TF; } // FIXME: Eventually remove. virtual const char* getDescription() const = 0; virtual bool isLeak() const { return false; } }; class UseAfterRelease : public CFRefBug { public: UseAfterRelease(CFRefCount* tf) : CFRefBug(tf, "Use-after-release") {} const char* getDescription() const { return "Reference-counted object is used after it is released"; } }; class BadRelease : public CFRefBug { public: BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {} const char* getDescription() const { return "Incorrect decrement of the reference count of an object that is " "not owned at this point by the caller"; } }; class DeallocGC : public CFRefBug { public: DeallocGC(CFRefCount *tf) : CFRefBug(tf, "-dealloc called while using garbage collection") {} const char *getDescription() const { return "-dealloc called while using garbage collection"; } }; class DeallocNotOwned : public CFRefBug { public: DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {} const char *getDescription() const { return "-dealloc sent to object that may be referenced elsewhere"; } }; class OverAutorelease : public CFRefBug { public: OverAutorelease(CFRefCount *tf) : CFRefBug(tf, "Object sent -autorelease too many times") {} const char *getDescription() const { return "Object sent -autorelease too many times"; } }; class ReturnedNotOwnedForOwned : public CFRefBug { public: ReturnedNotOwnedForOwned(CFRefCount *tf) : CFRefBug(tf, "Method should return an owned object") {} const char *getDescription() const { return "Object with +0 retain counts returned to caller where a +1 " "(owning) retain count is expected"; } }; class Leak : public CFRefBug { const bool isReturn; protected: Leak(CFRefCount* tf, llvm::StringRef name, bool isRet) : CFRefBug(tf, name), isReturn(isRet) {} public: const char* getDescription() const { return ""; } bool isLeak() const { return true; } }; class LeakAtReturn : public Leak { public: LeakAtReturn(CFRefCount* tf, llvm::StringRef name) : Leak(tf, name, true) {} }; class LeakWithinFunction : public Leak { public: LeakWithinFunction(CFRefCount* tf, llvm::StringRef name) : Leak(tf, name, false) {} }; //===---------===// // Bug Reports. // //===---------===// class CFRefReport : public RangedBugReport { protected: SymbolRef Sym; const CFRefCount &TF; public: CFRefReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym) : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {} CFRefReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym, llvm::StringRef endText) : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {} virtual ~CFRefReport() {} CFRefBug& getBugType() { return (CFRefBug&) RangedBugReport::getBugType(); } virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) { if (!getBugType().isLeak()) RangedBugReport::getRanges(beg, end); else beg = end = 0; } SymbolRef getSymbol() const { return Sym; } PathDiagnosticPiece* getEndPath(BugReporterContext& BRC, const ExplodedNode* N); std::pair<const char**,const char**> getExtraDescriptiveText(); PathDiagnosticPiece* VisitNode(const ExplodedNode* N, const ExplodedNode* PrevN, BugReporterContext& BRC); }; class CFRefLeakReport : public CFRefReport { SourceLocation AllocSite; const MemRegion* AllocBinding; public: CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym, GRExprEngine& Eng); PathDiagnosticPiece* getEndPath(BugReporterContext& BRC, const ExplodedNode* N); SourceLocation getLocation() const { return AllocSite; } }; } // end anonymous namespace static const char* Msgs[] = { // GC only "Code is compiled to only use garbage collection", // No GC. "Code is compiled to use reference counts", // Hybrid, with GC. "Code is compiled to use either garbage collection (GC) or reference counts" " (non-GC). The bug occurs with GC enabled", // Hybrid, without GC "Code is compiled to use either garbage collection (GC) or reference counts" " (non-GC). The bug occurs in non-GC mode" }; std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() { CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF(); switch (TF.getLangOptions().getGCMode()) { default: assert(false); case LangOptions::GCOnly: assert (TF.isGCEnabled()); return std::make_pair(&Msgs[0], &Msgs[0]+1); case LangOptions::NonGC: assert (!TF.isGCEnabled()); return std::make_pair(&Msgs[1], &Msgs[1]+1); case LangOptions::HybridGC: if (TF.isGCEnabled()) return std::make_pair(&Msgs[2], &Msgs[2]+1); else return std::make_pair(&Msgs[3], &Msgs[3]+1); } } static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V, ArgEffect X) { for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end(); I!=E; ++I) if (*I == X) return true; return false; } PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N, const ExplodedNode* PrevN, BugReporterContext& BRC) { if (!isa<PostStmt>(N->getLocation())) return NULL; // Check if the type state has changed. const GRState *PrevSt = PrevN->getState(); const GRState *CurrSt = N->getState(); const RefVal* CurrT = CurrSt->get<RefBindings>(Sym); if (!CurrT) return NULL; const RefVal &CurrV = *CurrT; const RefVal *PrevT = PrevSt->get<RefBindings>(Sym); // Create a string buffer to constain all the useful things we want // to tell the user. std::string sbuf; llvm::raw_string_ostream os(sbuf); // This is the allocation site since the previous node had no bindings // for this symbol. if (!PrevT) { const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { // Get the name of the callee (if it is available). SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee()); if (const FunctionDecl* FD = X.getAsFunctionDecl()) os << "Call to function '" << FD << '\''; else os << "function call"; } else { assert (isa<ObjCMessageExpr>(S)); os << "Method"; } if (CurrV.getObjKind() == RetEffect::CF) { os << " returns a Core Foundation object with a "; } else { assert (CurrV.getObjKind() == RetEffect::ObjC); os << " returns an Objective-C object with a "; } if (CurrV.isOwned()) { os << "+1 retain count (owning reference)."; if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) { assert(CurrV.getObjKind() == RetEffect::CF); os << " " "Core Foundation objects are not automatically garbage collected."; } } else { assert (CurrV.isNotOwned()); os << "+0 retain count (non-owning reference)."; } PathDiagnosticLocation Pos(S, BRC.getSourceManager()); return new PathDiagnosticEventPiece(Pos, os.str()); } // Gather up the effects that were performed on the object at this // program point llvm::SmallVector<ArgEffect, 2> AEffects; if (const RetainSummary *Summ = TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) { // We only have summaries attached to nodes after evaluating CallExpr and // ObjCMessageExprs. const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { // Iterate through the parameter expressions and see if the symbol // was ever passed as an argument. unsigned i = 0; for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) { // Retrieve the value of the argument. Is it the symbol // we are interested in? if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym) continue; // We have an argument. Get the effect! AEffects.push_back(Summ->getArg(i)); } } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { if (const Expr *receiver = ME->getInstanceReceiver()) if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) { // The symbol we are tracking is the receiver. AEffects.push_back(Summ->getReceiverEffect()); } } } do { // Get the previous type state. RefVal PrevV = *PrevT; // Specially handle -dealloc. if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) { // Determine if the object's reference count was pushed to zero. assert(!(PrevV == CurrV) && "The typestate *must* have changed."); // We may not have transitioned to 'release' if we hit an error. // This case is handled elsewhere. if (CurrV.getKind() == RefVal::Released) { assert(CurrV.getCombinedCounts() == 0); os << "Object released by directly sending the '-dealloc' message"; break; } } // Specially handle CFMakeCollectable and friends. if (contains(AEffects, MakeCollectable)) { // Get the name of the function. const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee()); const FunctionDecl* FD = X.getAsFunctionDecl(); const std::string& FName = FD->getNameAsString(); if (TF.isGCEnabled()) { // Determine if the object's reference count was pushed to zero. assert(!(PrevV == CurrV) && "The typestate *must* have changed."); os << "In GC mode a call to '" << FName << "' decrements an object's retain count and registers the " "object with the garbage collector. "; if (CurrV.getKind() == RefVal::Released) { assert(CurrV.getCount() == 0); os << "Since it now has a 0 retain count the object can be " "automatically collected by the garbage collector."; } else os << "An object must have a 0 retain count to be garbage collected. " "After this call its retain count is +" << CurrV.getCount() << '.'; } else os << "When GC is not enabled a call to '" << FName << "' has no effect on its argument."; // Nothing more to say. break; } // Determine if the typestate has changed. if (!(PrevV == CurrV)) switch (CurrV.getKind()) { case RefVal::Owned: case RefVal::NotOwned: if (PrevV.getCount() == CurrV.getCount()) { // Did an autorelease message get sent? if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount()) return 0; assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount()); os << "Object sent -autorelease message"; break; } if (PrevV.getCount() > CurrV.getCount()) os << "Reference count decremented."; else os << "Reference count incremented."; if (unsigned Count = CurrV.getCount()) os << " The object now has a +" << Count << " retain count."; if (PrevV.getKind() == RefVal::Released) { assert(TF.isGCEnabled() && CurrV.getCount() > 0); os << " The object is not eligible for garbage collection until the " "retain count reaches 0 again."; } break; case RefVal::Released: os << "Object released."; break; case RefVal::ReturnedOwned: os << "Object returned to caller as an owning reference (single retain " "count transferred to caller)."; break; case RefVal::ReturnedNotOwned: os << "Object returned to caller with a +0 (non-owning) retain count."; break; default: return NULL; } // Emit any remaining diagnostics for the argument effects (if any). for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(), E=AEffects.end(); I != E; ++I) { // A bunch of things have alternate behavior under GC. if (TF.isGCEnabled()) switch (*I) { default: break; case Autorelease: os << "In GC mode an 'autorelease' has no effect."; continue; case IncRefMsg: os << "In GC mode the 'retain' message has no effect."; continue; case DecRefMsg: os << "In GC mode the 'release' message has no effect."; continue; } } } while (0); if (os.str().empty()) return 0; // We have nothing to say! const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); PathDiagnosticLocation Pos(S, BRC.getSourceManager()); PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str()); // Add the range by scanning the children of the statement for any bindings // to Sym. for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) if (const Expr* Exp = dyn_cast_or_null<Expr>(*I)) if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) { P->addRange(Exp->getSourceRange()); break; } return P; } namespace { class FindUniqueBinding : public StoreManager::BindingsHandler { SymbolRef Sym; const MemRegion* Binding; bool First; public: FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {} bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal val) { SymbolRef SymV = val.getAsSymbol(); if (!SymV || SymV != Sym) return true; if (Binding) { First = false; return false; } else Binding = R; return true; } operator bool() { return First && Binding; } const MemRegion* getRegion() { return Binding; } }; } static std::pair<const ExplodedNode*,const MemRegion*> GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N, SymbolRef Sym) { // Find both first node that referred to the tracked symbol and the // memory location that value was store to. const ExplodedNode* Last = N; const MemRegion* FirstBinding = 0; while (N) { const GRState* St = N->getState(); RefBindings B = St->get<RefBindings>(); if (!B.lookup(Sym)) break; FindUniqueBinding FB(Sym); StateMgr.iterBindings(St, FB); if (FB) FirstBinding = FB.getRegion(); Last = N; N = N->pred_empty() ? NULL : *(N->pred_begin()); } return std::make_pair(Last, FirstBinding); } PathDiagnosticPiece* CFRefReport::getEndPath(BugReporterContext& BRC, const ExplodedNode* EndN) { // Tell the BugReporterContext to report cases when the tracked symbol is // assigned to different variables, etc. BRC.addNotableSymbol(Sym); return RangedBugReport::getEndPath(BRC, EndN); } PathDiagnosticPiece* CFRefLeakReport::getEndPath(BugReporterContext& BRC, const ExplodedNode* EndN){ // Tell the BugReporterContext to report cases when the tracked symbol is // assigned to different variables, etc. BRC.addNotableSymbol(Sym); // We are reporting a leak. Walk up the graph to get to the first node where // the symbol appeared, and also get the first VarDecl that tracked object // is stored to. const ExplodedNode* AllocNode = 0; const MemRegion* FirstBinding = 0; llvm::tie(AllocNode, FirstBinding) = GetAllocationSite(BRC.getStateManager(), EndN, Sym); // Get the allocate site. assert(AllocNode); const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt(); SourceManager& SMgr = BRC.getSourceManager(); unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart()); // Compute an actual location for the leak. Sometimes a leak doesn't // occur at an actual statement (e.g., transition between blocks; end // of function) so we need to walk the graph and compute a real location. const ExplodedNode* LeakN = EndN; PathDiagnosticLocation L; while (LeakN) { ProgramPoint P = LeakN->getLocation(); if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) { L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr); break; } else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { if (const Stmt* Term = BE->getSrc()->getTerminator()) { L = PathDiagnosticLocation(Term->getLocStart(), SMgr); break; } } LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin()); } if (!L.isValid()) { const Decl &D = EndN->getCodeDecl(); L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr); } std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Object allocated on line " << AllocLine; if (FirstBinding) os << " and stored into '" << FirstBinding->getString() << '\''; // Get the retain count. const RefVal* RV = EndN->getState()->get<RefBindings>(Sym); if (RV->getKind() == RefVal::ErrorLeakReturned) { // FIXME: Per comments in rdar://6320065, "create" only applies to CF // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership // to the caller for NS objects. ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl()); os << " is returned from a method whose name ('" << MD.getSelector().getAsString() << "') does not contain 'copy' or otherwise starts with" " 'new' or 'alloc'. This violates the naming convention rules given" " in the Memory Management Guide for Cocoa (object leaked)"; } else if (RV->getKind() == RefVal::ErrorGCLeakReturned) { ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl()); os << " and returned from method '" << MD.getSelector().getAsString() << "' is potentially leaked when using garbage collection. Callers " "of this method do not expect a returned object with a +1 retain " "count since they expect the object to be managed by the garbage " "collector"; } else os << " is no longer referenced after this point and has a retain count of" " +" << RV->getCount() << " (object leaked)"; return new PathDiagnosticEventPiece(L, os.str()); } CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode *n, SymbolRef sym, GRExprEngine& Eng) : CFRefReport(D, tf, n, sym) { // Most bug reports are cached at the location where they occured. // With leaks, we want to unique them by the location where they were // allocated, and only report a single path. To do this, we need to find // the allocation site of a piece of tracked memory, which we do via a // call to GetAllocationSite. This will walk the ExplodedGraph backwards. // Note that this is *not* the trimmed graph; we are guaranteed, however, // that all ancestor nodes that represent the allocation site have the // same SourceLocation. const ExplodedNode* AllocNode = 0; llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding. GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol()); // Get the SourceLocation for the allocation site. ProgramPoint P = AllocNode->getLocation(); AllocSite = cast<PostStmt>(P).getStmt()->getLocStart(); // Fill in the description of the bug. Description.clear(); llvm::raw_string_ostream os(Description); SourceManager& SMgr = Eng.getContext().getSourceManager(); unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite); os << "Potential leak "; if (tf.isGCEnabled()) { os << "(when using garbage collection) "; } os << "of an object allocated on line " << AllocLine; // FIXME: AllocBinding doesn't get populated for RegionStore yet. if (AllocBinding) os << " and stored into '" << AllocBinding->getString() << '\''; } //===----------------------------------------------------------------------===// // Main checker logic. //===----------------------------------------------------------------------===// /// GetReturnType - Used to get the return type of a message expression or /// function call with the intention of affixing that type to a tracked symbol. /// While the the return type can be queried directly from RetEx, when /// invoking class methods we augment to the return type to be that of /// a pointer to the class (as opposed it just being id). static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) { QualType RetTy = RetE->getType(); // If RetE is not a message expression just return its type. // If RetE is a message expression, return its types if it is something /// more specific than id. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE)) if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>()) if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || PT->isObjCClassType()) { // At this point we know the return type of the message expression is // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this // is a call to a class method whose type we can resolve. In such // cases, promote the return type to XXX* (where XXX is the class). const ObjCInterfaceDecl *D = ME->getReceiverInterface(); return !D ? RetTy : Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D)); } return RetTy; } void CFRefCount::EvalSummary(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, const Expr* Ex, InstanceReceiver Receiver, const RetainSummary& Summ, const MemRegion *Callee, ConstExprIterator arg_beg, ConstExprIterator arg_end, ExplodedNode* Pred, const GRState *state) { // Evaluate the effect of the arguments. RefVal::Kind hasErr = (RefVal::Kind) 0; unsigned idx = 0; SourceRange ErrorRange; SymbolRef ErrorSym = 0; llvm::SmallVector<const MemRegion*, 10> RegionsToInvalidate; // HACK: Symbols that have ref-count state that are referenced directly // (not as structure or array elements, or via bindings) by an argument // should not have their ref-count state stripped after we have // done an invalidation pass. llvm::DenseSet<SymbolRef> WhitelistedSymbols; for (ConstExprIterator I = arg_beg; I != arg_end; ++I, ++idx) { SVal V = state->getSValAsScalarOrLoc(*I); SymbolRef Sym = V.getAsLocSymbol(); if (Sym) if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) { WhitelistedSymbols.insert(Sym); state = Update(state, Sym, *T, Summ.getArg(idx), hasErr); if (hasErr) { ErrorRange = (*I)->getSourceRange(); ErrorSym = Sym; break; } } tryAgain: if (isa<Loc>(V)) { if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) { if (Summ.getArg(idx) == DoNothingByRef) continue; // Invalidate the value of the variable passed by reference. const MemRegion *R = MR->getRegion(); // Are we dealing with an ElementRegion? If the element type is // a basic integer type (e.g., char, int) and the underying region // is a variable region then strip off the ElementRegion. // FIXME: We really need to think about this for the general case // as sometimes we are reasoning about arrays and other times // about (char*), etc., is just a form of passing raw bytes. // e.g., void *p = alloca(); foo((char*)p); if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { // Checking for 'integral type' is probably too promiscuous, but // we'll leave it in for now until we have a systematic way of // handling all of these cases. Eventually we need to come up // with an interface to StoreManager so that this logic can be // approriately delegated to the respective StoreManagers while // still allowing us to do checker-specific logic (e.g., // invalidating reference counts), probably via callbacks. if (ER->getElementType()->isIntegralOrEnumerationType()) { const MemRegion *superReg = ER->getSuperRegion(); if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) || isa<ObjCIvarRegion>(superReg)) R = cast<TypedRegion>(superReg); } // FIXME: What about layers of ElementRegions? } // Mark this region for invalidation. We batch invalidate regions // below for efficiency. RegionsToInvalidate.push_back(R); continue; } else { // Nuke all other arguments passed by reference. // FIXME: is this necessary or correct? This handles the non-Region // cases. Is it ever valid to store to these? state = state->unbindLoc(cast<Loc>(V)); } } else if (isa<nonloc::LocAsInteger>(V)) { // If we are passing a location wrapped as an integer, unwrap it and // invalidate the values referred by the location. V = cast<nonloc::LocAsInteger>(V).getLoc(); goto tryAgain; } } // Block calls result in all captured values passed-via-reference to be // invalidated. if (const BlockDataRegion *BR = dyn_cast_or_null<BlockDataRegion>(Callee)) { RegionsToInvalidate.push_back(BR); } // Invalidate regions we designed for invalidation use the batch invalidation // API. // FIXME: We can have collisions on the conjured symbol if the // expression *I also creates conjured symbols. We probably want // to identify conjured symbols by an expression pair: the enclosing // expression (the context) and the expression itself. This should // disambiguate conjured symbols. unsigned Count = Builder.getCurrentBlockCount(); StoreManager::InvalidatedSymbols IS; // NOTE: Even if RegionsToInvalidate is empty, we must still invalidate // global variables. state = state->InvalidateRegions(RegionsToInvalidate.data(), RegionsToInvalidate.data() + RegionsToInvalidate.size(), Ex, Count, &IS, /* invalidateGlobals = */ true); for (StoreManager::InvalidatedSymbols::iterator I = IS.begin(), E = IS.end(); I!=E; ++I) { SymbolRef sym = *I; if (WhitelistedSymbols.count(sym)) continue; // Remove any existing reference-count binding. state = state->remove<RefBindings>(*I); } // Evaluate the effect on the message receiver. if (!ErrorRange.isValid() && Receiver) { SymbolRef Sym = Receiver.getSValAsScalarOrLoc(state).getAsLocSymbol(); if (Sym) { if (const RefVal* T = state->get<RefBindings>(Sym)) { state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr); if (hasErr) { ErrorRange = Receiver.getSourceRange(); ErrorSym = Sym; } } } } // Process any errors. if (hasErr) { ProcessNonLeakError(Dst, Builder, Ex, ErrorRange, Pred, state, hasErr, ErrorSym); return; } // Consult the summary for the return value. RetEffect RE = Summ.getRetEffect(); if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { bool found = false; if (Receiver) { SVal V = Receiver.getSValAsScalarOrLoc(state); if (SymbolRef Sym = V.getAsLocSymbol()) if (state->get<RefBindings>(Sym)) { found = true; RE = Summaries.getObjAllocRetEffect(); } } // FIXME: Otherwise, this is a send-to-super instance message. if (!found) RE = RetEffect::MakeNoRet(); } switch (RE.getKind()) { default: assert (false && "Unhandled RetEffect."); break; case RetEffect::NoRet: { // Make up a symbol for the return value (not reference counted). // FIXME: Most of this logic is not specific to the retain/release // checker. // FIXME: We eventually should handle structs and other compound types // that are returned by value. QualType T = Ex->getType(); // For CallExpr, use the result type to know if it returns a reference. if (const CallExpr *CE = dyn_cast<CallExpr>(Ex)) { const Expr *Callee = CE->getCallee(); if (const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl()) T = FD->getResultType(); } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { if (const ObjCMethodDecl *MD = ME->getMethodDecl()) T = MD->getResultType(); } if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SVal X = ValMgr.getConjuredSymbolVal(NULL, Ex, T, Count); state = state->BindExpr(Ex, X, false); } break; } case RetEffect::Alias: { unsigned idx = RE.getIndex(); assert (arg_end >= arg_beg); assert (idx < (unsigned) (arg_end - arg_beg)); SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx)); state = state->BindExpr(Ex, V, false); break; } case RetEffect::ReceiverAlias: { assert(Receiver); SVal V = Receiver.getSValAsScalarOrLoc(state); state = state->BindExpr(Ex, V, false); break; } case RetEffect::OwnedAllocatedSymbol: case RetEffect::OwnedSymbol: { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count); QualType RetT = GetReturnType(Ex, ValMgr.getContext()); state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT)); state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false); // FIXME: Add a flag to the checker where allocations are assumed to // *not fail. #if 0 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) { bool isFeasible; state = state.Assume(loc::SymbolVal(Sym), true, isFeasible); assert(isFeasible && "Cannot assume fresh symbol is non-null."); } #endif break; } case RetEffect::GCNotOwnedSymbol: case RetEffect::NotOwnedSymbol: { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count); QualType RetT = GetReturnType(Ex, ValMgr.getContext()); state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(), RetT)); state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false); break; } } // Generate a sink node if we are at the end of a path. ExplodedNode *NewNode = Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state) : Builder.MakeNode(Dst, Ex, Pred, state); // Annotate the edge with summary we used. if (NewNode) SummaryLog[NewNode] = &Summ; } void CFRefCount::EvalCall(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, const CallExpr* CE, SVal L, ExplodedNode* Pred) { RetainSummary *Summ = 0; // FIXME: Better support for blocks. For now we stop tracking anything // that is passed to blocks. // FIXME: Need to handle variables that are "captured" by the block. if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) { Summ = Summaries.getPersistentStopSummary(); } else { const FunctionDecl* FD = L.getAsFunctionDecl(); Summ = !FD ? Summaries.getDefaultSummary() : Summaries.getSummary(FD); } assert(Summ); EvalSummary(Dst, Eng, Builder, CE, 0, *Summ, L.getAsRegion(), CE->arg_begin(), CE->arg_end(), Pred, Builder.GetState(Pred)); } void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, const ObjCMessageExpr* ME, ExplodedNode* Pred, const GRState *state) { RetainSummary *Summ = ME->isInstanceMessage() ? Summaries.getInstanceMethodSummary(ME, state,Pred->getLocationContext()) : Summaries.getClassMethodSummary(ME); assert(Summ && "RetainSummary is null"); EvalSummary(Dst, Eng, Builder, ME, InstanceReceiver(ME, Pred->getLocationContext()), *Summ, NULL, ME->arg_begin(), ME->arg_end(), Pred, state); } namespace { class StopTrackingCallback : public SymbolVisitor { const GRState *state; public: StopTrackingCallback(const GRState *st) : state(st) {} const GRState *getState() const { return state; } bool VisitSymbol(SymbolRef sym) { state = state->remove<RefBindings>(sym); return true; } }; } // end anonymous namespace void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) { // Are we storing to something that causes the value to "escape"? bool escapes = false; // A value escapes in three possible cases (this may change): // // (1) we are binding to something that is not a memory region. // (2) we are binding to a memregion that does not have stack storage // (3) we are binding to a memregion with stack storage that the store // does not understand. const GRState *state = B.getState(); if (!isa<loc::MemRegionVal>(location)) escapes = true; else { const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion(); escapes = !R->hasStackStorage(); if (!escapes) { // To test (3), generate a new state with the binding removed. If it is // the same state, then it escapes (since the store cannot represent // the binding). escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal()))); } } // If our store can represent the binding and we aren't storing to something // that doesn't have local storage then just return and have the simulation // state continue as is. if (!escapes) return; // Otherwise, find all symbols referenced by 'val' that we are tracking // and stop tracking them. B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState()); } // Return statements. void CFRefCount::EvalReturn(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, const ReturnStmt* S, ExplodedNode* Pred) { const Expr* RetE = S->getRetValue(); if (!RetE) return; const GRState *state = Builder.GetState(Pred); SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol(); if (!Sym) return; // Get the reference count binding (if any). const RefVal* T = state->get<RefBindings>(Sym); if (!T) return; // Change the reference count. RefVal X = *T; switch (X.getKind()) { case RefVal::Owned: { unsigned cnt = X.getCount(); assert (cnt > 0); X.setCount(cnt - 1); X = X ^ RefVal::ReturnedOwned; break; } case RefVal::NotOwned: { unsigned cnt = X.getCount(); if (cnt) { X.setCount(cnt - 1); X = X ^ RefVal::ReturnedOwned; } else { X = X ^ RefVal::ReturnedNotOwned; } break; } default: return; } // Update the binding. state = state->set<RefBindings>(Sym, X); Pred = Builder.MakeNode(Dst, S, Pred, state); // Did we cache out? if (!Pred) return; // Update the autorelease counts. static unsigned autoreleasetag = 0; GenericNodeBuilder Bd(Builder, S, &autoreleasetag); bool stop = false; llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym, X, stop); // Did we cache out? if (!Pred || stop) return; // Get the updated binding. T = state->get<RefBindings>(Sym); assert(T); X = *T; // Any leaks or other errors? if (X.isReturnedOwned() && X.getCount() == 0) { Decl const *CD = &Pred->getCodeDecl(); if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) { const RetainSummary &Summ = *Summaries.getMethodSummary(MD); RetEffect RE = Summ.getRetEffect(); bool hasError = false; if (RE.getKind() != RetEffect::NoRet) { if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) { // Things are more complicated with garbage collection. If the // returned object is suppose to be an Objective-C object, we have // a leak (as the caller expects a GC'ed object) because no // method should return ownership unless it returns a CF object. hasError = true; X = X ^ RefVal::ErrorGCLeakReturned; } else if (!RE.isOwned()) { // Either we are using GC and the returned object is a CF type // or we aren't using GC. In either case, we expect that the // enclosing method is expected to return ownership. hasError = true; X = X ^ RefVal::ErrorLeakReturned; } } if (hasError) { // Generate an error node. static int ReturnOwnLeakTag = 0; state = state->set<RefBindings>(Sym, X); ExplodedNode *N = Builder.generateNode(PostStmt(S, Pred->getLocationContext(), &ReturnOwnLeakTag), state, Pred); if (N) { CFRefReport *report = new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this, N, Sym, Eng); BR->EmitReport(report); } } } } else if (X.isReturnedNotOwned()) { Decl const *CD = &Pred->getCodeDecl(); if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) { const RetainSummary &Summ = *Summaries.getMethodSummary(MD); if (Summ.getRetEffect().isOwned()) { // Trying to return a not owned object to a caller expecting an // owned object. static int ReturnNotOwnedForOwnedTag = 0; state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned); if (ExplodedNode *N = Builder.generateNode(PostStmt(S, Pred->getLocationContext(), &ReturnNotOwnedForOwnedTag), state, Pred)) { CFRefReport *report = new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned), *this, N, Sym); BR->EmitReport(report); } } } } } // Assumptions. const GRState* CFRefCount::EvalAssume(const GRState *state, SVal Cond, bool Assumption) { // FIXME: We may add to the interface of EvalAssume the list of symbols // whose assumptions have changed. For now we just iterate through the // bindings and check if any of the tracked symbols are NULL. This isn't // too bad since the number of symbols we will track in practice are // probably small and EvalAssume is only called at branches and a few // other places. RefBindings B = state->get<RefBindings>(); if (B.isEmpty()) return state; bool changed = false; RefBindings::Factory& RefBFactory = state->get_context<RefBindings>(); for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { // Check if the symbol is null (or equal to any constant). // If this is the case, stop tracking the symbol. if (state->getSymVal(I.getKey())) { changed = true; B = RefBFactory.Remove(B, I.getKey()); } } if (changed) state = state->set<RefBindings>(B); return state; } const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind& hasErr) { // In GC mode [... release] and [... retain] do nothing. switch (E) { default: break; case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break; case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break; case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break; case NewAutoreleasePool: E = isGCEnabled() ? DoNothing : NewAutoreleasePool; break; } // Handle all use-after-releases. if (!isGCEnabled() && V.getKind() == RefVal::Released) { V = V ^ RefVal::ErrorUseAfterRelease; hasErr = V.getKind(); return state->set<RefBindings>(sym, V); } switch (E) { default: assert (false && "Unhandled CFRef transition."); case Dealloc: // Any use of -dealloc in GC is *bad*. if (isGCEnabled()) { V = V ^ RefVal::ErrorDeallocGC; hasErr = V.getKind(); break; } switch (V.getKind()) { default: assert(false && "Invalid case."); case RefVal::Owned: // The object immediately transitions to the released state. V = V ^ RefVal::Released; V.clearCounts(); return state->set<RefBindings>(sym, V); case RefVal::NotOwned: V = V ^ RefVal::ErrorDeallocNotOwned; hasErr = V.getKind(); break; } break; case NewAutoreleasePool: assert(!isGCEnabled()); return state->add<AutoreleaseStack>(sym); case MayEscape: if (V.getKind() == RefVal::Owned) { V = V ^ RefVal::NotOwned; break; } // Fall-through. case DoNothingByRef: case DoNothing: return state; case Autorelease: if (isGCEnabled()) return state; // Update the autorelease counts. state = SendAutorelease(state, ARCountFactory, sym); V = V.autorelease(); break; case StopTracking: return state->remove<RefBindings>(sym); case IncRef: switch (V.getKind()) { default: assert(false); case RefVal::Owned: case RefVal::NotOwned: V = V + 1; break; case RefVal::Released: // Non-GC cases are handled above. assert(isGCEnabled()); V = (V ^ RefVal::Owned) + 1; break; } break; case SelfOwn: V = V ^ RefVal::NotOwned; // Fall-through. case DecRef: switch (V.getKind()) { default: // case 'RefVal::Released' handled above. assert (false); case RefVal::Owned: assert(V.getCount() > 0); if (V.getCount() == 1) V = V ^ RefVal::Released; V = V - 1; break; case RefVal::NotOwned: if (V.getCount() > 0) V = V - 1; else { V = V ^ RefVal::ErrorReleaseNotOwned; hasErr = V.getKind(); } break; case RefVal::Released: // Non-GC cases are handled above. assert(isGCEnabled()); V = V ^ RefVal::ErrorUseAfterRelease; hasErr = V.getKind(); break; } break; } return state->set<RefBindings>(sym, V); } //===----------------------------------------------------------------------===// // Handle dead symbols and end-of-path. //===----------------------------------------------------------------------===// std::pair<ExplodedNode*, const GRState *> CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd, ExplodedNode* Pred, GRExprEngine &Eng, SymbolRef Sym, RefVal V, bool &stop) { unsigned ACnt = V.getAutoreleaseCount(); stop = false; // No autorelease counts? Nothing to be done. if (!ACnt) return std::make_pair(Pred, state); assert(!isGCEnabled() && "Autorelease counts in GC mode?"); unsigned Cnt = V.getCount(); // FIXME: Handle sending 'autorelease' to already released object. if (V.getKind() == RefVal::ReturnedOwned) ++Cnt; if (ACnt <= Cnt) { if (ACnt == Cnt) { V.clearCounts(); if (V.getKind() == RefVal::ReturnedOwned) V = V ^ RefVal::ReturnedNotOwned; else V = V ^ RefVal::NotOwned; } else { V.setCount(Cnt - ACnt); V.setAutoreleaseCount(0); } state = state->set<RefBindings>(Sym, V); ExplodedNode *N = Bd.MakeNode(state, Pred); stop = (N == 0); return std::make_pair(N, state); } // Woah! More autorelease counts then retain counts left. // Emit hard error. stop = true; V = V ^ RefVal::ErrorOverAutorelease; state = state->set<RefBindings>(Sym, V); if (ExplodedNode *N = Bd.MakeNode(state, Pred)) { N->markAsSink(); std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Object over-autoreleased: object was sent -autorelease"; if (V.getAutoreleaseCount() > 1) os << V.getAutoreleaseCount() << " times"; os << " but the object has "; if (V.getCount() == 0) os << "zero (locally visible)"; else os << "+" << V.getCount(); os << " retain counts"; CFRefReport *report = new CFRefReport(*static_cast<CFRefBug*>(overAutorelease), *this, N, Sym, os.str()); BR->EmitReport(report); } return std::make_pair((ExplodedNode*)0, state); } const GRState * CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V, llvm::SmallVectorImpl<SymbolRef> &Leaked) { bool hasLeak = V.isOwned() || ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0); if (!hasLeak) return state->remove<RefBindings>(sid); Leaked.push_back(sid); return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak); } ExplodedNode* CFRefCount::ProcessLeaks(const GRState * state, llvm::SmallVectorImpl<SymbolRef> &Leaked, GenericNodeBuilder &Builder, GRExprEngine& Eng, ExplodedNode *Pred) { if (Leaked.empty()) return Pred; // Generate an intermediate node representing the leak point. ExplodedNode *N = Builder.MakeNode(state, Pred); if (N) { for (llvm::SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction : leakAtReturn); assert(BT && "BugType not initialized."); CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng); BR->EmitReport(report); } } return N; } void CFRefCount::EvalEndPath(GRExprEngine& Eng, GREndPathNodeBuilder& Builder) { const GRState *state = Builder.getState(); GenericNodeBuilder Bd(Builder); RefBindings B = state->get<RefBindings>(); ExplodedNode *Pred = 0; for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { bool stop = false; llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng, (*I).first, (*I).second, stop); if (stop) return; } B = state->get<RefBindings>(); llvm::SmallVector<SymbolRef, 10> Leaked; for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked); ProcessLeaks(state, Leaked, Bd, Eng, Pred); } void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst, GRExprEngine& Eng, GRStmtNodeBuilder& Builder, ExplodedNode* Pred, const GRState* state, SymbolReaper& SymReaper) { const Stmt *S = Builder.getStmt(); RefBindings B = state->get<RefBindings>(); // Update counts from autorelease pools for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I != E; ++I) { SymbolRef Sym = *I; if (const RefVal* T = B.lookup(Sym)){ // Use the symbol as the tag. // FIXME: This might not be as unique as we would like. GenericNodeBuilder Bd(Builder, S, Sym); bool stop = false; llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng, Sym, *T, stop); if (stop) return; } } B = state->get<RefBindings>(); llvm::SmallVector<SymbolRef, 10> Leaked; for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I != E; ++I) { if (const RefVal* T = B.lookup(*I)) state = HandleSymbolDeath(state, *I, *T, Leaked); } static unsigned LeakPPTag = 0; { GenericNodeBuilder Bd(Builder, S, &LeakPPTag); Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred); } // Did we cache out? if (!Pred) return; // Now generate a new node that nukes the old bindings. RefBindings::Factory& F = state->get_context<RefBindings>(); for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I); state = state->set<RefBindings>(B); Builder.MakeNode(Dst, S, Pred, state); } void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst, GRStmtNodeBuilder& Builder, const Expr* NodeExpr, SourceRange ErrorRange, ExplodedNode* Pred, const GRState* St, RefVal::Kind hasErr, SymbolRef Sym) { Builder.BuildSinks = true; ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St); if (!N) return; CFRefBug *BT = 0; switch (hasErr) { default: assert(false && "Unhandled error."); return; case RefVal::ErrorUseAfterRelease: BT = static_cast<CFRefBug*>(useAfterRelease); break; case RefVal::ErrorReleaseNotOwned: BT = static_cast<CFRefBug*>(releaseNotOwned); break; case RefVal::ErrorDeallocGC: BT = static_cast<CFRefBug*>(deallocGC); break; case RefVal::ErrorDeallocNotOwned: BT = static_cast<CFRefBug*>(deallocNotOwned); break; } CFRefReport *report = new CFRefReport(*BT, *this, N, Sym); report->addRange(ErrorRange); BR->EmitReport(report); } //===----------------------------------------------------------------------===// // Pieces of the retain/release checker implemented using a CheckerVisitor. // More pieces of the retain/release checker will be migrated to this interface // (ideally, all of it some day). //===----------------------------------------------------------------------===// namespace { class RetainReleaseChecker : public CheckerVisitor<RetainReleaseChecker> { CFRefCount *TF; public: RetainReleaseChecker(CFRefCount *tf) : TF(tf) {} static void* getTag() { static int x = 0; return &x; } void PostVisitBlockExpr(CheckerContext &C, const BlockExpr *BE); }; } // end anonymous namespace void RetainReleaseChecker::PostVisitBlockExpr(CheckerContext &C, const BlockExpr *BE) { // Scan the BlockDecRefExprs for any object the retain/release checker // may be tracking. if (!BE->hasBlockDeclRefExprs()) return; const GRState *state = C.getState(); const BlockDataRegion *R = cast<BlockDataRegion>(state->getSVal(BE).getAsRegion()); BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), E = R->referenced_vars_end(); if (I == E) return; // FIXME: For now we invalidate the tracking of all symbols passed to blocks // via captured variables, even though captured variables result in a copy // and in implicit increment/decrement of a retain count. llvm::SmallVector<const MemRegion*, 10> Regions; const LocationContext *LC = C.getPredecessor()->getLocationContext(); MemRegionManager &MemMgr = C.getValueManager().getRegionManager(); for ( ; I != E; ++I) { const VarRegion *VR = *I; if (VR->getSuperRegion() == R) { VR = MemMgr.getVarRegion(VR->getDecl(), LC); } Regions.push_back(VR); } state = state->scanReachableSymbols<StopTrackingCallback>(Regions.data(), Regions.data() + Regions.size()).getState(); C.addTransition(state); } //===----------------------------------------------------------------------===// // Transfer function creation for external clients. //===----------------------------------------------------------------------===// void CFRefCount::RegisterChecks(GRExprEngine& Eng) { BugReporter &BR = Eng.getBugReporter(); useAfterRelease = new UseAfterRelease(this); BR.Register(useAfterRelease); releaseNotOwned = new BadRelease(this); BR.Register(releaseNotOwned); deallocGC = new DeallocGC(this); BR.Register(deallocGC); deallocNotOwned = new DeallocNotOwned(this); BR.Register(deallocNotOwned); overAutorelease = new OverAutorelease(this); BR.Register(overAutorelease); returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this); BR.Register(returnNotOwnedForOwned); // First register "return" leaks. const char* name = 0; if (isGCEnabled()) name = "Leak of returned object when using garbage collection"; else if (getLangOptions().getGCMode() == LangOptions::HybridGC) name = "Leak of returned object when not using garbage collection (GC) in " "dual GC/non-GC code"; else { assert(getLangOptions().getGCMode() == LangOptions::NonGC); name = "Leak of returned object"; } // Leaks should not be reported if they are post-dominated by a sink. leakAtReturn = new LeakAtReturn(this, name); leakAtReturn->setSuppressOnSink(true); BR.Register(leakAtReturn); // Second, register leaks within a function/method. if (isGCEnabled()) name = "Leak of object when using garbage collection"; else if (getLangOptions().getGCMode() == LangOptions::HybridGC) name = "Leak of object when not using garbage collection (GC) in " "dual GC/non-GC code"; else { assert(getLangOptions().getGCMode() == LangOptions::NonGC); name = "Leak"; } // Leaks should not be reported if they are post-dominated by sinks. leakWithinFunction = new LeakWithinFunction(this, name); leakWithinFunction->setSuppressOnSink(true); BR.Register(leakWithinFunction); // Save the reference to the BugReporter. this->BR = &BR; // Register the RetainReleaseChecker with the GRExprEngine object. // Functionality in CFRefCount will be migrated to RetainReleaseChecker // over time. Eng.registerCheck(new RetainReleaseChecker(this)); } GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled, const LangOptions& lopts) { return new CFRefCount(Ctx, GCEnabled, lopts); }
f350952984febe47a0c14cf75fe8b531a460c871
6d2d502e7c98617323e51357d4c907bc47a9a700
/_repo/Bon/BonDlg.cpp
e24faa2ffd12890025f7eca38ec03c2ba4c903ad
[]
no_license
taira3/sample
8c44b5bcbce871fded402c96cebd3f29e5c905b3
b4629198394d99c6875d1bba58943851c778294c
refs/heads/master
2021-01-19T02:35:59.868511
2017-12-03T22:30:24
2017-12-03T22:30:24
63,316,816
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,783
cpp
BonDlg.cpp
// BonDlg.cpp : 実装ファイル // #include "stdafx.h" #include "Bon.h" #include "BonDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // アプリケーションのバージョン情報に使われる CAboutDlg ダイアログ class CAboutDlg : public CDialog { public: CAboutDlg(); // ダイアログ データ enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV サポート // 実装 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CBonDlg ダイアログ CBonDlg::CBonDlg(CWnd* pParent /*=NULL*/) : CDialog(CBonDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CBonDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CBonDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_WM_DROPFILES() ON_WM_DESTROY() END_MESSAGE_MAP() // CBonDlg メッセージ ハンドラ BOOL CBonDlg::OnInitDialog() { CDialog::OnInitDialog(); // "バージョン情報..." メニューをシステム メニューに追加します。 // IDM_ABOUTBOX は、システム コマンドの範囲内になければなりません。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // このダイアログのアイコンを設定します。アプリケーションのメイン ウィンドウがダイアログでない場合、 // Framework は、この設定を自動的に行います。 SetIcon(m_hIcon, TRUE); // 大きいアイコンの設定 SetIcon(m_hIcon, FALSE); // 小さいアイコンの設定 // TODO: 初期化をここに追加します。 m_bonFW = new BonFW(); m_bonFW->load(); m_log = new DebugLog(); m_ee = new EasterEgg(); m_dbg = new DebugLog(); return TRUE; // フォーカスをコントロールに設定した場合を除き、TRUE を返します。 } void CBonDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // ダイアログに最小化ボタンを追加する場合、アイコンを描画するための // 下のコードが必要です。ドキュメント/ビュー モデルを使う MFC アプリケーションの場合、 // これは、Framework によって自動的に設定されます。 void CBonDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 描画のデバイス コンテキスト SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // クライアントの四角形領域内の中央 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // アイコンの描画 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // ユーザーが最小化したウィンドウをドラッグしているときに表示するカーソルを取得するために、 // システムがこの関数を呼び出します。 HCURSOR CBonDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } #include <fstream> using namespace std; //#include "yaml-cpp/yaml.h" void CBonDlg::OnDropFiles(HDROP hDropInfo) { // TODO: ここにメッセージ ハンドラ コードを追加するか、既定の処理を呼び出します。 char FileName[MAX_PATH]; int NameSize = sizeof(FileName); CStatic *pMsg = (CStatic*)GetDlgItem(IDC_MSG); int FileNumber = DragQueryFileA(hDropInfo, 0xffffffff, FileName, NameSize); for( int i = 0 ; i < FileNumber ; i++ ) { DragQueryFileA(hDropInfo, i, FileName, NameSize); m_log->Info("File=%s\n",FileName); cout << FileName << endl ; CString msg ; pMsg->GetWindowText( msg ); msg.Format(_T("File:%s\n"),CA2W(FileName)); pMsg->SetWindowText( msg ); if( m_bonFW->entry( string(FileName) ) ) { msg += _T("Analyze....\n"); pMsg->SetWindowText( msg ); cout << "Analyze...." << endl ; BeginWaitCursor(); m_bonFW->createWorkspace(); bool res = m_bonFW->analyze(); EndWaitCursor(); if( res ) { msg += _T("Success."); pMsg->SetWindowText( msg ); cout << "Success." << endl ; } else { msg += _T("Error."); pMsg->SetWindowText( msg ); cout << "Error." << endl ; } } else { msg += _T("Not Support."); pMsg->SetWindowText( msg ); cout << "Not Support." << endl ; } } CDialog::OnDropFiles(hDropInfo); } void CBonDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: ここにメッセージ ハンドラ コードを追加します。 if( m_bonFW ) { delete m_bonFW ; } if( m_log ) { delete m_log ; } if( m_ee ) { delete m_ee ; } if( m_dbg ) { delete m_dbg ; } } BOOL CBonDlg::PreTranslateMessage(MSG* pMsg) { // TODO: ここに特定なコードを追加するか、もしくは基本クラスを呼び出してください。 switch( pMsg->message ) { case WM_KEYUP: TRACE( _T("WM_KEYUP: 0x%x\n"), pMsg->wParam ); // if( m_ee->AddCmd( pMsg->wParam ) ) { // イベント発生. TRACE("Event=%d\n",m_ee->getEvent()); m_dbg->setOutputConsole(); } break; } return CDialog::PreTranslateMessage(pMsg); }
7c1336efa8e5861fd5bf3ec5b689d29d38a6c08e
fa7474550cac23f55205666e13a99e59c749db97
/cryptohome/disk_cleanup.cc
a144fdb0972cfe9bfa15224a37e47a48a2e9b9f2
[ "BSD-3-Clause" ]
permissive
kalyankondapally/chromiumos-platform2
4fe8bac63a95a07ac8afa45088152c2b623b963d
5e5337009a65b1c9aa9e0ea565f567438217e91f
refs/heads/master
2023-01-05T15:25:41.667733
2020-11-08T06:12:01
2020-11-08T07:16:44
295,388,294
0
1
null
null
null
null
UTF-8
C++
false
false
12,346
cc
disk_cleanup.cc
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cryptohome/disk_cleanup.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <vector> #include <base/logging.h> #include <base/optional.h> #include <base/time/time.h> #include <base/timer/elapsed_timer.h> #include "cryptohome/cryptohome_metrics.h" #include "cryptohome/disk_cleanup_routines.h" #include "cryptohome/homedirs.h" #include "cryptohome/platform.h" #include "cryptohome/user_oldest_activity_timestamp_cache.h" namespace cryptohome { DiskCleanup::DiskCleanup() = default; DiskCleanup::~DiskCleanup() = default; bool DiskCleanup::Init(HomeDirs* homedirs, Platform* platform, UserOldestActivityTimestampCache* timestamp_cache) { homedirs_ = homedirs; platform_ = platform; timestamp_cache_ = timestamp_cache; routines_ = std::make_unique<DiskCleanupRoutines>(homedirs_, platform_); return true; } base::Optional<int64_t> DiskCleanup::AmountOfFreeDiskSpace() const { int64_t free_space = platform_->AmountOfFreeDiskSpace(homedirs_->shadow_root()); if (free_space < 0) { return base::nullopt; } else { return free_space; } } DiskCleanup::FreeSpaceState DiskCleanup::GetFreeDiskSpaceState() const { return GetFreeDiskSpaceState(AmountOfFreeDiskSpace()); } DiskCleanup::FreeSpaceState DiskCleanup::GetFreeDiskSpaceState( base::Optional<int64_t> free_disk_space) const { if (!free_disk_space) { return DiskCleanup::FreeSpaceState::kError; } int64_t value = free_disk_space.value(); if (value >= target_free_space_) { return DiskCleanup::FreeSpaceState::kAboveTarget; } else if (value >= normal_cleanup_threshold_) { return DiskCleanup::FreeSpaceState::kAboveThreshold; } else if (value >= aggressive_cleanup_threshold_) { return DiskCleanup::FreeSpaceState::kNeedNormalCleanup; } else { return DiskCleanup::FreeSpaceState::kNeedAggressiveCleanup; } } bool DiskCleanup::HasTargetFreeSpace() const { return GetFreeDiskSpaceState() == DiskCleanup::FreeSpaceState::kAboveTarget; } bool DiskCleanup::IsFreeableDiskSpaceAvailable() { if (!homedirs_->enterprise_owned()) return false; const auto homedirs = homedirs_->GetHomeDirs(); int unmounted_cryptohomes = std::count_if(homedirs.begin(), homedirs.end(), [](auto& dir) { return !dir.is_mounted; }); return unmounted_cryptohomes > 0; } void DiskCleanup::FreeDiskSpace() { auto free_space = AmountOfFreeDiskSpace(); switch (GetFreeDiskSpaceState(free_space)) { case DiskCleanup::FreeSpaceState::kAboveTarget: case DiskCleanup::FreeSpaceState::kAboveThreshold: // Already have enough space. No need to clean up. return; case DiskCleanup::FreeSpaceState::kNeedNormalCleanup: case DiskCleanup::FreeSpaceState::kNeedAggressiveCleanup: // trigger cleanup break; case DiskCleanup::FreeSpaceState::kError: LOG(ERROR) << "Failed to get the amount of free disk space"; return; default: LOG(ERROR) << "Unhandled free disk state"; return; } auto now = platform_->GetCurrentTime(); if (last_free_disk_space_) { auto diff = now - *last_free_disk_space_; ReportTimeBetweenFreeDiskSpace(diff.InSeconds()); } last_free_disk_space_ = now; base::ElapsedTimer total_timer; FreeDiskSpaceInternal(); int cleanup_time = total_timer.Elapsed().InMilliseconds(); ReportFreeDiskSpaceTotalTime(cleanup_time); VLOG(1) << "Disk cleanup took " << cleanup_time << "ms."; auto after_cleanup = AmountOfFreeDiskSpace(); if (!after_cleanup) { LOG(ERROR) << "Failed to get the amount of free disk space"; return; } ReportFreeDiskSpaceTotalFreedInMb( MAX(0, after_cleanup.value() - free_space.value()) / 1024 / 1024); LOG(INFO) << "Disk cleanup complete."; } void DiskCleanup::set_routines_for_testing(DiskCleanupRoutines* routines) { routines_.reset(routines); } void DiskCleanup::FreeDiskSpaceInternal() { // If ephemeral users are enabled, remove all cryptohomes except those // currently mounted or belonging to the owner. // |AreEphemeralUsers| will reload the policy to guarantee freshness. if (homedirs_->AreEphemeralUsersEnabled()) { homedirs_->RemoveNonOwnerCryptohomes(); ReportDiskCleanupProgress( DiskCleanupProgress::kEphemeralUserProfilesCleaned); return; } auto homedirs = homedirs_->GetHomeDirs(); // Initialize user timestamp cache if it has not been yet. This reads the // last-activity time from each homedir's SerializedVaultKeyset. This value // is only updated in the value keyset on unmount and every 24 hrs, so a // currently logged in user probably doesn't have an up to date value. This // is okay, since we don't delete currently logged in homedirs anyway. (See // Mount::UpdateCurrentUserActivityTimestamp()). if (!timestamp_cache_->initialized()) { timestamp_cache_->Initialize(); for (const auto& dir : homedirs) { homedirs_->AddUserTimestampToCache(dir.obfuscated); } } auto unmounted_homedirs = homedirs; FilterMountedHomedirs(&unmounted_homedirs); std::sort( unmounted_homedirs.begin(), unmounted_homedirs.end(), [&](const HomeDirs::HomeDir& a, const HomeDirs::HomeDir& b) { return timestamp_cache_->GetLastUserActivityTimestamp(a.obfuscated) > timestamp_cache_->GetLastUserActivityTimestamp(b.obfuscated); }); auto normal_cleanup_homedirs = unmounted_homedirs; if (last_normal_disk_cleanup_complete_) { base::Time cutoff = last_normal_disk_cleanup_complete_.value(); FilterHomedirsProcessedBeforeCutoff(cutoff, &normal_cleanup_homedirs); } // Clean Cache directories for every unmounted user that has logged out after // the last normal cleanup happened. for (auto dir = normal_cleanup_homedirs.rbegin(); dir != normal_cleanup_homedirs.rend(); dir++) { routines_->DeleteUserCache(dir->obfuscated); if (HasTargetFreeSpace()) { ReportDiskCleanupProgress( DiskCleanupProgress::kBrowserCacheCleanedAboveTarget); return; } } auto freeDiskSpace = AmountOfFreeDiskSpace(); if (!freeDiskSpace) { LOG(ERROR) << "Failed to get the amount of free space"; return; } bool earlyStop = false; // Clean GCache directories for every unmounted user that has logged out after // after the last normal cleanup happened. for (auto dir = normal_cleanup_homedirs.rbegin(); dir != normal_cleanup_homedirs.rend(); dir++) { routines_->DeleteUserGCache(dir->obfuscated); if (HasTargetFreeSpace()) { earlyStop = true; break; } } if (!earlyStop) last_normal_disk_cleanup_complete_ = platform_->GetCurrentTime(); const auto old_free_disk_space = freeDiskSpace; freeDiskSpace = AmountOfFreeDiskSpace(); if (!freeDiskSpace) { LOG(ERROR) << "Failed to get the amount of free space"; return; } const int64_t freed_gcache_space = freeDiskSpace.value() - old_free_disk_space.value(); // Report only if something was deleted. if (freed_gcache_space > 0) { ReportFreedGCacheDiskSpaceInMb(freed_gcache_space / 1024 / 1024); } switch (GetFreeDiskSpaceState(freeDiskSpace)) { case DiskCleanup::FreeSpaceState::kAboveTarget: ReportDiskCleanupProgress( DiskCleanupProgress::kGoogleDriveCacheCleanedAboveTarget); return; case DiskCleanup::FreeSpaceState::kAboveThreshold: case DiskCleanup::FreeSpaceState::kNeedNormalCleanup: ReportDiskCleanupProgress( DiskCleanupProgress::kGoogleDriveCacheCleanedAboveMinimum); return; case DiskCleanup::FreeSpaceState::kNeedAggressiveCleanup: // continue cleanup break; case DiskCleanup::FreeSpaceState::kError: LOG(ERROR) << "Failed to get the amount of free space"; return; default: LOG(ERROR) << "Unhandled free disk state"; return; } auto aggressive_cleanup_homedirs = unmounted_homedirs; if (last_aggressive_disk_cleanup_complete_) { base::Time cutoff = last_aggressive_disk_cleanup_complete_.value(); FilterHomedirsProcessedBeforeCutoff(cutoff, &aggressive_cleanup_homedirs); } // Clean Android cache directories for every unmounted user that has logged // out after after the last normal cleanup happened. for (auto dir = aggressive_cleanup_homedirs.rbegin(); dir != aggressive_cleanup_homedirs.rend(); dir++) { routines_->DeleteUserAndroidCache(dir->obfuscated); if (HasTargetFreeSpace()) { earlyStop = true; break; } } if (!earlyStop) last_aggressive_disk_cleanup_complete_ = platform_->GetCurrentTime(); switch (GetFreeDiskSpaceState()) { case DiskCleanup::FreeSpaceState::kAboveTarget: ReportDiskCleanupProgress( DiskCleanupProgress::kAndroidCacheCleanedAboveTarget); return; case DiskCleanup::FreeSpaceState::kAboveThreshold: case DiskCleanup::FreeSpaceState::kNeedNormalCleanup: ReportDiskCleanupProgress( DiskCleanupProgress::kAndroidCacheCleanedAboveMinimum); return; case DiskCleanup::FreeSpaceState::kNeedAggressiveCleanup: // continue cleanup break; case DiskCleanup::FreeSpaceState::kError: LOG(ERROR) << "Failed to get the amount of free space"; return; default: LOG(ERROR) << "Unhandled free disk state"; return; } // Delete old users, the oldest first. Count how many are deleted. // Don't delete anyone if we don't know who the owner is. // For consumer devices, don't delete the device owner. Enterprise-enrolled // devices have no owner, so don't delete the most-recent user. int deleted_users_count = 0; std::string owner; if (!homedirs_->enterprise_owned() && !homedirs_->GetOwner(&owner)) return; int mounted_cryptohomes_count = std::count_if(homedirs.begin(), homedirs.end(), [](auto& dir) { return dir.is_mounted; }); for (auto dir = unmounted_homedirs.rbegin(); dir != unmounted_homedirs.rend(); dir++) { if (homedirs_->enterprise_owned()) { // Leave the most-recent user on the device intact. // The most-recent user is the first in unmounted_homedirs. if (dir == unmounted_homedirs.rend() - 1 && mounted_cryptohomes_count == 0) { LOG(INFO) << "Skipped deletion of the most recent device user."; continue; } } else if (dir->obfuscated == owner) { // We never delete the device owner. LOG(INFO) << "Skipped deletion of the device owner."; continue; } LOG(INFO) << "Freeing disk space by deleting user " << dir->obfuscated; routines_->DeleteUserProfile(dir->obfuscated); timestamp_cache_->RemoveUser(dir->obfuscated); ++deleted_users_count; if (HasTargetFreeSpace()) break; } if (deleted_users_count > 0) { ReportDeletedUserProfiles(deleted_users_count); } // We had a chance to delete a user only if any unmounted homes existed. if (unmounted_homedirs.size() > 0) { ReportDiskCleanupProgress( HasTargetFreeSpace() ? DiskCleanupProgress::kWholeUserProfilesCleanedAboveTarget : DiskCleanupProgress::kWholeUserProfilesCleaned); } else { ReportDiskCleanupProgress(DiskCleanupProgress::kNoUnmountedCryptohomes); } } void DiskCleanup::FilterMountedHomedirs( std::vector<HomeDirs::HomeDir>* homedirs) { homedirs->erase(std::remove_if(homedirs->begin(), homedirs->end(), [](const HomeDirs::HomeDir& dir) { return dir.is_mounted; }), homedirs->end()); } void DiskCleanup::FilterHomedirsProcessedBeforeCutoff( base::Time cutoff, std::vector<HomeDirs::HomeDir>* homedirs) { homedirs->erase( std::remove_if(homedirs->begin(), homedirs->end(), [&](const HomeDirs::HomeDir& dir) { return timestamp_cache_->GetLastUserActivityTimestamp( dir.obfuscated) < cutoff; }), homedirs->end()); } } // namespace cryptohome
2602a66e791767c98b34d50e855d833de598534c
3b183fc148e60195a08dde1cd9271360483dc5c2
/216.combination-sum-iii.cpp
b6ece604fd94c8f6ac19550fa61b5a79e3220b92
[]
no_license
Elliotshui/leetcode_solution
781febc845f346124d1d0f40341d6c228fe83d4a
8fdc95f63e43b4a71ff99e3c4627c12c3379b2b9
refs/heads/master
2022-11-16T02:39:23.211852
2020-07-11T04:59:21
2020-07-11T04:59:21
274,080,469
0
0
null
null
null
null
UTF-8
C++
false
false
963
cpp
216.combination-sum-iii.cpp
/* * @lc app=leetcode id=216 lang=cpp * * [216] Combination Sum III */ // @lc code=start class Solution { public: vector<vector<int>> combinationSum(int k, int n, int s) { vector<vector<int>> res; if(k == 1) { if(n >= s && n <= 9) { res.push_back({n}); } } else { for(int i = s; i <= 9; ++i) { vector<vector<int>> res1 = combinationSum(k - 1, n - i, i + 1); for(int j = 0; j < res1.size(); ++j) { vector<int> tmp; tmp.push_back(i); for(int p = 0; p < res1[j].size(); ++p) { tmp.push_back(res1[j][p]); } res.push_back(tmp); } } } return res; } vector<vector<int>> combinationSum3(int k, int n) { return combinationSum(k, n, 1); } }; // @lc code=end
b20cc818ffece0b69a57f057ce158c7961be70fb
edc3f27cc4d8076a57d14f49b9664c5486c72c35
/ortc/windows/org/ortc/Error.h
448deffe5829579b463c9dea9888c472f4813736
[]
no_license
jacano/ortc.UWP
b9cc8dc2802081ea9872eb96a92e3568ad8a3aaf
0a717049f7b0970eea8d9939756c3e752a1e2478
refs/heads/master
2022-11-27T06:47:04.065612
2017-09-08T12:38:34
2017-09-08T12:38:34
102,836,778
1
1
null
2022-11-19T03:09:22
2017-09-08T08:16:17
C++
UTF-8
C++
false
false
4,689
h
Error.h
#pragma once #include <ortc/types.h> #include <zsLib/types.h> #include <zsLib/internal/types.h> #define ORG_ORTC_THROW_INVALID_PARAMETERS() {throw ref new Platform::InvalidArgumentException();} #define ORG_ORTC_THROW_INVALID_PARAMETERS_IF(xExpression) if (xExpression) {throw ref new Platform::InvalidArgumentException();} #define ORG_ORTC_THROW_INVALID_STATE_IF(xExpression) if (xExpression) {throw ref new Platform::COMException(E_NOT_VALID_STATE, #xExpression);} #define ORG_ORTC_THROW_INVALID_STATE(xStr) {throw ref new Platform::COMException(E_NOT_VALID_STATE, xStr);} #define ORG_ORTC_THROW_INVALID_STATE_MESSAGE(xStr) {throw ref new Platform::COMException(E_NOT_VALID_STATE, #xStr);} #define ORG_ORTC_THROW_NOT_SUPPORTED(xStr) {throw ref new Platform::COMException(CO_E_NOT_SUPPORTED, xStr);} #define ORG_ORTC_THROW_NOT_SUPPORTED_IF(xExpression) if (xExpression) {throw ref new Platform::COMException(CO_E_NOT_SUPPORTED, #xExpression);} #define ORG_ORTC_THROW_UNEXPECTED_IF(xExpression) if (xExpression) {throw ref new Platform::COMException(E_UNEXPECTED, #xExpression);} namespace Org { namespace Ortc { ZS_DECLARE_TYPEDEF_PTR(zsLib::Any, Any) ZS_DECLARE_TYPEDEF_PTR(::ortc::ErrorAny, ErrorAny) namespace Internal { ZS_DECLARE_CLASS_PTR(MediaStreamTrackDelegate); ZS_DECLARE_CLASS_PTR(RTCDtlsTransportDelegate); ZS_DECLARE_CLASS_PTR(RTCDataChannelDelegate); ZS_DECLARE_CLASS_PTR(RTCSrtpSdesTransportDelegate); ZS_DECLARE_CLASS_PTR(MediaDevicesPromiseObserver); ZS_DECLARE_CLASS_PTR(MediaStreamTrackConstraintsPromiseObserver); ZS_DECLARE_CLASS_PTR(RTCGenerateCertificatePromiseObserver); ZS_DECLARE_CLASS_PTR(RTCRtpSenderPromiseObserver); ZS_DECLARE_CLASS_PTR(RTCRtpReceiverPromiseObserver); ZS_DECLARE_CLASS_PTR(RTCStateProviderObserver); } // namespace internal namespace Adapter { namespace Internal { ZS_DECLARE_CLASS_PTR(RTCPeerConnectionPromiseWithDescriptionObserver); ZS_DECLARE_CLASS_PTR(RTCPeerConnectionPromiseWithSenderObserver); ZS_DECLARE_CLASS_PTR(RTCPeerConnectionPromiseWitDataChannelObserver); ZS_DECLARE_CLASS_PTR(RTCPeerConnectionPromiseObserver); } // namespace internal } // namespace adapter /// <summary> /// This object represents generic error information. /// </summary> public ref struct Error sealed { private: friend class Internal::RTCDtlsTransportDelegate; friend class Internal::MediaDevicesPromiseObserver; friend class Internal::RTCDataChannelDelegate; friend class Internal::RTCSrtpSdesTransportDelegate; friend class Internal::MediaStreamTrackConstraintsPromiseObserver; friend class Internal::RTCGenerateCertificatePromiseObserver; friend class Internal::RTCRtpSenderPromiseObserver; friend class Internal::RTCRtpReceiverPromiseObserver; friend class Internal::RTCStateProviderObserver; friend class Adapter::Internal::RTCPeerConnectionPromiseWithDescriptionObserver; friend class Adapter::Internal::RTCPeerConnectionPromiseWithSenderObserver; friend class Adapter::Internal::RTCPeerConnectionPromiseWitDataChannelObserver; friend class Adapter::Internal::RTCPeerConnectionPromiseObserver; static Error^ CreateIfGeneric(AnyPtr any); static Error^ CreateIfGeneric(ErrorAnyPtr error); public: /// <summary> /// Gets or sets a string representing the error code (see HTTP /// status codes). /// </summary> property uint16 ErrorCode; /// <summary> /// Gets or sets a string representing one of the error typename. /// </summary> property Platform::String^ Name; /// <summary> /// Gets or sets a string representing one of the error reason. /// </summary> property Platform::String^ Reason; }; /// <summary> /// This object represents the error event for event delegates. /// </summary> public ref struct ErrorEvent sealed { private: friend class Internal::MediaStreamTrackDelegate; friend class Internal::RTCDtlsTransportDelegate; friend class Internal::RTCDataChannelDelegate; friend class Internal::RTCSrtpSdesTransportDelegate; ErrorEvent(ref struct Error ^error) { _error = error; } public: /// <summary> /// Gets the error information associated with this event (if any). /// </summary> property Error^ Error { ref struct Error^ get() { return _error; } } private: ref struct Error^ _error; }; } // namespace ortc } // namespace org
8939a3d7037e5e09999d80105793ca0ae85b5dba
4ca41284a19cc0ccf681327dbbe47b81befd6d75
/BackUp/SpaceObsession/Classes/particles/ShowerParticle.h
8c15fbc15c201b02772ebc31c6d38e9cc90fa586
[]
no_license
droidsde/SillyatomGames
9e82c89a5390c4530f40a63cd7109e4aaeae6729
81e4c49fae9473b664f954bd0e8483ae4d404b2d
refs/heads/master
2020-07-05T01:09:10.928828
2016-04-13T17:12:44
2016-04-13T17:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
368
h
ShowerParticle.h
// // ShowerParticle.h // MyCppGame // // Created by Sillyatom on 30/12/14. // // #ifndef __MyCppGame__ShowerParticle__ #define __MyCppGame__ShowerParticle__ #include "cocos2d.h" USING_NS_CC; class ShowerParticle : public ParticleMeteor { public: CREATE_FUNC(ShowerParticle); virtual bool init(); }; #endif /* defined(__MyCppGame__ShowerParticle__) */
9c051e87aeeacf1f9272fa97e5a2959e6c9924bf
01190a4b1e643077cc8f1ce577d7b31f115f3c7e
/SVGReader/include/parser.hpp
86f490a54f0e3492f756eace8ef05a6fbc20e6f5
[ "MIT" ]
permissive
AHDiniz/CNCImagePlotter
44dd692bc3e7fcc7bc14dc81d3c7e24eb0912d82
d7917d574c3b601047eaa85be924e32d0bfa314b
refs/heads/master
2020-09-05T05:18:18.099135
2019-11-11T19:55:50
2019-11-11T19:55:50
219,994,195
0
0
null
null
null
null
UTF-8
C++
false
false
193
hpp
parser.hpp
#pragma once #include <tinyxml.h> #include "forms.hpp" namespace Parser { const std::vector<Forms::Form*> ReadSVGFile(); const char *GCodeCreator(const std::vector<Forms::Form*> forms); }
812668da35effe60f5d4f6112a386fbde1d10c45
6cc535e7509a399f565c136867af32972368a4f6
/UVa/11549/main.cc
37159b1e599b662e38a4b9cab1cdfa47488943c1
[]
no_license
xr1s/brush-title
645fc50156e43e9be8075579fbec9a92e579aa75
009852b58f902ead926548b39674384aadbdf69b
refs/heads/master
2021-05-23T05:30:44.128454
2018-10-01T02:49:42
2018-10-01T02:49:42
95,035,451
2
0
null
null
null
null
UTF-8
C++
false
false
1,439
cc
main.cc
#include <cstdio> #include <cctype> #include <functional> #include <type_traits> using namespace std; template <typename T, typename = typename enable_if<is_integral<T>::value>::type> T get() { char c; while (!isdigit(c = getchar()) && c != '-'); bool neg = c == '-'; T r = neg ? 0 : c - '0'; while (isdigit(c = getchar())) (r *= 10) += c - '0'; return neg ? -r : r; } template <typename T, typename = typename enable_if<is_integral<T>::value>::type> void putint(T x) { static char buf[sizeof(T) << 2]; static int len = 0; if (x < 0) putchar('-'), x = -x; do buf[len++] = x % 10; while (x /= 10); while (--len) putchar(buf[len] + '0'); putchar(*buf + '0'); } template <typename T, typename Next> T floyd(T s, Next f) { T t = s; T ans = s; do { ans = max(ans, s = f(s)); ans = max(ans, t = f(t)); ans = max(ans, t = f(t)); } while (s != t); return ans; } int main() { for (int T = get<int>(); T; --T) { long n = get<long>(), k = get<long>(); putint(floyd(k, [&n](long v) -> long { static char buf[20]; int len = 0; for (v *= v; v; v /= 10) buf[len++] = v % 10; long result = 0; for (int i = 1; i <= n; ++i) (result *= 10) += buf[len - i]; return result; })); putchar('\n'); } return 0; }
afdc880efc7003ffbf0febc91de9dc09c5885581
a338e09a6d50159c2a21e83bcc7d1c7db140d47e
/qdir-test.cpp
38fb3c4b4f8c347255a45a12c23a2cce177652a7
[]
no_license
dukebw/Qt_Design_Ch4
88b69114be4eab9ca33b64708331e0b67fa9f074
29a24be38d1aaa902124faf34c2f7a79dfc47332
refs/heads/master
2020-05-27T06:21:27.974843
2014-09-30T13:45:08
2014-09-30T13:45:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
667
cpp
qdir-test.cpp
// Tests for QDir #include <QCoreApplication> #include <QDir> #include <QString> #include <iostream> int main(int argc, char *argv[]) { QCoreApplication app{argc, argv}; QDir dir; dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); dir.setSorting(QDir::Size | QDir::Reversed); QFileInfoList list{dir.entryInfoList()}; std::cout << " Bytes Filename" << std::endl; for (int i=0; i<list.size(); ++i) { QFileInfo fileInfo{list.at(i)}; std::cout << qPrintable(QString{"%1 %2"}.arg(fileInfo.size(), 10) .arg(fileInfo.fileName())); std::cout << std::endl; } return 0; }
d0b9f09e0519b38fc6cf38c9251ca96a7c8be472
e0d94f2461da30b18e3d7123816d37fb96e53b4d
/core/ListParser.h
7318f8e634eafeeddb01695bb18a8942793fa2ac
[]
no_license
ollie314/rulekit
e257e439889efdaf769f63690e92d92dd9bc8d99
cf3ce85679df4e8de7c743739d0c68a1ebb292be
refs/heads/master
2021-01-10T05:55:51.051593
2011-11-23T12:58:31
2011-11-23T12:58:31
48,912,765
0
0
null
null
null
null
UTF-8
C++
false
false
4,840
h
ListParser.h
// // Copyright (c) 2011 Codesign LLC. All rights reserved. // License: GPL v3 // #ifndef NLParser_Test_ListParser_h #define NLParser_Test_ListParser_h #ifdef _M_CEE_SAFE #include "Tokenizer.h" namespace rulekit { value class ListElement { public: bool islist; System::String^ text; stl::vector<ListElement>^ list; //ListElement(String^ s) : islist(false), text(s) {} //ListElement(stl::vector<ListElement^> l) : islist(true), list(l) {} System::String^ getText() { return islist ? nullptr : text; } stl::vector<ListElement>% getList() { return *list; } bool operator==(ListElement% el) { if (islist) return text == el.text; else return list == el.list; } virtual System::String^ ToString() override { if (islist) { stx::stringstream ss; ss << "[ "; for each (auto% el in list) { ss << el.ToString() << " "; } ss << "]"; return ss.str(); } else return text; } }; ref class ListParser { private: stl::vector<System::String^> tokens; stl::vector<ListElement>^ parse(int% pos, bool% wellformed) { auto v = gcnew stl::vector<ListElement>(); wellformed = true; if (tokens[pos] != "(") wellformed = false; else { pos++; for (;;) { if (pos >= tokens.size()) { wellformed = false; break; } if (tokens[pos] == ")") { pos++; break; } if (tokens[pos] == "(") { auto list = parse(pos, wellformed); if (!wellformed) break; ListElement listElement; listElement.islist = true; listElement.list = list; v->push_back(listElement); } else { ListElement listElement; listElement.islist = false; listElement.text = tokens[pos]; v->push_back(listElement); pos++; } } } return v; } public: ListParser(System::String^ s) { Tokenizer t(s); tokens = t.tokens(); } ListParser(stl::vector<System::String^>% v) : tokens(v) {} stl::vector<ListElement> parse(bool% wellformed) { int pos = 0; return *parse(pos, wellformed); } }; } #else #include <sstream> #include <string.h> #include "Tokenizer.h" namespace rulekit { class ListElement { private: bool islist; std::string text; std::vector<ListElement> list; public: ListElement(const std::string& s) : islist(false), text(s) {} ListElement(const std::vector<ListElement>& l) : islist(true), list(l) {} const std::string* getText() const { return islist ? nullptr : &text; } const std::vector<ListElement>& getList() const { return list; } std::string description() const { if (islist) { std::stringstream ss; ss << "[ "; #ifdef __cplusplus_cli for each (const auto& el in list) { #else for (const auto& el : list) { #endif ss << el.description() << " "; } ss << "]"; return ss.str(); } else return text; } }; class ListParser { private: std::vector<std::string> tokens; std::vector<ListElement> parse(int& pos, bool& wellformed) const { std::vector<ListElement> v; wellformed = true; if (strcmp(tokens[pos].c_str(), "(")) wellformed = false; else { pos++; for (;;) { if (pos >= tokens.size()) { wellformed = false; break; } if (!strcmp(tokens[pos].c_str(), ")")) { pos++; break; } if (!strcmp(tokens[pos].c_str(), "(")) { auto list = parse(pos, wellformed); if (!wellformed) break; v.push_back(ListElement(list)); } else { v.push_back(ListElement(tokens[pos])); pos++; } } } return v; } public: ListParser(const std::string& s) { Tokenizer t(s); tokens = t.tokens(); } ListParser(const std::vector<std::string>& v) : tokens(v) {} std::vector<ListElement> parse(bool& wellformed) const { int pos = 0; return parse(pos, wellformed); } }; } #endif #endif
f0e51ae92e309d4b9226898d903c7648928e94f8
e9af6102d60621ab77f593e0e7fb3a23cd7c13ca
/Program/source/gui/pairsTab/pairstab.h
dc1736923462535431f46c08c5abc93b64378a36
[]
no_license
NII-APP/NPO
209390838c6dbdc0b6ce647d998936a75876faca
5b5ced5b9a1b9c605243fdcf3440b95f23d5c42f
refs/heads/master
2020-05-30T04:37:52.454852
2016-10-17T12:12:05
2016-10-17T12:12:05
25,005,665
2
4
null
null
null
null
UTF-8
C++
false
false
342
h
pairstab.h
#ifndef PAIRSTAB_H #define PAIRSTAB_H #include <QSplitter> class PairsView; class FEMPairViewer; class PairsTab : public QSplitter { Q_OBJECT public: explicit PairsTab(QWidget *parent = 0); public slots: void acceptNewProject(); private: PairsView* const __view; FEMPairViewer* const __viewer; }; #endif // PAIRTAB_H
b57d14ed8b020d5741b1c1841c2b4522f78e648a
31bae5eb9533fd82048615e4cb6f53863cec51e9
/covariance/parallel.h
dcd3b1ec33725cddd197857de5957318410e72c8
[ "MIT" ]
permissive
rufinag/Parallel-Computing
e99f653245c159feec340d893c300db1693edff6
dea47bda6a32fcacec98054e8c34e0d99118b84c
refs/heads/master
2020-09-15T13:21:59.891875
2020-06-26T09:15:25
2020-06-26T09:15:25
223,457,477
0
0
null
2020-06-26T09:15:26
2019-11-22T17:57:23
C++
UTF-8
C++
false
false
2,743
h
parallel.h
//Parallel header #include <omp.h> #include <vector> using namespace std; #define threads 4 //Find the mean of an mxn matrix column-wise vector<double> mean(vector<vector<double>> &mat) { vector<double> avg(mat[0].size(),0); //default value of vector is 0 int j; omp_set_num_threads(threads); #pragma omp parallel for schedule(dynamic,4) collapse(2) for(int i=0; i<mat.size(); i++) { for(j=0; j<mat[0].size(); j++) { avg[j] += mat[i][j]; } } #pragma omp parallel for schedule(dynamic,4) for(int i=0;i<avg.size();i++) { avg[i] /= mat.size(); } return avg; } //Find the sum of two mxn matrices vector<vector<double>> add(vector<vector<double>> &a, vector<vector<double>> &b) { vector<vector<double>> res(a.size(), vector<double>(a[0].size(),0)); int j; if((a.size()!=b.size())||(a[0].size()!=b[0].size())) { return res; } omp_set_num_threads(threads); #pragma omp parallel for schedule(dynamic,4) collapse(2) for(int i=0; i<a.size(); i++) { for(j=0; j<a[0].size(); j++) { res[i][j] = a[i][j] + b[i][j]; } } return res; } //Find the product of an nx1 vector and a 1xn vector vector<vector<double>> mult(vector<double> &p, vector<double> &q) { vector<vector<double>> res(p.size(),vector<double>(q.size(),0)); int j; if(p.size() != q.size()) { return res; } omp_set_num_threads(threads); #pragma omp parallel for schedule(dynamic,4) collapse(2) for(int i=0; i<p.size(); i++) { for(j=0; j<p.size(); j++) { res[i][j] = p[i] * q[j]; } } return res; } //Find the covariance of a matrix vector<vector<double>> covariance(vector<vector<double>> &mat, vector<double> &avg) { vector<vector<double>> res(avg.size(), vector<double>(avg.size(),0)); vector<vector<double>> prod(avg.size(), vector<double>(avg.size(),0)); vector<double> diff(avg.size(),0); int N = mat.size(),j; omp_set_num_threads(threads); for(int i=0; i<N; i++) { #pragma omp parallel for schedule(dynamic,4) //simd for(j=0; j<avg.size(); j++) { diff[j] = mat[i][j] - avg[j]; } prod = mult(diff,diff); res = add(res,prod); } #pragma omp parallel for schedule(dynamic,4) collapse(2) for(int i=0; i<res.size(); i++) { for(j=0; j<res[0].size(); j++) { res[i][j] = res[i][j] / N; } } return res; }