hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
3a684add91064043be77fbb66b750ef9133e14ea
684
hpp
C++
include/RED4ext/Types/generated/game/audio/events/DialogLine.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/game/audio/events/DialogLine.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/game/audio/events/DialogLine.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/generated/audio/DialogLineEventData.hpp> #include <RED4ext/Types/generated/red/Event.hpp> namespace RED4ext { namespace game::audio::events { struct DialogLine : red::Event { static constexpr const char* NAME = "gameaudioeventsDialogLine"; static constexpr const char* ALIAS = "DialogLineEvent"; audio::DialogLineEventData data; // 40 }; RED4EXT_ASSERT_SIZE(DialogLine, 0x68); } // namespace game::audio::events using DialogLineEvent = game::audio::events::DialogLine; } // namespace RED4ext
27.36
68
0.758772
Cyberpunk-Extended-Development-Team
3a6975611d34e5d11be9d96d1bc5c5b6dd7718d1
22,533
cpp
C++
Source/Catastrophe/Characters/PlayerCharacter/PlayerCharacter.cpp
Enderderder/CatastropheGame
251888d384ae59966788cce7bbbc98c3c0be7433
[ "MIT" ]
null
null
null
Source/Catastrophe/Characters/PlayerCharacter/PlayerCharacter.cpp
Enderderder/CatastropheGame
251888d384ae59966788cce7bbbc98c3c0be7433
[ "MIT" ]
null
null
null
Source/Catastrophe/Characters/PlayerCharacter/PlayerCharacter.cpp
Enderderder/CatastropheGame
251888d384ae59966788cce7bbbc98c3c0be7433
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "PlayerCharacter.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "Components/StaticMeshComponent.h" #include "Components/SkeletalMeshComponent.h" #include "Components/TimelineComponent.h" #include "Components/WidgetComponent.h" #include "Components/PostProcessComponent.h" #include "Classes/Particles/ParticleSystemComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "Perception/AIPerceptionStimuliSourceComponent.h" #include "Perception/AISense_Hearing.h" #include "Math/UnrealMathUtility.h" #include "Kismet/GameplayStatics.h" #include "Kismet/KismetMathLibrary.h" #include "GameFramework/PlayerController.h" #include "Gameplay/GameMode/CatastropheMainGameMode.h" #include "PlayerWidget.h" #include "PlayerAnimInstance.h" #include "Components/MovementModifierComponent.h" #include "Components/CharacterSprintMovementComponent.h" #include "Interactable/BaseClasses/InteractableComponent.h" #include "Components/BackPackComponent.h" #include "Gameplay/PlayerUtilities/Tomato.h" #include "Gameplay/CaveGameplay/CaveCameraTrack.h" #include "ThrowableProjectileIndicator.h" #include "Components/InventoryComponent.h" #include "UtilitySacks/TomatoSack.h" #include "DebugUtility/CatastropheDebug.h" // Sets default values APlayerCharacter::APlayerCharacter() { // Set this character to call Tick() every frame. PrimaryActorTick.bCanEverTick = true; // Setup the movement modifier component MovementModifierComponent = CreateDefaultSubobject<UMovementModifierComponent>(TEXT("MovementModifierComponent")); // Set up the sprint movement component SprintMovementComponent = CreateDefaultSubobject<UCharacterSprintMovementComponent>(TEXT("SprintMovementComponent")); SprintMovementComponent->bUseConstantSprintSpeed = false; SprintMovementComponent->OnSprintBegin.RemoveDynamic(this, &APlayerCharacter::OnSprintBegin); SprintMovementComponent->OnSprintBegin.AddDynamic(this, &APlayerCharacter::OnSprintBegin); SprintMovementComponent->OnSprintEnd.RemoveDynamic(this, &APlayerCharacter::OnSprintEnd); SprintMovementComponent->OnSprintEnd.AddDynamic(this, &APlayerCharacter::OnSprintEnd); // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; AimDownSightFocusPoint = CreateDefaultSubobject<USceneComponent>(TEXT("AimDownSightFocusPoint")); AimDownSightFocusPoint->SetupAttachment(GetMesh()); CamFocusPoint = CreateDefaultSubobject<USceneComponent>(TEXT("FollowCameraFocusPoint")); CamFocusPoint->SetupAttachment(RootComponent); // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(CamFocusPoint); CameraBoom->TargetArmLength = 300.0f; CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Holds player utilities InventoryComponent = CreateDefaultSubobject<UInventoryComponent>(TEXT("InventoryComponent")); // Back pack which holds the player collected items BackPackComponent = CreateDefaultSubobject<UBackPackComponent>(TEXT("BackPackComponent")); // A spawn location of all the throwable objects ThrowableSpawnPoint = CreateDefaultSubobject<USceneComponent>(TEXT("TomatoSpawnPoint")); ThrowableSpawnPoint->SetupAttachment(GetMesh()); // Set the tomato that will show inside players hand TomatoInHandMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("TomatoInHandMesh")); TomatoInHandMesh->SetupAttachment(GetMesh(), TEXT("RightHandSocket")); WorldUiAnchor = CreateDefaultSubobject<USceneComponent>(TEXT("InteractableWidgetAnchor")); WorldUiAnchor->SetupAttachment(RootComponent); // Create stimuli PerceptionStimuliSourceComponent = CreateDefaultSubobject<UAIPerceptionStimuliSourceComponent>(TEXT("PerceptionStimuliSource")); // Hiding post-process HidingPostProcess = CreateDefaultSubobject<UPostProcessComponent>(TEXT("HidingPostProcess")); HidingPostProcess->SetupAttachment(RootComponent); // Sprinting post-process SprintingPostProcess = CreateDefaultSubobject<UPostProcessComponent>(TEXT("SprintingPostProcess")); SprintingPostProcess->SetupAttachment(RootComponent); // Alert particle that appears when the player is getting chase SpottedAlertParticle = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("SpottedAlertParticle")); SpottedAlertParticle->SetupAttachment(GetMesh()); SpottedAlertParticle->SetVisibility(false); } // Called when the game starts or when spawned void APlayerCharacter::BeginPlay() { Super::BeginPlay(); // Configure player camera UGameplayStatics::GetPlayerCameraManager(this, 0)->ViewPitchMin = CameraPitchConstrainMin; UGameplayStatics::GetPlayerCameraManager(this, 0)->ViewPitchMax = CameraPitchConstrainMax; // Gets the player animation instance PlayerAnimInstance = Cast<UPlayerAnimInstance>(GetMesh()->GetAnimInstance()); if (!PlayerAnimInstance) CatastropheDebug::OnScreenErrorMsg(TEXT("PlayerCharacter: Invalid anim instance")); // Construct the zoom in timeline { if (!ZoomInCurve) UE_LOG(LogTemp, Error, TEXT("Player zoom in curve is nullptr!")); ZoomInTimeline = NewObject<UTimelineComponent>(this, TEXT("ZoomInTimeline")); ZoomInTimeline->CreationMethod = EComponentCreationMethod::UserConstructionScript; this->BlueprintCreatedComponents.Add(ZoomInTimeline); ZoomInTimeline->SetLooping(false); ZoomInTimeline->SetTimelineLength(0.3f); ZoomInTimeline->SetTimelineLengthMode(ETimelineLengthMode::TL_LastKeyFrame); FOnTimelineFloat onTimelineCallback; onTimelineCallback.BindUFunction(this, FName{ TEXT("TimelineSetCameraZoomValue") }); ZoomInTimeline->AddInterpFloat(ZoomInCurve, onTimelineCallback); ZoomInTimeline->RegisterComponent(); } // Set the stamina to full SetStamina(TotalStamina); // Store the default values PlayerDefaultValues.WalkSpeed = GetCharacterMovement()->MaxWalkSpeed; PlayerDefaultValues.JumpVelo = GetCharacterMovement()->JumpZVelocity; PlayerDefaultValues.CameraFOV = FollowCamera->FieldOfView; PlayerDefaultValues.CameraArmLength = CameraBoom->TargetArmLength; // Check if theres tomato in player's hand CheckTomatoInHand(); // Spawn the projectile indicator actor if (ThrowableProjectilIndicatorClass) { FActorSpawnParameters spawnParam; spawnParam.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; ThrowableProjectilIndicator = GetWorld()->SpawnActor<AThrowableProjectileIndicator>( ThrowableProjectilIndicatorClass, FTransform::Identity, spawnParam); } else { CatastropheDebug::OnScreenErrorMsg(TEXT("PlayerCharacter: Missing ThrowableProjectileIndicatorClass"), 30.0f); UE_LOG(LogTemp, Error, TEXT("PlayerCharacter: Missing ThrowableProjectileIndicatorClass")); } // Set default state for the player UI if (PlayerWidgetClass) { PlayerWidget = CreateWidget<UPlayerWidget>(GetWorld(), PlayerWidgetClass); if (PlayerWidget) { PlayerWidget->AddToViewport(); PlayerWidget->ToggleStamina(true); } } else { CatastropheDebug::OnScreenErrorMsg(TEXT("PlayerCharacter: Missing PlayerWidgetClass"), 30.0f); UE_LOG(LogTemp, Error, TEXT("PlayerCharacter: Missing PlayerWidgetClass")); } } // Called every frame void APlayerCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); // If player is sprinting, drain it XD if (SprintMovementComponent->IsSprinting()) { CurrentStamina = FMath::Max(0.0f, CurrentStamina - (StaminaDrainPerSec * DeltaTime)); if (CurrentStamina <= 0.0f) UnSprint(); } else if (!GetCharacterMovement()->IsFalling()) // Regen the stamina only when player is on ground { CurrentStamina = FMath::Min(TotalStamina, CurrentStamina + (StaminaDrainPerSec * DeltaTime)); } // Make sure to run the zoom in timeline if (ZoomInTimeline) { ZoomInTimeline->TickComponent(DeltaTime, ELevelTick::LEVELTICK_TimeOnly, nullptr); } // Do the interaction tick InteractionTick(DeltaTime); // Calculate the projectile prediction and update the projectile spline // if it should be shown if (ThrowableProjectilIndicator && bShowingProjectileIndicator) { FVector pathStartPosition = ThrowableSpawnPoint->GetComponentLocation(); CurrentThrowableLaunchVelocity = ThrowingStrength * FollowCamera->GetForwardVector().RotateAngleAxis( ThrowingAngle, FollowCamera->GetRightVector()); float projectileRadius = 10.0f; TArray<AActor*> actorsToIgnore; actorsToIgnore.Add(this); FPredictProjectilePathResult predictResult; FPredictProjectilePathParams predictParam; predictParam.StartLocation = pathStartPosition; predictParam.LaunchVelocity = CurrentThrowableLaunchVelocity; predictParam.bTraceComplex = true; predictParam.ProjectileRadius = projectileRadius; predictParam.ObjectTypes = ThrowablePrecdictObjectType; predictParam.bTraceComplex = false; predictParam.ActorsToIgnore = actorsToIgnore; predictParam.DrawDebugType = EDrawDebugTrace::Type::None; predictParam.SimFrequency = 15.0f; predictParam.MaxSimTime = 2.0f; predictParam.bTraceWithChannel = true; predictParam.bTraceWithCollision = true; predictParam.ObjectTypes = ObjectTypes; predictParam.TraceChannel = ECollisionChannel::ECC_Visibility; predictParam.OverrideGravityZ = ThrowableGravityOverwrite; UGameplayStatics::PredictProjectilePath(this, predictParam, predictResult); // Only do the update when there are some data in if (predictResult.PathData.Num() > 0) { TArray<FVector> pathLocations; for (FPredictProjectilePathPointData data : predictResult.PathData) { pathLocations.Add(data.Location); } ThrowableProjectilIndicator->UpdateIndicatorLine(pathLocations); } } } // Called to bind functionality to input void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); // Set up gameplay key bindings check(PlayerInputComponent); // General movement input setup PlayerInputComponent->BindAxis("MoveForward", this, &APlayerCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &APlayerCharacter::MoveRight); PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &APlayerCharacter::Sprint); PlayerInputComponent->BindAction("Sprint", IE_Released, this, &APlayerCharacter::UnSprint); PlayerInputComponent->BindAction("Crouch", IE_Pressed, this, &APlayerCharacter::CrouchBegin); PlayerInputComponent->BindAction("Crouch", IE_Released, this, &APlayerCharacter::CrouchEnd); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &APlayerCharacter::PlayerJump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &APlayerCharacter::PlayerStopJump); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APlayerCharacter::PlayerTurn); PlayerInputComponent->BindAxis("TurnRate", this, &APlayerCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APlayerCharacter::PlayerLookUp); PlayerInputComponent->BindAxis("LookUpRate", this, &APlayerCharacter::LookUpAtRate); // Interaction actions PlayerInputComponent->BindAction("Interact", IE_Pressed, this, &APlayerCharacter::InteractBegin); PlayerInputComponent->BindAction("Interact", IE_Released, this, &APlayerCharacter::InteractEnd); // HHU (Hand Hold utility) actions PlayerInputComponent->BindAction("HHUPrimary", IE_Pressed, this, &APlayerCharacter::HHUPrimaryActionBegin); PlayerInputComponent->BindAction("HHUPrimary", IE_Released, this, &APlayerCharacter::HHUPrimaryActionEnd); PlayerInputComponent->BindAction("HHUSecondary", IE_Pressed, this, &APlayerCharacter::HHUSecondaryActionBegin); PlayerInputComponent->BindAction("HHUSecondary", IE_Released, this, &APlayerCharacter::HHUSecondaryActionEnd); } void APlayerCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void APlayerCharacter::LookUpAtRate(float Rate) { // Calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void APlayerCharacter::Sprint() { if (bAllowMovementInput && CurrentStamina >= TotalStamina && // Only sprint player has full stamina !bHHUSecondaryActive&& // Cant sprint while aiming lol !GetCharacterMovement()->IsCrouching()) // Cant sprint while crouch { SprintMovementComponent->Sprint(); } } void APlayerCharacter::UnSprint() { SprintMovementComponent->UnSprint(); } void APlayerCharacter::OnSprintBegin() { FollowCamera->SetFieldOfView(PlayerDefaultValues.CameraFOV + 2.5f); SprintingPostProcess->bEnabled = true; } void APlayerCharacter::OnSprintEnd() { FollowCamera->SetFieldOfView(PlayerDefaultValues.CameraFOV); SprintingPostProcess->bEnabled = false; } void APlayerCharacter::CrouchBegin() { if (bAllowMovementInput || bForceCrouch) { Crouch(); HidingPostProcess->bEnabled = true; HHUSecondaryActionEnd(); if (SprintMovementComponent->IsSprinting()) SprintMovementComponent->UnSprint(); } } void APlayerCharacter::CrouchEnd() { if (!bForceCrouch) { UnCrouch(); HidingPostProcess->bEnabled = false; } } void APlayerCharacter::CheckTomatoInHand() { if (InventoryComponent) { if (InventoryComponent->GetCurrentItemSack()) { if (InventoryComponent->GetCurrentItemSack()->IsAbleToUse()) { TomatoInHandMesh->SetVisibility(true); return; } } } TomatoInHandMesh->SetVisibility(false); } void APlayerCharacter::MoveForward(float Value) { if (Controller && (Value != 0.0f) && bAllowMovementInput) { FRotator Rotation; FRotator YawRotation; // find out which way is forward switch (CurrentMovementSet) { case EPlayerMovementSet::NORMAL: { Rotation = Controller->GetControlRotation(); YawRotation = FRotator(0, Rotation.Yaw, 0); break; } case EPlayerMovementSet::CAVECHASE: { if (ACatastropheMainGameMode* mainGameMode = ACatastropheMainGameMode::GetGameModeInst(this)) { if (ACaveCameraTrack* caveCameraTrack = mainGameMode->GetCaveCameraTrack()) { FVector trackCameraLocation = caveCameraTrack->GetTrackFollowCamera()->GetComponentLocation(); Rotation = UKismetMathLibrary::FindLookAtRotation(trackCameraLocation, GetActorLocation()); YawRotation = FRotator(0, Rotation.Yaw, 0); } } break; } default: break; } // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void APlayerCharacter::MoveRight(float Value) { if (Controller && (Value != 0.0f) && bAllowMovementInput) { FRotator Rotation; FRotator YawRotation; // find out which way is forward switch (CurrentMovementSet) { case EPlayerMovementSet::NORMAL: { Rotation = Controller->GetControlRotation(); YawRotation = FRotator(0, Rotation.Yaw, 0); break; } case EPlayerMovementSet::CAVECHASE: { if (ACatastropheMainGameMode* mainGameMode = ACatastropheMainGameMode::GetGameModeInst(this)) { if (ACaveCameraTrack* caveCameraTrack = mainGameMode->GetCaveCameraTrack()) { FVector trackCameraLocation = caveCameraTrack->GetTrackFollowCamera()->GetComponentLocation(); Rotation = UKismetMathLibrary::FindLookAtRotation(trackCameraLocation, GetActorLocation()); YawRotation = FRotator(0, Rotation.Yaw, 0); } } break; } default: break; } // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } } void APlayerCharacter::PlayerJump() { if (bAllowMovementInput) { Jump(); } } void APlayerCharacter::PlayerStopJump() { StopJumping(); } void APlayerCharacter::PlayerTurn(float _value) { if (bAllowCameraInput) { AddControllerYawInput(_value); } } void APlayerCharacter::PlayerLookUp(float _value) { if (bAllowCameraInput) { AddControllerPitchInput(_value); } } void APlayerCharacter::TimelineSetCameraZoomValue(float _alpha) { float resultLength = FMath::Lerp( PlayerDefaultValues.CameraArmLength, PlayerDefaultValues.CameraArmLength * CameraZoomMultiplier, _alpha); CameraBoom->TargetArmLength = resultLength; } void APlayerCharacter::InteractBegin() { if (IsValid(InteractingTargetComponent) && InteractingTargetComponent->bCanInteract) { bInteracting = true; // Set the holding interaction begin InteractingTargetComponent->Interact(this, InteractionTimeHold); } } void APlayerCharacter::InteractEnd() { bInteracting = false; InteractionTimeHold = 0.0f; } void APlayerCharacter::InteractionTick(float _deltaTime) { if (bInteracting && IsValid(InteractingTargetComponent)) { InteractionTimeHold += _deltaTime; InteractingTargetComponent->Interact(this, InteractionTimeHold); } else if (!bInteracting && IsValid(InteractingTargetComponent)) { InteractingTargetComponent->StopInteract(); } } void APlayerCharacter::HHUPrimaryActionBegin() { // If cannot use HHU, just don't then if (!bCanUseHHU) return; // Set the activation state to true bHHUPrimaryActive = true; // Use the currently selected useable item InventoryComponent->UseItem(bHHUSecondaryActive); HHUSecondaryActionEnd(); } void APlayerCharacter::HHUPrimaryActionEnd() { // Only end if the action is already activated if (bHHUPrimaryActive) { // Flip the activation state bHHUPrimaryActive = false; } } void APlayerCharacter::HHUSecondaryActionBegin() { // If cannot use HHU, just don't then if (!bCanUseHHU || !IsValid(InventoryComponent) || !IsValid(ThrowableProjectilIndicator)) return; AItemSack* currentSack = InventoryComponent->GetCurrentItemSack(); if (currentSack && currentSack->IsAbleToUse() && currentSack->bAimingNeeded) { // Set the activation state to true bHHUSecondaryActive = true; // Let the character follow camera rotation if (SprintMovementComponent->IsSprinting()) UnSprint(); bUseControllerRotationYaw = true; CameraBoom->bEnableCameraLag = false; PlayerAnimInstance->bAiming = true; bShowingProjectileIndicator = true; ThrowableProjectilIndicator->SetIndicatorEnabled(true); ACatastropheMainGameMode::GetGameModeInst(this)->OnPlayerAimingBegin.Broadcast(); } } void APlayerCharacter::HHUSecondaryActionEnd() { // Only end if the action is already activated if (bHHUSecondaryActive) { // Let the character not follow camera rotation bUseControllerRotationYaw = false; CameraBoom->bEnableCameraLag = true; PlayerAnimInstance->bAiming = false; bShowingProjectileIndicator = false; if (ThrowableProjectilIndicator) ThrowableProjectilIndicator->SetIndicatorEnabled(false); ACatastropheMainGameMode::GetGameModeInst(this)->OnPlayerAimingEnd.Broadcast(); // Flip the activation state bHHUSecondaryActive = false; } } // Call to throw a smoke bomb onto the ground void APlayerCharacter::ThrowSmokeBomb() { Receive_OnSmokeBomb(); } // Set the player T pose state void APlayerCharacter::SetPlayerTPoseEable(bool _bEnable) { PlayerAnimInstance->bT = _bEnable; } // Setting the currently interacting component void APlayerCharacter::SetInteractionTarget(class UInteractableComponent* _interactTargetComponent) { if (IsValid(_interactTargetComponent)) { InteractingTargetComponent = _interactTargetComponent; } } // Remove the pointer of the given interacting component if its currently interacting with void APlayerCharacter::RemoveInteractionTarget(class UInteractableComponent* _interactTargetComponent) { if (_interactTargetComponent == InteractingTargetComponent) { InteractingTargetComponent = nullptr; } } void APlayerCharacter::ResetInteractionAction() { InteractEnd(); } void APlayerCharacter::ResetPlayerCharacter() { PlayerAnimInstance->ResetAnimationValues(); CurrentStamina = TotalStamina; bInteracting = false; ToggleSpottedAlert(false); bAllowMovementInput = true; bAllowCameraInput = true; bForceCrouch = false; bCanInteract = true; bSprinting = false; } void APlayerCharacter::SetStamina(float _value) { CurrentStamina = FMath::Min(_value, TotalStamina); } void APlayerCharacter::SetMovementActionEnable(bool _bEnable) { UnSprint(); CrouchEnd(); bAllowMovementInput = _bEnable; } void APlayerCharacter::SetCameraInputEnable(bool _bEnable) { bAllowCameraInput = _bEnable; } void APlayerCharacter::SetForceCrouchEnable(bool _bEnable) { bForceCrouch = _bEnable; if (_bEnable) { CrouchBegin(); } else { CrouchEnd(); } } void APlayerCharacter::TogglePlayerHUD(bool _bEnable) { if (PlayerWidget) { if (_bEnable) { PlayerWidget->SetVisibility(ESlateVisibility::Visible); //PlayerWidget->RemoveFromParent(); //PlayerWidget->AddToViewport(0); } else { PlayerWidget->SetVisibility(ESlateVisibility::Hidden); //PlayerWidget->RemoveFromParent(); } } } void APlayerCharacter::ToggleSpottedAlert(bool _bEnable) { if (_bEnable) { SpottedAlertParticle->ActivateSystem(); } else { SpottedAlertParticle->DeactivateSystem(); } } // Return the crouching state from the movement component bool APlayerCharacter::IsPlayerCrouched() const { return GetCharacterMovement()->IsCrouching(); }
31.33936
180
0.783695
Enderderder
3a6e88550fd003de6bea000f87299ed1695604ad
3,837
cpp
C++
src/SUAPI-CppWrapper/model/Opening.cpp
TommyKaneko/Sketchup-API-C-Wrapper
8210ce29aa93a7375ae520d271305987e4269ec6
[ "MIT" ]
20
2017-04-05T07:29:44.000Z
2022-01-10T18:41:42.000Z
src/SUAPI-CppWrapper/model/Opening.cpp
TommyKaneko/Sketchup-API-C-Wrapper
8210ce29aa93a7375ae520d271305987e4269ec6
[ "MIT" ]
42
2017-05-21T07:47:14.000Z
2019-10-31T16:19:00.000Z
src/SUAPI-CppWrapper/model/Opening.cpp
TommyKaneko/Sketchup-API-C-Wrapper
8210ce29aa93a7375ae520d271305987e4269ec6
[ "MIT" ]
9
2017-04-20T13:03:13.000Z
2022-02-08T23:53:36.000Z
// // Opening.cpp // // Sketchup C++ Wrapper for C API // MIT License // // Copyright (c) 2017 Tom Kaneko // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Macro for getting rid of unused variables commonly for assert checking #define _unused(x) ((void)(x)) #include "SUAPI-CppWrapper/model/Opening.hpp" #include <cassert> #include <stdexcept> namespace CW { /****************************** ** Constructors / Destructor ** *******************************/ Opening::Opening() : m_opening(std::shared_ptr<SUOpeningRef>SU_INVALID) {} Opening::Opening(SUOpeningRef ref) : m_opening(std::shared_ptr<SUOpeningRef>(&ref)) {} Opening::Opening(std::shared_ptr<SUOpeningRef> opening) : m_opening(opening) {} Opening::Opening(const Opening& other) : m_opening(!other ? std::shared_ptr<SUOpeningRef>SU_INVALID : other.m_opening) {} Opening::~Opening() { if (!!(*this) && m_opening.use_count() < 2) { SU_RESULT res = SUOpeningRelease(m_opening.get()); assert (res != SU_ERROR_INVALID_INPUT); } } bool Opening::operator!() const { return SUIsInvalid(*m_opening.get()); } Opening& Opening::operator=(const Opening& other) { // Destroy this object if there are no other references if (!!(*this) && m_opening.use_count() < 2) { SU_RESULT res = SUOpeningRelease(m_opening.get()); if (res == SU_ERROR_INVALID_INPUT) { throw std::logic_error("CW::Opening::operator=(): Opening reference is invalid. The code may point to dereferenced pointer."); } } m_opening = other.m_opening; return (*this); } /******************* ** Public Methods ** ********************/ size_t Opening::get_num_points() const { if (!(*this)) { throw std::logic_error("CW::Opening::get_num_points(): Opening is invalid"); } size_t count = 0; SU_RESULT res = SUOpeningGetNumPoints(*m_opening.get(), &count); if (res == SU_ERROR_NULL_POINTER_OUTPUT) { throw std::logic_error("CW::Opening::get_num_points(): points or count is NULL"); } assert(res == SU_ERROR_NONE); _unused(res); return count; } std::vector<Point3D> Opening::get_points() const { if (!(*this)) { throw std::logic_error("CW::Opening::get_points(): Opening is invalid"); } size_t count = this->get_num_points(); std::vector<SUPoint3D> points_array(count, SU_INVALID); size_t count_returned = 0; SU_RESULT res = SUOpeningGetPoints(*m_opening.get(), count, points_array.data(), &count_returned); if (res == SU_ERROR_NULL_POINTER_OUTPUT) { throw std::logic_error("CW::Opening::get_points(): points or count is NULL"); } assert(res == SU_ERROR_NONE); _unused(res); assert(count_returned == count); std::vector<Point3D> points; points.reserve(count_returned); for (SUPoint3D p : points_array) { points.push_back(p); } return points; } } // end namespace CW
30.212598
133
0.69325
TommyKaneko
3a7510edc6c733b143b5ffd248c2ef231b464bc1
1,150
cpp
C++
src/NPC.cpp
CS126SP20/final-project-tessarm2
e4134d69207d610b0dc2464d8bed67908186fbee
[ "MIT" ]
null
null
null
src/NPC.cpp
CS126SP20/final-project-tessarm2
e4134d69207d610b0dc2464d8bed67908186fbee
[ "MIT" ]
null
null
null
src/NPC.cpp
CS126SP20/final-project-tessarm2
e4134d69207d610b0dc2464d8bed67908186fbee
[ "MIT" ]
null
null
null
// // Created by tessa on 4/21/2020. // #include "mylibrary/NPC.h" #include <cinder/gl/gl.h> namespace myLibrary { void NPC::draw() { ci::gl::pushModelMatrix(); ci::gl::translate(location); sprite->draw(); ci::gl::popModelMatrix(); } void NPC::setHealth(int setHealth) { health = setHealth; } void NPC::setIsEnemy(bool isEnemy) { is_enemy = isEnemy; } void NPC::setDesc(std::string setDesc) { desc = setDesc; } int NPC::getHealth() { return health; } int NPC::getIsEnemy() { return is_enemy; } int NPC::getAttack() { return attack; } std::string NPC::getName() { return name; } std::string NPC::getDesc() { return desc; } std::string NPC::getAttackDesc() { return attack_desc; } void NPC::setLoc(ci::vec2 setLoc) { location = setLoc; } ci::vec2 NPC::getLoc() { return location; } cinder::gl::Texture2dRef NPC::getTex() { return obj_tex; } void NPC::setSprite(po::SpritesheetAnimationRef set_sprite) { sprite = set_sprite; sprite->play(); } po::SpritesheetAnimationRef NPC::getSprite() { return sprite; } }
17.692308
63
0.613043
CS126SP20
b91c20feb67fe26d655677887255b040b67eb42f
7,153
cpp
C++
IPlug/AAX/IPlugAAX_Parameters.cpp
onqel/iPlug2
d6d4c45935119fe87bf9049861a2e004df605b80
[ "Zlib" ]
1
2019-06-09T19:16:53.000Z
2019-06-09T19:16:53.000Z
IPlug/AAX/IPlugAAX_Parameters.cpp
onqel/iPlug2
d6d4c45935119fe87bf9049861a2e004df605b80
[ "Zlib" ]
null
null
null
IPlug/AAX/IPlugAAX_Parameters.cpp
onqel/iPlug2
d6d4c45935119fe87bf9049861a2e004df605b80
[ "Zlib" ]
null
null
null
/* ============================================================================== This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers. See LICENSE.txt for more info. ============================================================================== */ #include "IPlugAAX_Parameters.h" AAX_Result AAX_CIPlugParameters::ResetFieldData (AAX_CFieldIndex iFieldIndex, void * oData, uint32_t iDataSize) const //override from CEffectParameters. { //If this is the IPlugparameters field, let's initialize it to our this pointer. if (iFieldIndex == AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mPrivateData) ) { //Make sure everything is at least initialized to 0. AAX_ASSERT( iDataSize == sizeof(AAX_SIPlugPrivateData) ); memset(oData, iDataSize, 0); //Set all of the private data variables. AAX_SIPlugPrivateData* privateData = static_cast <AAX_SIPlugPrivateData*> (oData); privateData->mIPlugParametersPtr = (AAX_CIPlugParameters*) this; return AAX_SUCCESS; } //Call into the base class to clear all other private data. return AAX_CEffectParameters::ResetFieldData(iFieldIndex, oData, iDataSize); } //StaticDescribeAlgorithm does all of the basic context setup and pointer passing work. Call this from Describe. AAX_Result AAX_CIPlugParameters::StaticDescribe(AAX_IEffectDescriptor * ioDescriptor, const AAX_SIPlugSetupInfo & setupInfo) { AAX_Result err = AAX_SUCCESS; AAX_IComponentDescriptor * compDesc = ioDescriptor->NewComponentDescriptor (); // Register MIDI nodes. To avoid context corruption, register small blocks of private data in case node doesn't needed. AAX_CFieldIndex globalNodeID = AAX_FIELD_INDEX(AAX_SIPlugRenderInfo, mGlobalNode); AAX_CFieldIndex localInputNodeID = AAX_FIELD_INDEX(AAX_SIPlugRenderInfo, mInputNode); AAX_CFieldIndex localOutputNodeID = AAX_FIELD_INDEX(AAX_SIPlugRenderInfo, mOutputNode); AAX_CFieldIndex transportNodeID = AAX_FIELD_INDEX(AAX_SIPlugRenderInfo, mTransportNode); if (setupInfo.mNeedsGlobalMIDI) err |= compDesc->AddMIDINode ( globalNodeID, AAX_eMIDINodeType_Global, setupInfo.mGlobalMIDINodeName, setupInfo.mGlobalMIDIEventMask ); else err |= compDesc->AddPrivateData( globalNodeID, sizeof(float), AAX_ePrivateDataOptions_DefaultOptions ); if (setupInfo.mNeedsInputMIDI) err |= compDesc->AddMIDINode ( localInputNodeID, AAX_eMIDINodeType_LocalInput, setupInfo.mInputMIDINodeName, setupInfo.mInputMIDIChannelMask ); else err |= compDesc->AddPrivateData( localInputNodeID, sizeof(float), AAX_ePrivateDataOptions_DefaultOptions ); if (setupInfo.mNeedsOutputMIDI) err |= compDesc->AddMIDINode ( localOutputNodeID, AAX_eMIDINodeType_LocalOutput, setupInfo.mOutputMIDINodeName, setupInfo.mOutputMIDIChannelMask ); else err |= compDesc->AddPrivateData( localOutputNodeID, sizeof(float), AAX_ePrivateDataOptions_DefaultOptions ); if (setupInfo.mNeedsTransport) err |= compDesc->AddMIDINode ( transportNodeID, AAX_eMIDINodeType_Transport, "Transport", 0xffff ); else err |= compDesc->AddPrivateData( transportNodeID, sizeof(float), AAX_ePrivateDataOptions_DefaultOptions ); // AAX_ASSERT(setupInfo.mNumAdditionalInputMIDINodes <= kMaxAdditionalMIDINodes); // for (int32_t index=0; index < kMaxAdditionalMIDINodes; index++) // { // AAX_CFieldIndex nodeID = AAX_FIELD_INDEX(AAX_SInstrumentRenderInfo, mAdditionalInputMIDINodes[index]); // AAX_CString nodeName(setupInfo.mInputMIDINodeName); // nodeName.AppendNumber(index+1); // if (index < setupInfo.mNumAdditionalInputMIDINodes) // err |= compDesc->AddMIDINode ( nodeID, AAX_eMIDINodeType_LocalInput, nodeName.CString(), setupInfo.mInputMIDIChannelMask ); // else // err |= compDesc->AddPrivateData( nodeID, sizeof(float), AAX_ePrivateDataOptions_DefaultOptions ); //Just here to fill the port. Not used. // } //Add outputs, meters, info, etc err |= compDesc->AddAudioIn( AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mAudioInputs) ); err |= compDesc->AddAudioOut( AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mAudioOutputs) ); err |= compDesc->AddAudioBufferLength( AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mNumSamples) ); if (setupInfo.mNumMeters > 0) err |= compDesc->AddMeters( AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mMeters), setupInfo.mMeterIDs, setupInfo.mNumMeters ); else err |= compDesc->AddPrivateData( AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mMeters), sizeof(float), AAX_ePrivateDataOptions_DefaultOptions ); //Add optional aux output stems. for (int32_t index=0; index < setupInfo.mNumAuxOutputStems; index++) { err |= compDesc->AddAuxOutputStem (0 /*not used*/, setupInfo.mAuxOutputStemFormats[index], setupInfo.mAuxOutputStemNames[index] ); } //Add pointer to the data model instance and other interesting information. err |= compDesc->AddPrivateData( AAX_FIELD_INDEX (AAX_SIPlugRenderInfo, mPrivateData), sizeof(AAX_SIPlugPrivateData), AAX_ePrivateDataOptions_DefaultOptions ); //Additional properties on the algorithm AAX_IPropertyMap * properties = compDesc->NewPropertyMap (); // Host generated GUI or not. if (setupInfo.mUseHostGeneratedGUI) properties->AddProperty ( AAX_eProperty_UsesClientGUI, true ); // initial latency err |= properties->AddProperty( AAX_eProperty_LatencyContribution, setupInfo.mLatency); err |= properties->AddProperty ( AAX_eProperty_InputStemFormat, setupInfo.mInputStemFormat ); err |= properties->AddProperty ( AAX_eProperty_OutputStemFormat, setupInfo.mOutputStemFormat ); err |= properties->AddProperty ( AAX_eProperty_CanBypass, setupInfo.mCanBypass ); err |= properties->AddProperty ( AAX_eProperty_ManufacturerID, setupInfo.mManufacturerID ); err |= properties->AddProperty ( AAX_eProperty_ProductID, setupInfo.mProductID ); err |= properties->AddProperty ( AAX_eProperty_PlugInID_RTAS, setupInfo.mPluginID ); //This is a native only convenience layer, so there is no need for a DSP type. if (setupInfo.mAudioSuiteID != 'none') { err |= properties->AddProperty ( AAX_eProperty_PlugInID_AudioSuite, setupInfo.mAudioSuiteID ); } err |= compDesc->AddProcessProc_Native( AAX_CIPlugParameters::StaticRenderAudio, properties ); err |= ioDescriptor->AddComponent( compDesc ); return err; } //Static RenderAudio ( This version would only work for non-distributed algorithms. ) void AAX_CALLBACK AAX_CIPlugParameters::StaticRenderAudio(AAX_SIPlugRenderInfo* const inInstancesBegin [], const void* inInstancesEnd) { for (AAX_SIPlugRenderInfo * const * instanceRenderInfoPtr = inInstancesBegin; instanceRenderInfoPtr != inInstancesEnd; ++instanceRenderInfoPtr) { AAX_SIPlugPrivateData* privateData = (*instanceRenderInfoPtr)->mPrivateData; if (privateData != 0) { //Grab the object pointer from the Context and call RenderAudio on it. AAX_CIPlugParameters* parameters = privateData->mIPlugParametersPtr; if (parameters != 0) parameters->RenderAudio(*instanceRenderInfoPtr); } } }
51.833333
172
0.744303
onqel
b91d3b952c13286fdf7737c47a19722cd3c6d563
1,206
cpp
C++
Framework/Graphics/Src/GeometryShader.cpp
amyrhzhao/CooEngine
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
[ "MIT" ]
3
2020-07-23T02:50:11.000Z
2020-10-20T14:49:40.000Z
Framework/Graphics/Src/GeometryShader.cpp
amyrhzhao/CooEngine
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
[ "MIT" ]
null
null
null
Framework/Graphics/Src/GeometryShader.cpp
amyrhzhao/CooEngine
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
[ "MIT" ]
null
null
null
#include "Precompiled.h" #include "GeometryShader.h" #include "D3DUtil.h" using namespace Coo::Graphics; void Coo::Graphics::GeometryShader::Initialize(const wchar_t * filename) { auto device = GetDevice(); ID3DBlob* shaderBlob = nullptr; ID3DBlob* errorBlob = nullptr; HRESULT hr; // Compile geometry shader hr = D3DCompileFromFile( filename, nullptr, nullptr, "GS", "gs_5_0", 0, 0, &shaderBlob, &errorBlob); ASSERT(SUCCEEDED(hr), "Failed to compile geometry shader. Error: %s", (const char*)errorBlob->GetBufferPointer()); // Create geometry shader hr = device->CreateGeometryShader( shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), nullptr, &mGeometryShader); ASSERT(SUCCEEDED(hr), "Failed to create geometry shader."); SafeRelease(shaderBlob); SafeRelease(errorBlob); } void Coo::Graphics::GeometryShader::Terminate() { SafeRelease(mGeometryShader); } void Coo::Graphics::GeometryShader::Bind() { auto context = GetContext(); context->GSSetShader(mGeometryShader, nullptr, 0); } void Coo::Graphics::GeometryShader::Unbind() { auto context = GetContext(); context->GSSetShader(nullptr, nullptr, 0); }
24.612245
116
0.703151
amyrhzhao
b924021cccabda765fe55abce0072e2e9ac0aae2
1,817
hpp
C++
libs/messenger/include/messenger/mailbox_interface.hpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
96
2018-08-23T16:49:05.000Z
2021-11-25T00:47:16.000Z
libs/messenger/include/messenger/mailbox_interface.hpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
1,011
2018-08-17T12:25:21.000Z
2021-11-18T09:30:19.000Z
libs/messenger/include/messenger/mailbox_interface.hpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
65
2018-08-20T20:05:40.000Z
2022-02-26T23:54:35.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "messenger/message.hpp" #include "muddle/muddle_endpoint.hpp" #include "muddle/muddle_interface.hpp" #include <deque> #include <unordered_map> namespace fetch { namespace messenger { class MailboxInterface { public: using MessageList = std::deque<Message>; using Address = muddle::Address; using DeliveryFunction = std::function<void(Message const &msg)>; virtual ~MailboxInterface() = default; virtual void SetDeliveryFunction(DeliveryFunction const &attempt_delivery) = 0; virtual void SendMessage(Message message) = 0; virtual MessageList GetMessages(Address messenger) = 0; virtual void ClearMessages(Address messenger, uint64_t count) = 0; virtual void RegisterMailbox(Address messenger) = 0; virtual void UnregisterMailbox(Address messenger) = 0; }; } // namespace messenger } // namespace fetch
37.081633
88
0.604843
chr15murray
b9277633998eb319a2f7371251524db62119a493
1,352
cpp
C++
src/toolchain/core/CodeDom/UnaryExpression.cpp
layerzero/cc0
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
[ "BSD-2-Clause" ]
null
null
null
src/toolchain/core/CodeDom/UnaryExpression.cpp
layerzero/cc0
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
[ "BSD-2-Clause" ]
null
null
null
src/toolchain/core/CodeDom/UnaryExpression.cpp
layerzero/cc0
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
[ "BSD-2-Clause" ]
2
2015-03-03T04:36:51.000Z
2018-10-01T03:04:11.000Z
#include "UnaryExpression.h" #include <stdlib.h> #include "ExpressionVisitor.h" #include <core/Type/PointerType.h> #include <core/Type/BooleanType.h> UnaryExpression::UnaryExpression(): Expression(Expression::Nop), Operand(NULL) { } UnaryExpression::UnaryExpression(Expression::ExpressionAction nodeType, Expression* operand) : Expression(nodeType) { this->Operand = operand; } UnaryExpression::~UnaryExpression() { } void UnaryExpression::Accept(ExpressionVisitor* visitor) { visitor->Visit(this); } Expression* UnaryExpression::GetLValue() { switch (this->GetAction()) { case Dereference: return this; default: return NULL; } } Expression* UnaryExpression::GetOperand() { return Operand; } Type* UnaryExpression::GetType() { switch (this->GetAction()) { case Expression::Plus: case Expression::Minus: return Operand->GetType(); case Expression::Not: return new BooleanType(); case Expression::Reference: return new PointerType(Operand->GetType()); case Expression::Dereference: { PointerType *pointerType = dynamic_cast<PointerType *>(Operand->GetType()); return pointerType->GetUnderlyingType(); } default: abort(); } }
21.125
92
0.636834
layerzero
b92cb27346af5460a72add726852bf1d134198e2
4,830
hpp
C++
include/libpmemobj++/detail/compound_pool_ptr.hpp
B-sudo/Clevel-Hashing
47c095ccc875f6ac89a26e07e5d2bf8231cd08b8
[ "BSD-3-Clause" ]
35
2020-06-11T09:27:10.000Z
2022-03-26T14:42:32.000Z
include/libpmemobj++/detail/compound_pool_ptr.hpp
ZhiHaoi/Nam_Hashing
bd12ad16300acb95e4f4be519a03c5e91d67c4af
[ "BSD-3-Clause" ]
2
2021-02-07T18:26:35.000Z
2022-02-28T04:00:05.000Z
include/libpmemobj++/detail/compound_pool_ptr.hpp
ZhiHaoi/Nam_Hashing
bd12ad16300acb95e4f4be519a03c5e91d67c4af
[ "BSD-3-Clause" ]
11
2020-07-21T06:27:46.000Z
2022-03-26T14:42:40.000Z
#ifndef LIBPMEMOBJ_CPP_COMPOUND_POOL_PTR_HPP #define LIBPMEMOBJ_CPP_COMPOUND_POOL_PTR_HPP namespace pmem { namespace detail { /** * Similar to the "persistent_pool_ptr" except for two differences: * (1) no transactions * (2) "off" encodes "partial", "address", and "marker" info */ template <typename T> class compound_pool_ptr { template <typename Y> friend class compound_pool_ptr; typedef compound_pool_ptr<T> this_type; public: /** * Type of an actual object with all qualifier removed, * used for easy underlying type access */ typedef typename pmem::detail::sp_element<T>::type element_type; compound_pool_ptr() : off(0) { verify_type(); } /** * Default null constructor, zeroes the off. */ compound_pool_ptr(std::nullptr_t) noexcept : off(0) { verify_type(); } /** * PMEMoid constructor. * * Provided for easy interoperability between C++ and C API's. * * @param oid C-style persistent pointer */ compound_pool_ptr(PMEMoid oid) noexcept : off(oid.off) { verify_type(); } /** * PMEMoid constructor. * * Provided for easy interoperability between C++ and C API's. * * @param off offset inside persistent memory pool */ compound_pool_ptr(uint64_t _off) noexcept : off(_off) { verify_type(); } /* * Copy constructor. * * @param r Persistent pool pointer to the same type. */ compound_pool_ptr(const compound_pool_ptr &r) noexcept : off(r.off) { verify_type(); } /** * Move constructor. */ compound_pool_ptr(compound_pool_ptr &&r) noexcept : off(std::move(r.off)) { verify_type(); } /** * Move assignment operator. */ compound_pool_ptr & operator=(compound_pool_ptr &&r) { this->off = std::move(r.off); return *this; } compound_pool_ptr &operator=(std::nullptr_t) { this->off = 0; return *this; } compound_pool_ptr & operator=(const compound_pool_ptr &r) { this->off = r.off; return *this; } const uint64_t & raw() const noexcept { return this->off; } PMEMoid raw_ptr(uint64_t pool_uuid) const noexcept { uint64_t ptr = (this->off & 0x0000FFFFFFFFFFFC); PMEMoid oid = {pool_uuid, ptr}; return oid; } /** * Get a direct pointer. * * Performs a calculations on the underlying C-style pointer. * * @return a direct pointer to the object. */ element_type * get_address(uint64_t pool_uuid) const noexcept { uint64_t ptr = (this->off & 0x0000FFFFFFFFFFFC); PMEMoid oid = {pool_uuid, ptr}; return static_cast<element_type *>(pmemobj_direct(oid)); } element_type * operator()(uint64_t pool_uuid) const noexcept { return get_address(pool_uuid); } /** * Swaps two compound_pool_ptr objects of the same type. */ void swap(compound_pool_ptr &other) noexcept { std::swap(this->off, other.off); } /* * Bool conversion operator. */ explicit operator bool() const noexcept { return this->off != 0; } /** * Get the two-bit marker. */ uint8_t get_marker() const { return (uint8_t)(this->off & 0x3); } /** * Advance the two-bit marker. */ uint64_t next_state() const { return (this->off & 0xFFFFFFFFFFFFFFFC) | (get_marker() + 1U); } bool is_next_state_of(const compound_pool_ptr &r) { return get_marker() == (r.get_marker() + 1U); } /** * Get the encoded offset in compound_pool_ptr. */ uint64_t get_offset() { return (this->off & 0x0000FFFFFFFFFFFC); } // private: /* offset of persistent object in a persistent memory pool*/ uint64_t off; void verify_type() { static_assert(!std::is_polymorphic<element_type>::value, "Polymorphic types are not supported"); } }; /** * Equality operator. * * This checks if underlying PMEMoids are equal. */ template <typename T, typename Y> inline bool operator==(const compound_pool_ptr<T> &lhs, const compound_pool_ptr<Y> &rhs) noexcept { return lhs.raw() == rhs.raw(); } /** * Inequality operator. */ template <typename T, typename Y> inline bool operator!=(const compound_pool_ptr<T> &lhs, const compound_pool_ptr<Y> &rhs) noexcept { return !(lhs == rhs); } /** * Inequality operator with nullptr. */ template <typename T> inline bool operator!=(const compound_pool_ptr<T> &lhs, std::nullptr_t) noexcept { return lhs.raw() != 0; } /** * Inequality operator with nullptr. */ template <typename T> inline bool operator!=(std::nullptr_t, const compound_pool_ptr<T> &lhs) noexcept { return lhs.raw() != 0; } /** * Equality operator with nullptr. */ template <typename T> inline bool operator==(const compound_pool_ptr<T> &lhs, std::nullptr_t) noexcept { return lhs.raw() == 0; } /** * Equality operator with nullptr. */ template <typename T> inline bool operator==(std::nullptr_t, const compound_pool_ptr<T> &lhs) noexcept { return lhs.raw() == 0; } } /* namespace detail */ } /* namespace pmem */ #endif
17.436823
68
0.678054
B-sudo
b930adb8549ce7431936f6ba748d44930b333497
3,063
cpp
C++
Project-7/C/Pr15-6.cpp
lele0108/adv-c
f6c6bd36cc5a4489023ad782a1c1ac0a943d5543
[ "MIT" ]
null
null
null
Project-7/C/Pr15-6.cpp
lele0108/adv-c
f6c6bd36cc5a4489023ad782a1c1ac0a943d5543
[ "MIT" ]
null
null
null
Project-7/C/Pr15-6.cpp
lele0108/adv-c
f6c6bd36cc5a4489023ad782a1c1ac0a943d5543
[ "MIT" ]
null
null
null
// Jimmy Liu // Project 7 // December 4 2015 (Extension Requested) // XCode 7.0 // This program demonstrates the Car, Truck, and SUV // classes that are derived from the Automobile class. #include <iostream> #include <string> #include <algorithm> #include <iomanip> #include <fstream> #include <sstream> #include <cstring> #include "Car.h" #include "Truck.h" #include "SUV.h" using namespace std; void readThisFile(); void printCar(Car &car); void printTruck(Truck &truck); void printSUV(SUV &suv); // Main test function of program int main() { readThisFile(); return 0; } // Reads text file and creates a single Car, Truck, and SUV void readThisFile() { string line; ifstream myfile ("cars.txt"); if (myfile.is_open()) { int j = 0; while (getline(myfile, line)) { string hold[5]; string temp; int i = 0; istringstream ss(line.substr(3)); while(getline(ss, temp, ',')) { hold[i] = temp; i++; } if (j == 0) { Car car(hold[0], atoi(hold[1].c_str()), atoi(hold[2].c_str()), atoi(hold[3].c_str()), atoi(hold[4].c_str())); printCar(car); } else if (j == 1) { Truck truck(hold[0], atoi(hold[1].c_str()), atoi(hold[2].c_str()), atoi(hold[3].c_str()), hold[4]); printTruck(truck); } else { SUV suv(hold[0], atoi(hold[1].c_str()), atoi(hold[2].c_str()), atoi(hold[3].c_str()), atoi(hold[4].c_str())); printSUV(suv); } j++; } } } // Prints the car void printCar(Car &car) { cout << fixed << showpoint << setprecision(2); cout << "We have the following car in inventory:\n" << car.getModel() << " " << car.getMake() << " with " << car.getDoors() << " doors and " << car.getMileage() << " miles.\nPrice: $" << car.getPrice() << endl << endl; } // Prints the truck void printTruck(Truck &truck) { cout << fixed << showpoint << setprecision(2); cout << "We have the following truck in inventory:\n" << truck.getModel() << " " << truck.getMake() << " with " << truck.getDriveType() << " drive type and " << truck.getMileage() << " miles.\nPrice: $" << truck.getPrice() << endl << endl; } // Prints the SUV void printSUV(SUV &suv) { cout << fixed << showpoint << setprecision(2); cout << "We have the following SUV in inventory:\n" << suv.getModel() << " " << suv.getMake() << " with " << suv.getMileage() << " miles and " << suv.getPassengers() << " passenger capacity.\n" << "Price: $" << suv.getPrice() << endl; } /* MacBook-Pro-3:C jimmyliu$ ./a.out We have the following car in inventory: 2007 with 4 doors and 50000 miles. Price: $15000.00 We have the following truck in inventory: 2006 ota with 4WD drive type and 40000 miles. Price: $12000.00 We have the following SUV in inventory: 2005 vo with 30000 miles and 5 passenger capacity. Price: $18000.00 */
28.896226
118
0.567091
lele0108
b932f1fa2fca0432ca2bb917b36d10f23a170133
19,319
cpp
C++
src/dispatcher.cpp
chardin-cpi/simppl
e0a7e13519e5a7703c12b0dcb6f0120b66be38a0
[ "MIT" ]
null
null
null
src/dispatcher.cpp
chardin-cpi/simppl
e0a7e13519e5a7703c12b0dcb6f0120b66be38a0
[ "MIT" ]
null
null
null
src/dispatcher.cpp
chardin-cpi/simppl
e0a7e13519e5a7703c12b0dcb6f0120b66be38a0
[ "MIT" ]
null
null
null
#include "simppl/dispatcher.h" #include <sys/timerfd.h> #include <sys/poll.h> #include <unistd.h> #include <iostream> #include <map> #include <set> #include <atomic> #include "simppl/detail/util.h" #include "simppl/timeout.h" #include "simppl/skeletonbase.h" #include "simppl/string.h" #include "simppl/vector.h" #define SIMPPL_DISPATCHER_CPP #include "simppl/serverside.h" #include "simppl/clientside.h" #undef SIMPPL_DISPATCHER_CPP #define SIMPPL_USE_POLL using namespace std::placeholders; using namespace std::literals::chrono_literals; namespace { std::string generate_matchstring(simppl::dbus::StubBase& stub, const char* signame) { std::ostringstream match_string; match_string << "type='signal'" << ", sender='" << stub.busname() << "'" << ", interface='" << stub.iface() << "'" << ", member='" << signame << "'"; return match_string.str(); } std::string generate_property_matchstring(simppl::dbus::StubBase& stub) { std::ostringstream match_string; match_string << "type='signal'" << ",sender='" << stub.busname() << "'" << ",interface='org.freedesktop.DBus.Properties'" << ",member='PropertiesChanged'" << ",path='" << stub.objectpath() << "'"; return match_string.str(); } inline std::chrono::steady_clock::time_point get_lookup_duetime() { return std::chrono::steady_clock::now() + 5s; } DBusHandlerResult signal_filter(DBusConnection* /*connection*/, DBusMessage* msg, void *user_data) { simppl::dbus::Dispatcher* disp = (simppl::dbus::Dispatcher*)user_data; return disp->try_handle_signal(msg); } short make_poll_events(int flags) { short rc = 0; if (flags & DBUS_WATCH_READABLE) rc |= POLLIN; if (flags & DBUS_WATCH_WRITABLE) rc |= POLLOUT; // do not expect to have read and write simultaneously from DBus API assert(flags | ((DBUS_WATCH_READABLE&DBUS_WATCH_WRITABLE) != (DBUS_WATCH_READABLE&DBUS_WATCH_WRITABLE))); return rc; } int make_dbus_flags(short events) { int rc = 0; if (events & POLLIN) rc |= DBUS_WATCH_READABLE; if (events & POLLOUT) rc |= DBUS_WATCH_WRITABLE; if (events & POLLHUP) rc |= DBUS_WATCH_HANGUP; if (events & POLLERR) rc |= DBUS_WATCH_ERROR; return rc; } } // namespace // --------------------------------------------------------------------------------------- namespace simppl { namespace dbus { // --- need this in order to resolve cyclic dependencies --------------- void dispatcher_add_stub(Dispatcher& disp, StubBase& stub) { disp.add_client(stub); } void dispatcher_add_skeleton(Dispatcher& disp, SkeletonBase& stub) { disp.add_server(stub); } // --------------------------------------------------------------------- struct Dispatcher::Private { static dbus_bool_t add_watch(DBusWatch *watch, void *data) { return ((simppl::dbus::Dispatcher::Private*)data)->add_watch(watch); } static void remove_watch(DBusWatch *watch, void *data) { ((simppl::dbus::Dispatcher::Private*)data)->remove_watch(watch); } static void toggle_watch(DBusWatch *watch, void *data) { ((simppl::dbus::Dispatcher::Private*)data)->toggle_watch(watch); } static dbus_bool_t add_timeout(DBusTimeout *timeout, void *data) { return ((simppl::dbus::Dispatcher::Private*)data)->add_timeout(timeout); } static void remove_timeout(DBusTimeout *timeout, void *data) { ((simppl::dbus::Dispatcher::Private*)data)->remove_timeout(timeout); } static void toggle_timeout(DBusTimeout *timeout, void *data) { ((simppl::dbus::Dispatcher::Private*)data)->toggle_timeout(timeout); } Private() : running_(false) { // NOOP } dbus_bool_t add_watch(DBusWatch* w) { //std::cout << "add_watch" << std::endl; pollfd fd = { 0 }; fd.fd = dbus_watch_get_unix_fd(w); if (dbus_watch_get_enabled(w)) { fd.events = make_poll_events(dbus_watch_get_flags(w)); fds_.push_back(fd); } //else // std::cout << "Not enabled" << std::endl; watch_handlers_.insert(std::make_pair(fd.fd, w)); return TRUE; } void remove_watch(DBusWatch* w) { //std::cout << "remove_watch" << std::endl; auto result = watch_handlers_.equal_range(dbus_watch_get_unix_fd(w)); for(auto iter = result.first; iter != result.second; ++iter) { if (iter->second == w) { auto pfditer = std::find_if(fds_.begin(), fds_.end(), [w](auto& pfd){ return dbus_watch_get_unix_fd(w) == pfd.fd && pfd.revents & make_poll_events(dbus_watch_get_flags(w)); }); if (pfditer != fds_.end()) { // std::cout << "ok found" << std::endl; fds_.erase(pfditer); } watch_handlers_.erase(iter); break; } } } void toggle_watch(DBusWatch* w) { assert(false); // not implemented /* auto iter = std::find_if(fds_.begin(), fds_.end(), [w](auto& pfd){ return dbus_watch_get_unix_fd(w) == pfd.fd; }); if (iter != fds_.end()) { if (dbus_watch_get_enabled(w)) { iter->events = make_poll_events(dbus_watch_get_flags(w)); } else iter->events = 0; }*/ } dbus_bool_t add_timeout(DBusTimeout* t) { pollfd fd; fd.fd = timerfd_create(CLOCK_MONOTONIC, 0); fd.events = POLLIN; //std::cout << "add_timeout fd=" << fd.fd << std::endl; if (dbus_timeout_get_enabled(t)) { int interval_ms = dbus_timeout_get_interval(t); struct itimerspec spec = { { interval_ms / 1000, (interval_ms % 1000) * 1000000L }, { interval_ms / 1000, (interval_ms % 1000) * 1000000L } }; timerfd_settime(fd.fd, 0, &spec, 0); } dbus_timeout_set_data(t, reinterpret_cast<void*>(fd.fd), 0); fds_.push_back(fd); tm_handlers_[fd.fd] = t; return TRUE; } void remove_timeout(DBusTimeout* t) { //std::cout << "remove_timeout fd=" << reinterpret_cast<int>(dbus_timeout_get_data(t)) << std::endl; auto iter = std::find_if(fds_.begin(), fds_.end(), [t](auto& pfd){ return reinterpret_cast<int64_t>(dbus_timeout_get_data(t)) == pfd.fd; }); if (iter != fds_.end()) { tm_handlers_.erase(iter->fd); ::close(iter->fd); fds_.erase(iter); } } void toggle_timeout(DBusTimeout* t) { //std::cout << "toggle_timeout" << std::endl; auto iter = std::find_if(fds_.begin(), fds_.end(), [t](auto& pfd){ return reinterpret_cast<int64_t>(dbus_timeout_get_data(t)) == pfd.fd; }); if (iter != fds_.end()) { if (dbus_timeout_get_enabled(t)) { int interval_ms = dbus_timeout_get_interval(t); struct itimerspec spec = { { interval_ms / 1000, (interval_ms % 1000) * 1000000L }, { interval_ms / 1000, (interval_ms % 1000) * 1000000L } }; timerfd_settime(iter->fd, 0, &spec, 0); } else timerfd_settime(iter->fd, 0, 0, 0); } } int poll(int timeout) { //std::cout << "poll" << std::endl; if (::poll(&fds_[0], fds_.size(), timeout) > 0) { for(auto& pfd : fds_) { if (pfd.revents) { auto result = watch_handlers_.equal_range(pfd.fd); bool handled = false; for(auto iter = result.first; iter != result.second; ++iter) { handled = true; // ok, fd found... if (pfd.revents & make_poll_events(dbus_watch_get_flags(iter->second))) { //std::cout << "handle watch" << std::endl; dbus_watch_handle(iter->second, make_dbus_flags(pfd.revents)); break; } } // must be a timeout if (!handled) { auto t_iter = tm_handlers_.find(pfd.fd); if (t_iter != tm_handlers_.end()) { int64_t data; int rc = ::read(pfd.fd, &data, sizeof(data)); (void)rc; // std::cout << "handle timeout" << std::endl; dbus_timeout_handle(t_iter->second); } } break; } } } return 0; } void init(DBusConnection* conn) { dbus_connection_set_watch_functions(conn, &add_watch, &remove_watch, nullptr, this, nullptr); dbus_connection_set_timeout_functions (conn, &add_timeout, &remove_timeout, &toggle_timeout, this, nullptr); } std::atomic_bool running_; std::vector<pollfd> fds_; std::multimap<int, DBusWatch*> watch_handlers_; std::map<int, DBusTimeout*> tm_handlers_; std::multimap<std::string, StubBase*> stubs_; std::map<std::string, int> signal_matches_; /// service registration's list std::set<std::string> busnames_; }; DBusObjectPathVTable stub_v_table = { nullptr, &SkeletonBase::method_handler, nullptr, nullptr, nullptr, nullptr }; void enable_threads() { dbus_threads_init_default(); } void Dispatcher::init(int have_introspection, const char* busname) { // compile check if stubs or skeletons are compiled with the settings // used for building the library assert(SIMPPL_HAVE_INTROSPECTION == have_introspection); d = new Dispatcher::Private; conn_ = nullptr; request_timeout_ = DBUS_TIMEOUT_USE_DEFAULT; DBusError err; dbus_error_init(&err); assert(!busname || !strncmp(busname, "bus:", 4)); const char* action = "connect"; if (!busname || !strcmp(busname, "bus:session")) { action = "dbus_bus_get_private"; conn_ = dbus_bus_get_private(DBUS_BUS_SESSION, &err); } else { if (!strcmp(busname, "bus:system")) { action = "dbus_bus_get_private"; conn_ = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err); } else { action = "dbus_connection_open_private"; conn_ = dbus_connection_open_private(busname, &err); if (conn_) { dbus_error_init(&err); action = "dbus_bus_register"; dbus_bus_register(conn_, &err); } } } if (dbus_error_is_set(&err)) throw RuntimeError(action, std::move(err)); dbus_error_free(&err); dbus_connection_add_filter(conn_, &signal_filter, this, 0); // register for busname change notifications // response is (name, old, new) dbus_error_init(&err); dbus_bus_add_match(conn_, "type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus'", &err); if (dbus_error_is_set(&err)) throw RuntimeError("dbus_bus_add_match", std::move(err)); dbus_error_free(&err); dbus_error_init(&err); std::ostringstream match_string; match_string << "type='signal',interface='org.simppl.dispatcher',member='notify_client',path='/org/simppl/dispatcher/" << ::getpid() << '/' << this << "'"; dbus_bus_add_match(conn_, match_string.str().c_str(), &err); if (dbus_error_is_set(&err)) throw RuntimeError("dbus_bus_add_match", std::move(err)); dbus_error_free(&err); // call ListNames to get list of available services on the bus DBusMessage* msg = dbus_message_new_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames"); dbus_error_init(&err); DBusMessage* reply = dbus_connection_send_with_reply_and_block(conn_, msg, 1000, &err); assert(reply); dbus_error_free(&err); std::vector<std::string> busnames; DBusMessageIter iter; dbus_message_iter_init(reply, &iter); decode(iter, busnames); for(auto& busname : busnames) { if (busname[0] != ':') d->busnames_.insert(busname); } dbus_message_unref(msg); dbus_message_unref(reply); } Dispatcher::~Dispatcher() { dbus_connection_close(conn_); dbus_connection_unref(conn_); delete d; d = 0; } void Dispatcher::notify_clients(const std::string& busname, ConnectionState state) { std::for_each(d->stubs_.begin(), d->stubs_.end(), [busname, state](auto& entry){ if (busname == entry.second->busname()) entry.second->connection_state_changed(state); }); } void Dispatcher::add_server(SkeletonBase& serv) { DBusError err; dbus_error_init(&err); if (serv.busname()[0] != '\0') dbus_bus_request_name(conn_, serv.busname(), 0, &err); if (dbus_error_is_set(&err)) { throw RuntimeError("dbus_bus_request_name", std::move(err)); } // register same path as busname, just with / instead of . dbus_error_init(&err); // register object path dbus_connection_try_register_object_path(conn_, serv.objectpath(), &stub_v_table, &serv, &err); if (dbus_error_is_set(&err)) { throw RuntimeError("dbus_connection_register_object_path", std::move(err)); } serv.disp_ = this; } void Dispatcher::remove_server(SkeletonBase& serv) { dbus_connection_unregister_object_path(conn_, serv.objectpath()); } void Dispatcher::register_signal(StubBase& stub, ClientSignalBase& sigbase) { register_signal_match(generate_matchstring(stub, sigbase.name())); } void Dispatcher::unregister_signal(StubBase& stub, ClientSignalBase& sigbase) { unregister_signal_match(generate_matchstring(stub, sigbase.name())); } void Dispatcher::register_properties(StubBase& stub) { register_signal_match(generate_property_matchstring(stub)); } void Dispatcher::unregister_properties(StubBase& stub) { unregister_signal_match(generate_property_matchstring(stub)); } void Dispatcher::register_signal_match(const std::string& match_string) { auto iter = d->signal_matches_.find(match_string); if (iter == d->signal_matches_.end()) { DBusError err; dbus_error_init(&err); dbus_bus_add_match(conn_, match_string.c_str(), &err); if (dbus_error_is_set(&err)) throw RuntimeError("dbus_bus_add_match", std::move(err)); dbus_error_free(&err); d->signal_matches_[match_string] = 1; } else ++iter->second; } void Dispatcher::unregister_signal_match(const std::string& match_string) { auto iter = d->signal_matches_.find(match_string); if (iter != d->signal_matches_.end()) { if (--iter->second == 0) { DBusError err; dbus_error_init(&err); d->signal_matches_.erase(iter); dbus_bus_remove_match(conn_, match_string.c_str(), &err); if (dbus_error_is_set(&err)) throw RuntimeError("dbus_bus_remove_match", std::move(err)); dbus_error_free(&err); } } } DBusHandlerResult Dispatcher::try_handle_signal(DBusMessage* msg) { // FIXME better check! if (dbus_message_get_type(msg) == DBUS_MESSAGE_TYPE_SIGNAL) { //std::cout << this << ": having signal '" << dbus_message_get_member(msg) << "'" << std::endl; if (!strcmp(dbus_message_get_member(msg), "notify_client")) { std::string busname; DBusMessageIter iter; dbus_message_iter_init(msg, &iter); decode(iter, busname); if (d->busnames_.find(busname) != d->busnames_.end()) notify_clients(busname, ConnectionState::Connected); return DBUS_HANDLER_RESULT_HANDLED; } else if (!strcmp(dbus_message_get_member(msg), "NameOwnerChanged")) { // bus name, not interface std::string bus_name; std::string old_name; std::string new_name; DBusMessageIter iter; dbus_message_iter_init(msg, &iter); decode(iter, bus_name, old_name, new_name); if (bus_name[0] != ':') { if (old_name.empty()) { d->busnames_.insert(bus_name); notify_clients(bus_name, ConnectionState::Connected); } else if (new_name.empty()) { d->busnames_.erase(bus_name); notify_clients(bus_name, ConnectionState::Disconnected); } } return DBUS_HANDLER_RESULT_HANDLED; } // ordinary signals... bool handled = false; auto range = d->stubs_.equal_range(dbus_message_get_path(msg)); for (auto iter = range.first; iter != range.second; ++iter) { iter->second->try_handle_signal(msg); handled = true; } if (handled) return DBUS_HANDLER_RESULT_HANDLED; // else // nobody interested in signal - go on with other filters } return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } void Dispatcher::stop() { d->running_.store(false); } bool Dispatcher::is_running() const { return d->running_.load(); } void Dispatcher::add_client(StubBase& clnt) { clnt.disp_ = this; d->stubs_.insert(std::make_pair(clnt.objectpath(), &clnt)); // send connected request from event loop auto iter = d->busnames_.find(clnt.busname()); if (iter != d->busnames_.end()) { std::ostringstream objpath; objpath << "/org/simppl/dispatcher/" << ::getpid() << '/' << this; DBusMessage* msg = dbus_message_new_signal(objpath.str().c_str(), "org.simppl.dispatcher", "notify_client"); DBusMessageIter iter; dbus_message_iter_init_append(msg, &iter); encode(iter, clnt.busname()); dbus_connection_send(conn_, msg, nullptr); dbus_message_unref(msg); } } void Dispatcher::remove_client(StubBase& clnt) { for(auto iter = d->stubs_.begin(); iter != d->stubs_.end(); ++iter) { if (&clnt == iter->second) { clnt.cleanup(); d->stubs_.erase(iter); break; } } } void Dispatcher::dispatch() { int rc; do { rc = dbus_connection_dispatch(conn_); } while(rc != DBUS_DISPATCH_COMPLETE); } int Dispatcher::step_ms(int timeout_ms) { #ifdef SIMPPL_USE_POLL d->poll(timeout_ms); dispatch(); #else dbus_connection_read_write_dispatch(conn_, 100); #endif return 0; } void Dispatcher::init() { #ifdef SIMPPL_USE_POLL d->init(conn_); #endif } int Dispatcher::run() { init(); d->running_.store(true); while(d->running_.load()) { step_ms(100); } return 0; } } // namespace dbus } // namespace simppl
24.547649
170
0.587246
chardin-cpi
b9342a02d69d4e628dfcc9a588afe0b806aa350f
1,747
cpp
C++
Classes/Fish.cpp
8410/FishingJoy
65978f6d492046de7229273f584037e2000e3c40
[ "MIT" ]
null
null
null
Classes/Fish.cpp
8410/FishingJoy
65978f6d492046de7229273f584037e2000e3c40
[ "MIT" ]
null
null
null
Classes/Fish.cpp
8410/FishingJoy
65978f6d492046de7229273f584037e2000e3c40
[ "MIT" ]
null
null
null
#include "Fish.h" Fish::Fish(void) { } Fish::~Fish(void) { } Fish* Fish::create(FishType type/* = k_Fish_Type_SmallFish */) { Fish* fish = new Fish; if (fish && fish->init(type)) { fish->autorelease(); return fish; } else { CC_SAFE_DELETE(fish); return NULL; } } bool Fish::init(FishType type /* = k_Fish_Type_SmallFish */) { do { if (!CCNode::init()) { return false; } if (type < k_Fish_Type_SmallFish || type >= k_Fish_Type_Count) { type = k_Fish_Type_SmallFish; } setType(type); //_type = type CCString* animationName = CCString::createWithFormat("fish_animation_%02d", _type + 1); CCAnimation* animation = CCAnimationCache::sharedAnimationCache()->animationByName(animationName->getCString()); CC_BREAK_IF(!animation); CCAnimate* animate = CCAnimate::create(animation); _fishSprite = CCSprite::create(); addChild(_fishSprite); _fishSprite->runAction(CCRepeatForever::create(animate)); return true; } while (0); return false; } int Fish::getScore(void) { return 0; } int Fish::getSpeed(void) { return 200; } CCRect Fish::getCollisionArea() { CCSize size = _fishSprite->getContentSize(); CCPoint pos = getParent()->convertToWorldSpace(getPosition()); return CCRect(pos.x - size.width / 2, pos.y - size.height/2, size.width, size.height); } void Fish::beCaught(){ CCCallFunc* callFunc = CCCallFunc::create(this,callfunc_selector(Fish::beCaught_CallFunc)); CCSequence* sequence = CCSequence::create(CCDelayTime::create(1.0f),callFunc,NULL); CCBlink* blink = CCBlink::create(1.0f, 8); CCSpawn* spawn = CCSpawn::create(sequence, blink, NULL); _fishSprite->runAction(spawn); } void Fish::beCaught_CallFunc() { if(isRunning()) { getParent()->removeChild(this,true); } }
21.048193
114
0.69834
8410
b93676a0e2bf8247004ae4b0185a980ce00299d8
2,077
hpp
C++
src/lib/meecan_lib.hpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/lib/meecan_lib.hpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/lib/meecan_lib.hpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
// // Created by alexweiss on 8/9/19. // #ifndef INC_7405M_CODE_SRC_LIB_MEECAN_LIB_HPP_ #define INC_7405M_CODE_SRC_LIB_MEECAN_LIB_HPP_ #include "geometry/Displacement1d.hpp" #include "geometry/Pose2d.hpp" #include "geometry/Pose2dWithCurvature.hpp" #include "geometry/Rotation2d.hpp" #include "geometry/Translation2d.hpp" #include "geometry/Twist2d.hpp" #include "physics/DCMotorTransmission.hpp" #include "physics/DifferentialDrive.hpp" #include "physics/DriveCharacterization.hpp" #include "spline/CubicHermiteSpline.hpp" #include "spline/QuinticHermiteSpline.hpp" #include "spline/Spline.hpp" #include "spline/SplineGenerator.hpp" #include "trajectory/timing/CentripetalAccelerationConstraint.hpp" #include "trajectory/timing/DifferentialDriveDynamicsConstraint.hpp" #include "trajectory/timing/TimedState.hpp" #include "trajectory/timing/TimingConstraint.hpp" #include "trajectory/timing/TimingUtil.hpp" #include "trajectory/timing/VelocityLimitRegionConstraint.hpp" #include "trajectory/DistanceView.hpp" #include "trajectory/IndexView.hpp" #include "trajectory/IPathFollower.hpp" #include "trajectory/PurePursuitController.hpp" #include "trajectory/TimedView.hpp" #include "trajectory/Trajectory.hpp" #include "trajectory/TrajectoryIterator.hpp" #include "trajectory/TrajectoryPoint.hpp" #include "trajectory/TrajectorySamplePoint.hpp" #include "trajectory/TrajectoryUtil.hpp" #include "trajectory/TrajectoryPoint.hpp" #include "utility/interfaces/CSVLoggable.hpp" #include "utility/interfaces/Interpolable.hpp" #include "utility/interfaces/InverseInterpolable.hpp" #include "utility/CircularBuffer.hpp" #include "utility/DelayedBoolean.hpp" #include "utility/DriveSignal.hpp" #include "utility/InterpolatingDouble.hpp" #include "utility/InterpolatingLong.hpp" #include "utility/InterpolatingMap.hpp" #include "utility/LatchedBoolean.hpp" #include "utility/MovingAverage.hpp" #include "utility/PolynomialRegression.hpp" #include "utility/Singleton.hpp" #include "utility/Units.hpp" #include "utility/Utility.hpp" #endif //INC_7405M_CODE_SRC_LIB_MEECAN_LIB_HPP_
33.5
68
0.82571
roboFiddle
b94a8cde72f561515c1b1a4cb75731de73badb90
41,424
cpp
C++
src/hsp3dish/win32/hgdx.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
127
2018-02-24T20:41:15.000Z
2022-03-22T05:57:56.000Z
src/hsp3dish/win32/hgdx.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2018-09-11T15:04:22.000Z
2022-02-03T09:30:16.000Z
src/hsp3dish/win32/hgdx.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2019-03-28T07:49:44.000Z
2021-12-25T02:49:07.000Z
// // High performance Graphic Image access (draw main) // onion software/onitama 2011/11 // #include <stdio.h> #include <stdlib.h> #include <math.h> #include "hgdx.h" //#include "hgtex.h" //#include "omkedraw.h" #if defined(HSPWIN) || defined(HSPLINUX) || defined(HSPEMSCRIPTEN) #include "../hsp3/hsp3config.h" #else #include "hsp3config.h" #endif #include "sysreq.h" #include "supio.h" #define AlertMsgf Alertf /*------------------------------------------------------------*/ /* initalizer */ /*------------------------------------------------------------*/ int hgdx::Reset( void ) { // Graphics I/O初期化 // int i; Terminate(); hgmode = 1; // Startup phase2 // GeometryInit(); // 各種パラメーター初期化 // hgmode = 2; bgclr = 1; bgcolor = 0; fntmode = -1; fntalpha = 0; mozcolors = NULL; landaxis = 0.0f; landlimit = -15.0f; tmes_mode = 0; tmes_spacing = 0; tmes_lspacing = 0; allmove = 1; maxobj = GetSysReq( SYSREQ_MAXOBJ ); mem_obj = (hgobj **)malloc( maxobj * sizeof(void *) ); mem_sortobj = (hgobj **)malloc( maxobj * sizeof(void *) ); for(i=0;i<maxobj;i++) { mem_obj[i]=NULL; } maxmodel = GetSysReq( SYSREQ_MAXMODEL ); mem_model = (hgmodel **)malloc( maxmodel * sizeof(void *) ); for(i=0;i<maxmodel;i++) { mem_model[i]=NULL; } maxevent = GetSysReq( SYSREQ_MAXEVENT ); mem_event = (hgevent **)malloc( maxevent * sizeof(void *) ); for(i=0;i<maxevent;i++) { mem_event[i]=NULL; } maxemitter = GetSysReq( SYSREQ_MAXEMITTER ); mem_emitter = (hgemitter **)malloc( maxemitter * sizeof(void *) ); for(i=0;i<maxemitter;i++) { mem_emitter[i]=NULL; } camera = AddObj(); camera->SetPos( 0.0f, 0.0f, 50.0f ); camera->SetDir( 0.0f, 0.0f, 0.0f ); camera->SetEfx( 0.25f*3.141592654f, 0.5f, 768.0f ); // fov,near,far SetCamMode( CAMMODE_NORMAL ); //SetCamMode( CAMMODE_LOOKAT ); light = AddObj(); light->SetRot( -1.0f, 1.0f, 0.0f ); light->SetScale( 255.0f, 255.0f, 255.0f ); light->SetDir( 30.0f, 30.0f, 30.0f ); //light->SetDir( 30.0f, 30.0f, 30.0f ); //light->SetRot( -3.2f, 2.7f, 0.0f ); //light->SetRot( 1.0f, -0.5f, 0.5f ); SetVector( &border1, -50.0f, 0.0f, -50.0f, 0.0f ); SetVector( &border2, 50.0f, -100.0f, 50.0f, 0.0f ); SetTargetID( 0 ); SetBoundFactor( 1.0f ); SetGainFactor( 0.95f, 0.95f ); // SetViewPort( 0,0, 0,0 ); return 0; } hgdx::hgdx( void ) { hgmode = 0; light = NULL; camera = NULL; mem_obj = NULL; mem_sortobj = NULL; mem_model = NULL; mem_event = NULL; mem_emitter = NULL; } hgdx::~hgdx( void ) { Terminate(); } void hgdx::Terminate( void ) { int i; if ( hgmode == 0 ) return; if ( hgmode > 1 ) { // システムの破棄 // if ( mem_obj != NULL ) { for(i=0;i<maxobj;i++) { DeleteObj( i ); } free( mem_obj ); mem_obj = NULL; } if ( mem_sortobj != NULL ) { free( mem_sortobj ); mem_sortobj = NULL; } if ( mem_model != NULL ) { for(i=0;i<maxmodel;i++) { DeleteModel( i ); } free( mem_model ); mem_model = NULL; } if ( mem_event != NULL ) { for(i=0;i<maxevent;i++) { DeleteEvent( i ); } free( mem_event ); mem_event = NULL; } if ( mem_emitter != NULL ) { for(i=0;i<maxemitter;i++) { DeleteEmitter( i ); } free( mem_emitter ); mem_emitter = NULL; } GeometryTerm(); } hgmode = 1; } void hgdx::SetDest( void *dest, int x, int y, int sx, int sy, int centerx, int centery ) { center_x = centerx; if ( center_x < 0 ) center_x = (float)(( sx / 2 ) + x); center_y = centery; if ( center_y < 0 ) center_y = (float)(( sy / 2 ) + y); nDestWidth = sx; nDestHeight = sy; hgio_setcenter( center_x, center_y ); //io.setDest( dest, x, y, sx, sy ); } void hgdx::DeleteObjSub( int id ) { hgobj *obj; hgobj *obj2; obj = mem_obj[id]; if ( obj != NULL ) { if ( obj->child != NULL ) { obj2 = (hgobj *)obj->child; DeleteObjSub( obj2->id ); } if ( obj->sibling != NULL ) { obj2 = (hgobj *)obj->sibling; DeleteObjSub( obj2->id ); } delete obj; mem_obj[id] = NULL; } } void hgdx::DeleteObj( int id ) { hgobj *obj; obj = mem_obj[id]; if ( obj != NULL ) { if ( obj->parent != NULL ) { // 親がある場合は、親から切り離す hgobj *tmpobj; tmpobj = (hgobj *)obj->parent; tmpobj->child = NULL; return; } DeleteObjSub( id ); } } void hgdx::DeleteModel( int id ) { hgmodel *model; model = GetModel( id ); if ( model != NULL ) { delete model; mem_model[id] = NULL; } } int hgdx::AddSpriteModel( int tex, int attr, int tx0, int ty0, int tx1, int ty1 ) { hgmodel *model; model = AddModel(); model->RegistData( HGMODEL_FLAG_2DSPRITE ); model->SetAttribute( attr ); model->SetTexture( tex ); // model->SetOffset( center_x, center_y ); model->SetUV( tx0, ty0, tx1, ty1 ); return model->id; } int hgdx::AttachObjWithModel( int objid, int modelid ) { hgobj *obj; hgmodel *model; float *fval; model = GetModel( modelid ); if ( model == NULL ) return -1; if ( objid < 0 ) { obj = AddObj(); } else { obj = GetObj(objid); } if ( obj == NULL ) return -1; obj->model = model; obj->SetAttribute( obj->model->GetAttribute() ); obj->SetTexture( obj->model->GetTexture() ); obj->SetSpeed( model->GetDefaultSpeed() ); fval = model->GetDefaultColScale(); obj->SetColScale( fval[0], fval[1], fval[2] ); fval = model->GetDefaultColParam(); obj->SetColParam( fval[0], fval[1], fval[2] ); return obj->id; } int hgdx::GetObjModelId( int objid ) { int i; hgobj *obj; hgmodel *model; obj = GetObj(objid); if ( obj == NULL ) return -1; model = obj->model; if ( model == NULL ) return -1; for(i=0;i<maxmodel;i++) { if ( model == GetModel(i) ) return i; } return -1; } int hgdx::AddObjWithModel( int modelid ) { return AttachObjWithModel( -1, modelid ); } hgobj *hgdx::AddObj( void ) { int i,sel; hgobj *obj; sel = -1; for(i=0;i<maxobj;i++) { if ( mem_obj[i] == NULL ) { sel=i; break; } } if ( sel >= 0 ) { obj = new hgobj; obj->id = sel; // obj->SetProjMatrix( (MATRIX *)&mProjection ); // obj->SetViewMatrix( (MATRIX *)&mView ); // obj->SetLight( light->GetRot() ); // obj->SetLightColor( light->GetScale() ); // obj->SetLightAmbient( light->GetDir() ); mem_obj[sel] = obj; return obj; } return NULL; } hgmodel *hgdx::AddModel( void ) { int i,sel; hgmodel *model; sel = -1; for(i=0;i<maxmodel;i++) { if ( mem_model[i] == NULL ) { sel=i; break; } } if ( sel >= 0 ) { model = new hgmodel; model->id = sel; // model->SetHGProc( &io ); mem_model[sel] = model; return model; } return NULL; } VECTOR *hgdx::GetObjVectorPrm( int id, int prmid ) { hgobj *obj; if (( id < 0 )||( id >= maxobj )) return NULL; obj = GetObj( id ); if ( obj == NULL ) return NULL; return obj->GetVectorPrm(prmid); } hgmodel *hgdx::GetModel( int id ) { if (( id < 0 )||( id >= maxmodel )) { AlertMsgf( "Invalid ModelID#%d",id ); return NULL; } return mem_model[id]; } hgobj *hgdx::GetObj( int id ) { if (( id < 0 )||( id >= maxobj )) { AlertMsgf( "Invalid ObjID#%d",id ); return NULL; } return mem_obj[id]; } /*------------------------------------------------------------*/ /* event process */ /*------------------------------------------------------------*/ int hgdx::AttachEvent( int objid, int eventid, int entry ) { hgevent *ev; hgobj *obj; int i; obj = GetObj( objid ); if ( obj == NULL ) return -1; if ( eventid < 0 ) { obj->DeleteEvent( entry ); return entry; } ev = GetEvent( eventid ); if ( ev == NULL ) return -1; i = entry; if ( i < 0 ) { i = obj->GetEmptyEvent(); if ( i < 0 ) return -1; } obj->StartEvent( ev, i ); return i; } int hgdx::GetEmptyEventId( void ) { int sel,i; sel = -1; for(i=0;i<maxevent;i++) { if ( mem_event[i] == NULL ) { sel = i; break; } } return sel; } hgevent *hgdx::AddEvent( int eventid ) { int sel; hgevent *ev; hgevent *tmp; hgevent *ev_next; sel = eventid; if ( sel < 0 ) { sel = GetEmptyEventId(); if ( sel < 0 ) return NULL; } ev = new hgevent; ev->id = sel; if ( mem_event[ sel ] == NULL ) { // 新規イベントの追加 mem_event[ sel ] = ev; } else { tmp = mem_event[ sel ]; while(1) { // 既存のイペントに追加する ev_next = tmp->GetNextEvent(); if ( ev_next == NULL ) { tmp->SetNextEvent( ev ); break; } tmp = ev_next; } } return ev; } void hgdx::DeleteEvent( int eventid ) { hgevent *ev; hgevent *nextev; ev = mem_event[ eventid ]; while(1) { if ( ev == NULL ) break; nextev = ev->GetNextEvent(); delete ev; ev = nextev; } mem_event[ eventid ] = NULL; } float hgdx::GetTimerFromFrame( int frame ) { return 1.0f / ((float)frame); } int hgdx::AddWaitEvent( int eventid, int frame ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_WAIT; if ( frame >= 0 ) { ev->timer = GetTimerFromFrame( frame ); } else { ev->source = HGEVENT_SOURCE_WORK; } return ev->id; } int hgdx::AddJumpEvent( int eventid, int gonum, int rate ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_JUMP; ev->target = gonum; ev->value = rate; return ev->id; } int hgdx::AddParamEvent( int eventid, int mode, int target, int param ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_PRMSET + mode; ev->target = target & HGEVENT_MOCOPT_TARGET_BIT; ev->value = param; return ev->id; } int hgdx::AddMoveEvent( int eventid, int target, float x, float y, float z, int frame, int sw ) { hgevent *ev; ev = AddEvent( eventid ); if ( sw == 0 ) { ev->flag = HGEVENT_FLAG_MOVETARGET; } else { ev->flag = HGEVENT_FLAG_MOVETARGET3; } ev->target = target & HGEVENT_MOCOPT_TARGET_BIT; if ( target & HGEVENT_MOCOPT_SRCWORK ) ev->source = HGEVENT_SOURCE_WORK; ev->SetEventVector( x, y, z ); ev->timer = GetTimerFromFrame( frame ); return ev->id; } int hgdx::AddSplineMoveEvent( int eventid, int target, float x, float y, float z, int frame, int sw ) { hgevent *ev; ev = AddEvent( eventid ); if ( sw == 0 ) { ev->flag = HGEVENT_FLAG_MOVETARGET2; } else { ev->flag = HGEVENT_FLAG_MOVETARGET4; } ev->target = target & HGEVENT_MOCOPT_TARGET_BIT; if ( target & HGEVENT_MOCOPT_SRCWORK ) { ev->source = HGEVENT_SOURCE_WORK; } ev->SetEventVector( x, y, z ); ev->timer = GetTimerFromFrame( frame ); return ev->id; } int hgdx::AddPlusEvent( int eventid, int target, float x, float y, float z ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_PLUSTARGET; ev->target = target & HGEVENT_MOCOPT_TARGET_BIT; if ( target & HGEVENT_MOCOPT_SRCWORK ) ev->source = HGEVENT_SOURCE_WORK; ev->SetEventVector( x, y, z ); return ev->id; } int hgdx::AddChangeEvent( int eventid, int target, float x1, float y1, float z1, float x2, float y2, float z2 ) { float f; hgevent *ev; f = 1.0f / 1024.0f; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_SETTARGET; ev->target = target & HGEVENT_MOCOPT_TARGET_BIT; ev->SetEventVector( x1, y1, z1 ); ev->SetEventVector2( (x2-x1)*f, (y2-y1)*f, (z2-z1)*f ); return ev->id; } int hgdx::AddUVEvent( int eventid, int ysize, int count ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_UVANIM; ev->target = ysize; ev->value = count; return ev->id; } int hgdx::AddRegobjEvent( int eventid, int model, int event ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_REGOBJ; ev->target = model; ev->value = event; return ev->id; } int hgdx::AddEPrimEvent( int eventid, int model, int prm, float x1, float y1 ) { float f; hgevent *ev; f = 1.0f / 1024.0f; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_SETEPRIM; ev->target = model; ev->value = prm; ev->SetEventVector( x1, (y1-x1)*f, 0.0f ); return ev->id; } int hgdx::AddAimEvent( int eventid, int target, int mode, float x, float y, float z ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_AIM; ev->target = target; ev->value = mode; ev->SetEventVector( x, y, z ); return ev->id; } int hgdx::AddAnimEvent( int eventid, int anim, int opt, float speed ) { hgevent *ev; ev = AddEvent( eventid ); ev->flag = HGEVENT_FLAG_OBJACT; ev->target = anim; ev->value = opt; ev->SetEventVector( speed, 0.0f, 0.0f ); return ev->id; } void hgdx::StoreNextVector( hgevent *myevent ) { // 次のmovevectorを検索して補完する // int flag,fl; int target; hgevent *lastjp; hgevent *ev; hgevent *nextev; target = myevent->target; lastjp = NULL; ev = myevent->GetNextEvent(); while(1) { if ( ev == NULL ) break; if ( ev == myevent ) break; flag = ev->flag; if (( flag == HGEVENT_FLAG_MOVETARGET2 )||( flag == HGEVENT_FLAG_MOVETARGET4 )) { // スプライン移動か? if ( ev->target == target ) { // 自分と同じターゲットか? myevent->nextvec = ev->GetEventVector(); return; } } if ( flag == HGEVENT_FLAG_JUMP ) { nextev = mem_event[ ev->id ]; for(fl=0;fl<ev->target;fl++) { nextev = nextev->GetNextEvent(); } ev = nextev; if ( lastjp == ev ) break; lastjp = ev; } else { ev = ev->GetNextEvent(); } } myevent->nextvec = myevent->GetEventVector(); // 次のデータがない場合は自分のvectorを入れる } void hgdx::ExecuteObjEvent( hgobj *obj, float timepass, int entry ) { // イベント実行 // hgevent *ev; hgevent *nextev; VECTOR *v0; VECTOR *v1; VECTOR *v2; VECTOR *v3; VECTOR *v4; VECTOR *pdir; VECTOR tmp; VECTOR tmp2; float tbase; float tval; short *p; int fl; ev = obj->GetEvent(entry); tbase = obj->time[entry]; obj->time[entry] += timepass; while( ev != NULL ) { switch( ev->flag ) { case HGEVENT_FLAG_WAIT: if ( ev->source != HGEVENT_SOURCE_VEC ) { v1 = obj->GetVectorPrm( ev->source ); if ( v1->x == 0.0f ) tval = 1.0f; else tval = tbase / v1->x; } else { tval = tbase * ev->timer; } if ( tval >= 1.0f ) { obj->SetEvent( ev->GetNextEvent(), entry ); // 次のイベントへ進む return; } return; case HGEVENT_FLAG_JUMP: if ( ev->value ) { fl = rand()%100; if ( fl >= ev->value ) { obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; } } nextev = mem_event[ ev->id ]; for(fl=0;fl<ev->target;fl++) { nextev = nextev->GetNextEvent(); } obj->SetEvent( nextev, entry ); return; case HGEVENT_FLAG_PRMSET: if ( ev->target == 0 ) { obj->mode = ev->value; break; } p = (short *)&obj->flag; p[ ev->target - 1 ] = (short)ev->value; obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; case HGEVENT_FLAG_PRMON: if ( ev->target == 0 ) { obj->mode |= ev->value; break; } p = (short *)&obj->flag; p[ ev->target - 1 ] |= (short)ev->value; obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; case HGEVENT_FLAG_PRMOFF: fl = ~ev->value; if ( ev->target == 0 ) { obj->mode &= fl; break; } p = (short *)&obj->flag; p[ ev->target - 1 ] &= (short)fl; obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; case HGEVENT_FLAG_UVANIM: { HGMODEL_DRAWPRM *prm; prm = obj->GetPrm(); prm->ua_flag = 1; prm->ua_ofsx = ev->target; prm->ua_ofsy = ev->value; obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; } case HGEVENT_FLAG_MOVETARGET: // targetにlinear補間 v0 = obj->GetVectorPrm( ev->target ); v1 = obj->GetVectorPrm( MOC_POS2 + ev->target ); if ( ev->source == HGEVENT_SOURCE_VEC ) v2 = ev->GetEventVector(); else { v2 = obj->GetVectorPrm( ev->source ); } if ( tbase == 0.0f ) { CopyVector( v1, v0 ); } tval = tbase * ev->timer; if ( tval > 1.0f ) tval = 1.0f; SubVector( &tmp, v2, v1 ); ScaleVector( &tmp, &tmp, tval ); AddVector( v0, v1, &tmp ); break; case HGEVENT_FLAG_MOVETARGET2: { // targetにspline補間 VECTOR key0; VECTOR key1; VECTOR key2; VECTOR key3; VECTOR fa; VECTOR fb; VECTOR *nextv; float t1,t2,t3; if ( ev->nextvec == NULL ) StoreNextVector( ev ); v0 = obj->GetVectorPrm( ev->target ); v1 = obj->GetVectorPrm( MOC_POS2 + ev->target ); nextv = ev->nextvec; if ( ev->source == HGEVENT_SOURCE_VEC ) v2 = ev->GetEventVector(); else { v2 = obj->GetVectorPrm( ev->source ); nextv = v2; } if ( tbase == 0.0f ) { CopyVector( v1, v0 ); } tval = tbase * ev->timer; if ( tval > 1.0f ) tval = 1.0f; t1 = tval; t2 = t1 * t1; t3 = t2 * t1; // r0 = kframe[i]; // r1 = kframe[i+1]; // r2 = kframe[i+1]-kframe[i]; // r3 = kframe[i+2]-kframe[i+1]; CopyVector( &key0 , v1 ); CopyVector( &key1 , v2 ); SubVector( &key2 , &key1, &key0 ); SubVector( &key3 , nextv, &key1 ); // fa = 2.0f * r0 - 2.0f * r1 + r2 + r3; ScaleVector( &fa , &key0, 2.0f ); ScaleVector( &tmp , &key1, 2.0f ); SubVector( &fa , &fa, &tmp ); AddVector( &fa , &fa, &key2 ); AddVector( &fa , &fa, &key3 ); // fb = -3.0f * r0 + 3.0f * r1 - 2.0f * r2 - r3; ScaleVector( &fb , &key0, -3.0f ); ScaleVector( &tmp , &key1, 3.0f ); AddVector( &fb , &fb, &tmp ); ScaleVector( &tmp , &key2, 2.0f ); SubVector( &fb , &fb, &tmp ); SubVector( &fb , &fb, &key3 ); // fc = r2; // fd = r0; // res = fa * t3 + fb * t2 + fc * t + fd; ScaleVector( &fa, &fa, t3 ); ScaleVector( &fb, &fb, t2 ); ScaleVector( &key2, &key2, t1 ); AddVector( &tmp, &fa, &fb ); AddVector( &tmp, &tmp, &key2 ); AddVector( v0, &tmp, &key0 ); break; } case HGEVENT_FLAG_MOVETARGET3: // targetにlinear補間(相対) v0 = obj->GetVectorPrm( ev->target ); v1 = obj->GetVectorPrm( MOC_POS2 + ev->target ); if ( ev->source == HGEVENT_SOURCE_VEC ) v2 = ev->GetEventVector(); else { v2 = obj->GetVectorPrm( ev->source ); } if ( tbase == 0.0f ) { CopyVector( v1, v0 ); } tval = tbase * ev->timer; if ( tval > 1.0f ) tval = 1.0f; ScaleVector( &tmp, v2, tval ); AddVector( v0, v1, &tmp ); break; case HGEVENT_FLAG_MOVETARGET4: { // targetにspline補間(相対) VECTOR key0; VECTOR key1; VECTOR key2; VECTOR key3; VECTOR fa; VECTOR fb; VECTOR *nextv; float t1,t2,t3; if ( ev->nextvec == NULL ) StoreNextVector( ev ); v0 = obj->GetVectorPrm( ev->target ); v1 = obj->GetVectorPrm( MOC_POS2 + ev->target ); nextv = ev->nextvec; if ( ev->source == HGEVENT_SOURCE_VEC ) v2 = ev->GetEventVector(); else { v2 = obj->GetVectorPrm( ev->source ); nextv = v2; } if ( tbase == 0.0f ) { CopyVector( v1, v0 ); } tval = tbase * ev->timer; if ( tval > 1.0f ) tval = 1.0f; t1 = tval; t2 = t1 * t1; t3 = t2 * t1; // r0 = kframe[i]; // r1 = kframe[i+1]; // r2 = kframe[i+1]-kframe[i]; // r3 = kframe[i+2]-kframe[i+1]; CopyVector( &key0 , v1 ); CopyVector( &key1 , v1 ); AddVector( &key1, &key1, v2 ); CopyVector( &key2 , v2 ); CopyVector( &key3 , nextv ); // fa = 2.0f * r0 - 2.0f * r1 + r2 + r3; ScaleVector( &fa , &key0, 2.0f ); ScaleVector( &tmp , &key1, 2.0f ); SubVector( &fa , &fa, &tmp ); AddVector( &fa , &fa, &key2 ); AddVector( &fa , &fa, &key3 ); // fb = -3.0f * r0 + 3.0f * r1 - 2.0f * r2 - r3; ScaleVector( &fb , &key0, -3.0f ); ScaleVector( &tmp , &key1, 3.0f ); AddVector( &fb , &fb, &tmp ); ScaleVector( &tmp , &key2, 2.0f ); SubVector( &fb , &fb, &tmp ); SubVector( &fb , &fb, &key3 ); // fc = r2; // fd = r0; // res = fa * t3 + fb * t2 + fc * t + fd; ScaleVector( &fa, &fa, t3 ); ScaleVector( &fb, &fb, t2 ); ScaleVector( &key2, &key2, t1 ); AddVector( &tmp, &fa, &fb ); AddVector( &tmp, &tmp, &key2 ); AddVector( v0, &tmp, &key0 ); break; } case HGEVENT_FLAG_PLUSTARGET: // target+=dir:dir+=vec を実行する v0 = obj->GetVectorPrm( ev->target ); if ( ev->source == HGEVENT_SOURCE_VEC ) { v1 = ev->GetEventVector(); } else { v1 = obj->GetVectorPrm( ev->source ); } AddVector( v0, v0, v1 ); break; case HGEVENT_FLAG_SETTARGET: { // targetを再設定する float t1,t2,t3; v0 = obj->GetVectorPrm( ev->target ); v1 = ev->GetEventVector(); v2 = ev->GetEventVector2(); if ( v2->x == 0.0f ) { v0->x = v1->x; } else { t1 = (float)( rand() & 1023 ); v0->x = v2->x * t1 + v1->x; } if ( v2->y == 0.0f ) { v0->y = v1->y; } else { t2 = (float)( rand() & 1023 ); v0->y = v2->y * t2 + v1->y; } if ( v2->z == 0.0f ) { v0->z = v1->z; } else { t3 = (float)( rand() & 1023 ); v0->z = v2->z * t3 + v1->z; } obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; } case HGEVENT_FLAG_SUICIDE: // イベント自体を消滅させる obj->SetEvent( NULL, entry ); fl = ev->id; DeleteEvent( fl ); return; case HGEVENT_FLAG_REGOBJ: { // 新しいOBJを設定 int objid; VECTOR tmp; objid = AddObjWithModel( ev->target ); AttachEvent( objid, ev->value, -1 ); v0 = obj->GetVectorPrm( 0 ); v1 = ev->GetEventVector(); AddVector( &tmp, obj->GetPos(), obj->GetWork() ); GetObj(objid)->SetPos( tmp.x, tmp.y, tmp.z ); // obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; } #if 0 case HGEVENT_FLAG_SETEPRIM: { // eprimを設定 hgmodel *model; float t1,val; if ( ev->target < 0 ) { model = obj->model; } else { model = GetModel( ev->target ); } if ( model != NULL ) { v1 = ev->GetEventVector(); if ( v1->y == 0.0f ) { val = v1->x; } else { t1 = (float)( rand() & 1023 ); val = t1 * v1->y + v1->x; } if ( ev->value >= 16 ) { model->SetEfxColorFloat( ev->value - 16, val ); } else { model->SetEfxInfo( ev->value, val ); } } //obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; } #endif case HGEVENT_FLAG_AIM: { // 向きを設定 int i,j,val,evpass; hgobj *obj2; evpass = 1; v0 = obj->GetVectorPrm( ev->target ); v1 = ev->GetEventVector(); val = ev->value; if ( val & 0xf0000 ) { obj2 = GetObj( val & 0xffff ); if (( obj2->flag & HGOBJ_FLAG_ENTRY ) == 0 ) break; v2 = obj2->GetVectorPrm( ev->target ); val = (val>>16) - 1; } else { v2 = obj->GetWork(); } switch( val ) { case 0: SubVector( &tmp, v2, v0 ); if ( tmp.x > v1->x ) tmp.x = v1->x; if ( tmp.y > v1->y ) tmp.y = v1->y; if ( tmp.z > v1->z ) tmp.z = v1->z; if ( tmp.x < -v1->x ) tmp.x = -v1->x; if ( tmp.y < -v1->y ) tmp.y = -v1->y; if ( tmp.z < -v1->z ) tmp.z = -v1->z; AddVector( v0, v0, &tmp ); GetTargetAngle( &tmp, v0, v2 ); obj->SetRot( -tmp.x, -tmp.y, -tmp.z ); evpass = 0; break; case 1: SubVector( &tmp, v2, v0 ); if ( tmp.x > v1->x ) tmp.x = v1->x; if ( tmp.y > v1->y ) tmp.y = v1->y; if ( tmp.z > v1->z ) tmp.z = v1->z; if ( tmp.x < -v1->x ) tmp.x = -v1->x; if ( tmp.y < -v1->y ) tmp.y = -v1->y; if ( tmp.z < -v1->z ) tmp.z = -v1->z; obj->SetDir( tmp.x, tmp.y, tmp.z ); break; case 2: GetTargetAngle( &tmp, v0, v2 ); //obj->SetRot( 0.0f, -tmp.y, 0.0f ); InitMatrix(); RotY( tmp.y + obj->GetWork()->x ); ApplyMatrix( &tmp, v1 ); obj->SetDir( -tmp.x, obj->GetWork()->y, -tmp.z ); break; case 3: if ( obj->evtimer >= 5 ) break; case 4: GetTargetAngle( &tmp, v0, v2 ); obj->SetRot( -tmp.x, -tmp.y, -tmp.z ); InitMatrix(); RotY( tmp.y ); RotX( -tmp.x ); ApplyMatrix( &tmp, v1 ); obj->SetDir( -tmp.x, -tmp.y, -tmp.z ); obj->evtimer++; break; case 5: if ( obj->evtimer >= 20 ) break; case 6: GetTargetAngle( &tmp, v0, v2 ); if ( obj->evtimer > 0 ) { //DebugMsg( "#%f => %f",tmp.y, obj->GetRot()->y ); v3 = obj->GetWork(); v4 = obj->GetRot(); tmp2.x = tmp.x - v4->x; if ( abs( tmp.x - (v4->x+PI2)) < abs(tmp2.x) ) tmp2.x = tmp.x - (v4->x+PI2); tmp2.y = tmp.y - v4->y; if ( abs( tmp.y - (v4->y+PI2)) < abs(tmp2.y) ) tmp2.y = tmp.y - (v4->y+PI2); tmp2.z = tmp.z - v4->z; if ( abs( tmp.z - (v4->z+PI2)) < abs(tmp2.z) ) tmp2.z = tmp.z - (v4->z+PI2); if ( tmp2.y > v3->y ) tmp2.y = v3->y; if ( tmp2.y < -v3->y ) tmp2.y = -v3->y; if ( tmp2.x > v3->x ) tmp2.x = v3->x; if ( tmp2.x < -v3->x ) tmp2.x = -v3->x; if ( tmp2.z > v3->z ) tmp2.z = v3->z; if ( tmp2.z < -v3->z ) tmp2.z = -v3->z; AddVector( v4, v4, &tmp2 ); } obj->SetRot( tmp.x, tmp.y, tmp.z ); InitMatrix(); RotY( tmp.y ); RotX( -tmp.x ); ApplyMatrix( &tmp, v1 ); pdir = obj->GetDir(); pdir->x = -tmp.x; pdir->z = -tmp.z; //obj->SetDir( -tmp.x, -tmp.y, -tmp.z ); obj->evtimer++; break; case 7: // special missile if ( obj->evtimer >= 20 ) break; // StartObjFind( 0, (int)(v2->y) ); obj2 = NULL; for(i=0;i<(int)(v2->x);i++) { j = FindObj(); if ( j >= 0 ) obj2 = GetObj( j ); } if ( obj2 == NULL ) { obj->evtimer = 999; break; } //obj2 = GetObj( (int)(v2->x) ); if (( obj2->flag & HGOBJ_FLAG_ENTRY ) == 0 ) { obj->evtimer = 999; break; } v2 = obj2->GetVectorPrm( ev->target ); // GetTargetAngle( &tmp, v0, v2 ); obj->SetRot( tmp.x, tmp.y, tmp.z ); InitMatrix(); RotY( tmp.y ); RotX( -tmp.x ); ApplyMatrix( &tmp, v1 ); obj->SetDir( -tmp.x, -tmp.y, -tmp.z ); obj->evtimer++; break; default: break; } if ( evpass ) { obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする } break; } #if 0 case HGEVENT_FLAG_OBJACT: v1 = ev->GetEventVector(); StartAnimation( obj->id, ev->target, ev->value ); if ( v1->x != 0.0f ) { SetObjSpeed( obj->id, v1->x ); } obj->SetEvent( ev->GetNextEvent(), entry ); // イベントをパスする break; #endif default: AlertMsgf( "Invalid event:%d",ev->flag ); obj->SetEvent( NULL, entry ); return; } ev = ev->GetNextEvent(); } obj->SetEvent( NULL, entry ); } /*------------------------------------------------------------*/ /* interface */ /*------------------------------------------------------------*/ void hgdx::MoveObj( hgobj *obj, float timepass ) { // オブジェクト動作 // int mode,i; // VECTOR dum; VECTOR *v0; VECTOR *v1; // VECTOR *tpos; // VECTOR *vnorm; // VECTOR v2; hgobj *refobj; // float dot; // float dist; // オブジェクトイベントの処理 // for(i=0;i<HGOBJ_MULTIEVENT_MAX;i++) { if ( obj->GetEvent(i) != NULL ) ExecuteObjEvent( obj, timepass, i ); } // モードごとの動作チェック // mode = obj->mode; { // 通常の場合 if ( mode & HGOBJ_MODE_MOVE ) { v0 = obj->GetVectorPrm( MOC_POS ); v1 = obj->GetVectorPrm( MOC_DIR ); AddVector( v0, v0, v1 ); } if ( mode & HGOBJ_MODE_LAND ) { refobj = (hgobj *)obj->parent; if ( refobj != NULL ) { v0 = obj->GetPos(); v1 = refobj->GetPos(); v0->x = v1->x; v0->y = landaxis; v0->z = v1->z; } } } if ( mode & HGOBJ_MODE_LOOKAT ) { v1 = obj->GetVectorPrm( MOC_DIR ); obj->LookAt( v1 ); } if ( mode & HGOBJ_MODE_XFRONT ) { v0 = obj->GetRot(); v1 = camera->GetRot(); v0->x = v1->x; v0->y = v1->y; } if ( mode & HGOBJ_MODE_TREE ) { v0 = obj->GetRot(); v1 = camera->GetRot(); v0->y = v1->y; } if ( mode & HGOBJ_MODE_EMITTER ) { hgemitter *emi; emi = GetEmitter( obj->emitid ); if ( emi != NULL ) { emi->Emit( this, obj->GetVectorPrm( MOC_POS ) ); } } if ( mode & HGOBJ_MODE_AUTOROT ) { v0 = obj->GetRot(); v0->x += ((float)(obj->GetPrm()->ua_ofsx)) * 0.002f; v0->y += ((float)(obj->GetPrm()->ua_ofsy)) * 0.002f; } // 自動範囲クリップ // if ( mode & HGOBJ_MODE_BORDER ) { VECTOR *pos; VECTOR *dir; int cflag,thru; pos = obj->GetVectorPrm( MOC_POS ); dir = obj->GetVectorPrm( MOC_DIR ); cflag = 0; thru = GetSysReq( SYSREQ_THROUGHFLAG ); if ( thru & 1 ) { if ( pos->x < border1.x ) { pos->x = border2.x - ( border1.x - pos->x ); } if ( pos->x > border2.x ) { pos->x = border1.x + ( pos->x - border2.x ); } } if ( thru & 2 ) { if ( pos->y < border1.y ) { pos->y = border2.y - ( border1.y - pos->y ); } if ( pos->y > border2.y ) { pos->y = border1.y + ( pos->y - border2.y ); } } if ( thru & 4 ) { if ( pos->z < border1.z ) { pos->z = border2.z - ( border1.z - pos->z ); } if ( pos->z > border2.z ) { pos->z = border1.z + ( pos->z - border2.z ); } } if ( mode & HGOBJ_MODE_FLIP ) { if ( pos->x < border1.x ) { pos->x = border1.x; dir->x *= -1.0f; } if ( pos->x > border2.x ) { pos->x = border2.x; dir->x *= -1.0f; } if ( pos->y < border1.y ) { pos->y = border1.y; dir->y *= -1.0f; } if ( pos->y > border2.y ) { pos->y = border2.y; dir->y *= -1.0f; } if ( pos->z < border1.z ) { pos->z = border1.z; dir->z *= -1.0f; } if ( pos->z > border2.z ) { pos->z = border2.z; dir->z *= -1.0f; } } else { if ( pos->x < border1.x ) { cflag++; } if ( pos->x > border2.x ) { cflag++; } if ( pos->y < border1.y ) { cflag++; } if ( pos->y > border2.y ) { cflag++; } if ( pos->z < border1.z ) { cflag++; } if ( pos->z > border2.z ) { cflag++; } if ( cflag ) { //if ( mode & OBJ_MODE_WIPEBOM ) { // a = RegistObj( 0, evmodel[EVENT_MODEL_BOM] ); // SetObjPos( a, &pos ); //} obj->flag = HGOBJ_FLAG_NONE; return; } } } // 最後にアニメーションフレームを更新する // obj->UpdateAnimation( 1.0f ); } void hgdx::DrawObj( hgobj *obj ) { // モデル表示 // hgmodel *model = obj->model; obj->UpdateMatrix(); obj->drawresult = model->Draw( obj->GetPrm() ); obj->drawflag = 0; } void hgdx::RegistSortObj( hgobj *obj ) { mem_sortobj[maxsortobj] = obj; maxsortobj++; obj->UpdateSortZ(); obj->sortdrawflag = obj->drawflag; obj->drawflag = 0; } /* static int compare_hgobj(hgobj *a, hgobj *b) { // if ( a->GetPos()->z > b->GetPos()->z ) return 1; if ( a->sortz > b->sortz ) return 1; return -1; } */ void hgdx::SortSwap(hgobj **a, hgobj **b) { hgobj *c = *a; *a = *b; *b = c; } void hgdx::SortObjAll( void ) { int i, j; if ( maxsortobj <= 0 ) return; for (i = 0; i < maxsortobj - 1; i++) { for (j = maxsortobj - 1; j >= i + 1; j--) { if ( mem_sortobj[j]->sortz > mem_sortobj[j-1]->sortz ) SortSwap(&mem_sortobj[j], &mem_sortobj[j-1]); } } //qsort(mem_sortobj, maxsortobj, sizeof(void *), (int (*)(const void*, const void*))compare_hgobj); } int hgdx::DrawObjAll( void ) { int i; int flag; int total; short df; float t; hgobj **obj; hgobj *pobj; hgmodel *model; // 表示処理 // total = 0; t = 1.0f; obj = mem_obj; maxsortobj = 0; for(i=0;i<maxobj;i++) { pobj = *obj; if ( pobj != NULL ) { flag = pobj->flag; if ( flag != HGOBJ_FLAG_NONE ) { pobj->matupdate = 0; // マトリクス計算フラグをリセット if (( flag & HGOBJ_FLAG_MOVING )&&( allmove )) MoveObj( pobj, t ); df = 0; if ( flag & HGOBJ_FLAG_VISIBLE) { model = pobj->model; if ( model != NULL ) { if ( pobj->mode & HGOBJ_MODE_HIDE ) df = 0; else { df = model->GetFlag(); } } } total += pobj->drawresult; pobj->drawflag = df; pobj->drawresult = 0; } else { // オブジェクトは削除される DeleteObj( pobj->id ); } } obj++; } // // 先に描画するもの(HGOBJ_MODE_FIRSTあり) // obj = mem_obj; for(i=0;i<maxobj;i++) { pobj = *obj; if ( pobj != NULL ) { if ( pobj->mode & HGOBJ_MODE_FIRST ) { if ( pobj->drawflag ) { DrawObj( pobj ); // 通常のオブジェクト } } } obj++; } // // 2番目に描画するもの(OBJ_LATEなし) // obj = mem_obj; for(i=0;i<maxobj;i++) { pobj = *obj; if ( pobj != NULL ) { if (( pobj->mode & HGOBJ_MODE_LATE ) == 0 ) { if ( pobj->drawflag ) { if ( pobj->mode & HGOBJ_MODE_SORT ) { RegistSortObj( pobj ); } else { DrawObj( pobj ); // 通常のオブジェクト } } } } obj++; } // // Zソートオブジェクトの処理 // #if 0 SortObjAll(); obj = mem_sortobj; // ソートしたオブジェクトの検索 for(i=0;i<maxsortobj;i++) { pobj = *obj; DrawObj( pobj ); // 通常のオブジェクト pobj->sortdrawflag = 0; obj++; } #endif // // 後で描画するもの(OBJ_LATEあり) // obj = mem_obj; for(i=0;i<maxobj;i++) { pobj = *obj; if ( pobj != NULL ) { // if ( pobj->mode & HGOBJ_MODE_LATE ) { if ( pobj->drawflag ) { DrawObj( pobj ); // 2Dオブジェクト } // } } obj++; } return total; } void hgdx::EnumObj( int group ) { enum_group = group; enum_id = 0; } int hgdx::GetEnumObj( void ) { int i; hgobj *obj; if ( enum_id >= maxobj ) return -1; for(i=enum_id;i<maxobj;i++) { obj = GetObj( i ); if ( obj != NULL ) { if ( obj->mygroup & enum_group ) { enum_id = i+1; return i; } } } return -1; } void hgdx::CutObjChild( int parentid ) { hgobj *obj; hgobj *obj2; hgobj *p_obj; obj = GetObj( parentid ); if ( obj == NULL ) return; if ( obj->child == NULL ) return; p_obj = obj; obj = (hgobj *)p_obj->child; p_obj->child = NULL; while(1) { obj->parent = NULL; obj2 = (hgobj *)obj->sibling; if ( obj2 == NULL ) break; obj->sibling = NULL; obj = obj2; } } void hgdx::SetObjChild( int parentid, int objid ) { hgobj *obj; hgobj *obj2; hgobj *p_obj; obj = GetObj( parentid ); obj2 = GetObj( objid ); if (( obj == NULL )||( obj2 == NULL )) return; if ( obj2->parent != NULL ) return; p_obj = obj; if ( obj->child == NULL ) { obj->child = obj2; obj2->parent = obj; return; } obj = (hgobj *)obj->child; while(1) { if ( obj->sibling == NULL ) { obj->sibling = obj2; obj2->parent = p_obj; break; } obj = (hgobj *)obj->sibling; } } void hgdx::UpdateLight( void ) { // ライト動作 // //VECTOR lightvec,lightcolor,ambientcolor; //CopyVector( &lightvec, light->GetRot() ); //CopyVector( &lightcolor, light->GetDir() ); //ScaleVector( &lightcolor, light->GetDir(), 1.0f / 256.0f ); // ライト色を設定する //ScaleVector( &ambientcolor, light->GetEfx(), 1.0f / 256.0f ); // アンビエント色を設定する //io.SetLight( &lightvec ); } void hgdx::SetCamMode( int mode, int id ) { cammode = mode; camera->SetLookObj( id ); } void hgdx::UpdateCamera( void ) { } void hgdx::SetBorder( float x0, float x1, float y0, float y1, float z0, float z1 ) { SetVector( &border1, x0, y0, z0, 0.0f ); SetVector( &border2, x1, y1, z1, 0.0f ); } void hgdx::GetBorder( VECTOR *v1, VECTOR *v2 ) { CopyVector( v1, &border1 ); CopyVector( v2, &border2 ); } int hgdx::UpdateObjColi( int id, float size, int addcol ) { int i; int flg_2d; int chkgroup; VECTOR *pos; hgobj *ene; hgobj **obj; hgobj *o; // 表示処理 // o = mem_obj[id]; if ( o == NULL ) return -1; o->colinfo = -1; if ( addcol == 0 ) { chkgroup = o->colgroup; } else { chkgroup = addcol; } pos = o->GetPos(); if ( o->flag == HGOBJ_FLAG_NONE ) return -1; if ( chkgroup == 0 ) return -1; hgmodel *model = o->model; if ( model == NULL ) return -1; flg_2d = 0; if ( model->GetFlag() == HGMODEL_FLAG_2DSPRITE ) flg_2d = 1; obj = mem_obj; for(i=0;i<maxobj;i++) { ene = *obj; if ( ene != NULL ) { if ( ene->flag & HGOBJ_FLAG_VISIBLE ) { if (( ene->mygroup & chkgroup )&&( i != id )) { if ( flg_2d ) { if ( ene->GetDistance2D( pos, size ) ) { o->colinfo = i; return i; } } else { if ( ene->GetDistance( pos, size ) ) { o->colinfo = i; return i; } } } } } obj++; } return -1; } void hgdx::StartObjFind( int mode, int group ) { // オブジェクト検索設定 // mode:除外するモード // group:対象となるcollision group // objfind_exmode = mode; objfind_group = group; objfind_id = 0; } int hgdx::FindObj( void ) { // オブジェクト検索 // (ret:-1=検索終了) // int i; hgobj *o; while(1) { if ( objfind_id >= maxobj ) return -1; o = mem_obj[objfind_id]; if ( o != NULL ) { if ( o->flag != HGOBJ_FLAG_NONE ) { if ( o->mygroup & objfind_group ) { if (( o->mode & objfind_exmode )==0 ) { break; } } } } objfind_id++; } i = objfind_id; objfind_id++; return i; } hgobj *hgdx::AddLightObj( void ) { hgobj *lg; lg = AddObj(); lg->SetRot( 0.0f, 1.0f, 0.0f ); lg->SetScale( 255.0f, 255.0f, 255.0f ); lg->SetDir( 0.0f, 0.0f, 0.0f ); return lg; } void hgdx::SetObjLight( int id, int refid, int mode ) { hgobj *o; hgobj *ref; o = GetObj( id ); if ( o == NULL ) return; ref = GetObj( refid ); if ( ref == NULL ) return; // if ( mode & 1 ) o->SetLight( ref->GetRot() ); // if ( mode & 2 ) o->SetLightColor( ref->GetScale() ); // if ( mode & 4 ) o->SetLightAmbient( ref->GetDir() ); } float hgdx::ObjAim( int id, int target, int mode, float x, float y, float z ) { hgobj *obj; VECTOR *v0; VECTOR *v1; VECTOR *v2; VECTOR *v3; VECTOR vec; VECTOR tmp; int val; float rval; rval = 0.0f; obj = GetObj( id ); if ( obj == NULL ) return rval; v0 = obj->GetVectorPrm( target ); v1 = &vec; SetVector( &vec, x, y, z, 1.0 ); val = mode; if ( val & 0xf0000 ) { v2 = GetObj( val & 0xffff )->GetVectorPrm( target ); val = (val>>16) - 1; } else { v2 = obj->GetWork(); } switch( val ) { case 0: SubVector( &tmp, v2, v0 ); if ( tmp.x > v1->x ) tmp.x = v1->x; if ( tmp.y > v1->y ) tmp.y = v1->y; if ( tmp.z > v1->z ) tmp.z = v1->z; if ( tmp.x < -v1->x ) tmp.x = -v1->x; if ( tmp.y < -v1->y ) tmp.y = -v1->y; if ( tmp.z < -v1->z ) tmp.z = -v1->z; if ( tmp.y != 0.0f ) { // AlertMsgf( "%f,%f,%f---%f,%f,%f",tmp.x,tmp.y,tmp.z,v0->x, v0->y, v0->z ); } AddVector( v0, v0, &tmp ); rval = GetVectorDistance( v0, v2 ); break; case 1: SubVector( &tmp, v2, v0 ); if ( tmp.x > v1->x ) tmp.x = v1->x; if ( tmp.y > v1->y ) tmp.y = v1->y; if ( tmp.z > v1->z ) tmp.z = v1->z; if ( tmp.x < -v1->x ) tmp.x = -v1->x; if ( tmp.y < -v1->y ) tmp.y = -v1->y; if ( tmp.z < -v1->z ) tmp.z = -v1->z; obj->SetDir( tmp.x, tmp.y, tmp.z ); rval = GetVectorDistance( v0, v2 ); break; case 2: GetTargetAngle( &tmp, v0, v2 ); obj->SetRot( 0.0f, -tmp.y + vec.y, 0.0f ); rval = GetVectorDistance( v0, v2 ); break; case 3: case 4: GetTargetAngle( &tmp, v0, v2 ); obj->SetRot( tmp.x, tmp.y, tmp.z ); InitMatrix(); RotY( tmp.y ); RotX( -tmp.x ); ApplyMatrix( &tmp, v1 ); obj->SetDir( -tmp.x, -tmp.y, -tmp.z ); rval = GetVectorDistance( v0, v2 ); break; case 5: case 6: GetTargetAngle( &tmp, v0, v2 ); //if ( obj->evtimer > 0 ) { SubVector( &tmp, &tmp, obj->GetRot() ); v3 = obj->GetWork(); if ( tmp.x > v3->x ) tmp.x = v3->x; if ( tmp.y > v3->y ) tmp.y = v3->y; if ( tmp.z > v3->z ) tmp.z = v3->z; if ( tmp.x < -v3->x ) tmp.x = -v3->x; if ( tmp.y < -v3->y ) tmp.y = -v3->y; if ( tmp.z < -v3->z ) tmp.z = -v3->z; AddVector( &tmp, &tmp, obj->GetRot() ); //} obj->SetRot( tmp.x, tmp.y, tmp.z ); InitMatrix(); RotY( tmp.y ); RotX( -tmp.x ); ApplyMatrix( &tmp, v1 ); obj->SetDir( -tmp.x, -tmp.y, -tmp.z ); rval = GetVectorDistance( v0, v2 ); break; default: break; } return rval; } int hgdx::GetNearestObj( int id, float range, int colgroup ) { int i; int flg_2d; int res; VECTOR *pos; hgobj *ene; hgobj **obj; hgobj *o; hgmodel *model; float maxrange; float dist; // 表示処理 // o = mem_obj[id]; if ( o == NULL ) return -1; pos = o->GetPos(); if ( o->flag == HGOBJ_FLAG_NONE ) return -1; if ( colgroup == 0 ) return -1; model = o->model; if ( model == NULL ) return -1; res = -1; maxrange = range; flg_2d = 0; if ( model->GetFlag() == HGMODEL_FLAG_2DSPRITE ) flg_2d = 1; obj = mem_obj; for(i=0;i<maxobj;i++) { ene = *obj; if (( ene != NULL )&&( i != id )) { if ( ene->flag & HGOBJ_FLAG_VISIBLE ) { if ( ene->mygroup & colgroup ) { if ( flg_2d ) { dist = ene->GetDistance2D( pos ); } else { dist = ene->GetDistance( pos ); } if ( dist < maxrange ) { res = i; maxrange = dist; } } } } obj++; } return res; } /*------------------------------------------------------------*/ /* for Emitter */ /*------------------------------------------------------------*/ hgemitter *hgdx::GetEmitter( int emitid ) { hgemitter *emi; if (( emitid < 0 )||( emitid >= maxemitter )) return NULL; emi = mem_emitter[emitid]; return emi; } int hgdx::GetEmptyEmitterId( void ) { int sel,i; sel = -1; for(i=0;i<maxemitter;i++) { if ( mem_emitter[i] == NULL ) { sel = i; break; } } return sel; } int hgdx::AddEmitter( int id, int mode, int num ) { int sel; hgemitter *emi; sel = id; if ( sel < 0 ) { sel = GetEmptyEmitterId(); if ( sel < 0 ) return -1; } DeleteEmitter( sel ); emi = new hgemitter; emi->mode = mode; emi->out_num = num; mem_emitter[ sel ] = emi; return sel; } void hgdx::DeleteEmitter( int id ) { hgemitter *emi; emi = mem_emitter[ id ]; if ( emi == NULL ) return; delete emi; mem_emitter[ id ] = NULL; } void hgdx::SetObjEmitter( int id, int emitid ) { hgobj *o; o = GetObj( id ); if ( o == NULL ) return; o->SetEmitter( emitid ); } void hgdx::GroupModify( int group, int param, int calcopt, VECTOR *data ) { int i; hgobj **obj; hgobj *ene; VECTOR *vec; obj = mem_obj; for(i=0;i<maxobj;i++) { ene = *obj; if ( ene != NULL ) { if ( ene->flag & HGOBJ_FLAG_VISIBLE ) { if ( ene->mygroup & group ) { vec = ene->GetVectorPrm( param ); switch( calcopt ) { case 0: CopyVector( vec, data ); break; case 1: AddVector( vec, vec, data ); break; case 2: SubVector( vec, vec, data ); break; case 3: MulVector( vec, vec, data ); break; } } } } obj++; } } void hgdx::SetModelColScale( int id, float scale1, float scale2 , float scale3 ) { hgmodel *mdl; mdl = GetModel( id ); if ( mdl != NULL ) { mdl->SetDefaultColScale( scale1, scale2, scale3 ); } } void hgdx::SetModelColParam( int id, float scale1, float scale2 , float scale3 ) { hgmodel *mdl; mdl = GetModel( id ); if ( mdl != NULL ) { mdl->SetDefaultColParam( scale1, scale2, scale3 ); } }
21.102394
111
0.552071
m4saka
b94cc9d19e7e4aa1486aef0e32a0a93ed80f07ae
952
cpp
C++
v_0_2/graph_handlers/graph_depos_handler.cpp
TimoLoomets/TeamSuccessRobotex2018Taxify
702da19a93761892174f3950924e0da07ea0c568
[ "MIT" ]
1
2018-07-03T21:17:29.000Z
2018-07-03T21:17:29.000Z
v_0_2/graph_handlers/graph_depos_handler.cpp
TimoLoomets/TeamSuccessRobotex2018Taxify
702da19a93761892174f3950924e0da07ea0c568
[ "MIT" ]
null
null
null
v_0_2/graph_handlers/graph_depos_handler.cpp
TimoLoomets/TeamSuccessRobotex2018Taxify
702da19a93761892174f3950924e0da07ea0c568
[ "MIT" ]
2
2018-07-03T21:17:31.000Z
2018-07-06T15:55:21.000Z
#ifndef GRAPH_DEPOS_HANDLER_CPP #define GRAPH_DEPOS_HANDLER_CPP #include <bits/stdc++.h> #include "../util_functions/util_functions.hpp" #include "../graph_handlers/graph_points_handler.cpp" void add_depo_to_graph( std::map<std::pair<double, double>, std::map<std::pair<double, double>, double> > * map_graph_pointer, depo_data * depo_pointer){ depo_pointer->nodes = add_point_to_graph(map_graph_pointer, std::make_pair(depo_pointer->lat, depo_pointer->lon)); } void add_depos_to_graph( std::map<std::pair<double, double>, std::map<std::pair<double, double>, double> > * map_graph_pointer, std::vector<depo_data> * depos_pointer){ for(std::vector<depo_data>::iterator depos_it = (*depos_pointer).begin(); depos_it < (*depos_pointer).end(); ++depos_it){ //std::cout << "adding depo nr: " << depos_it - (*depos_pointer).begin() << "\n"; add_depo_to_graph(map_graph_pointer, &(*depos_it)); } } /* int main(){ return 0; } */ #endif
34
122
0.719538
TimoLoomets
b953e8a4a78ff0216c8f6cd7d380a3bd9439af18
327
cpp
C++
ProjectClasses/Utility.cpp
arnelimperial/rigid-c-
f9c903635d856fadef62ef8314b29b08a656bf82
[ "Zlib" ]
null
null
null
ProjectClasses/Utility.cpp
arnelimperial/rigid-c-
f9c903635d856fadef62ef8314b29b08a656bf82
[ "Zlib" ]
null
null
null
ProjectClasses/Utility.cpp
arnelimperial/rigid-c-
f9c903635d856fadef62ef8314b29b08a656bf82
[ "Zlib" ]
null
null
null
//For Function definition #include "Utility.h" Utility::Utility(){ cout << "Object is created!!" << endl; } Utility::Utility(string a){ // a = "HELLO C++"; txt1 = a; } Utility:: Utility(int c){ num = c; } string Utility::display(){ return txt1; } int Utility::operate(){ return num * 100; }
10.21875
42
0.571865
arnelimperial
b95669f9f67839b1d23b8a5e13d7581d8c342842
4,710
cpp
C++
tests/iterator_types.cpp
keipertk/Utilities
5b0ab5e20f374bc7f790523a8548fdcfddcfa311
[ "Apache-2.0" ]
1
2019-09-29T16:52:01.000Z
2019-09-29T16:52:01.000Z
tests/iterator_types.cpp
keipertk/Utilities
5b0ab5e20f374bc7f790523a8548fdcfddcfa311
[ "Apache-2.0" ]
null
null
null
tests/iterator_types.cpp
keipertk/Utilities
5b0ab5e20f374bc7f790523a8548fdcfddcfa311
[ "Apache-2.0" ]
null
null
null
#include <utilities/type_traits/iterator_types.hpp> #include <utilities/type_traits/type_traits_extensions.hpp> #include <catch2/catch.hpp> using namespace utilities; using namespace detail_; struct Iterator : public InputIteratorBase<Iterator, int> { int value_ = 0; Iterator& increment() { ++value_; return *this; } const int& dereference() const { return value_; } bool are_equal(const Iterator& other) const noexcept { return value_ == other.value_; } }; struct Iterator2 : public InputIteratorBase<Iterator, const int> {}; TEST_CASE("InputIterator base class") { Iterator itr; SECTION("Satisfies iterator concept") { bool is_itr = is_input_iterator<Iterator>::value; REQUIRE(is_itr); } SECTION("Can be dereferenced in non-const state") { int& value = *itr; REQUIRE(value == 0); REQUIRE(&value == &itr.value_); } SECTION("Can be dereferenced in a const state") { const int& value = *const_cast<const Iterator&>(itr); // NOLINT REQUIRE(value == 0); REQUIRE(&value == &itr.value_); } SECTION("Can be prefix-incremented") { auto& rv = ++itr; REQUIRE(&rv == &itr); REQUIRE(*rv == 1); SECTION("Equality works") { REQUIRE(rv == itr); } } SECTION("Can be post-incremented") { auto rv = itr++; REQUIRE(*rv == 0); REQUIRE(&rv.value_ != &itr.value_); REQUIRE(*itr == 1); SECTION("Inequality works") { REQUIRE(rv != itr); } } SECTION("Const is obeyed") { bool is_const = std::is_same<const int&, typename Iterator2::reference>::value; REQUIRE(is_const); } } struct BidirectionalIterator : public BidirectionalIteratorBase<BidirectionalIterator, int> { int value_ = 0; BidirectionalIterator& increment() { ++value_; return *this; } BidirectionalIterator& decrement() { --value_; return *this; } const int& dereference() const { return value_; } bool are_equal(const BidirectionalIterator& other) const noexcept { return value_ == other.value_; } }; TEST_CASE("BidirectionalIterator base class") { BidirectionalIterator itr; SECTION("Satisfies iterator concept") { bool is_itr = is_bidirectional_iterator<BidirectionalIterator>::value; REQUIRE(is_itr); } SECTION("Can be prefix decremented") { BidirectionalIterator& rv = --itr; REQUIRE(*itr == -1); REQUIRE(&rv == &itr); } SECTION("Can be postfix decremented") { BidirectionalIterator rv = itr--; REQUIRE(&rv.value_ != &itr.value_); REQUIRE(*rv == 0); REQUIRE(*itr == -1); } } struct RandomAccessIterator : public RandomAccessIteratorBase<RandomAccessIterator, int> { int value_ = 0; RandomAccessIterator& increment() { ++value_; return *this; } RandomAccessIterator& decrement() { --value_; return *this; } const int& dereference() const { return value_; } bool are_equal(const RandomAccessIterator& other) const noexcept { return value_ == other.value_; } long int distance_to(const RandomAccessIterator& other) const noexcept { return other.value_ - value_; } RandomAccessIterator& advance(long int n) { value_ += n; return *this; } }; TEST_CASE("RandomAccessIterator base class") { RandomAccessIterator itr; SECTION("Satisfies iterator concept") { bool is_itr = is_random_access_iterator<RandomAccessIterator>::value; REQUIRE(is_itr); } SECTION("Order comparisons work") { RandomAccessIterator itr2; RandomAccessIterator itr3; itr3.value_ = 10; REQUIRE(itr < itr3); REQUIRE(itr <= itr2); REQUIRE(itr3 > itr); REQUIRE(itr2 >= itr); } SECTION("Advancing works") { RandomAccessIterator& rv = (itr += 10); REQUIRE(&rv == &itr); REQUIRE(rv.value_ == 10); } SECTION("Advance and copy works") { RandomAccessIterator rv = (itr + 10); REQUIRE(itr.value_ == 0); REQUIRE(rv.value_ == 10); } SECTION("Go backwards works") { RandomAccessIterator& rv = (itr -= 10); REQUIRE(&rv == &itr); REQUIRE(itr.value_ == -10); } SECTION("Go backwards and copy works") { RandomAccessIterator rv = (itr - 10); REQUIRE(itr.value_ == 0); REQUIRE(rv.value_ == -10); } SECTION("Random access works") { int rv = itr[100]; REQUIRE(itr.value_ == 0); REQUIRE(rv == 100); } }
27.225434
78
0.599151
keipertk
b957323024851bcb87eb7fff929f21549639d604
1,082
cpp
C++
3dEngine/src/api/render/pipeline/PipelineContainer.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
24
2015-10-05T00:13:57.000Z
2020-05-06T20:14:06.000Z
3dEngine/src/api/render/pipeline/PipelineContainer.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
1
2019-11-01T08:00:55.000Z
2019-11-01T08:00:55.000Z
3dEngine/src/api/render/pipeline/PipelineContainer.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
10
2015-11-25T07:33:13.000Z
2020-03-02T08:21:10.000Z
#include <api/render/pipeline/PipelineContainer.h> namespace urchin { PipelineContainer::~PipelineContainer() { cleanPipelines(); for (const auto& [pipelineId, pipeline] : pipelines) { Logger::instance().logError("Pipeline not released: " + pipeline->getName()); } } std::shared_ptr<Pipeline> PipelineContainer::getPipeline(std::size_t pipelineHash) const { auto itFind = pipelines.find(pipelineHash); if (itFind != pipelines.end()) { return itFind->second; } return std::shared_ptr<Pipeline>(nullptr); } void PipelineContainer::addPipeline(const std::shared_ptr<Pipeline>& pipeline) { #ifdef URCHIN_DEBUG assert(pipelines.find(pipeline->getId()) == pipelines.end()); #endif pipelines.try_emplace(pipeline->getId(), pipeline); } void PipelineContainer::cleanPipelines() { std::erase_if(pipelines, [](const auto& pipeline) { return pipeline.second.use_count() <= 1; //pipeline not used anymore }); } }
32.787879
94
0.627542
petitg1987
b9580795fefc92426af2f47bb1f44e56aac19058
4,928
hpp
C++
include/lbann/data_readers/image_utils.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
include/lbann/data_readers/image_utils.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
include/lbann/data_readers/image_utils.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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. // // image_utils .cpp .hpp - Image I/O utility functions //////////////////////////////////////////////////////////////////////////////// #ifndef LBANN_IMAGE_UTILS_HPP #define LBANN_IMAGE_UTILS_HPP #include "lbann/base.hpp" #include <type_traits> #include <typeinfo> // operator typeid #ifdef LBANN_HAS_OPENCV #include "lbann/data_readers/cv_utils.hpp" #include "lbann/data_readers/cv_process_patches.hpp" #endif namespace lbann { class image_utils { public: static bool loadIMG(std::vector<unsigned char>& image_buf, int& Width, int& Height, bool Flip, unsigned char *&Pixels); static bool loadIMG(const std::string& Imagefile, int& Width, int& Height, bool Flip, unsigned char *&Pixels, std::vector<char>& buf); static bool saveIMG(const std::string& Imagefile, int Width, int Height, bool Flip, unsigned char *Pixels); #ifdef LBANN_HAS_OPENCV // The other load/import methods rely on these core methods /// process an image and put it into an LBANN Mat data block static bool process_image(cv::Mat& image, int& Width, int& Height, int& Type, cv_process& pp, ::Mat& out); /// process an image and put it into a serialized buffer static bool process_image(cv::Mat& image, int& Width, int& Height, int& Type, cv_process& pp, std::vector<uint8_t>& out); /// process an image and put it into an LBANN Mat data blocks static bool process_image(cv::Mat& image, int& Width, int& Height, int& Type, cv_process_patches& pp, std::vector<::Mat>& out); #endif // LBANN_HAS_OPENCV // new function, to support sharded data reader and data store functionality static bool load_image(std::vector<unsigned char>& image_buf, int& Width, int& Height, int& Type, cv_process& pp, ::Mat& data, cv::Mat* cv_buf = nullptr); // new function, to support sharded data reader and data store functionality static bool load_image(std::vector<unsigned char>& image_buf, int& Width, int& Height, int& Type, cv_process_patches& pp, std::vector<::Mat>& data, cv::Mat* cv_buf = nullptr); // load/save an image into/from an LBANN data block of El::Matrix<DataType> type // Use a thread save temporary buffer for decoding the image /// Load an image from a file and put it into an LBANN Mat data block static bool load_image(const std::string& filename, int& Width, int& Height, int& Type, cv_process& pp, ::Mat& data, std::vector<char>& buf, cv::Mat* cv_buf = nullptr); /// Load an image from a file, extract patches from it and put them into LBANN Mat data blocks static bool load_image(const std::string& filename, int& Width, int& Height, int& Type, cv_process_patches& pp, std::vector<::Mat>& data, std::vector<char>& buf, cv::Mat* cv_buf = nullptr); /// Save an image using data from an LBANN Mat data block static bool save_image(const std::string& filename, const int Width, const int Height, const int Type, cv_process& pp, const ::Mat& data); // import/export via a buffer of std::vector<uchar> containg the raw bytes of an image file /// Import an image from a file buffer (inbuf) and put it into an LBANN Mat data block static bool import_image(cv::InputArray inbuf, int& Width, int& Height, int& Type, cv_process& pp, ::Mat& data, cv::Mat* cv_buf = nullptr); /// Import an image from a file buffer (inbuf), extract patches from it and put them into LBANN Mat data blocks static bool import_image(cv::InputArray inbuf, int& Width, int& Height, int& Type, cv_process_patches& pp, std::vector<::Mat>& data, cv::Mat* cv_buf = nullptr); /// Export an image using data from an LBANN Mat block into a file buffer (outbuf) static bool export_image(const std::string& fileExt, std::vector<uchar>& outbuf, const int Width, const int Height, const int Type, cv_process& pp, const ::Mat& data); }; } // end of namespace lbann #endif // LBANN_IMAGE_UTILS_HPP
56.643678
191
0.705763
andy-yoo
b9594ed79027d67c4be534e9b9a17822352cde7a
301
cc
C++
src/ila/ast/ast.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
src/ila/ast/ast.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
src/ila/ast/ast.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
/// \file /// Source for the class Ast. #include <ilang/ila/ast/ast.h> namespace ilang { typedef Ast::InstrLvlAbsPtr InstrLvlAbsPtr; Ast::Ast() {} Ast::Ast(const std::string& name) : Object(name) {} Ast::~Ast() {} void Ast::set_host(InstrLvlAbsPtr host) { host_ = host; } } // namespace ilang
15.842105
57
0.664452
yuex1994
b95a8501964dcd8003f24637d53328be6828fe52
1,962
cpp
C++
src/CDiamond/src/CD_Engine2D.cpp
polymergames/jDiamond
60cce36882988d2b02833648cf2ea9988eed85a9
[ "Apache-2.0" ]
4
2017-09-17T17:49:20.000Z
2020-12-12T19:04:25.000Z
src/CDiamond/src/CD_Engine2D.cpp
polymergames/jDiamond
60cce36882988d2b02833648cf2ea9988eed85a9
[ "Apache-2.0" ]
2
2017-01-04T22:18:01.000Z
2017-01-09T15:35:35.000Z
src/CDiamond/src/CD_Engine2D.cpp
polymergames/jdiamond
60cce36882988d2b02833648cf2ea9988eed85a9
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Ahnaf Siddiqui Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "CD_Engine2D.h" #include "CD_Game2D.h" using namespace Diamond; static Config config; static Engine2D* engine = nullptr; void dEngine2DConfigureGraphics(char* windowTitle, int windowWidth, int windowHeight, bool fullscreen, bool vsync) { config.game_name = windowTitle; config.window_width = windowWidth; config.window_height = windowHeight; config.fullscreen = fullscreen; config.vsync = vsync; } void dEngine2DConfigureAudio(int numChannels, int frequency, int sampleSize) { config.audio_channels = numChannels < 2 ? D_MONO : D_STEREO; config.audio_out_freq = frequency; config.audio_out_sample_size = sampleSize; } bool dEngine2DInit() { bool success = true; engine = new Engine2D(config, success); if (!success) { delete engine; engine = nullptr; } return success; } void dEngine2DDestroy() { delete engine; engine = nullptr; } void dEngine2DLaunchGame() { auto game = dGame2DGetGame(); if (engine && game) { engine->launch(*game); } } void dEngine2DQuitGame() { if (engine) engine->quit(); } Engine2D* dEngine2DGetEngine() { return engine; }
25.815789
76
0.637615
polymergames
b95c095ff26d33c8ad604f907899d47d3ec26ac7
145
hpp
C++
test/input/pass_string_escape.hpp
zero318/json5pp
1f47bf205dffea1e380503032a7f05d8d69cd56b
[ "MIT" ]
15
2019-09-02T03:19:35.000Z
2022-03-08T03:04:24.000Z
test/input/pass_string_escape.hpp
zero318/json5pp
1f47bf205dffea1e380503032a7f05d8d69cd56b
[ "MIT" ]
2
2020-11-09T09:26:33.000Z
2021-01-28T01:52:57.000Z
test/input/pass_string_escape.hpp
zero318/json5pp
1f47bf205dffea1e380503032a7f05d8d69cd56b
[ "MIT" ]
4
2020-07-20T17:25:05.000Z
2021-03-16T05:24:20.000Z
#include "../../json5pp.hpp" static bool verify(const json5pp::value& value) { return value.as_string() == "a\bcde\fg_\"\t\\test\nbar\r/d"; }
20.714286
62
0.648276
zero318
b95dcc65e016052467ade23130ffa8eee57ba9e7
379
hpp
C++
src/armnn/backends/ITensorHandle.hpp
Air000/armnn_s32v
ec3ee60825d6b7642a70987c4911944cef7a3ee6
[ "MIT" ]
1
2019-03-19T08:44:28.000Z
2019-03-19T08:44:28.000Z
src/armnn/backends/ITensorHandle.hpp
Air000/armnn_s32v
ec3ee60825d6b7642a70987c4911944cef7a3ee6
[ "MIT" ]
null
null
null
src/armnn/backends/ITensorHandle.hpp
Air000/armnn_s32v
ec3ee60825d6b7642a70987c4911944cef7a3ee6
[ "MIT" ]
1
2019-10-11T05:58:56.000Z
2019-10-11T05:58:56.000Z
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #pragma once namespace armnn { class ITensorHandle { public: enum Type { Cpu, CL, Neon }; virtual ~ITensorHandle(){} virtual void Allocate() = 0; virtual ITensorHandle::Type GetType() const = 0; }; }
14.576923
69
0.614776
Air000
b960eb8927fe28ca27d77fa9db9ab9a87566d408
30,811
cpp
C++
tools/analyze_phonons.cpp
wichoi77/alamode
f0b3f4cc9903a807006b8f2d183de77dd461f61c
[ "MIT" ]
1
2021-01-27T19:05:03.000Z
2021-01-27T19:05:03.000Z
tools/analyze_phonons.cpp
wichoi77/alamode
f0b3f4cc9903a807006b8f2d183de77dd461f61c
[ "MIT" ]
null
null
null
tools/analyze_phonons.cpp
wichoi77/alamode
f0b3f4cc9903a807006b8f2d183de77dd461f61c
[ "MIT" ]
1
2021-04-26T14:01:15.000Z
2021-04-26T14:01:15.000Z
/* analyze_phonons.cpp Copyright (c) 2014, 2015, 2016 Terumasa Tadano This file is distributed under the terms of the MIT license. Please see the file 'LICENCE.txt' in the root directory or http://opensource.org/licenses/mit-license.php for information. */ #include <stdlib.h> #include <iostream> #include <fstream> #include <iomanip> #include <vector> #include "memory.h" #include "analyze_phonons.h" using namespace std; int main(int argc, char *argv[]) { string str; cout << "# Result analyzer ver. 1.0.5" << endl; cout << "# Input file : " << argv[1] << endl; calc = argv[2]; average_gamma = atoi(argv[3]); // Read information from .result file ifs.open(argv[1], std::ios::in); if (!ifs) { cout << "ERROR: Cannot open file " << argv[1] << endl; exit(1); } if (!locate_tag("#SYSTEM")) { cout << "ERROR: Cannot find #SYSTEM tag" << endl; exit(1); } ifs >> nat >> nkd; ifs >> volume; ns = nat * 3; if (!locate_tag("#TEMPERATURE")) { cout << "ERROR: Cannot find #TEMPERATURE tag" << endl; exit(1); } ifs >> tmin >> tmax >> dt; if (abs(dt) < eps && (tmin == tmax)) dt = 1.0; nt = static_cast<int>((tmax - tmin) / dt) + 1; allocate(temp, nt); for (i = 0; i < nt; ++i) temp[i] = tmin + dt * static_cast<double>(i); if (!locate_tag("#CLASSICAL")) { classical = false; } else { ifs >> classical; } if (!locate_tag("#KPOINT")) { cout << "ERROR: Cannot find #KPOINT tag" << endl; exit(1); } ifs >> nkx >> nky >> nkz; ifs >> nk; if (!locate_tag("##Phonon Frequency")) { cout << "ERROR: Cannot find ##Phonon Frequency tag" << endl; exit(1); } getline(ifs, str); allocate(omega, nk, ns); allocate(tau, nt, nk, ns); allocate(vel, nk, ns, 48, 3); allocate(n_weight, nk); int idummy, jdummy; for (i = 0; i < nk; ++i) { for (j = 0; j < ns; ++j) { ifs >> idummy >> jdummy >> omega[i][j]; } } if (!locate_tag("##Phonon Relaxation Time")) { cout << "ERROR: Cannot find ##Phonon Relaxation Time tag" << endl; exit(1); } double vel_tmp[3]; double damp_tmp; for (i = 0; i < nk; ++i) { for (j = 0; j < ns; ++j) { getline(ifs, str); getline(ifs, str); ifs >> n_weight[i]; for (k = 0; k < n_weight[i]; ++k) { ifs >> vel_tmp[0] >> vel_tmp[1] >> vel_tmp[2]; for (l = 0; l < 3; ++l) vel[i][j][k][l] = vel_tmp[l]; } for (k = 0; k < nt; ++k) { ifs >> damp_tmp; if (omega[i][j] < eps6) { tau[k][i][j] = 0.0; // Neglect contributions from imaginary branches } else { tau[k][i][j] = 1.0e+12 * Hz_to_kayser * 0.5 / damp_tmp; } } ifs.ignore(); getline(ifs, str); } } ifs.close(); if (average_gamma) average_gamma_at_degenerate_point(omega, tau, nt, nk, ns); if (calc == "tau") { // Print phonon lifetimes at uniform q-grid at the given temperature beg_k = atoi(argv[4]) - 1; end_k = atoi(argv[5]); if (end_k == 0) end_k = nk; if (beg_k < 0 || beg_k >= nk || end_k < 0 || end_k > nk) { cout << "ERROR: kpoint index out-of-range [" << 1 << ":" << nk << "] : " << setw(5) << beg_k + 1 << setw(5) << end_k << endl; exit(1); } beg_s = atoi(argv[6]) - 1; end_s = atoi(argv[7]); if (end_s == 0) end_s = ns; if (beg_s < 0 || beg_s >= ns || end_s < 0 || end_s > ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << beg_s + 1 << setw(5) << end_s << endl; exit(1); } int itemp; double target_temp; target_temp = atof(argv[8]); if (fmod(target_temp - tmin, dt) > eps12) { cout << "ERROR: No information is found at the given temperature." << endl; exit(1); } itemp = static_cast<int>((target_temp - tmin) / dt); isotope = atoi(argv[9]); file_isotope = argv[10]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); calc_tau(itemp); } else if (calc == "tau_temp") { // Print temperature dependence of phonon lifetime int target_k, target_s; target_k = atoi(argv[4]) - 1; target_s = atoi(argv[5]) - 1; if (target_k < 0 || target_k >= nk) { cout << "ERROR: kpoint index out-of-range [" << 1 << ":" << nk << "] : " << setw(5) << target_k + 1 << endl; exit(1); } if (target_s < 0 || target_s >= ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << target_s + 1 << endl; exit(1); } isotope = atoi(argv[6]); file_isotope = argv[7]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); calc_tau_temp(target_k, target_s); } else if (calc == "kappa") { // Print thermal conductivity beg_s = atoi(argv[4]) - 1; end_s = atoi(argv[5]); if (end_s == 0) end_s = ns; if (beg_s < 0 || beg_s >= ns || end_s < 0 || end_s > ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << beg_s + 1 << setw(5) << end_s << endl; exit(1); } isotope = atoi(argv[6]); file_isotope = argv[7]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); calc_kappa(); } else if (calc == "cumulative") { // Print the cumulative thermal conductivity // isotropic case double max_len, d_len; int itemp; double target_temp; beg_s = atoi(argv[4]) - 1; end_s = atoi(argv[5]); if (end_s == 0) end_s = ns; if (beg_s < 0 || beg_s >= ns || end_s < 0 || end_s > ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << beg_s + 1 << setw(5) << end_s << endl; exit(1); } isotope = atoi(argv[6]); file_isotope = argv[7]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); max_len = atof(argv[8]); d_len = atof(argv[9]); target_temp = atof(argv[10]); if (fmod(target_temp - tmin, dt) > eps12) { cout << "ERROR: No information is found at the given temperature." << endl; exit(1); } itemp = static_cast<int>((target_temp - tmin) / dt); calc_kappa_cumulative(max_len, d_len, itemp); } else if (calc == "cumulative2") { // Print the cumulative thermal conductivity // Direction specific case double max_len, d_len; int size_flag[3]; int itemp; double target_temp; beg_s = atoi(argv[4]) - 1; end_s = atoi(argv[5]); if (end_s == 0) end_s = ns; if (beg_s < 0 || beg_s >= ns || end_s < 0 || end_s > ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << beg_s + 1 << setw(5) << end_s << endl; exit(1); } isotope = atoi(argv[6]); file_isotope = argv[7]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); max_len = atof(argv[8]); d_len = atof(argv[9]); target_temp = atof(argv[10]); if (fmod(target_temp - tmin, dt) > eps12) { cout << "ERROR: No information is found at the given temperature." << endl; exit(1); } itemp = static_cast<int>((target_temp - tmin) / dt); for (i = 0; i < 3; ++i) { size_flag[i] = atoi(argv[11 + i]); } calc_kappa_cumulative2(max_len, d_len, itemp, size_flag); } else if (calc == "kappa_matthiessen") { // Print the thermal conductivity with boundary effects // considered by the Matthiessen's rule. double max_len, d_len; int size_flag[3]; int itemp; double target_temp; beg_s = atoi(argv[4]) - 1; end_s = atoi(argv[5]); if (end_s == 0) end_s = ns; if (beg_s < 0 || beg_s >= ns || end_s < 0 || end_s > ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << beg_s + 1 << setw(5) << end_s << endl; exit(1); } isotope = atoi(argv[6]); file_isotope = argv[7]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); max_len = atof(argv[8]); d_len = atof(argv[9]); target_temp = atof(argv[10]); if (fmod(target_temp - tmin, dt) > eps12) { cout << "ERROR: No information is found at the given temperature." << endl; exit(1); } itemp = static_cast<int>((target_temp - tmin) / dt); for (i = 0; i < 3; ++i) { size_flag[i] = atoi(argv[11 + i]); } calc_kappa_boundary2(max_len, d_len, itemp, size_flag); } else if (calc == "kappa_boundary") { // Print the temperature dependence of thermal conductivity // with boundary effects considered by the Matthiessen's rule. double len_boundary; beg_s = atoi(argv[4]) - 1; end_s = atoi(argv[5]); if (end_s == 0) end_s = ns; if (beg_s < 0 || beg_s >= ns || end_s < 0 || end_s > ns) { cout << "ERROR: mode index out-of-range [" << 1 << ":" << ns << "] : " << setw(5) << beg_s + 1 << setw(5) << end_s << endl; exit(1); } isotope = atoi(argv[6]); file_isotope = argv[7]; if (isotope) update_tau_isotope(file_isotope, omega, tau, nt, nk, ns); len_boundary = atof(argv[8]); calc_kappa_boundary(len_boundary); } return 0; } void calc_tau(int itemp) { int ik, is; double vel_norm; double factor = 1.0e+18 / (pow(Bohr_in_Angstrom, 3) * static_cast<double>(nkx * nky * nkz) * volume); double kappa[3][3]; double tau_tmp, c_tmp; cout << "# Phonon lifetime at temperature " << temp[itemp] << " K." << endl; cout << "# kpoint range " << beg_k + 1 << " " << end_k << endl; cout << "# mode range " << beg_s + 1 << " " << end_s << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# ik, is, Frequency [cm^{-1}], Lifetime [ps], |Velocity| [m/s], MFP [nm], "; cout << "Multiplicity, Thermal conductivity par mode (xx, xy, ...) [W/mK]" << endl; for (ik = beg_k; ik < end_k; ++ik) { for (is = beg_s; is < end_s; ++is) { tau_tmp = tau[itemp][ik][is]; if (classical) { c_tmp = k_Boltzmann; } else { c_tmp = Cv(omega[ik][is], temp[itemp]); } for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { kappa[i][j] = 0.0; } } for (k = 0; k < n_weight[ik]; ++k) { for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { kappa[i][j] += c_tmp * vel[ik][is][k][i] * vel[ik][is][k][j] * tau_tmp; } } } vel_norm = sqrt(vel[ik][is][0][0] * vel[ik][is][0][0] + vel[ik][is][0][1] * vel[ik][is][0][1] + vel[ik][is][0][2] * vel[ik][is][0][2]); cout << setw(5) << ik + 1 << setw(5) << is + 1; cout << setw(15) << omega[ik][is] << setw(15) << tau_tmp; cout << setw(15) << vel_norm << setw(15) << tau_tmp * vel_norm * 0.001; cout << setw(5) << n_weight[ik]; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cout << setw(15) << kappa[i][j] * factor / static_cast<double>(n_weight[ik]); } } cout << endl; } } } void calc_tau_temp(int target_k, int target_s) { double vel_norm; vel_norm = sqrt(vel[target_k][target_s][0][0] * vel[target_k][target_s][0][0] + vel[target_k][target_s][0][1] * vel[target_k][target_s][0][1] + vel[target_k][target_s][0][2] * vel[target_k][target_s][0][2]); cout << "# Temperature dependence of the damping function will be printed" << endl; cout << "# for phonon specified by kpoint " << target_k + 1 << " and mode " << target_s + 1 << endl; cout << "# Frequency = " << omega[target_k][target_s] << " [cm^-1]" << endl; cout << "# Velocity = " << vel_norm << " [m/s]" << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# Temperature [k], Lifetime [ps], MFP [nm]" << endl; for (i = 0; i < nt; ++i) { cout << setw(9) << temp[i]; cout << setw(15) << tau[i][target_k][target_s]; cout << setw(15) << tau[i][target_k][target_s] * vel_norm * 0.001 << endl; } } void calc_kappa() { int it, ik, is; double ***kappa; double c_tmp, tau_tmp; allocate(kappa, nt, 3, 3); double factor = 1.0e+18 / (pow(Bohr_in_Angstrom, 3) * static_cast<double>(nkx * nky * nkz) * volume); cout << "# Temperature dependence of thermal conductivity will be printed." << endl; cout << "# mode range " << beg_s + 1 << " " << end_s << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# Temperature [K], kappa [W/mK] (xx, xy, xz, yx, yy, yz, zx, zy, zz)" << endl; for (i = 0; i < nt; ++i) { for (j = 0; j < 3; ++j) { for (k = 0; k < 3; ++k) { kappa[i][j][k] = 0.0; } } } for (it = 0; it < nt; ++it) { for (ik = 0; ik < nk; ++ik) { for (is = beg_s; is < end_s; ++is) { tau_tmp = tau[it][ik][is]; if (classical) { c_tmp = k_Boltzmann; } else { c_tmp = Cv(omega[ik][is], temp[it]); } for (i = 0; i < n_weight[ik]; ++i) { for (j = 0; j < 3; ++j) { for (k = 0; k < 3; ++k) { kappa[it][j][k] += c_tmp * vel[ik][is][i][j] * vel[ik][is][i][k] * tau_tmp; } } } } } cout << setw(10) << temp[it]; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cout << setw(15) << kappa[it][i][j] * factor; } } cout << endl; } deallocate(kappa); } void calc_kappa_cumulative(double max_length, double delta_length, int itemp) { int nlength = static_cast<int>(max_length / delta_length); double length; double kappa[3][3]; int il, ik, is; int nsame; double tau_tmp, c_tmp, vel_tmp, mfp_tmp; double factor = 1.0e+18 / (pow(Bohr_in_Angstrom, 3) * static_cast<double>(nkx * nky * nkz) * volume); cout << "# Cumulative thermal conductivity at temperature " << temp[itemp] << " K." << endl; cout << "# mode range " << beg_s + 1 << " " << end_s << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# Each phonon contribute to the total thermal conductivity if" << endl; cout << "# (v_x)^2+(v_y)^2+(v_z)^2 < L^2 is satisfied." << endl; cout << "# L [nm], kappa [W/mK] (xx, xy, ...)" << endl; for (il = 0; il < nlength; ++il) { length = delta_length * static_cast<double>(il); for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { kappa[i][j] = 0.0; } } for (ik = 0; ik < nk; ++ik) { nsame = n_weight[ik]; for (is = beg_s; is < end_s; ++is) { tau_tmp = tau[itemp][ik][is]; if (classical) { c_tmp = k_Boltzmann; } else { c_tmp = Cv(omega[ik][is], temp[itemp]); } vel_tmp = pow(vel[ik][is][0][0], 2) + pow(vel[ik][is][0][1], 2) + pow(vel[ik][is][0][2], 2); mfp_tmp = tau_tmp * sqrt(vel_tmp) * 0.001; if (mfp_tmp < length) { for (i = 0; i < nsame; ++i) { for (j = 0; j < 3; ++j) { for (k = 0; k < 3; ++k) { kappa[j][k] += c_tmp * vel[ik][is][i][j] * vel[ik][is][i][k] * tau_tmp; } } } } } } cout << setw(15) << length; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cout << setw(15) << kappa[i][j] * factor; } } cout << endl; } } void calc_kappa_cumulative2(double max_length, double delta_length, int itemp, int flag[3]) { int nlength = static_cast<int>(max_length / delta_length); double length; double kappa[3][3]; int il, ik, is; int nsame; double tau_tmp, c_tmp; double mfp_tmp[3]; bool is_longer_than_L[3]; double factor = 1.0e+18 / (pow(Bohr_in_Angstrom, 3) * static_cast<double>(nkx * nky * nkz) * volume); cout << "# Cumulative thermal conductivity at temperature " << temp[itemp] << " K." << endl; cout << "# mode range " << beg_s + 1 << " " << end_s << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# Each phonon contribute to the total thermal conductivity if" << endl; cout << "# |v_{x,y,z}| < L is satisfied." << endl; cout << "# Boundary direction flag :" << flag[0] << " " << flag[1] << " " << flag[2] << endl; cout << "# L [nm], kappa [W/mK] (xx, xy, ...)" << endl; for (il = 0; il < nlength; ++il) { length = delta_length * static_cast<double>(il); for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { kappa[i][j] = 0.0; } } for (ik = 0; ik < nk; ++ik) { nsame = n_weight[ik]; for (is = beg_s; is < end_s; ++is) { tau_tmp = tau[itemp][ik][is]; if (classical) { c_tmp = k_Boltzmann; } else { c_tmp = Cv(omega[ik][is], temp[itemp]); } for (i = 0; i < nsame; ++i) { for (j = 0; j < 3; ++j) { mfp_tmp[j] = tau_tmp * abs(vel[ik][is][i][j]) * 0.001; is_longer_than_L[j] = mfp_tmp[j] > length; } if ((flag[0] && is_longer_than_L[0]) | (flag[1] && is_longer_than_L[1]) | (flag[2] && is_longer_than_L[2])) continue; for (j = 0; j < 3; ++j) { for (k = 0; k < 3; ++k) { kappa[j][k] += c_tmp * vel[ik][is][i][j] * vel[ik][is][i][k] * tau_tmp; } } } } } cout << setw(15) << length; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cout << setw(15) << kappa[i][j] * factor; } } cout << endl; } } void calc_kappa_boundary(const double len_boundary) { int it, ik, is; double ***kappa; double c_tmp, tau_tmp; double mfp_tmp, vel_norm; allocate(kappa, nt, 3, 3); double factor = 1.0e+18 / (pow(Bohr_in_Angstrom, 3) * static_cast<double>(nkx * nky * nkz) * volume); cout << "# Temperature dependence of thermal conductivity with boundary effects." << endl; cout << "# mode range " << beg_s + 1 << " " << end_s << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# Size of boundary " << len_boundary << " [nm]" << endl; cout << "# Temperature [K], kappa [W/mK] (xx, xy, xz, yx, yy, yz, zx, zy, zz)" << endl; for (i = 0; i < nt; ++i) { for (j = 0; j < 3; ++j) { for (k = 0; k < 3; ++k) { kappa[i][j][k] = 0.0; } } } for (it = 0; it < nt; ++it) { for (ik = 0; ik < nk; ++ik) { for (is = beg_s; is < end_s; ++is) { tau_tmp = tau[it][ik][is]; if (classical) { c_tmp = k_Boltzmann; } else { c_tmp = Cv(omega[ik][is], temp[it]); } vel_norm = vel[ik][is][0][0] * vel[ik][is][0][0] + vel[ik][is][0][1] * vel[ik][is][0][1] + vel[ik][is][0][2] * vel[ik][is][0][2]; mfp_tmp = std::sqrt(vel_norm) * tau_tmp * 0.001; for (i = 0; i < n_weight[ik]; ++i) { for (j = 0; j < 3; ++j) { for (k = 0; k < 3; ++k) { kappa[it][j][k] += c_tmp * vel[ik][is][i][j] * vel[ik][is][i][k] * tau_tmp * len_boundary / (len_boundary + 2.0 * mfp_tmp); } } } } } cout << setw(10) << temp[it]; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cout << setw(15) << kappa[it][i][j] * factor; } } cout << endl; } deallocate(kappa); } void calc_kappa_boundary2(double max_length, double delta_length, int itemp, int flag[3]) { int nlength = static_cast<int>(max_length / delta_length); double length; double kappa[3][3]; int il, ik, is; int nsame; double tau_tmp, c_tmp; double mfp_tmp[3]; double factor = 1.0e+18 / (pow(Bohr_in_Angstrom, 3) * static_cast<double>(nkx * nky * nkz) * volume); cout << "# Size dependent thermal conductivity at temperature " << temp[itemp] << " K." << endl; cout << "# Relaxation time will be modified following Matthiesen's rule " << endl; cout << "# mode range " << beg_s + 1 << " " << end_s << endl; if (isotope) cout << "# With phonon-isotope scatterings." << endl; cout << "# Size change flag :" << flag[0] << " " << flag[1] << " " << flag[2] << endl; cout << "# L [nm], kappa [W/mK] (xx, xy, ...)" << endl; for (il = 0; il < nlength; ++il) { length = delta_length * static_cast<double>(il); for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { kappa[i][j] = 0.0; } } for (ik = 0; ik < nk; ++ik) { nsame = n_weight[ik]; for (is = beg_s; is < end_s; ++is) { tau_tmp = tau[itemp][ik][is]; if (classical) { c_tmp = k_Boltzmann; } else { c_tmp = Cv(omega[ik][is], temp[itemp]); } for (i = 0; i < nsame; ++i) { for (j = 0; j < 3; ++j) { mfp_tmp[j] = tau_tmp * abs(vel[ik][is][i][j]) * 0.001; if (flag[j]) { for (k = 0; k < 3; ++k) { kappa[j][k] += c_tmp * vel[ik][is][i][j] * vel[ik][is][i][k] * tau_tmp * length / (length + 2.0 * mfp_tmp[j]); } } else { for (k = 0; k < 3; ++k) { kappa[j][k] += c_tmp * vel[ik][is][i][j] * vel[ik][is][i][k] * tau_tmp; } } } } } } cout << setw(15) << length; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cout << setw(15) << kappa[i][j] * factor; } } cout << endl; } } int locate_tag(string key) { int ret = 0; string line, line2; ifs.clear(); ifs.seekg(0, std::ios_base::beg); while (getline(ifs, line)) { line2 = line; line = trim(line2); if (line == key) { ret = 1; break; } } return ret; } double Cv(double omega, double temp) { double x; if (abs(temp) < 1.0e-12 || omega < eps8) return 0.0; x = omega * kayser_to_Ryd / (temp * T_to_Ryd); return k_Boltzmann * pow(x / (2.0 * sinh(0.5 * x)), 2.0); } void update_tau_isotope(const std::string file, double **omega, double ***tau, const int nt, const int nk, const int ns) { int i; int ik, is, jk, js; double omega_tmp, tau_tmp; ifstream ifs; string line; double **tau_isotope; ifs.open(file.c_str(), ios::in); if (!ifs) { cout << "ERROR: Cannot open file " << file << endl; exit(1); } allocate(tau_isotope, nk, ns); for (i = 0; i < 3; ++i) getline(ifs, line); for (ik = 0; ik < nk; ++ik) { getline(ifs, line); getline(ifs, line); for (is = 0; is < ns; ++is) { ifs >> jk >> js >> omega_tmp >> tau_tmp; if (jk < 1 || jk > nk) { cout << "ERROR: In file " << file << ", k point index is out-of-range. " << endl; exit(1); } if (js < 1 || js > ns) { cout << "ERROR: In file " << file << ", mode index is out-of-range. " << endl; exit(1); } if (omega[ik][is] < eps6) { tau_isotope[ik][is] = 0.0; // Neglect contributions from imaginary branches } else { tau_isotope[ik][is] = 1.0e+12 * Hz_to_kayser * 0.5 / tau_tmp; } } ifs.ignore(); getline(ifs, line); } ifs.close(); average_gamma_isotope_at_degenerate_point(omega, tau_isotope, nk, ns); // Now, update the original tau for (ik = 0; ik < nk; ++ik) { for (is = 0; is < ns; ++is) { if (omega[ik][is] >= eps6) { for (i = 0; i < nt; ++i) { tau_tmp = 1.0 / tau[i][ik][is] + 1.0 / tau_isotope[ik][is]; tau[i][ik][is] = 1.0 / tau_tmp; } } } } deallocate(tau_isotope); } void average_gamma_at_degenerate_point(double **e, double ***tau, const int nt, const int nk, const int ns) { int ideg, is; double omega_prev, omega_now; double tol_omega = 1.0e-3; vector<int> degeneracy_at_k; double *damp_sum; allocate(damp_sum, nt); for (i = 0; i < nk; ++i) { degeneracy_at_k.clear(); omega_prev = e[i][0]; ideg = 1; for (j = 1; j < ns; ++j) { omega_now = e[i][j]; if (abs(omega_now - omega_prev) < tol_omega) { ++ideg; } else { degeneracy_at_k.push_back(ideg); ideg = 1; omega_prev = omega_now; } } degeneracy_at_k.push_back(ideg); is = 0; for (j = 0; j < degeneracy_at_k.size(); ++j) { ideg = degeneracy_at_k[j]; if (ideg > 1) { for (k = 0; k < nt; ++k) damp_sum[k] = 0.0; for (k = is; k < is + ideg; ++k) { for (l = 0; l < nt; ++l) damp_sum[l] += 1.0 / tau[l][i][k]; } for (k = is; k < is + ideg; ++k) { for (l = 0; l < nt; ++l) tau[l][i][k] = static_cast<double>(ideg) / damp_sum[l]; } } is += ideg; } } deallocate(damp_sum); } void average_gamma_isotope_at_degenerate_point(double **e, double **tau, const int nk, const int ns) { int ideg, is; double omega_prev, omega_now; double tol_omega = 1.0e-3; vector<int> degeneracy_at_k; double damp_sum; for (i = 0; i < nk; ++i) { degeneracy_at_k.clear(); omega_prev = e[i][0]; ideg = 1; for (j = 1; j < ns; ++j) { omega_now = e[i][j]; if (abs(omega_now - omega_prev) < tol_omega) { ++ideg; } else { degeneracy_at_k.push_back(ideg); ideg = 1; omega_prev = omega_now; } } degeneracy_at_k.push_back(ideg); is = 0; for (j = 0; j < degeneracy_at_k.size(); ++j) { ideg = degeneracy_at_k[j]; if (ideg > 1) { damp_sum = 0.0; for (k = is; k < is + ideg; ++k) { damp_sum += 1.0 / tau[i][k]; } for (k = is; k < is + ideg; ++k) { tau[i][k] = static_cast<double>(ideg) / damp_sum; } } is += ideg; } } }
29.260209
105
0.421343
wichoi77
b9634054319d77fc946cd60813f21161d48c2555
961
cpp
C++
Cpp/misc/2019_09_25/ICPC_D.cpp
MarioJim/CompetitiveProgramming
ade07551e37e32be3f6511bfe68ed633701c3a4d
[ "MIT" ]
1
2019-01-28T15:12:20.000Z
2019-01-28T15:12:20.000Z
Cpp/misc/2019_09_25/ICPC_D.cpp
MarioJim/ClubDeProgra
ade07551e37e32be3f6511bfe68ed633701c3a4d
[ "MIT" ]
null
null
null
Cpp/misc/2019_09_25/ICPC_D.cpp
MarioJim/ClubDeProgra
ade07551e37e32be3f6511bfe68ed633701c3a4d
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int N, K, tempInput; cin >> N >> K; vector<pair<int,int>> arr; arr.emplace_back(0,1); for (int i = 1; i < N; ++i) { cin >> tempInput; arr.emplace_back(tempInput - 1, 1); } int result = 0; while (K > 0) { // Set weights for (int i = 1; i < N; ++i) if (arr[i].second != 0) arr[i].second = arr[arr[i].first].second + 1; // Check node with max weight int max = 0; for (int i = 0; i < N; ++i) if (arr[i].second > arr[max].second) max = i; // Add weight result += arr[max].second; arr[max].second = 0; // Update weights while (max != 0) { arr[arr[max].first].second = 0; max = arr[max].first; } --K; } // Print result cout << result << "\n"; return 0; }
24.641026
61
0.448491
MarioJim
b96468872c194cd5ac8a512e0f6ed09360bab5e3
16,752
cpp
C++
src/CommObd2Can.cpp
doudoune144/evDash
a49d349b88c524fcfa01eda9da1505c02a25704f
[ "MIT" ]
42
2020-12-09T13:37:19.000Z
2022-03-12T16:58:48.000Z
src/CommObd2Can.cpp
doudoune144/evDash
a49d349b88c524fcfa01eda9da1505c02a25704f
[ "MIT" ]
21
2020-12-03T10:38:08.000Z
2022-02-10T08:30:46.000Z
src/CommObd2Can.cpp
doudoune144/evDash
a49d349b88c524fcfa01eda9da1505c02a25704f
[ "MIT" ]
28
2020-12-02T07:31:41.000Z
2022-03-23T07:59:26.000Z
#include "CommObd2Can.h" #include "BoardInterface.h" #include "LiveData.h" #include <mcp_can.h> //#include <string.h> /** Connect CAN adapter */ void CommObd2Can::connectDevice() { connectAttempts--; syslog->println("CAN connectDevice"); //CAN = new MCP_CAN(pinCanCs); // todo: remove if smart pointer is ok CAN.reset(new MCP_CAN(pinCanCs)); // smart pointer so it's automatically cleaned when out of context and also free to re-init if (CAN == nullptr) { syslog->println("Error: Not enough memory to instantiate CAN class"); syslog->println("init_can() failed"); return; } // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled. if (CAN->begin(MCP_STDEXT, CAN_500KBPS, MCP_8MHZ) == CAN_OK) { syslog->println("MCP2515 Initialized Successfully!"); board->displayMessage(" > CAN init OK", ""); } else { syslog->println("Error Initializing MCP2515..."); board->displayMessage(" > CAN init failed", ""); return; } if (liveData->settings.carType == CAR_BMW_I3_2014) { //initialise mask and filter to allow only receipt of 0x7xx CAN IDs CAN->init_Mask(0, 0, 0x07000000); // Init first mask... CAN->init_Mask(1, 0, 0x07000000); // Init second mask... for (uint8_t i = 0; i < 6; ++i) { CAN->init_Filt(i, 0, 0x06000000); //Init filters } } if (MCP2515_OK != CAN->setMode(MCP_NORMAL)) { // Set operation mode to normal so the MCP2515 sends acks to received data. syslog->println("Error: CAN->setMode(MCP_NORMAL) failed"); board->displayMessage(" > CAN init failed", ""); return; } pinMode(pinCanInt, INPUT); // Configuring pin for /INT input // Serve first command (ATZ) liveData->commConnected = true; liveData->commandQueueIndex = 0; doNextQueueCommand(); syslog->println("init_can() done"); } /** Disconnect device */ void CommObd2Can::disconnectDevice() { liveData->commConnected = false; // CAN->setMode(MCP_SLEEP); syslog->println("COMM disconnectDevice"); } /** Scan device list, from menu */ void CommObd2Can::scanDevices() { syslog->println("COMM scanDevices"); } /** Main loop */ void CommObd2Can::mainLoop() { CommInterface::mainLoop(); // if delay between commands is defined, check if this delay is not expired if (liveData->delayBetweenCommandsMs != 0) { if (bResponseProcessed && (unsigned long)(millis() - lastDataSent) > liveData->delayBetweenCommandsMs) { bResponseProcessed = false; liveData->canSendNextAtCommand = true; return; } } // Read data const uint8_t firstByte = receivePID(); if ((firstByte & 0xf0) == 0x10) { // First frame, request another sendFlowControlFrame(); delay(10); for (uint16_t i = 0; i < 1000; i++) { receivePID(); if (rxRemaining <= 2) break; delay(1); // apply timeout for next frames loop too if (lastDataSent != 0 && (unsigned long)(millis() - lastDataSent) > liveData->rxTimeoutMs) { syslog->info(DEBUG_COMM, "CAN execution timeout (multiframe message)."); break; } } // Process incomplette messages if (liveData->responseRowMerged.length() > 7) { processMergedResponse(); return; } } if (lastDataSent != 0 && (unsigned long)(millis() - lastDataSent) > liveData->rxTimeoutMs) { syslog->info(DEBUG_COMM, "CAN execution timeout. Continue with next command."); liveData->canSendNextAtCommand = true; return; } } /** Send command to CAN bus */ void CommObd2Can::executeCommand(String cmd) { syslog->infoNolf(DEBUG_COMM, "executeCommand "); syslog->info(DEBUG_COMM, cmd); if (cmd.equals("") || cmd.startsWith("AT")) { // skip AT commands as not used by direct CAN connection lastDataSent = 0; liveData->canSendNextAtCommand = true; return; } // Send command liveData->responseRowMerged = ""; liveData->currentAtshRequest.replace(" ", ""); // remove possible spaces String atsh = "0" + liveData->currentAtshRequest.substring(4); // remove ATSH cmd.replace(" ", ""); // remove possible spaces sendPID(liveData->hexToDec(atsh, 4, false), cmd); delay(40); } /** Send PID remark: parameter cmd as const reference to aviod copying */ void CommObd2Can::sendPID(const uint32_t pid, const String &cmd) { uint8_t txBuf[8] = {0}; // init with zeroes String tmpStr; if (liveData->bAdditionalStartingChar) { struct Packet_t { uint8_t startChar; uint8_t length; uint8_t payload[6]; }; Packet_t *pPacket = (Packet_t *)txBuf; pPacket->startChar = liveData->commandStartChar; // todo: handle similar way as cmd input param? pPacket->length = cmd.length() / 2; for (uint8_t i = 0; i < sizeof(pPacket->payload); i++) { tmpStr = cmd; tmpStr = tmpStr.substring(i * 2, ((i + 1) * 2)); if (tmpStr != "") { pPacket->payload[i] = liveData->hexToDec(tmpStr, 1, false); } } } else { struct Packet_t { uint8_t length; uint8_t payload[7]; }; Packet_t *pPacket = (Packet_t *)txBuf; pPacket->length = cmd.length() / 2; for (uint8_t i = 0; i < sizeof(pPacket->payload); i++) { tmpStr = cmd; tmpStr = tmpStr.substring(i * 2, ((i + 1) * 2)); if (tmpStr != "") { pPacket->payload[i] = liveData->hexToDec(tmpStr, 1, false); } } } lastPid = pid; bResponseProcessed = false; // logic to choose from 11-bit or 29-bit by testing if PID is bigger than 4095 (ie bigger than FF) byte is29bit=0; if (pid>4095) is29bit=1; const uint8_t sndStat = CAN->sendMsgBuf(pid, is29bit, 8, txBuf); // 11 bit or 29 bit if (sndStat == CAN_OK) { syslog->infoNolf(DEBUG_COMM, "SENT "); lastDataSent = millis(); } else { syslog->infoNolf(DEBUG_COMM, "Error sending PID "); lastDataSent = millis(); } syslog->infoNolf(DEBUG_COMM, pid); for (uint8_t i = 0; i < 8; i++) { sprintf(msgString, " 0x%.2X", txBuf[i]); syslog->infoNolf(DEBUG_COMM, msgString); } syslog->info(DEBUG_COMM, ""); } /** sendFlowControlFrame */ void CommObd2Can::sendFlowControlFrame() { uint8_t txBuf[8] = {0x30, requestFramesCount /*request count*/, 20 /*ms between frames*/, 0, 0, 0, 0, 0}; // insert start char if needed if (liveData->bAdditionalStartingChar) { memmove(txBuf + 1, txBuf, 7); txBuf[0] = liveData->commandStartChar; } // logic to choose from 11-bit or 29-bit byte is29bit=0; if (lastPid>4095) is29bit=1; const uint8_t sndStat = CAN->sendMsgBuf(lastPid, is29bit, 8, txBuf); // VW:29bit vs others:11 bit if (sndStat == CAN_OK) { syslog->infoNolf(DEBUG_COMM, "Flow control frame sent "); } else { syslog->infoNolf(DEBUG_COMM, "Error sending flow control frame "); } syslog->infoNolf(DEBUG_COMM, lastPid); for (auto txByte : txBuf) { sprintf(msgString, " 0x%.2X", txByte); syslog->infoNolf(DEBUG_COMM, msgString); } syslog->info(DEBUG_COMM, ""); } /** Receive PID */ uint8_t CommObd2Can::receivePID() { if (!digitalRead(pinCanInt)) // If CAN0_INT pin is low, read receive buffer { lastDataSent = millis(); syslog->infoNolf(DEBUG_COMM, " CAN READ "); CAN->readMsgBuf(&rxId, &rxLen, rxBuf); // Read data: len = data length, buf = data byte(s) if ((rxId & 0x80000000) == 0x80000000) // Determine if ID is standard (11 bits) or extended (29 bits) sprintf(msgString, "Extended ID: 0x%.8lX DLC: %1d Data:", (rxId & 0x1FFFFFFF), rxLen); else sprintf(msgString, "Standard ID: 0x%.3lX DLC: %1d Data:", rxId, rxLen); syslog->infoNolf(DEBUG_COMM, msgString); if ((rxId & 0x40000000) == 0x40000000) { // Determine if message is a remote request frame. sprintf(msgString, " REMOTE REQUEST FRAME"); syslog->infoNolf(DEBUG_COMM, msgString); } else { for (uint8_t i = 0; i < rxLen; i++) { sprintf(msgString, " 0x%.2X", rxBuf[i]); syslog->infoNolf(DEBUG_COMM, msgString); } } // Check if this packet shall be discarded due to its length. // If liveData->expectedPacketLength is set to 0, accept any length. if (liveData->expectedMinimalPacketLength != 0 && rxLen < liveData->expectedMinimalPacketLength) { syslog->info(DEBUG_COMM, " [Ignored packet]"); return 0xff; } // Filter received messages (Ioniq only) if (liveData->settings.carType == CAR_HYUNDAI_IONIQ_2018) { long unsigned int atsh_response = liveData->hexToDec(liveData->currentAtshRequest.substring(4), 2, false) + 8; if (rxId != atsh_response) { syslog->info(DEBUG_COMM, " [Filtered packet]"); return 0xff; } } syslog->info(DEBUG_COMM, ""); processFrameBytes(); //processFrame(); } else { //syslog->println(" CAN NOT READ "); return 0xff; } const uint8_t rxBuffOffset = liveData->bAdditionalStartingChar ? 1 : 0; return rxBuf[0 + rxBuffOffset]; // return byte containing frame type, which requires removing offset byte } void printHexBuffer(uint8_t *pData, const uint16_t length, const bool bAddNewLine) { char str[8] = {0}; for (uint8_t i = 0; i < length; i++) { sprintf(str, " 0x%.2X", pData[i]); syslog->infoNolf(DEBUG_COMM, str); } if (bAddNewLine) { syslog->info(DEBUG_COMM, ""); } } static void buffer2string(String &out_targetString, uint8_t *in_pBuffer, const uint16_t in_length) { char str[8] = {0}; for (uint16_t i = 0; i < in_length; i++) { sprintf(str, "%.2X", in_pBuffer[i]); out_targetString += str; } } CommObd2Can::enFrame_t CommObd2Can::getFrameType(const uint8_t firstByte) { const uint8_t frameType = (firstByte & 0xf0) >> 4; // frame type is in bits 7 to 4 switch (frameType) { case 0: return enFrame_t::single; case 1: return enFrame_t::first; case 2: return enFrame_t::consecutive; default: return enFrame_t::unknown; } } /** Process can frame on byte level https://en.wikipedia.org/wiki/ISO_15765-2 */ bool CommObd2Can::processFrameBytes() { const uint8_t rxBuffOffset = liveData->bAdditionalStartingChar ? 1 : 0; uint8_t *pDataStart = rxBuf + rxBuffOffset; // set pointer to data start based on specific offset of car const auto frameType = getFrameType(*pDataStart); const uint8_t frameLenght = rxLen - rxBuffOffset; switch (frameType) { case enFrame_t::single: // Single frame { struct SingleFrame_t { uint8_t size : 4; uint8_t frameType : 4; uint8_t pData[]; }; SingleFrame_t *pSingleFrame = (SingleFrame_t *)pDataStart; mergedData.assign(pSingleFrame->pData, pSingleFrame->pData + pSingleFrame->size); rxRemaining = 0; //syslog->print("----Processing SingleFrame payload: "); printHexBuffer(pSingleFrame->pData, pSingleFrame->size, true); // single frame - process directly buffer2string(liveData->responseRowMerged, mergedData.data(), mergedData.size()); liveData->vResponseRowMerged.assign(mergedData.begin(), mergedData.end()); processMergedResponse(); return true; } break; case enFrame_t::first: // First frame { struct FirstFrame_t { uint8_t sizeMSB : 4; uint8_t frameType : 4; uint8_t sizeLSB : 8; uint8_t pData[]; uint16_t lengthOfFullPacket() { return (256 * sizeMSB) + sizeLSB; } }; FirstFrame_t *pFirstFrame = (FirstFrame_t *)pDataStart; rxRemaining = pFirstFrame->lengthOfFullPacket(); // length of complete data mergedData.clear(); dataRows.clear(); const uint8_t framePayloadSize = frameLenght - sizeof(FirstFrame_t); // remove one byte of header dataRows[0].assign(pFirstFrame->pData, pFirstFrame->pData + framePayloadSize); rxRemaining -= framePayloadSize; //syslog->print("----Processing FirstFrame payload: "); printHexBuffer(pFirstFrame->pData, framePayloadSize, true); } break; case enFrame_t::consecutive: // Consecutive frame { struct ConsecutiveFrame_t { uint8_t index : 4; uint8_t frameType : 4; uint8_t pData[]; }; //const uint8_t structSize = sizeof(ConsecutiveFrame_t); //syslog->print("[debug] sizeof(ConsecutiveFrame_t) is expected to be 1 and it's "); syslog->println(structSize); ConsecutiveFrame_t *pConseqFrame = (ConsecutiveFrame_t *)pDataStart; const uint8_t framePayloadSize = frameLenght - sizeof(ConsecutiveFrame_t); // remove one byte of header dataRows[pConseqFrame->index].assign(pConseqFrame->pData, pConseqFrame->pData + framePayloadSize); rxRemaining -= framePayloadSize; //syslog->print("----Processing ConsecFrame payload: "); printHexBuffer(pConseqFrame->pData, framePayloadSize, true); } break; default: syslog->infoNolf(DEBUG_COMM, "Unknown frame type within CommObd2Can::processFrameBytes(): "); syslog->info(DEBUG_COMM, (uint8_t)frameType); return false; break; } // \switch (frameType) // Merge data if all data was received if (rxRemaining <= 0) { // multiple frames and no data remaining - merge everything to single packet for (int i = 0; i < dataRows.size(); i++) { //syslog->print("------merging packet index "); //syslog->print(i); //syslog->print(" with length "); //syslog->println(dataRows[i].size()); mergedData.insert(mergedData.end(), dataRows[i].begin(), dataRows[i].end()); } buffer2string(liveData->responseRowMerged, mergedData.data(), mergedData.size()); // output for string parsing liveData->vResponseRowMerged.assign(mergedData.begin(), mergedData.end()); // output for binary parsing processMergedResponse(); } return true; } /** Process can frame https://en.wikipedia.org/wiki/ISO_15765-2 */ bool CommObd2Can::processFrame() { const uint8_t frameType = (rxBuf[0] & 0xf0) >> 4; uint8_t start = 1; // Single and Consecutive starts with pos 1 uint8_t index = 0; // 0 - f liveData->responseRow = ""; switch (frameType) { // Single frame case 0: rxRemaining = (rxBuf[1] & 0x0f); requestFramesCount = 0; break; // First frame case 1: rxRemaining = ((rxBuf[0] & 0x0f) << 8) + rxBuf[1]; requestFramesCount = ceil((rxRemaining - 6) / 7.0); liveData->responseRowMerged = ""; for (uint16_t i = 0; i < rxRemaining - 1; i++) liveData->responseRowMerged += "00"; liveData->responseRow = "0:"; start = 2; break; // Consecutive frames case 2: index = (rxBuf[0] & 0x0f); sprintf(msgString, "%.1X:", index); liveData->responseRow = msgString; // convert 0..15 to ascii 0..F); break; } syslog->infoNolf(DEBUG_COMM, "> frametype:"); syslog->infoNolf(DEBUG_COMM, frameType); syslog->infoNolf(DEBUG_COMM, ", r: "); syslog->infoNolf(DEBUG_COMM, rxRemaining); syslog->infoNolf(DEBUG_COMM, " "); for (uint8_t i = start; i < rxLen; i++) { sprintf(msgString, "%.2X", rxBuf[i]); liveData->responseRow += msgString; rxRemaining--; } syslog->infoNolf(DEBUG_COMM, ", r: "); syslog->infoNolf(DEBUG_COMM, rxRemaining); syslog->info(DEBUG_COMM, " "); //parseResponse(); // We need to sort frames // 1 frame data syslog->info(DEBUG_COMM, liveData->responseRow); // Merge frames 0:xxxx 1:yyyy 2:zzzz to single response xxxxyyyyzzzz string if (liveData->responseRow.length() >= 2 && liveData->responseRow.charAt(1) == ':') { //liveData->responseRowMerged += liveData->responseRow.substring(2); uint8_t rowNo = liveData->hexToDec(liveData->responseRow.substring(0, 1), 1, false); uint16_t startPos = (rowNo * 14) - ((rowNo > 0) ? 2 : 0); uint16_t endPos = ((rowNo + 1) * 14) - ((rowNo > 0) ? 2 : 0); liveData->responseRowMerged = liveData->responseRowMerged.substring(0, startPos) + liveData->responseRow.substring(2) + liveData->responseRowMerged.substring(endPos); syslog->info(DEBUG_COMM, liveData->responseRowMerged); } // Send response to board module if (rxRemaining <= 2) { processMergedResponse(); return false; } return true; } /** processMergedResponse */ void CommObd2Can::processMergedResponse() { syslog->infoNolf(DEBUG_COMM, "merged:"); syslog->info(DEBUG_COMM, liveData->responseRowMerged); parseRowMerged(); liveData->prevResponseRowMerged = liveData->responseRowMerged; liveData->responseRowMerged = ""; liveData->vResponseRowMerged.clear(); bResponseProcessed = true; // to allow delay untill next message if (liveData->delayBetweenCommandsMs == 0) { liveData->canSendNextAtCommand = true; // allow next command immediately } }
27.689256
170
0.649654
doudoune144
b969f74cb241fbf7851922b726c0d4f2edb13b7b
1,160
hpp
C++
test/integration/utils/include/er_network_variant.hpp
anarthal/mysql-asio
13d3615464f41222052d9ad8fa0c86bcdddee537
[ "BSL-1.0" ]
47
2019-10-21T14:54:39.000Z
2020-07-06T19:36:58.000Z
test/integration/utils/include/er_network_variant.hpp
anarthal/mysql-asio
13d3615464f41222052d9ad8fa0c86bcdddee537
[ "BSL-1.0" ]
5
2020-03-05T12:03:02.000Z
2020-07-06T18:18:35.000Z
test/integration/utils/include/er_network_variant.hpp
anarthal/mysql-asio
13d3615464f41222052d9ad8fa0c86bcdddee537
[ "BSL-1.0" ]
4
2020-03-05T11:28:55.000Z
2020-05-20T09:06:21.000Z
// // Copyright (c) 2019-2022 Ruben Perez Hidalgo (rubenperez038 at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_MYSQL_TEST_INTEGRATION_UTILS_INCLUDE_ER_NETWORK_VARIANT_HPP #define BOOST_MYSQL_TEST_INTEGRATION_UTILS_INCLUDE_ER_NETWORK_VARIANT_HPP #include "er_connection.hpp" #include <boost/asio/ssl/context.hpp> #include <functional> #include <boost/asio/io_context.hpp> namespace boost { namespace mysql { namespace test { class er_network_variant { public: virtual ~er_network_variant() {} virtual bool supports_ssl() const = 0; virtual const char* stream_name() const = 0; virtual const char* variant_name() const = 0; virtual er_connection_ptr create(boost::asio::io_context::executor_type, boost::asio::ssl::context&) = 0; }; const std::vector<er_network_variant*>& all_variants(); const std::vector<er_network_variant*>& ssl_variants(); const std::vector<er_network_variant*>& non_ssl_variants(); er_network_variant* tcp_sync_errc_variant(); } // test } // mysql } // boost #endif
28.292683
109
0.763793
anarthal
b96bac60ea0b236b92cb6f420bad1677bed2796d
1,322
cpp
C++
source/dllmain.cpp
taxi2za/WINE-anti-cheat
5e941f19f5d2f1dfbb7bf162c2d77eb0bea710cd
[ "MIT" ]
5
2020-05-01T16:54:52.000Z
2021-06-09T04:52:27.000Z
source/dllmain.cpp
SimonVoorman/WINE-anti-cheat
5e941f19f5d2f1dfbb7bf162c2d77eb0bea710cd
[ "MIT" ]
null
null
null
source/dllmain.cpp
SimonVoorman/WINE-anti-cheat
5e941f19f5d2f1dfbb7bf162c2d77eb0bea710cd
[ "MIT" ]
3
2019-02-23T03:41:56.000Z
2019-12-16T17:44:46.000Z
#include "includes.hpp" #include "util/values.hpp" LRESULT CALLBACK hook_procedure(int code, WPARAM w_param, LPARAM l_param) { if (code == HC_ACTION) { const auto detection_manager = G::detection_manager; std::for_each(detection_manager.detections.begin(), detection_manager.detections.end(), [&](C_Detection* detection) { detection->on_mouse(w_param); }); } return CallNextHookEx(nullptr, code, w_param, l_param); } DWORD WINAPI entry_point() { const auto mouse_hook = SetWindowsHookEx(WH_MOUSE_LL, hook_procedure, GetModuleHandle(nullptr), NULL); MSG msg; while (GetMessage(&msg, nullptr, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-noreturn" while (true) { // Practically a keep-alive std::this_thread::sleep_for(std::chrono::milliseconds(10000)); } #pragma clang diagnostic pop } BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) { switch (reason) { case DLL_PROCESS_ATTACH: CreateThread(nullptr, NULL, (LPTHREAD_START_ROUTINE) entry_point, nullptr, NULL, nullptr); break; default: break; } return TRUE; }
24.481481
123
0.653555
taxi2za
b96fc3f20002692683d4211fc182f865861b1c88
9,051
cpp
C++
ClearScript/V8/ClearScriptV8/V8IsolateProxyImpl.cpp
erik-kallen/ClearScript
33036db296dea4cafcd9b0bd8ab076882a0ab70e
[ "MIT" ]
null
null
null
ClearScript/V8/ClearScriptV8/V8IsolateProxyImpl.cpp
erik-kallen/ClearScript
33036db296dea4cafcd9b0bd8ab076882a0ab70e
[ "MIT" ]
null
null
null
ClearScript/V8/ClearScriptV8/V8IsolateProxyImpl.cpp
erik-kallen/ClearScript
33036db296dea4cafcd9b0bd8ab076882a0ab70e
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "ClearScriptV8Managed.h" namespace Microsoft { namespace ClearScript { namespace V8 { //------------------------------------------------------------------------- // V8IsolateProxyImpl implementation //------------------------------------------------------------------------- V8IsolateProxyImpl::V8IsolateProxyImpl(String^ gcName, V8RuntimeConstraints^ gcConstraints, V8RuntimeFlags flags, Int32 debugPort): m_gcLock(gcnew Object) { const V8IsolateConstraints* pConstraints = nullptr; V8IsolateConstraints constraints; if (gcConstraints != nullptr) { constraints.Set(AdjustConstraint(gcConstraints->MaxNewSpaceSize), AdjustConstraint(gcConstraints->MaxOldSpaceSize), AdjustConstraint(gcConstraints->MaxExecutableSize)); pConstraints = &constraints; } V8Isolate::Options options; options.EnableDebugging = flags.HasFlag(V8RuntimeFlags::EnableDebugging); options.EnableRemoteDebugging = flags.HasFlag(V8RuntimeFlags::EnableRemoteDebugging); options.DebugPort = debugPort; try { m_pspIsolate = new SharedPtr<V8Isolate>(V8Isolate::Create(StdString(gcName), pConstraints, options)); } catch (const V8Exception& exception) { exception.ThrowScriptEngineException(); } } //------------------------------------------------------------------------- UIntPtr V8IsolateProxyImpl::MaxHeapSize::get() { return (UIntPtr)GetIsolate()->GetMaxHeapSize(); } //------------------------------------------------------------------------- void V8IsolateProxyImpl::MaxHeapSize::set(UIntPtr value) { GetIsolate()->SetMaxHeapSize(static_cast<size_t>(value)); } //------------------------------------------------------------------------- TimeSpan V8IsolateProxyImpl::HeapSizeSampleInterval::get() { return TimeSpan::FromMilliseconds(GetIsolate()->GetHeapSizeSampleInterval()); } //------------------------------------------------------------------------- void V8IsolateProxyImpl::HeapSizeSampleInterval::set(TimeSpan value) { GetIsolate()->SetHeapSizeSampleInterval(value.TotalMilliseconds); } //------------------------------------------------------------------------- UIntPtr V8IsolateProxyImpl::MaxStackUsage::get() { return (UIntPtr)GetIsolate()->GetMaxStackUsage(); } //------------------------------------------------------------------------- void V8IsolateProxyImpl::MaxStackUsage::set(UIntPtr value) { GetIsolate()->SetMaxStackUsage(static_cast<size_t>(value)); } //------------------------------------------------------------------------- void V8IsolateProxyImpl::AwaitDebuggerAndPause() { try { return GetIsolate()->AwaitDebuggerAndPause(); } catch (const V8Exception& exception) { exception.ThrowScriptEngineException(); } } //------------------------------------------------------------------------- V8Script^ V8IsolateProxyImpl::Compile(DocumentInfo documentInfo, String^ gcCode) { try { return gcnew V8ScriptImpl(documentInfo, GetIsolate()->Compile(V8DocumentInfo(documentInfo), StdString(gcCode))); } catch (const V8Exception& exception) { exception.ThrowScriptEngineException(); } } //------------------------------------------------------------------------- V8Script^ V8IsolateProxyImpl::Compile(DocumentInfo documentInfo, String^ gcCode, V8CacheKind cacheKind, [Out] array<Byte>^% gcCacheBytes) { #pragma warning(push) #pragma warning(disable:4947) /* 'Microsoft::ClearScript::V8::V8CacheKind::Parser': marked as obsolete */ if (cacheKind == V8CacheKind::None) { gcCacheBytes = nullptr; return Compile(documentInfo, gcCode); } try { std::vector<std::uint8_t> cacheBytes; auto cacheType = (cacheKind == V8CacheKind::Parser) ? V8CacheType::Parser : V8CacheType::Code; auto gcScript = gcnew V8ScriptImpl(documentInfo, GetIsolate()->Compile(V8DocumentInfo(documentInfo), StdString(gcCode), cacheType, cacheBytes)); auto length = static_cast<int>(cacheBytes.size()); if (length < 1) { gcCacheBytes = nullptr; } else { gcCacheBytes = gcnew array<Byte>(length); Marshal::Copy((IntPtr)&cacheBytes[0], gcCacheBytes, 0, length); } return gcScript; } catch (const V8Exception& exception) { exception.ThrowScriptEngineException(); } #pragma warning(pop) } //------------------------------------------------------------------------- V8Script^ V8IsolateProxyImpl::Compile(DocumentInfo documentInfo, String^ gcCode, V8CacheKind cacheKind, array<Byte>^ gcCacheBytes, [Out] Boolean% cacheAccepted) { #pragma warning(push) #pragma warning(disable:4947) /* 'Microsoft::ClearScript::V8::V8CacheKind::Parser': marked as obsolete */ if ((cacheKind == V8CacheKind::None) || (gcCacheBytes == nullptr) || (gcCacheBytes->Length < 1)) { cacheAccepted = false; return Compile(documentInfo, gcCode); } try { auto length = gcCacheBytes->Length; std::vector<std::uint8_t> cacheBytes(length); Marshal::Copy(gcCacheBytes, 0, (IntPtr)&cacheBytes[0], length); bool tempCacheAccepted; auto cacheType = (cacheKind == V8CacheKind::Parser) ? V8CacheType::Parser : V8CacheType::Code; auto gcScript = gcnew V8ScriptImpl(documentInfo, GetIsolate()->Compile(V8DocumentInfo(documentInfo), StdString(gcCode), cacheType, cacheBytes, tempCacheAccepted)); cacheAccepted = tempCacheAccepted; return gcScript; } catch (const V8Exception& exception) { exception.ThrowScriptEngineException(); } #pragma warning(pop) } //------------------------------------------------------------------------- V8RuntimeHeapInfo^ V8IsolateProxyImpl::GetHeapInfo() { V8IsolateHeapInfo heapInfo; GetIsolate()->GetHeapInfo(heapInfo); auto gcHeapInfo = gcnew V8RuntimeHeapInfo(); gcHeapInfo->TotalHeapSize = heapInfo.GetTotalHeapSize(); gcHeapInfo->TotalHeapSizeExecutable = heapInfo.GetTotalHeapSizeExecutable(); gcHeapInfo->TotalPhysicalSize = heapInfo.GetTotalPhysicalSize(); gcHeapInfo->UsedHeapSize = heapInfo.GetUsedHeapSize(); gcHeapInfo->HeapSizeLimit = heapInfo.GetHeapSizeLimit(); return gcHeapInfo; } //------------------------------------------------------------------------- void V8IsolateProxyImpl::CollectGarbage(bool exhaustive) { GetIsolate()->CollectGarbage(exhaustive); } //------------------------------------------------------------------------- SharedPtr<V8Isolate> V8IsolateProxyImpl::GetIsolate() { BEGIN_LOCK_SCOPE(m_gcLock) if (m_pspIsolate == nullptr) { throw gcnew ObjectDisposedException(ToString()); } return *m_pspIsolate; END_LOCK_SCOPE } //------------------------------------------------------------------------- V8IsolateProxyImpl::~V8IsolateProxyImpl() { SharedPtr<V8Isolate> spIsolate; BEGIN_LOCK_SCOPE(m_gcLock) if (m_pspIsolate != nullptr) { // hold V8 isolate for destruction outside lock scope spIsolate = *m_pspIsolate; delete m_pspIsolate; m_pspIsolate = nullptr; } END_LOCK_SCOPE if (!spIsolate.IsEmpty()) { GC::SuppressFinalize(this); } } //------------------------------------------------------------------------- V8IsolateProxyImpl::!V8IsolateProxyImpl() { if (m_pspIsolate != nullptr) { delete m_pspIsolate; m_pspIsolate = nullptr; } } //------------------------------------------------------------------------- int V8IsolateProxyImpl::AdjustConstraint(int value) { const int maxValueInMiB = 1024 * 1024; if (value > maxValueInMiB) { const double bytesPerMiB = 1024 * 1024; return Convert::ToInt32(Math::Ceiling(Convert::ToDouble(value) / bytesPerMiB)); } return value; } //------------------------------------------------------------------------- ENSURE_INTERNAL_CLASS(V8IsolateProxyImpl) }}}
32.557554
180
0.518064
erik-kallen
b979a03964c2aca974055e613d33e2aea288dd43
18,088
cpp
C++
hw1/sorting.cpp
aydayurtoglu/cs202_cpp
263ef1d1e30c2108c9848f89f98b663446da75b4
[ "MIT" ]
null
null
null
hw1/sorting.cpp
aydayurtoglu/cs202_cpp
263ef1d1e30c2108c9848f89f98b663446da75b4
[ "MIT" ]
null
null
null
hw1/sorting.cpp
aydayurtoglu/cs202_cpp
263ef1d1e30c2108c9848f89f98b663446da75b4
[ "MIT" ]
null
null
null
/* * Title: Sorting and Algorithm Efficiency * Author: Ayda Yurtoglu * ID: 21903153 * Section: 1 * Assignment: 1 * Description: Sorting source code */ #include "sorting.h" #include <iostream> #include <math.h> #include <cstdlib> #include <cstdio> #include <ctime> using namespace std; sorting::sorting() { //ctor } void sorting::selectionSort(int *arr, const int size, int &compCount, int &moveCount){ int comp = 0; int move = 0; for (int last = size-1; last >= 1; --last) { int indexSoFar = last+1; int indexOfmax = 0; // finding maximum for (int i = 1; i < indexSoFar; ++i){ if (arr[i] > arr[indexOfmax]){ indexOfmax = i; } comp++; } // swap operation int temp = arr[indexOfmax]; arr[indexOfmax] = arr[last]; arr[last] = temp; move+=3; // swap operation has 3 data moves } compCount = comp; moveCount = move; } void sorting::mergeSort(int *arr, const int size, int &compCount, int &moveCount){ int comp = 0; int move = 0; mergeSort2(arr, 0, size-1, comp, move); compCount = comp; moveCount = move; } void sorting::mergeSort2(int *arr, int first, int last, int &compCount, int &moveCount){ if (first < last) { int mid = (first + last)/2; mergeSort2(arr, first, mid, compCount, moveCount); mergeSort2(arr, mid+1, last, compCount, moveCount); merge(arr, first, mid, last, compCount, moveCount); } } void sorting::merge( int *arr, int first, int mid, int last, int &compCount, int &moveCount) { int tempArray[last+1]; int first1 = first; int last1 = mid; int first2 = mid + 1; int last2 = last; int index = first1; for ( ; (first1 <= last1) && (first2 <= last2); ++index) { if (arr[first1] < arr[first2]) { tempArray[index] = arr[first1]; ++first1; } else { tempArray[index] = arr[first2]; ++first2; } compCount++; moveCount++; } // finish off the first subarray, if necessary for (; first1 <= last1; ++first1, ++index){ tempArray[index] = arr[first1]; moveCount++; } // finish off the second subarray, if necessary for (; first2 <= last2; ++first2, ++index){ tempArray[index] = arr[first2]; moveCount++; } // copy the result back into the original array for (index = first; index <= last; ++index){ arr[index] = tempArray[index]; moveCount++; } } void sorting::quickSort(int *arr, const int size, int &compCount, int &moveCount){ int comp = 0; int move = 0; quickSort2(arr, 0, size-1, comp, move); compCount = comp; moveCount = move; } void sorting::quickSort2(int *arr, int first, int last, int &compCount, int &moveCount){ int pivotIndex; if (first < last) { partition(arr, first, last, pivotIndex,compCount, moveCount); quickSort2(arr, first, pivotIndex-1, compCount, moveCount); quickSort2(arr, pivotIndex+1, last, compCount, moveCount); } } void sorting::partition(int *arr, int first, int last, int &pivotIndex, int &compCount, int &moveCount) { int pivot = arr[first]; moveCount++; int lastS1 = first; int firstUnknown = first + 1; for ( ; firstUnknown <= last; ++firstUnknown) { if (arr[firstUnknown] < pivot) { ++lastS1; swap(arr[firstUnknown], arr[lastS1], moveCount); } compCount++; } swap(arr[first], arr[lastS1], moveCount); pivotIndex = lastS1; } void sorting::swap(int &x, int &y, int &moveCount) { int temp = x; x = y; y = temp; moveCount+=3; } void sorting::radixSort(int *arr, const int size){ // find the maximum element of the array int max = arr[0]; for (int i = 0; i < size; i++){ if (arr[i] > max){ max = arr[i]; } } // calculate its digit number int digitNo = log10(max)+1; radixSort2(arr, size, digitNo); } void sorting::radixSort2(int *arr, const int size, int digitNo){ for (int i = 1; i <= digitNo; i++) { // Initialize 10 groups to empty int groups[10][size]; int counter[10]; // Initialize each counter with 0 for (int j = 0; j < 10; j++){ counter[j] = 0; for ( int k = 0; k < size; k++){ groups[j][k] = 0; } } for (int a = 0; a < size; a++){ int k = 0; if (i == 1){ k = arr[a]%10; } else{ k = arr[a]/pow(10,i-1); k = k % pow(10,i-1); } if (k > 9){ groups[0][counter[0]] = arr[a]; counter[0] = counter[0] + 1; } else { groups[k][counter[k]] = arr[a]; counter[k] = counter[k] + 1; } } int index = 0; for(int b = 0; b < 10;b++){ for(int c = 0; c < counter[b]; c++) { arr[index] = groups[b][c]; index++; } } } } int sorting::pow(int a, int b){ // integer based power int result = 1; if(b == 0) return 1; for( int i = 0; i < b; i++){ result = result * a; } return result; } void sorting::displayArray(const int *arr, const int size){ cout << "{ "; for (int i = 0; i < size-1; i++){ cout << arr[i] << ", "; } cout << arr[size-1] << " }" << endl; } void sorting::createRandomArrays(int *&arr1, int *&arr2, int *&arr3, int *&arr4, const int size){ delete []arr1; delete []arr2; delete []arr3; delete []arr4; arr1 = new int[size]; arr2 = new int[size]; arr3 = new int[size]; arr4 = new int[size]; for (int i = 0; i < size; i++){ int random = rand() % size; // in the range 0 to array size arr1[i] = random; arr2[i] = random; arr3[i] = random; arr4[i] = random; } } void sorting::createAscendingArrays(int *&arr1, int *&arr2, int *&arr3, int *&arr4, const int size){ int *temp = new int[size]; delete []arr1; delete []arr2; delete []arr3; delete []arr4; arr1 = new int[size]; arr2 = new int[size]; arr3 = new int[size]; arr4 = new int[size]; for (int i = 0; i < size; i++){ int random = rand() % size; // in the range 0 to array size temp[i] = random; } int a = 0; mergeSort( temp, size, a, a); for (int i = 0; i < size; i++){ arr1[i] = temp[i]; arr2[i] = temp[i]; arr3[i] = temp[i]; arr4[i] = temp[i]; } delete []temp; } void sorting::createDescendingArrays(int *&arr1, int *&arr2, int *&arr3, int *&arr4, const int size){ int *temp = new int[size]; delete []arr1; delete []arr2; delete []arr3; delete []arr4; arr1 = new int[size]; arr2 = new int[size]; arr3 = new int[size]; arr4 = new int[size]; for (int i = 0; i < size; i++){ int random = rand() % size; // in the range 0 to array size temp[i] = random; } int a = 0; mergeSort( temp, size, a, a); for (int i = 0; i < size; i++){ arr1[i] = temp[size-i-1]; arr2[i] = temp[size-i-1]; arr3[i] = temp[size-i-1]; arr4[i] = temp[size-i-1]; } delete []temp; } void sorting::performanceAnalysis(){ int sizes[7] = {6000,10000,14000,18000,22000,26000,30000}; int size = 0; double sortTime1[7], sortTime2[7], sortTime3[7], sortTime4[7]; int compSelection[7], moveSelection[7], compMerge[7], moveMerge[7], compQuick[7], moveQuick[7]; cout << endl; cout << "RANDOM ARRAYS " << endl; for (int i = 0; i < 7; i++){ size = sizes[i]; int compCount = 0; int moveCount = 0; double elapsedTime; int *arr1 = new int[size]; int *arr2 = new int[size]; int *arr3 = new int[size]; int *arr4 = new int[size]; createRandomArrays(arr1, arr2, arr3, arr4, size); clock_t startTime = clock(); selectionSort(arr1, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime1[i] = elapsedTime; compSelection[i] = compCount; moveSelection[i] = moveCount; elapsedTime = 0; startTime = clock(); mergeSort(arr2, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime2[i] = elapsedTime; compMerge[i] = compCount; moveMerge[i] = moveCount; elapsedTime = 0; startTime = clock(); quickSort(arr3, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime3[i] = elapsedTime; compQuick[i] = compCount; moveQuick[i] = moveCount; elapsedTime = 0; startTime = clock(); radixSort(arr4, size); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime4[i] = elapsedTime; delete []arr1; delete []arr2; delete []arr3; delete []arr4; } cout << "-----------------------------------------------------" << endl; cout << "Analysis of Selection Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime1[i] << " ms " << compSelection[i] << " " << moveSelection[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Merge Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime2[i] << " ms " << compMerge[i] << " " << moveMerge[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Quick Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime3[i] << " ms " << compQuick[i] << " " << moveQuick[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Radix Sort" << endl; cout << "Array Size " << "Elapsed Time " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime4[i] << " ms"<< endl; } cout << endl; cout << "ASCENDING ARRAYS " << endl; for (int i = 0; i < 7; i++){ size = sizes[i]; int compCount = 0; int moveCount = 0; double elapsedTime = 0; int *arr1 = new int[size]; int *arr2 = new int[size]; int *arr3 = new int[size]; int *arr4 = new int[size]; createAscendingArrays(arr1, arr2, arr3, arr4, size); clock_t startTime = clock(); selectionSort(arr1, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime1[i] = elapsedTime; compSelection[i] = compCount; moveSelection[i] = moveCount; elapsedTime = 0; startTime = clock(); mergeSort(arr2, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime2[i] = elapsedTime; compMerge[i] = compCount; moveMerge[i] = moveCount; elapsedTime = 0; startTime = clock(); quickSort(arr3, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime3[i] = elapsedTime; compQuick[i] = compCount; moveQuick[i] = moveCount; elapsedTime = 0; startTime = clock(); radixSort(arr4, size); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime4[i] = elapsedTime; delete []arr1; delete []arr2; delete []arr3; delete []arr4; } cout << "-----------------------------------------------------" << endl; cout << "Analysis of Selection Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime1[i] << " ms " << compSelection[i] << " " << moveSelection[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Merge Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime2[i] << " ms " << compMerge[i] << " " << moveMerge[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Quick Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime3[i] << " ms " << compQuick[i] << " " << moveQuick[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Radix Sort" << endl; cout << "Array Size " << "Elapsed Time " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime4[i] << " ms" << endl; } cout << endl; cout << "DESCENDING ARRAYS " << endl; for (int i = 0; i < 7; i++){ size = sizes[i]; int compCount = 0; int moveCount = 0; double elapsedTime = 0; int *arr1 = new int[size]; int *arr2 = new int[size]; int *arr3 = new int[size]; int *arr4 = new int[size]; createDescendingArrays(arr1, arr2, arr3, arr4, size); clock_t startTime = clock(); selectionSort(arr1, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime1[i] = elapsedTime; compSelection[i] = compCount; moveSelection[i] = moveCount; elapsedTime = 0; startTime = clock(); mergeSort(arr2, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime2[i] = elapsedTime; compMerge[i] = compCount; moveMerge[i] = moveCount; elapsedTime = 0; startTime = clock(); quickSort(arr3, size, compCount, moveCount); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime3[i] = elapsedTime; compQuick[i] = compCount; moveQuick[i] = moveCount; elapsedTime = 0; startTime = clock(); radixSort(arr4, size); elapsedTime = 1000 * double( clock() - startTime ) / CLOCKS_PER_SEC; sortTime4[i] = elapsedTime; delete []arr1; delete []arr2; delete []arr3; delete []arr4; } cout << "-----------------------------------------------------" << endl; cout << "Analysis of Selection Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime1[i] << " ms " << compSelection[i] << " " << moveSelection[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Merge Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime2[i] << " ms " << compMerge[i] << " " << moveMerge[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Quick Sort" << endl; cout << "Array Size " << "Elapsed Time " << "compCount " << "moveCount " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime3[i] << " ms " << compQuick[i] << " " << moveQuick[i] << endl; } cout << endl; cout << "-----------------------------------------------------" << endl; cout << "Analysis of Radix Sort" << endl; cout << "Array Size " << "Elapsed Time " << endl; for (int i = 0; i < 7; i++){ cout << sizes[i] << " " << sortTime4[i] << " ms" << endl; } }
31.079038
152
0.460084
aydayurtoglu
b98495b8db9184bc2d81cd389b9d1b35015a341f
264
hpp
C++
NWNXLib/API/Mac/API/CExoLinkedListTemplatedCRes.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
NWNXLib/API/Mac/API/CExoLinkedListTemplatedCRes.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/CExoLinkedListTemplatedCRes.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once #include <cstdint> namespace NWNXLib { namespace API { // Forward class declarations (defined in the source file) struct CExoLinkedListInternal; struct CExoLinkedListTemplatedCRes { CExoLinkedListInternal* m_pcExoLinkedListInternal; }; } }
13.2
58
0.780303
acaos
b9856f98d498dde495d461c436e1dce8a65d089f
772
cpp
C++
src/uarttest.cpp
ASM-Advised-Projects/rasm-software
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
[ "MIT" ]
3
2019-10-31T15:04:35.000Z
2021-06-24T16:35:18.000Z
src/uarttest.cpp
ASM-Advised-Projects/rasm-software
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
[ "MIT" ]
null
null
null
src/uarttest.cpp
ASM-Advised-Projects/rasm-software
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
[ "MIT" ]
2
2019-02-26T20:41:15.000Z
2019-05-14T01:40:40.000Z
#include <iostream> #include <string> #include "c-periphery/serial.h" using std::string; using std::cout; using std::cin; using std::endl; int main(int argc, char **argv) { serial_t uartport1; std::string device_file_1 = "/dev/ttyO1"; int baudrate = 115200; int result1 = serial_open(&uartport1, device_file_1.c_str(), baudrate); cout << "uart port result: " << result1 << endl; char sendbuf[10]; sendbuf[0] = 'p'; int sendlen = 1; char recvbuf[10]; int recvlen = 1; while (true) { serial_write(&uartport1, (const uint8_t *)sendbuf, sendlen); serial_flush(&uartport1); recvbuf[0] = 'n'; int bytesread = serial_read(&uartport2, (uint8_t *)recvbuf, recvlen, 100); cout << bytesread << ", " << recvbuf[0] << endl; } }
19.3
78
0.642487
ASM-Advised-Projects
b98bc1d5d3df2cca03e5143dcdd187d29fdd4fb5
4,420
cpp
C++
SMACOF.cpp
LiliamPumpernickel/DAMIS
51369f27ad907b21548bccd6ad184e2e2858e707
[ "Apache-2.0" ]
1
2018-05-13T11:42:44.000Z
2018-05-13T11:42:44.000Z
SMACOF.cpp
LiliamPumpernickel/DAMIS
51369f27ad907b21548bccd6ad184e2e2858e707
[ "Apache-2.0" ]
null
null
null
SMACOF.cpp
LiliamPumpernickel/DAMIS
51369f27ad907b21548bccd6ad184e2e2858e707
[ "Apache-2.0" ]
1
2018-05-01T16:53:27.000Z
2018-05-01T16:53:27.000Z
/////////////////////////////////////////////////////////// // SMACOF.cpp // Implementation of the Class SMACOF // Created on: 07-Lie-2013 20:07:32 // Original author: Povilas /////////////////////////////////////////////////////////// /*! \class SMACOF \brief A class of methods and attributes for SMACOF algorithm. */ #include "SMACOF.h" #include "ShufleObjects.h" #include <string> #include <sstream> #include <vector> #include "DataObject.h" #include <float.h> #include <cmath> #include <iostream> #include "AdditionalMethods.h" #include "DistanceMetrics.h" SMACOF::SMACOF() { } SMACOF::~SMACOF() { } SMACOF::SMACOF(double eps, int maxIter, int d):MDS(eps, maxIter, d) { X = ObjectMatrix(AdditionalMethods::inputDataFile); X.loadDataMatrix(); readFile = true; int m = X.getObjectCount(); gutman = ObjectMatrix(m); std::vector<double> gutmanRow; gutmanRow.resize(m, 0); for (int i = 0; i < m; i++) gutman.addObject(DataObject(gutmanRow)); initializeProjectionMatrix(); } SMACOF::SMACOF(double eps, int maxIter, int d, ObjectMatrix X_base, ObjectMatrix Y_base):MDS(eps, maxIter, d) { X = X_base; readFile = false; int m = X.getObjectCount(); gutman = ObjectMatrix(m); std::vector<double> gutmanRow; gutmanRow.resize(m, 0); for (int i = 0; i < m; i++) gutman.addObject(DataObject(gutmanRow)); Y = Y_base; } /*SMACOF::SMACOF(ObjectMatrix initialY, double eps, int maxIter, int d):MDS(eps, maxIter, d){ Y = initialY; }*/ SMACOF::SMACOF(double eps, int maxIter, int d, ObjectMatrix initialX):MDS(eps, maxIter, d) { X = initialX; readFile = false; int m = X.getObjectCount(); gutman = ObjectMatrix(m); std::vector<double> gutmanRow; gutmanRow.resize(m, 0); for (int i = 0; i < m; i++) gutman.addObject(DataObject(gutmanRow)); // Y = Y_base; initializeProjectionMatrix(); } ObjectMatrix SMACOF::getProjection() { stressErrors.reserve(maxIteration); int iteration = 0; int m = X.getObjectCount(); //double str = getStress(); stressErrors.push_back(getStress()); double sum = 0.0; double Epsilon = DBL_MAX; // ObjectMatrix Gutman; ObjectMatrix Y_new(m); ObjectMatrix Y_loc = Y; // runs faster if have local copy of Y matrix std::vector<double> Y_newRow; Y_newRow.reserve(d); DataObject obj1; while (iteration < maxIteration && Epsilon > epsilon) { Y_new.clearDataObjects(); gutman = getGutman(); for (int i = 0; i < m; i++) { Y_newRow.clear(); obj1 = gutman.getObjectAt(i); for (int j = 0; j < d; j++) { sum = 0.0; for (int k = 0; k < m; k++) sum += obj1.getFeatureAt(k) * Y_loc.getObjectAt(k).getFeatureAt(j); //get from local copy Y_newRow.push_back(sum / (float) m); } Y_new.addObject(DataObject(Y_newRow), X.getObjectAt(i).getClassLabel()); } Y = Y_new; Y_loc = Y; //str = getStress(); stressErrors.push_back(getStress()); iteration++; Epsilon = std::fabs(stressErrors.at(iteration - 1) - stressErrors.at(iteration)); // std::cout << iteration << " " << Epsilon << " " << str << std::endl; } Y.setPrintClass(X.getStringClassAttributes()); return Y; } double SMACOF::getStress() { if (readFile) //depends if it was standalone run or was called from relative MDS method return DimReductionMethod::getStress(); else { double stress = 0.0, weight= 0.0; int m = X.getObjectCount(); double distX = 0.0; double distY = 0.0; double tmp; DataObject objXi, objYi; for (int i = 0; i < m - 1; i++) { objXi = X.getObjectAt(i); objYi = Y.getObjectAt(i); for (int j = i + 1; j < m; j++) { distX = DistanceMetrics::getDistance(objXi, X.getObjectAt(j), EUCLIDEAN); distY = DistanceMetrics::getDistance(objYi, Y.getObjectAt(j), EUCLIDEAN); tmp = distX - distY; stress += tmp * tmp; weight += distX * distX; } } return stress / weight; } } /*ObjectMatrix SMACOF::getGutmanMatrix() { return MDS::getGutman(); }*/
26.787879
109
0.567195
LiliamPumpernickel
b98c41aaddf198e3a1d4bf159fe816f692609ac1
1,018
cpp
C++
codes/hpc/malloc/malloc03/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
3
2022-01-25T07:33:43.000Z
2022-03-30T10:25:09.000Z
codes/hpc/malloc/malloc03/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
null
null
null
codes/hpc/malloc/malloc03/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
2
2022-01-17T13:39:12.000Z
2022-03-30T10:25:12.000Z
#include <omp.h> #include <benchmark/benchmark.h> #include <iostream> #include <vector> #include <chrono> typedef std::chrono::high_resolution_clock Clock; #define TIME_BEGIN(x) auto clock_time_##x = Clock::now(); #define TIME_END(x) { auto curr_time = Clock::now(); \ auto dt = curr_time - clock_time_##x; \ std::cout << #x ": " \ << std::chrono::duration_cast<std::chrono::nanoseconds>(dt).count() << " ns " \ << std::chrono::duration_cast<std::chrono::microseconds>(dt).count() << " micros " \ << std::chrono::duration_cast<std::chrono::milliseconds>(dt).count() << " ms " \ << std::endl; } constexpr size_t n = 1<<29; int main(int argc, char** argv) { int *arr = (int *)malloc(n * sizeof(int)); TIME_BEGIN(write_first); for ( size_t i = 0; i < n; ++ i ) { arr[i] = 1; } TIME_END(write_first); TIME_BEGIN(write_second); for ( size_t i = 0; i < n; ++ i ) { arr[i] = 1; } TIME_END(write_second); free(arr); return 0; }
27.513514
85
0.587426
eric2003
b98f2a8a88298873b0e701b53b7321efa1a70d6f
8,087
cpp
C++
game/state/tilemap/tileobject_vehicle.cpp
trevortomesh/OpenApoc
53cd163889fbfd21a9c128183427dad4255ac1a3
[ "MIT" ]
1
2019-11-19T11:41:36.000Z
2019-11-19T11:41:36.000Z
game/state/tilemap/tileobject_vehicle.cpp
FilmBoy84/OpenApoc_FB84
a6b69cafba01744998ced6c67b93fbd937d32d26
[ "MIT" ]
null
null
null
game/state/tilemap/tileobject_vehicle.cpp
FilmBoy84/OpenApoc_FB84
a6b69cafba01744998ced6c67b93fbd937d32d26
[ "MIT" ]
null
null
null
#ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include "game/state/tilemap/tileobject_vehicle.h" #include "framework/renderer.h" #include "game/state/city/vehicle.h" #include "game/state/city/vehiclemission.h" #include "game/state/rules/city/vehicletype.h" #include "game/state/tilemap/tilemap.h" #include "library/voxel.h" #include <glm/glm.hpp> #include <glm/gtx/vector_angle.hpp> namespace OpenApoc { void TileObjectVehicle::draw(Renderer &r, TileTransform &transform, Vec2<float> screenPosition, TileViewMode mode, bool visible, int currentLevel, bool friendly, bool hostile) { auto vehicle = this->vehicle.lock(); if (!vehicle) { LogError("Called with no owning vehicle object"); return; } drawStatic(r, vehicle, transform, screenPosition, mode, visible, currentLevel, friendly, hostile); } void TileObjectVehicle::drawStatic(Renderer &r, sp<Vehicle> vehicle, TileTransform &transform, Vec2<float> screenPosition, TileViewMode mode, bool, int, bool friendly, bool hostile) { static const Colour COLOUR_TRANSPARENT = {255, 255, 255, 95}; static const Colour COLOUR_STUNNED = {128, 128, 255, 255}; static const int offset_arrow = 5; static const int offset_large = 1; static const std::map<float, int> offset_dir_map = { {0.0f, 0}, {0.25f * (float)M_PI, 1}, {0.5f * (float)M_PI, 2}, {0.75f * (float)M_PI, 3}, {(float)M_PI, 4}, {1.25f * (float)M_PI, 5}, {1.5f * (float)M_PI, 6}, {1.75f * (float)M_PI, 7}, }; std::ignore = transform; switch (mode) { case TileViewMode::Isometric: { float closestAngle = FLT_MAX; sp<Image> closestImage; if (vehicle->type->type == VehicleType::Type::UFO) { if (vehicle->crashed) { closestImage = vehicle->type->crashed_sprite; } else { closestImage = *vehicle->animationFrame; } } else { closestImage = vehicle->type->directional_sprites.at(vehicle->banking).at(vehicle->direction); } if (!closestImage) { LogError("No image found for vehicle"); return; } if (vehicle->isCloaked()) { r.drawTinted(closestImage, screenPosition - vehicle->type->image_offset, COLOUR_TRANSPARENT); } else if (vehicle->stunTicksRemaining > 0) { r.drawTinted(closestImage, screenPosition - vehicle->type->image_offset, COLOUR_STUNNED); } else { r.draw(closestImage, screenPosition - vehicle->type->image_offset); } break; } case TileViewMode::Strategy: { float closestDiff = FLT_MAX; int facing_offset = 0; for (auto &p : offset_dir_map) { float d1 = p.first - vehicle->facing; if (d1 < 0.0f) { d1 += 2.0f * (float)M_PI; } float d2 = vehicle->facing - p.first; if (d2 < 0.0f) { d2 += 2.0f * (float)M_PI; } float diff = std::min(d1, d2); if (diff < closestDiff) { closestDiff = diff; facing_offset = p.second; } } // 1 = friendly, 0 = enemy, 2 = neutral int side_offset = friendly ? 1 : (hostile ? 0 : 2); switch (vehicle->type->mapIconType) { case VehicleType::MapIconType::Arrow: r.draw(vehicle->strategyImages->at(side_offset * 14 + offset_arrow + facing_offset), screenPosition - Vec2<float>{4, 4}); break; case VehicleType::MapIconType::SmallCircle: r.draw(vehicle->strategyImages->at(side_offset * 14), screenPosition - Vec2<float>{4, 4}); break; case VehicleType::MapIconType::LargeCircle: r.draw(vehicle->strategyImages->at(side_offset * 14 + offset_large + 0), screenPosition - Vec2<float>{8.0f, 8.0f}); r.draw(vehicle->strategyImages->at(side_offset * 14 + offset_large + 1), screenPosition - Vec2<float>{0.0f, 8.0f}); r.draw(vehicle->strategyImages->at(side_offset * 14 + offset_large + 2), screenPosition - Vec2<float>{8.0f, 0.0f}); r.draw(vehicle->strategyImages->at(side_offset * 14 + offset_large + 3), screenPosition - Vec2<float>{0.0f, 0.0f}); break; } break; } default: LogError("Unsupported view mode"); } } TileObjectVehicle::~TileObjectVehicle() = default; TileObjectVehicle::TileObjectVehicle(TileMap &map, sp<Vehicle> vehicle) : TileObject(map, Type::Vehicle, {0.0f, 0.0f, 0.0f}), vehicle(vehicle) { } Vec3<float> TileObjectVehicle::getVoxelCentrePosition() const { // We could do all the following, but since we always aim at voxelmap's center, // regardless of which bits are filled or not (only accounting for height) // it is enough to just offset center according to voxelmap's height // Leaving the code here though as it may be useful later /* auto vtype = this->getVehicle()->type; auto facing = vtype->getVoxelMapFacing(getDirection()); auto size = vtype->size.at(facing); Vec3<int> voxelCentre = {0, 0, 0}; for (int x = 0; x < size.x; x++) { for (int y = 0; y < size.y; y++) { for (int z = 0; z < size.z; z++) { voxelCentre += getVoxelMap({x, y, z})->centre; } } } voxelCentre /= size.x * size.y * size.z; auto objPos = this->getCenter(); objPos -= this->getVoxelOffset(); return Vec3<float>(objPos.x + (float)voxelCentre.x / map.voxelMapSize.x, objPos.y + (float)voxelCentre.y / map.voxelMapSize.y, objPos.z + (float)voxelCentre.z / map.voxelMapSize.z); */ // Simple version: auto objPos = this->getCenter(); auto v = getVehicle(); // Fire at crashed's top or ground's centre if (v->crashed || v->type->isGround()) { return Vec3<float>(objPos.x, objPos.y, objPos.z + (float)v->type->height / 2.0f / 16.0f); } // Fire at flyer's centre else { return Vec3<float>(objPos.x, objPos.y, objPos.z); } } sp<VoxelMap> TileObjectVehicle::getVoxelMap(Vec3<int> mapIndex, bool los) const { auto v = this->getVehicle(); auto vtype = v->type; auto facing = vtype->getVoxelMapFacing(v->facing); auto size = vtype->size.at(facing); if (mapIndex.x >= size.x || mapIndex.y >= size.y || mapIndex.z >= size.z) { return nullptr; } // Crashed vehicles have proper voxel models if (los || v->crashed) { return vtype->voxelMapsLOS.at(facing).at(mapIndex.z * size.y * size.x + mapIndex.y * size.x + mapIndex.x); } else { return vtype->voxelMaps.at(facing).at(mapIndex.z * size.y * size.x + mapIndex.y * size.x + mapIndex.x); } } sp<Vehicle> TileObjectVehicle::getVehicle() const { return this->vehicle.lock(); } Vec3<float> TileObjectVehicle::getPosition() const { auto v = this->vehicle.lock(); if (!v) { LogError("Called with no owning vehicle object"); return {0, 0, 0}; } return v->getPosition(); } void TileObjectVehicle::setPosition(Vec3<float> newPosition) { auto v = this->getVehicle(); auto vtype = v->type; auto facing = vtype->getVoxelMapFacing(v->facing); auto size = vtype->size.at(facing); setBounds({size.x, size.y, size.z}); TileObject::setPosition(newPosition); } void TileObjectVehicle::addToDrawnTiles(Tile *tile) { auto v = getVehicle(); if (!v) { return; } Vec3<int> maxCoords = {-1, -1, -1}; for (auto &intersectingTile : intersectingTiles) { int x = intersectingTile->position.x; int y = intersectingTile->position.y; int z = intersectingTile->position.z; // Vehicles are drawn in the topmost tile they intersect if (maxCoords.z * 1000 + maxCoords.x + maxCoords.y < z * 1000 + x + y) { tile = intersectingTile; maxCoords = {x, y, z}; } } // Vehicles are also never drawn below level 1, so that when they take off they're drawn above // landing pad's scenery if (!v->missions.empty() && v->missions.front()->isTakingOff(*v)) { tile = map.getTile(tile->position.x, tile->position.y, tile->position.z + 1); } TileObject::addToDrawnTiles(tile); } } // namespace OpenApoc
27.886207
95
0.628292
trevortomesh
b98f3342c4a2b067eb6ee1a7825ba15e8f869183
4,415
cpp
C++
modules/monkey/native/bbgc.cpp
nitrologic/monkey2-pi
a46ce707a68657afeee3fac4ee71c73024450b32
[ "Zlib" ]
1
2019-01-19T06:13:24.000Z
2019-01-19T06:13:24.000Z
modules/monkey/native/bbgc.cpp
nitrologic/monkey2
a46ce707a68657afeee3fac4ee71c73024450b32
[ "Zlib" ]
null
null
null
modules/monkey/native/bbgc.cpp
nitrologic/monkey2
a46ce707a68657afeee3fac4ee71c73024450b32
[ "Zlib" ]
null
null
null
//v1001 #include <utility> #include "bbgc.h" // For testing only... // #define BBGC_DISABLED 1 //For future ref... #if BB_THREADED //fast but unpredictable //#define BBGC_LOCK while( bbGC::spinlock.test_and_set( std::memory_order_acquire ) ) std::this_thread::yield(); //#define BBGC_UNLOCK bbGC::spinlock.clear( std::memory_order_release ); //pretty slow... //#define BBGC_LOCK bbGC::mutex.lock(); //#define BBGC_UNLOCK bbGC::mutex.unlock(); //better...a 'Benaphore' apparently... #define BBGC_LOCK \ if( ++bbGC::locks>1 ){ \ std::unique_lock<std::mutex> lock( bbGC::mutex ); \ bbGC::cond_var.wait( lock,[]{ return bbGC::sem_count>0;} ); \ --bbGC::sem_count; \ } #define BBGC_UNLOCK \ if( --bbGC::locks>0 ){ \ std::unique_lock<std::mutex> lock( bbGC::mutex ); \ ++bbGC::sem_count; \ bbGC::cond_var.notify_one(); \ } int sem_count; std::mutex mutex; std::atomic_int locks; std::condition_variable cond_var; std::atomic_flag spinlock=ATOMIC_FLAG_INIT; #endif namespace bbGC{ int markedBit; int unmarkedBit; bbGCNode *markQueue; bbGCNode *markedList; bbGCNode *unmarkedList; bbGCRoot *roots; bbGCFiber *fibers; bbGCFiber *currentFiber; bbGCNode markLists[2]; bbGCNode freeList; size_t markedBytes; size_t unmarkedBytes; size_t allocedBytes; void init(){ static bool done; if( done ) return; done=true; markedBit=1; markedList=&markLists[0]; markedList->succ=markedList->pred=markedList; unmarkedBit=2; unmarkedList=&markLists[1]; unmarkedList->succ=unmarkedList->pred=unmarkedList; freeList.succ=freeList.pred=&freeList; fibers=new bbGCFiber; currentFiber=fibers; } void destroy( bbGCNode *p ){ // printf( "destroying: %s %p\n",p->typeName(),p ); #if BBGC_DEBUG p->flags=3; #else p->~bbGCNode(); bbFree( p ); #endif } void reclaim( size_t size=0x7fffffff ){ while( freeList.succ!=&freeList ){ bbGCNode *p=freeList.succ; size_t psize=bbMallocSize( p ); remove( p ); destroy( p ); if( psize>=size ) break; size-=psize; } } void mark( bbGCNode *p ){ if( !p || p->flags==markedBit ) return; remove( p ); insert( p,markedList ); p->flags=markedBit; markedBytes+=bbMallocSize( p ); p->gcMark(); } void markRoots(){ for( bbGCRoot *root=roots;root;root=root->succ ){ root->gcMark(); } } void markFrames(){ bbGCFiber *fiber=fibers; for(;;){ for( bbGCFrame *frame=fiber->frames;frame;frame=frame->succ ){ frame->gcMark(); } for( bbGCNode *node=fiber->ctoring;node;node=node->succ ){ node->gcMark(); } fiber=fiber->succ; if( fiber==fibers ) break; } } void markQueued( size_t tomark=0x7fffffff ){ while( markQueue && markedBytes<tomark ){ bbGCNode *p=markQueue; markQueue=p->succ; insert( p,markedList ); markedBytes+=bbMallocSize( p ); // printf( "marking %s\n",p->typeName() );fflush( stdout ); p->gcMark(); } } void sweep(){ // puts( "bbGC::sweep()" );fflush( stdout ); markFrames(); markQueued(); if( unmarkedList->succ!=unmarkedList ){ //append unmarked to end of free queue unmarkedList->succ->pred=freeList.pred; unmarkedList->pred->succ=&freeList; freeList.pred->succ=unmarkedList->succ; freeList.pred=unmarkedList->pred; //clear unmarked unmarkedList->succ=unmarkedList->pred=unmarkedList; } std::swap( markedList,unmarkedList ); std::swap( markedBit,unmarkedBit ); unmarkedBytes=markedBytes; markedBytes=0; allocedBytes=0; markRoots(); } bbGCNode *alloc( size_t size ){ #ifndef BBGC_DISABLED if( allocedBytes>=BBGC_TRIGGER ){ sweep(); #if BBGC_AGGRESSIVE reclaim(); #endif }else{ #if BBGC_INCREMENTAL // size_t tomark=double( allocedBytes ) / double( BBGC_TRIGGER ) * double( unmarkedBytes + allocedBytes ); size_t tomark=double( allocedBytes ) / double( BBGC_TRIGGER ) * double( unmarkedBytes + BBGC_TRIGGER ); markQueued( tomark ); #endif } #endif bbGCNode *p=(bbGCNode*)bbMalloc( size ); *((void**)p)=(void*)0xcafebabe; p->flags=0; size=bbMallocSize( p ); allocedBytes+=size; #if !BBGC_AGGRESSIVE reclaim( size ); #endif return p; } void collect(){ sweep(); reclaim(); // printf( "GCCollect: in use=%i\n",(int)unmarkedBytes );fflush( stdout ); } }
17.112403
112
0.644621
nitrologic
b98ff2e92c21fbe33db68281a908c406de1cc056
1,061
cpp
C++
test/AnyCallSignature.cpp
thecppzoo/zoo
6b82e4ba4ca30cd8a71404f2dec946e3bac9e52f
[ "MIT" ]
32
2018-10-23T16:48:00.000Z
2022-03-25T04:09:32.000Z
test/AnyCallSignature.cpp
thecppzoo/zoo
6b82e4ba4ca30cd8a71404f2dec946e3bac9e52f
[ "MIT" ]
7
2018-11-12T19:54:46.000Z
2020-06-30T21:40:48.000Z
test/AnyCallSignature.cpp
thecppzoo/zoo
6b82e4ba4ca30cd8a71404f2dec946e3bac9e52f
[ "MIT" ]
4
2017-09-02T16:53:00.000Z
2020-12-14T09:10:51.000Z
// // AnyCallSignature.cpp // // Created by Eduardo Madrid on 7/22/19. // #include "zoo/AnyCallSignature.h" #include "zoo/FunctionPolicy.h" #include "zoo/AnyContainer.h" #include "catch2/catch.hpp" int doubler(int a) { return 2*a; } int multiply(int f1, int f2) { return f1*f2; } TEST_CASE("AnyCallSignature", "[any][type-erasure][functional][undefined-behavior]") { using Canonical = zoo::AnyContainer< //zoo::RuntimePolymorphicAnyPolicy<sizeof(void *), alignof(void *)> zoo::Policy<void *, zoo::Destroy, zoo::Move, zoo::Copy> >; using ACS = zoo::AnyCallSignature<Canonical>; ACS acs(std::in_place_type<int(int)>, doubler); SECTION("Calling") { CHECK(6 == acs.as<int(int)>()(3)); } SECTION("Constructing from an existing value") { ACS copy(acs); CHECK(8 == copy.as<int(int)>()(4)); } SECTION("Rebinding, to a different signature") { acs = ACS(std::in_place_type<int(int, int)>, multiply); CHECK(15 == acs.as<int(int, int)>()(3, 5)); } }
28.675676
86
0.611687
thecppzoo
b995ac9c841ecaf9ec401609699e7e769d71c437
4,585
cpp
C++
test/opengl/select.cpp
jwitz54/Halide-2016-HLS
dd95daab3a7c871dd2f15c514912e21fb3c2bb7c
[ "MIT" ]
4
2020-08-02T18:41:31.000Z
2021-12-30T07:29:45.000Z
test/opengl/select.cpp
jwitz54/Halide-2016-HLS
dd95daab3a7c871dd2f15c514912e21fb3c2bb7c
[ "MIT" ]
null
null
null
test/opengl/select.cpp
jwitz54/Halide-2016-HLS
dd95daab3a7c871dd2f15c514912e21fb3c2bb7c
[ "MIT" ]
1
2020-07-10T16:00:39.000Z
2020-07-10T16:00:39.000Z
#include "Halide.h" #include <stdio.h> #include <stdlib.h> using namespace Halide; int test_per_channel_select() { // This test must be run with an OpenGL target. const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL); Func gpu("gpu"), cpu("cpu"); Var x("x"), y("y"), c("c"); gpu(x, y, c) = cast<uint8_t>(select(c == 0, 128, c == 1, x, c == 2, y, x*y)); gpu.bound(c, 0, 4); gpu.glsl(x, y, c); gpu.compute_root(); cpu(x, y, c) = gpu(x, y, c); Image<uint8_t> out(10, 10, 4); cpu.realize(out, target); // Verify the result for (int y=0; y!=out.height(); ++y) { for (int x=0; x!=out.width(); ++x) { for (int c=0; c!=out.channels(); ++c) { uint8_t expected; switch (c) { case 0: expected = 128; break; case 1: expected = x; break; case 2: expected = y; break; default: expected = x*y; break; } uint8_t actual = out(x,y,c); if (expected != actual) { fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n", out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3), x, y); return 1; } } } } return 0; } int test_flag_scalar_select() { // This test must be run with an OpenGL target. const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL); Func gpu("gpu"), cpu("cpu"); Var x("x"), y("y"), c("c"); int flag_value = 0; Param<int> flag("flag"); flag.set(flag_value); gpu(x, y, c) = cast<uint8_t>(select(flag != 0, 128, 255)); gpu.bound(c, 0, 4); gpu.glsl(x, y, c); gpu.compute_root(); // This should trigger a copy_to_host operation cpu(x, y, c) = gpu(x, y, c); Image<uint8_t> out(10, 10, 4); cpu.realize(out, target); // Verify the result for (int y=0; y!=out.height(); ++y) { for (int x=0; x!=out.width(); ++x) { for (int c=0; c!=out.channels(); ++c) { uint8_t expected = !flag_value ? 255 : 128; uint8_t actual = out(x,y,c); if (expected != actual) { fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n", out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3), x, y); return 1; } } } } return 0; } int test_flag_pixel_select() { // This test must be run with an OpenGL target. const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL); Func gpu("gpu"), cpu("cpu"); Var x("x"), y("y"), c("c"); int flag_value = 0; Param<int> flag("flag"); flag.set(flag_value); Image<uint8_t> image(10, 10, 4); for (int y=0; y<image.height(); y++) { for (int x=0; x<image.width(); x++) { for (int c=0; c<image.channels(); c++) { image(x, y, c) = 128; } } } gpu(x, y, c) = cast<uint8_t>(select(flag != 0, image(x,y,c), 255)); gpu.bound(c, 0, 4); gpu.glsl(x, y, c); gpu.compute_root(); // This should trigger a copy_to_host operation cpu(x, y, c) = gpu(x, y, c); Image<uint8_t> out(10, 10, 4); cpu.realize(out, target); // Verify the result for (int y=0; y!=out.height(); ++y) { for (int x=0; x!=out.width(); ++x) { for (int c=0; c!=out.channels(); ++c) { uint8_t expected = !flag_value ? 255 : 128; uint8_t actual = out(x,y,c); if (expected != actual) { fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n", out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3), x, y); return 1; } } } } return 0; } int main() { int err = 0; err |= test_per_channel_select(); err |= test_flag_scalar_select(); err |= test_flag_pixel_select(); if (err) { printf("FAILED\n"); return 1; } printf("Success!\n"); return 0; }
26.812865
89
0.443402
jwitz54
b9975b4da8bb9551fd52154f043eefc036f90520
981
cpp
C++
examples/3-complex_layout.cpp
nathanrpage97/libfort
41237162a9bd34a30a88069ee4e230584ae8d674
[ "MIT" ]
388
2018-07-16T06:18:37.000Z
2022-03-27T10:31:16.000Z
examples/3-complex_layout.cpp
nathanrpage97/libfort
41237162a9bd34a30a88069ee4e230584ae8d674
[ "MIT" ]
64
2019-05-03T07:02:23.000Z
2022-02-26T01:08:30.000Z
examples/3-complex_layout.cpp
nathanrpage97/libfort
41237162a9bd34a30a88069ee4e230584ae8d674
[ "MIT" ]
55
2018-07-27T07:33:52.000Z
2022-03-21T19:26:02.000Z
#include <iostream> #include "fort.hpp" int main() { fort::char_table table; /* Set table border style */ table.set_border_style(FT_DOUBLE2_STYLE); // Fill table with data table << fort::header << "Sed" << "Aenean" << "Text" << fort::endr; table << "Duis" << "Aliquam" << "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n" "In accumsan felis eros, nec malesuada sapien bibendum eget." << fort::endr; table << "Mauris" << "Curabitur" << "Proin condimentum eros viverra nunc ultricies, at fringilla \n" "quam pellentesque." << fort::endr; table << "Summary" << "" << "Sed tempor est eget odio varius dignissim." << fort::endr; table[0][2].set_cell_text_align(fort::text_align::center); table[3][0].set_cell_text_align(fort::text_align::center); table[3][0].set_cell_span(2); std::cout << table.to_string() << std::endl; }
27.25
77
0.588175
nathanrpage97
b9994203ce56691e6e53446f6e86c2f14ac5f02e
2,117
cpp
C++
src/main/cpp/Vision.cpp
VLPatton/2022-Rapid-React-Code
221312d98bf0eb780c2c2263949fcc439e0da42a
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Vision.cpp
VLPatton/2022-Rapid-React-Code
221312d98bf0eb780c2c2263949fcc439e0da42a
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Vision.cpp
VLPatton/2022-Rapid-React-Code
221312d98bf0eb780c2c2263949fcc439e0da42a
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** Description: CVisionPacket implementation Class: CVisionPacket Project: 2022 Rapid React Robot Code ******************************************************************************/ #include "Vision.h" #include <fmt/core.h> #include <frc/smartdashboard/SmartDashboard.h> #include <frc/DriverStation.h> using namespace frc; using namespace std; /////////////////////////////////////////////////////////////////////////////// CVisionPacket::CVisionPacket(const char* pPacketArr, unsigned int length) { // Allocate the packet data m_pRawPacket = (char*)malloc(length); // Copy the packet (allocated on the stack) to a new array. memcpy((void*)m_pRawPacket, (void*)pPacketArr, length); // Read in the actual data from the packet. m_nRandVal = m_pRawPacket[0]; m_nDetectionCount = m_pRawPacket[1]; m_kDetectionLocation = (DetectionLocation)m_pRawPacket[2]; } CVisionPacket::CVisionPacket() { m_nRandVal = 0xFF; m_nDetectionCount = 0xFF; m_kDetectionLocation = DetectionLocation::eNONE; m_pDetections = nullptr; m_pRawPacket = nullptr; } CVisionPacket::~CVisionPacket() { free(m_pRawPacket); } CVisionPacket* CVisionPacket::GetReceivedPacket() { // Retrive the processed vision packet from our coprocessor. string processed_vision = SmartDashboard::GetRaw("processed_vision", ""); if(!processed_vision.empty()) { const char* pVisionPacketArr = processed_vision.c_str(); CVisionPacket* pVisionPacket = new CVisionPacket(pVisionPacketArr, processed_vision.length()); if(pVisionPacket->m_nRandVal != 0xFF) { return pVisionPacket; } } return nullptr; } void CVisionPacket::ParseDetections() { m_kDetectionLocation = (DetectionLocation)m_pRawPacket[0]; // Preallocate the array m_pDetections = (sObjectDetection**)malloc(m_nDetectionCount * sizeof(sObjectDetection)); for(int i = 0; i < m_nDetectionCount; i++) { // Get the offset that we are into the packet. int packetOffset = 3 + (i * sizeof(sObjectDetection)); m_pDetections[i] = new sObjectDetection(m_pRawPacket, packetOffset); } }
30.681159
96
0.670288
VLPatton
b99c3e1ca9ba64f534b9e23a6fae6541559777aa
4,602
cpp
C++
node_modules/gl/angle/src/libGLESv2/global_state.cpp
aaverty/editly
71bccaf91f8d68609c80ba59425b79e3f94579ad
[ "MIT" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
Source/ANGLE/libGLESv2/global_state.cpp
wpbest/XPF
cb54ad82a8c6f675f2d5bc840a78f66f03de65e2
[ "MIT" ]
2
2020-03-14T04:03:53.000Z
2021-09-02T04:26:49.000Z
Source/ANGLE/libGLESv2/global_state.cpp
wpbest/XPF
cb54ad82a8c6f675f2d5bc840a78f66f03de65e2
[ "MIT" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
// // Copyright(c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // global_state.cpp : Implements functions for querying the thread-local GL and EGL state. #include "libGLESv2/global_state.h" #include "libANGLE/Context.h" #include "libANGLE/Error.h" #include "common/debug.h" #include "common/platform.h" #include "common/tls.h" namespace { static TLSIndex currentTLS = TLS_INVALID_INDEX; struct Current { EGLint error; EGLenum API; egl::Display *display; egl::Surface *drawSurface; egl::Surface *readSurface; gl::Context *context; }; Current *AllocateCurrent() { ASSERT(currentTLS != TLS_INVALID_INDEX); if (currentTLS == TLS_INVALID_INDEX) { return NULL; } Current *current = new Current(); current->error = EGL_SUCCESS; current->API = EGL_OPENGL_ES_API; current->display = reinterpret_cast<egl::Display*>(EGL_NO_DISPLAY); current->drawSurface = reinterpret_cast<egl::Surface*>(EGL_NO_SURFACE); current->readSurface = reinterpret_cast<egl::Surface*>(EGL_NO_SURFACE); current->context = reinterpret_cast<gl::Context*>(EGL_NO_CONTEXT); if (!SetTLSValue(currentTLS, current)) { ERR("Could not set thread local storage."); return NULL; } return current; } Current *GetCurrentData() { // Create a TLS index if one has not been created for this DLL if (currentTLS == TLS_INVALID_INDEX) { currentTLS = CreateTLSIndex(); } Current *current = reinterpret_cast<Current*>(GetTLSValue(currentTLS)); // ANGLE issue 488: when the dll is loaded after thread initialization, // thread local storage (current) might not exist yet. return (current ? current : AllocateCurrent()); } #ifdef ANGLE_PLATFORM_WINDOWS void DeallocateCurrent() { Current *current = reinterpret_cast<Current*>(GetTLSValue(currentTLS)); SafeDelete(current); SetTLSValue(currentTLS, NULL); } extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { switch (reason) { case DLL_PROCESS_ATTACH: currentTLS = CreateTLSIndex(); if (currentTLS == TLS_INVALID_INDEX) { return FALSE; } AllocateCurrent(); break; case DLL_THREAD_ATTACH: AllocateCurrent(); break; case DLL_THREAD_DETACH: DeallocateCurrent(); break; case DLL_PROCESS_DETACH: DeallocateCurrent(); if (currentTLS != TLS_INVALID_INDEX) { DestroyTLSIndex(currentTLS); currentTLS = TLS_INVALID_INDEX; } break; } return TRUE; } #endif } namespace gl { Context *GetGlobalContext() { Current *current = GetCurrentData(); return current->context; } Context *GetValidGlobalContext() { gl::Context *context = GetGlobalContext(); if (context) { if (context->isContextLost()) { context->recordError(gl::Error(GL_OUT_OF_MEMORY, "Context has been lost.")); return nullptr; } else { return context; } } return nullptr; } } namespace egl { void SetGlobalError(const Error &error) { Current *current = GetCurrentData(); current->error = error.getCode(); } EGLint GetGlobalError() { Current *current = GetCurrentData(); return current->error; } EGLenum GetGlobalAPI() { Current *current = GetCurrentData(); return current->API; } void SetGlobalAPI(EGLenum API) { Current *current = GetCurrentData(); current->API = API; } void SetGlobalDisplay(Display *dpy) { Current *current = GetCurrentData(); current->display = dpy; } Display *GetGlobalDisplay() { Current *current = GetCurrentData(); return current->display; } void SetGlobalDrawSurface(Surface *surface) { Current *current = GetCurrentData(); current->drawSurface = surface; } Surface *GetGlobalDrawSurface() { Current *current = GetCurrentData(); return current->drawSurface; } void SetGlobalReadSurface(Surface *surface) { Current *current = GetCurrentData(); current->readSurface = surface; } Surface *GetGlobalReadSurface() { Current *current = GetCurrentData(); return current->readSurface; } void SetGlobalContext(gl::Context *context) { Current *current = GetCurrentData(); current->context = context; } gl::Context *GetGlobalContext() { Current *current = GetCurrentData(); return current->context; } }
19.417722
90
0.658627
aaverty
b99c59116310443134cf872a6ac6afcdbc5e3d5a
426
cpp
C++
tests/2017/11.cpp
voivoid/advent-of-code
efc02f558ad7718d02dfc205fadeba6b857ce4ae
[ "MIT" ]
6
2019-03-01T14:15:38.000Z
2021-12-10T21:39:23.000Z
tests/2017/11.cpp
voivoid/advent-of-code
efc02f558ad7718d02dfc205fadeba6b857ce4ae
[ "MIT" ]
3
2018-10-22T09:42:26.000Z
2018-10-22T11:45:06.000Z
tests/2017/11.cpp
voivoid/advent-of-code
efc02f558ad7718d02dfc205fadeba6b857ce4ae
[ "MIT" ]
null
null
null
#include "boost/test/unit_test.hpp" #include "aoc_fixture.h" #include "AoC/2017/problem_11.h" using namespace AoC_2017::problem_11; BOOST_FIXTURE_TEST_CASE( problem2017_11_1, AocFixture ) { BOOST_CHECK_EQUAL( 3, run( &solve_1, "ne,ne,ne" ) ); BOOST_CHECK_EQUAL( 0, run( &solve_1, "ne,ne,sw,sw" ) ); BOOST_CHECK_EQUAL( 2, run( &solve_1, "ne,ne,s,s" ) ); BOOST_CHECK_EQUAL( 3, run( &solve_1, "se,sw,se,sw,sw" ) ); }
26.625
60
0.692488
voivoid
b99dba9fb68da1093a77d598f37b0d3dc63eb420
1,771
cc
C++
src/FbgemmBfloat16ConvertAvx512.cc
menchunlei/FBGEMM
588ecfcca3d83186461554cd28dedc41532d75b4
[ "BSD-3-Clause" ]
1
2020-05-02T14:18:06.000Z
2020-05-02T14:18:06.000Z
src/FbgemmBfloat16ConvertAvx512.cc
menchunlei/FBGEMM
588ecfcca3d83186461554cd28dedc41532d75b4
[ "BSD-3-Clause" ]
null
null
null
src/FbgemmBfloat16ConvertAvx512.cc
menchunlei/FBGEMM
588ecfcca3d83186461554cd28dedc41532d75b4
[ "BSD-3-Clause" ]
1
2020-04-21T08:10:22.000Z
2020-04-21T08:10:22.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <immintrin.h> #include "fbgemm/FbgemmConvert.h" namespace fbgemm { namespace { inline __m256i QuantizeBfloat16Avx512(const __m512& x0) { // Add 2^15 and right shift 16 to do round-nearest __m512i y0 = _mm512_srli_epi32( _mm512_add_epi32(_mm512_castps_si512(x0), _mm512_set1_epi32(1 << 15)), 16); return _mm512_cvtepi32_epi16(y0); } inline void FloatToBfloat16KernelAvx512(const float* src, bfloat16* dst) { // One float m512i -> One bfloat16 m256i const __m512 src_reg0 = _mm512_loadu_ps(src); __m256i dst_reg0 = QuantizeBfloat16Avx512(src_reg0); _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), dst_reg0); } inline void Bfloat16ToFloatKernelAvx512(const bfloat16* src, float* dst) { // One bfloat16 m256i -> One float m512i const __m256i src_reg = _mm256_lddqu_si256(reinterpret_cast<const __m256i*>(src)); __m512i dst_reg_bf16 = _mm512_cvtepu16_epi32(src_reg); __m512i dst_reg = _mm512_slli_epi32(dst_reg_bf16, 16); _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), dst_reg); } } // namespace void FloatToBfloat16_avx512(const float* src, bfloat16* dst, int size) { int i = 0; for (i = 0; i + 16 <= size; i += 16) { FloatToBfloat16KernelAvx512(src + i, dst + i); } FloatToBfloat16_avx2(src + i, dst + i, size - i); } void Bfloat16ToFloat_avx512(const bfloat16* src, float* dst, int size) { int i = 0; for (i = 0; i + 16 <= size; i += 16) { Bfloat16ToFloatKernelAvx512(src + i, dst + i); } Bfloat16ToFloat_avx2(src + i, dst + i, size - i); } } // namespace fbgemm
31.070175
76
0.713721
menchunlei
b9a1da7c8fd64b49fbf4301ab3b32006a155d382
17,211
cpp
C++
src/game/wbengine.cpp
Torom/Banksia
30498fd75196c1a8f29aac8e7c249ce6817644d2
[ "Apache-2.0" ]
55
2019-07-01T11:42:59.000Z
2022-03-09T18:59:18.000Z
src/game/wbengine.cpp
Torom/Banksia
30498fd75196c1a8f29aac8e7c249ce6817644d2
[ "Apache-2.0" ]
15
2019-07-13T01:29:09.000Z
2021-12-31T21:09:59.000Z
src/game/wbengine.cpp
Torom/Banksia
30498fd75196c1a8f29aac8e7c249ce6817644d2
[ "Apache-2.0" ]
13
2019-07-10T12:30:55.000Z
2022-01-10T09:41:59.000Z
/* This file is part of Banksia. Copyright (c) 2019 Nguyen Hong Pham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <regex> #include "wbengine.h" using namespace banksia; const std::unordered_map<std::string, int> WbEngine::wbEngineCmd { { "feature", static_cast<int>(WbEngine::WbEngineCmd::feature) }, { "move", static_cast<int>(WbEngine::WbEngineCmd::move) }, { "resign", static_cast<int>(WbEngine::WbEngineCmd::resign) }, { "offer", static_cast<int>(WbEngine::WbEngineCmd::offer) }, { "illegal", static_cast<int>(WbEngine::WbEngineCmd::illegal) }, { "Illegal", static_cast<int>(WbEngine::WbEngineCmd::illegal) }, { "Error", static_cast<int>(WbEngine::WbEngineCmd::error) }, { "ping", static_cast<int>(WbEngine::WbEngineCmd::ping) }, { "pong", static_cast<int>(WbEngine::WbEngineCmd::pong) }, { "tellopponent", static_cast<int>(WbEngine::WbEngineCmd::tellopponent) }, { "tellothers", static_cast<int>(WbEngine::WbEngineCmd::tellothers) }, { "tellall", static_cast<int>(WbEngine::WbEngineCmd::tellall) }, { "telluser", static_cast<int>(WbEngine::WbEngineCmd::telluser) }, { "tellusererror", static_cast<int>(WbEngine::WbEngineCmd::tellusererror) }, { "tellicsnoalias", static_cast<int>(WbEngine::WbEngineCmd::tellicsnoalias) }, }; const std::unordered_map<std::string, int>& WbEngine::getEngineCmdMap() const { return wbEngineCmd; } std::string WbEngine::protocolString() const { return "xboard\nprotover 2"; } bool WbEngine::sendOptions() { return true; } bool WbEngine::candoSyncTaskNow(SyncTask task) { if (feature_ping && expectingPongCnt) { std::lock_guard<std::mutex> dolock(syncMutex); if (expectingPongCnt) { syncTasks.push_back(task); return false; } } return true; } bool WbEngine::doSyncTask() { assert(feature_ping); if (expectingPongCnt || syncTasks.empty()) { return false; } std::lock_guard<std::mutex> dolock(syncMutex); if (expectingPongCnt || syncTasks.empty()) { return false; } auto task = syncTasks.front(); syncTasks.erase(syncTasks.begin()); switch (task) { case SyncTask::newgame: newGame_straight(); break; case SyncTask::go: go_straight(); break; default: break; } return true; } void WbEngine::newGame() { if (!candoSyncTaskNow(SyncTask::newgame)) { return; } newGame_straight(); } void WbEngine::newGame_straight() { assert(getState() == PlayerState::ready); computingState = EngineComputingState::idle; sendMemoryAndCoreOptions(); write(ponderMode ? "hard" : "easy"); write("post"); if (isFeatureOn("reuse", true)) { write("new"); } if (!board->fromOriginPosition()) { write("setboard " + board->getStartingFen()); } if (!board->histList.empty()) { // TODO: check logic again. No ping here // force to avoid some engines such as Crafty auto computing write("force"); for (auto && hist : board->histList) { std::string str = move2String(hist.move, hist.moveString); write(str); } } write(timeControlString()); if (feature_ping) { // fake ping to avoid other cmd be run expectingPongCnt++; std::this_thread::sleep_for(std::chrono::milliseconds(200)); sendPing(); } else { setState(PlayerState::playing); } } void WbEngine::prepareToDeattach() { if (tick_deattach >= 0) return; stop(); tick_deattach = tick_period_deattach; } bool WbEngine::stop() { return write("force"); } bool WbEngine::goPonder(const Move& pondermove) { Engine::go(); // just for setting flags return false; } bool WbEngine::go() { if (!candoSyncTaskNow(SyncTask::go)) { return false; } return go_straight(); } bool WbEngine::go_straight() { Engine::go(); computingState = EngineComputingState::thinking; return write(timeLeftString()) && write("go"); } std::string WbEngine::timeLeftString() const { switch (timeController->mode) { case TimeControlMode::movetime: { auto centiSeconds = static_cast<int>(timeController->time * 100); auto s = std::to_string(centiSeconds); return "time " + s + "\notim " + s; } case TimeControlMode::standard: { // timeController unit: second -> centi second auto sd = static_cast<int>(board->side); auto time = int(timeController->getTimeLeft(sd) * 100); auto otime = int(timeController->getTimeLeft(1 - sd) * 100); return "time " + std::to_string(time) + "\notim " + std::to_string(otime); } default: break; } return ""; } std::string WbEngine::timeControlString() const { switch (timeController->mode) { case TimeControlMode::infinite: return "analyze"; case TimeControlMode::depth: return "sd " + std::to_string(timeController->depth); case TimeControlMode::movetime: return "st " + std::to_string(timeController->time); case TimeControlMode::standard: { // timeController unit: second auto sd = static_cast<int>(board->side); auto time = int(timeController->getTimeLeft(sd)), m = time / 60, s = time % 60; auto timeString = std::to_string(m) + (s > 0 ? ":" + std::to_string(s) : ""); int inc = int(timeController->increment); auto n = timeController->moves; auto halfCnt = int(board->histList.size()); int fullCnt = halfCnt / 2; auto movestogo = 0; if (n > 0) { // n == 0 => Fischer's clock int curMoveCnt = fullCnt % n; movestogo = n - curMoveCnt; } // level 40 0:30 0 std::string str = "level " + std::to_string(movestogo) + " " + timeString + " " + std::to_string(inc) ; return str; } default: break; } return ""; } bool WbEngine::sendPing() { assert(feature_ping); expectingPongCnt++; return write("ping " + std::to_string(++pingCnt)); } bool WbEngine::sendPong(const std::string& str) { return write("pong " + str); } void WbEngine::tickWork() { EngineProfile::tickWork(); if (getState() == PlayerState::starting) { if (tick_delay_2_ready > 0) { tick_delay_2_ready--; if (tick_delay_2_ready == 0) { write("force"); if (feature_ping) { sendPing(); } setState(PlayerState::ready); } } else if (tick_state > 10 * 2 && correctCmdCnt < 2) { // crashed setState(PlayerState::stopped); } } } void WbEngine::tickPing() { if (computingState == EngineComputingState::thinking || !feature_ping) { return; } tick_ping++; if (tick_ping >= tick_period_ping) { resetPing(); sendPing(); } else { doSyncTask(); } } bool WbEngine::isIdleCrash() const { // if engine send feature done=0 (feature_done_finished = false), it can wait longer return !feature_done_finished && tick_idle > tick_period_idle_dead; } bool WbEngine::isFeatureOn(const std::string& featureName, bool defaultValue) { auto p = featureMap.find(featureName); return p == featureMap.end() ? defaultValue : p->second == "1"; } bool WbEngine::sendMemoryAndCoreOptions() { // cores N, memory N std::string str; if (isFeatureOn("memory")) { Option option = ConfigMng::instance->getOverrideOption("memory"); if (!option.isValid()) { for(auto && o : config.optionList) { if (o.name == "memory") { option = o; break; } } } if (option.isValid()) { str += option.name + " " + option.getValueAsString(); } } if (isFeatureOn("smp")) { Option option = ConfigMng::instance->getOverrideOption("cores"); if (!option.isValid()) { for(auto && o : config.optionList) { if (o.name == "cores") { option = o; break; } } } if (option.isValid()) { if (!str.empty()) str += "\n"; str += option.name + " " + option.getValueAsString(); } } return !str.empty() && write(str); } bool WbEngine::parseFeature(const std::string& name, const std::string& content, bool quote) { if (name.empty() || content.empty()) { return false; } if (name == "option") { auto vec = splitString(content, ' '); if (vec.size() < 2) return true; auto optionName = vec.front(); for(auto && o : config.optionList) { if (o.name != optionName) { continue; } if (!isWritable() || o.isDefaultValue() || o.name == "memory" || o.name == "cores") { break; } std::string str = "option " + o.name + "=" + o.getValueAsString(); write(str); break; } return true; } if (name == "san") { feature_san = content == "1"; } else if (name == "usermove") { feature_usermove = content == "1"; } else if (name == "ping") { feature_ping = content == "1"; } else if (name == "variants") { config.variantSet.clear(); auto varList = splitString(content, ','); for(auto && s : varList) { trim(s); if (!s.empty()) { config.variantSet.insert(s); } } } else if (name == "done") { if (content == "0") { tick_delay_2_ready = 60 * 60 * 2; // 1h feature_done_finished = false; } else { setState(PlayerState::ready); feature_done_finished = true; } return true; } else if (name == "smp" || name == "memory") { // changed into option if (content == "1") { int dInt = name == "smp" ? 1 : 16, minInt = 1, maxInt = 256; Option option; option.name = name == "smp" ? "cores" : "memory"; option.type = OptionType::spin; option.setDefaultValue(dInt, minInt, maxInt); config.updateOption(option); } } else if (name == "myname") { config.idName = content; } write("accepted " + name); featureMap[name] = content; return true; } void WbEngine::parseFeatures(const std::string& line) { // "feature " length = 8 std::string featureName; for(size_t i = 8, k = -1, quote = 0; i < line.size(); i++) { auto ch = line[i]; if (ch == '=') { if (k < 0 || i <= k) break; // somethings wrong featureName = line.substr(k, i - k); k = i + 1; continue; } if (ch == '"') { if (quote == 0) { quote++; k = i + 1; } else { if (!featureName.empty() && k > 0 && i > k + 1) { auto content = line.substr(k, i - k); parseFeature(featureName, content, true); } featureName = ""; quote = 0; k = -1; continue; } } if ((ch == ' ' || i + 1 == line.size()) && quote == 0) { if (!featureName.empty() && k > 0) { auto len = i - k; if (i + 1 == line.size()) len++; auto content = line.substr(k, len); parseFeature(featureName, content, false); } featureName = ""; quote = 0; k = -1; continue; } if (k < 0) k = i; } } std::string WbEngine::move2String(const Move& move, const std::string& sanMoveString) const { std::string str; if (feature_usermove) { str += "usermove "; } if (feature_san) { str += sanMoveString; } else { str += move.toCoordinateString(); } return str; } bool WbEngine::oppositeMadeMove(const Move& move, const std::string& sanMoveString) { write("force"); // we don't want this engine starts calculating after this move std::string str = move2String(move, sanMoveString); return write(str); } bool WbEngine::engineMove(const std::string& moveString, bool mustSend) { if (moveString.length() < 2 || !isalpha(moveString.at(0)) || computingState != EngineComputingState::thinking) { // some engines don't orbey 'force' and create moves too fast -> ignore some cases return false; } auto timeCtrl = timeController; auto moveRecv = moveReceiver; if (timeCtrl == nullptr || moveRecv == nullptr) { return false; } auto move = board->moveFromCoordiateString(moveString); if (!move.isValid()) { move = board->fromSanString(moveString); } if (mustSend || move.isValid()) { auto period = timeCtrl->moveTimeConsumed(); // moveTimeConsumed(); auto oldComputingState = computingState; computingState = EngineComputingState::idle; (moveRecv)(move, moveString, Move::illegalMove, period, oldComputingState); return true; } return false; } void WbEngine::parseLine(int cmdInt, const std::string& cmdString, const std::string& line) { if (cmdInt < 0) { if (state != PlayerState::playing) { return; } if (computingState != EngineComputingState::thinking) { return; } auto ch = line.front(); if (isdigit(ch)) { // it may be thinking output -> ignore // 9 156 1084 48000 Nf3 Nc6 Nc3 Nf6 // ply score time nodes pv auto vec = splitString(line, ' '); if (vec.size() >= 4) { depth = std::atoi(vec[0].c_str()); score = std::atoi(vec[1].c_str()); nodes = std::atoi(vec[3].c_str()); if (depth > 0 && nodes > 0) { engineSentCorrectCmds(); } } } return; } if (tick_delay_2_ready < 0) tick_delay_2_ready = 3; auto cmd = static_cast<WbEngineCmd>(cmdInt); switch (cmd) { case WbEngineCmd::move: { auto vec = splitString(line, ' '); if (vec.size() < 2) { // something wrong return; } engineMove(vec.at(1), true); break; } case WbEngineCmd::feature: { tick_delay_2_ready = std::max(3, tick_delay_2_ready); // extent init time a bit parseFeatures(line); break; } case WbEngineCmd::ping: { auto vec = splitString(line, ' '); sendPong(vec.size() >= 2 ? vec.at(1) : ""); break; } case WbEngineCmd::pong: { expectingPongCnt = 0; pongCnt++; if (getState() == PlayerState::ready) { setState(PlayerState::playing); } doSyncTask(); break; } case WbEngineCmd::resign: { if (resignFunc != nullptr) { (resignFunc)(); } break; } default: break; } }
27.939935
145
0.532392
Torom
b9a2a8c419f5f3e118e4655cd9702850e50ad892
19,174
cc
C++
src/logkafka/zookeeper.cc
Qihoo360/logkafka
f329b5a9806e0b0f716884759edbe54e72e4dec0
[ "MIT" ]
568
2015-06-23T07:41:50.000Z
2022-03-30T11:32:05.000Z
src/logkafka/zookeeper.cc
Qihoo360/logkafka
f329b5a9806e0b0f716884759edbe54e72e4dec0
[ "MIT" ]
26
2015-09-27T07:25:31.000Z
2021-07-25T13:30:09.000Z
src/logkafka/zookeeper.cc
Qihoo360/logkafka
f329b5a9806e0b0f716884759edbe54e72e4dec0
[ "MIT" ]
138
2015-06-23T07:41:50.000Z
2021-12-13T02:31:40.000Z
/////////////////////////////////////////////////////////////////////////// // // logkafka - Collect logs and send lines to Apache Kafka v0.8+ // /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Qihoo 360 Technology Co., Ltd. All rights reserved. // // Licensed under the MIT 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://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////// #include "logkafka/zookeeper.h" #include <cstdlib> #include <sstream> #include "base/tools.h" #include "logkafka/producer.h" #include "easylogging/easylogging++.h" using namespace base; namespace logkafka { const unsigned long Zookeeper::REFRESH_INTERVAL_MS = 30000UL; const unsigned long Zookeeper::SESSION_TIMEOUT_MS = 30000UL; Zookeeper::Zookeeper() {/*{{{*/ m_zhandle = NULL; m_loop = NULL; m_zk_log_fp = NULL; m_refresh_timer_trigger = NULL; m_thread = NULL; m_log_config = "{}"; m_broker_urls = ""; m_session_timeout_ms = SESSION_TIMEOUT_MS; m_clientid = NULL; m_registered = false; }/*}}}*/ Zookeeper::~Zookeeper() {/*{{{*/ delete m_loop; m_loop = NULL; delete m_zk_log_fp; m_zk_log_fp = NULL; delete m_refresh_timer_trigger; m_refresh_timer_trigger = NULL; delete m_thread; m_thread = NULL; delete m_clientid; m_clientid = NULL; }/*}}}*/ bool Zookeeper::init(const string &zookeeper_urls, const string &kafka_chroot_path, const string &logkafka_id, long refresh_interval) {/*{{{*/ m_zookeeper_urls = zookeeper_urls; m_kafka_chroot_path = kafka_chroot_path; m_logkafka_id = logkafka_id; m_zk_log_fp = fopen("/dev/null", "w"); zoo_set_log_stream(m_zk_log_fp); m_broker_ids_path = m_kafka_chroot_path + "/brokers/ids"; m_logkafka_config_path = m_kafka_chroot_path + "/logkafka/config"; m_logkafka_client_path = m_kafka_chroot_path + "/logkafka/client"; m_client_logkafka_id_path = m_logkafka_client_path + "/" + m_logkafka_id; m_config_logkafka_id_path = m_logkafka_config_path + "/" + m_logkafka_id; refresh((void *)this); /* Use one zookeeper loop for all watchers */ m_loop = new uv_loop_t(); int res = uv_loop_init(m_loop); if (res < 0) { LERROR << "Fail to init uv loop, " << uv_strerror(res); return false; } /* The existence of the async handle will keep the loop alive. */ m_exit_handle.data = this; uv_async_init(m_loop, &m_exit_handle, exitAsyncCb); m_refresh_timer_trigger = new TimerWatcher(); if (!m_refresh_timer_trigger->init(m_loop, 0, refresh_interval, this, &refresh)) { LERROR << "Fail to init refresh timer"; delete m_refresh_timer_trigger; m_refresh_timer_trigger = NULL; return false; } /* Run zookeeper loop in another thread */ m_thread = new uv_thread_t(); uv_thread_create(m_thread, &threadFunc, m_loop); return true; }/*}}}*/ void Zookeeper::threadFunc(void *arg) {/*{{{*/ uv_loop_t *loop = reinterpret_cast<uv_loop_t *>(arg); int res = uv_run(loop, UV_RUN_DEFAULT); if (res < 0) { LERROR << "Fail to run loop, " << uv_strerror(res); } }/*}}}*/ bool Zookeeper::connect() {/*{{{*/ if (NULL != m_zhandle) { LINFO << "Close invaild zookeeper connection..."; zookeeper_close(m_zhandle); m_zhandle = NULL; } int flags = 0; LDEBUG << "Initiating client connection" << ", zookeeper urls = " << m_zookeeper_urls << ", watcher = " << globalWatcher << ", sessionTimeout = " << m_session_timeout_ms << ", sessionId = " << (m_clientid == 0 ? 0 : m_clientid->client_id) << ", sessionPasswd = " << ((m_clientid == 0) || (strncmp(m_clientid->passwd, "", 2) == 0) ? "<null>" : "<hidden>") << ", context = " << (void*)this << ", flags = " << flags; m_zhandle = zookeeper_init(m_zookeeper_urls.c_str(), globalWatcher, m_session_timeout_ms, m_clientid, (void*)this, flags); if (NULL == m_zhandle) { LERROR << "Fail to init zhandle, zookeeper urls " << m_zookeeper_urls; return false; } return true; }/*}}}*/ void Zookeeper::close() {/*{{{*/ m_refresh_timer_trigger->close(); uv_stop(m_loop); uv_async_send(&m_exit_handle); ScopedLock lk(m_zhandle_mutex); if (NULL != m_zhandle) { zookeeper_close(m_zhandle); m_zhandle = NULL; } if (NULL != m_zk_log_fp) { fclose(m_zk_log_fp); m_zk_log_fp = NULL; } }/*}}}*/ void Zookeeper::exitAsyncCb(uv_async_t* handle) {/*{{{*/ /* After closing the async handle, it will no longer keep the loop alive. */ Zookeeper *zookeeper = reinterpret_cast<Zookeeper *>(handle->data); uv_close((uv_handle_t*) &zookeeper->m_exit_handle, NULL); } /*}}}*/ void Zookeeper::refresh(void *arg) {/*{{{*/ if (NULL == arg) { LERROR << "Zookeeper refresh function arg is NULL"; return; } Zookeeper *zookeeper = reinterpret_cast<Zookeeper *>(arg); if (!zookeeper->refreshConnection()) { LERROR << "Fail to refresh zookeeper connection"; return; } if (!zookeeper->refreshBrokerUrls()) { LERROR << "Fail to refresh broker urls"; } if (!zookeeper->refreshWatchers()) { LERROR << "Fail to refresh zookeeper watchers"; } if (!zookeeper->refreshLogConfig()) { LERROR << "Fail to refresh log config"; } }/*}}}*/ bool Zookeeper::refreshConnection() {/*{{{*/ ScopedLock l(m_zhandle_mutex); int res = zoo_state(m_zhandle); if (NULL == m_zhandle || ZOO_EXPIRED_SESSION_STATE == res) { LDEBUG << "Zookeeper error, " << zerror(res); if (!connect()) { LERROR << "Fail to reset zookeeper connection"; return false; } } return true; }/*}}}*/ bool Zookeeper::refreshWatchers() {/*{{{*/ ScopedLock l(m_zhandle_mutex); /* set config change watcher */ if (!setWatcher(m_config_logkafka_id_path, configChangeWatcher, (void*)this)) { LERROR << "Fail to set config change watcher"; return false; } /* set broker change watcher */ if (!setChildrenWatcher(m_broker_ids_path, brokerChangeWatcher, (void*)this)) { LERROR << "Fail to set broker change watcher"; return false; } if (!ensurePathExist(m_logkafka_client_path)) { LERROR << "Fail to create zookeeper path, " << m_logkafka_client_path; return false; } /* create EPHEMERAL node for checking whether logkafka is alive */ struct Stat stat; int status = ZOK; int len = 0; char *buf = NULL; buf = (char *)malloc(len + 1); bzero(buf, len + 1); status = zoo_get(m_zhandle, m_client_logkafka_id_path.c_str(), 0, buf, &len, &stat); if (ZOK == status) { if (0 == stat.ephemeralOwner) { // persistent node LINFO << "Deleting persistent zookeeper path, " << m_client_logkafka_id_path; if (ZOK != zoo_delete(m_zhandle, m_client_logkafka_id_path.c_str(), -1)) { LERROR << "Fail to delete persistent zookeeper path, " << m_client_logkafka_id_path; return false; } } else { // ephemeral node /* if this process have never created client/logkafka_id node, * it must be created by another process, we must quit */ if (!m_registered) { LERROR << "This error may emerge in two situations: \n" << " 1. Another logkafka process with the same id " << m_logkafka_id << " is running.\n" << " 2. Last running process with the same id just stopped" << " a moment ago, wait for " << (m_session_timeout_ms/1000) << " seconds and retry"; exit(EXIT_FAILURE); } } } free(buf); if (ZOK != status) { LDEBUG << "Zookeeper get error, " << zerror(status); LDEBUG << "Creating zookeeper path, " << m_client_logkafka_id_path; if (zoo_create(m_zhandle, m_client_logkafka_id_path.c_str(), NULL, 0, &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, NULL, 0) != ZOK) { LERROR << "Fail to create zookeeper path, " << m_client_logkafka_id_path; return false; } m_registered = true; } return true; }/*}}}*/ bool Zookeeper::refreshLogConfig() {/*{{{*/ ScopedLock l(m_log_config_mutex); string log_config; if (!getZnodeData(m_config_logkafka_id_path, log_config)) { LERROR << "Fail to get log config"; return false; } m_log_config = log_config; return true; }/*}}}*/ bool Zookeeper::refreshBrokerUrls() {/*{{{*/ ScopedLock l(m_broker_urls_mutex); vector<string> ids; if (!getBrokerIds(ids)) { return false; } m_broker_urls = ""; vector<string>::const_iterator iter; for (iter = ids.begin(); iter != ids.end(); ++iter) { string host, port; string bid = *iter; if (!getBrokerIpAndPort(bid, host, port)) { return false; } if (iter != ids.begin()) { m_broker_urls.append(","); } m_broker_urls.append(host); m_broker_urls.append(":"); m_broker_urls.append(port); } LDEBUG << "Broker urls: " << m_broker_urls.c_str(); return true; }/*}}}*/ string Zookeeper::getLogConfig() {/*{{{*/ ScopedLock l(m_log_config_mutex); return m_log_config; }/*}}}*/ bool Zookeeper::ensurePathExist(const string& path) {/*{{{*/ if (NULL == m_zhandle) { LWARNING << "Zookeeper handle is NULL"; return false; } if (ZOK == zoo_exists(m_zhandle, path.c_str(), 0, NULL)) { LINFO << "Zookeeper node " << path << " already exists"; return true; } size_t start_pos = 1; size_t pos = 0; while ((pos = path.find('/', start_pos)) != string::npos) { string parent_path = path.substr(0, pos); start_pos = pos+1; zoo_create(m_zhandle, parent_path.c_str(), NULL, 0, &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0); } int ret = zoo_create(m_zhandle, path.c_str(), NULL, 0, &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0); if (ret != ZOK && ret != ZNODEEXISTS) { LERROR << "Create znode failed: " << path.c_str() << ", error: " << zerror(ret); return false; } return true; }/*}}}*/ bool Zookeeper::getZnodeData(const string& path, string &data) {/*{{{*/ if (NULL == m_zhandle) { LWARNING << "Zookeeper handle is NULL"; return false; } struct Stat stat; int status = ZOK; int len = 0; bool ret = false; char *buf = NULL; status = zoo_exists(m_zhandle, path.c_str(), 0, &stat); len = (status == ZOK) ? stat.dataLength : ZNODE_BUF_MAX_LEN; buf = (char *)malloc(len + 1); bzero(buf, len + 1); status = zoo_get(m_zhandle, path.c_str(), 0, buf, &len, NULL); if (status == ZOK) { data = string(buf); ret = true; } else { LERROR << "Get znode error" << ", path: " << path << ", error:%s" << zerror(status); } free(buf); return ret; }/*}}}*/ bool Zookeeper::setWatcher(const string& path, watcher_fn watcher, void *wctx) {/*{{{*/ LINFO << "Try to set watcher " << path.c_str(); if (NULL == m_zhandle) { LWARNING << "Zookeeper handle is NULL"; return false; } if (!ensurePathExist(path)) { LERROR << "Create znode " << path; return false; } int len = 0; int ret; if (ZOK != (ret = zoo_wget(m_zhandle, path.c_str(), watcher, wctx, NULL, &len, NULL))) { LWARNING << "Set watcher failed: " << path; return false; } LINFO << "Set watcher success: " << path.c_str(); return true; }/*}}}*/ bool Zookeeper::setChildrenWatcher(const string& path, watcher_fn watcher, void *wctx) {/*{{{*/ LINFO << "Try to set children watcher " << path.c_str(); if (NULL == m_zhandle) { LWARNING << "Zookeeper handle is NULL"; return false; } if (!ensurePathExist(path)) { LERROR << "Create znode " << path.c_str(); return false; } int ret = ZOK; if (ZOK != (ret = zoo_wget_children(m_zhandle, path.c_str(), watcher, wctx, NULL))) { LWARNING << "Set children watcher failed: " << path.c_str(); return false; } LINFO << "Set children watcher success: " << path.c_str(); return true; }/*}}}*/ const char* Zookeeper::state2String(int state) {/*{{{*/ if (state == 0) return "CLOSED_STATE"; if (state == ZOO_CONNECTING_STATE) return "CONNECTING_STATE"; if (state == ZOO_ASSOCIATING_STATE) return "ASSOCIATING_STATE"; if (state == ZOO_CONNECTED_STATE) return "CONNECTED_STATE"; if (state == ZOO_EXPIRED_SESSION_STATE) return "EXPIRED_SESSION_STATE"; if (state == ZOO_AUTH_FAILED_STATE) return "AUTH_FAILED_STATE"; return "INVALID_STATE"; }/*}}}*/ const char* Zookeeper::event2String(int ev) {/*{{{*/ switch (ev) { case 0: return "ZOO_ERROR_EVENT"; case CREATED_EVENT_DEF: return "ZOO_CREATED_EVENT"; case DELETED_EVENT_DEF: return "ZOO_DELETED_EVENT"; case CHANGED_EVENT_DEF: return "ZOO_CHANGED_EVENT"; case CHILD_EVENT_DEF: return "ZOO_CHILD_EVENT"; case SESSION_EVENT_DEF: return "ZOO_SESSION_EVENT"; case NOTWATCHING_EVENT_DEF: return "ZOO_NOTWATCHING_EVENT"; } return "INVALID_EVENT"; }/*}}}*/ void Zookeeper::globalWatcher(zhandle_t* zhandle, int type, int state, const char* path, void* context) {/*{{{*/ LINFO << "Watcher event: " << event2String(type) << ", state: " << state2String(state) << ", path: " << path; if (NULL == context) { LWARNING << "Broker change watcher context is NULL"; return; } Zookeeper *zookeeper = reinterpret_cast<Zookeeper *>(context); if (type == ZOO_SESSION_EVENT) { if (state == ZOO_CONNECTED_STATE) { LINFO << "Connect to zookeeper successfully."; } if (state == ZOO_AUTH_FAILED_STATE) { LERROR << "Authentication failure, shutting down..."; } if (state == ZOO_EXPIRED_SESSION_STATE) { LINFO << "Session expired, try to reconnect..."; refresh((void*)zookeeper); } } }/*}}}*/ void Zookeeper::brokerChangeWatcher(zhandle_t* zhandle, int type, int state, const char* path, void* context) {/*{{{*/ LINFO << "Watcher event: " << event2String(type) << ", state: " << state2String(state) << ", path: " << path; if (NULL == context) { LWARNING << "Broker change watcher context is NULL"; return; } Zookeeper *zookeeper = reinterpret_cast<Zookeeper *>(context); zookeeper->refreshWatchers(); if (type != ZOO_SESSION_EVENT) { zookeeper->refreshBrokerUrls(); } }/*}}}*/ void Zookeeper::configChangeWatcher(zhandle_t* zhandle, int type, int state, const char* path, void* context) {/*{{{*/ LINFO << "Watcher event: " << event2String(type) << ", state: " << state2String(state) << ", path: " << path; if (NULL == context) { LWARNING << "Config change watcher context is NULL"; return; } Zookeeper *zookeeper = reinterpret_cast<Zookeeper *>(context); zookeeper->refreshWatchers(); if (type != ZOO_SESSION_EVENT) { zookeeper->refreshLogConfig(); } }/*}}}*/ bool Zookeeper::getBrokerIds(vector<string>& ids) {/*{{{*/ if (NULL == m_zhandle) { LWARNING << "Zookeeper handle is NULL"; return false; } struct String_vector brokerids; int ret = zoo_get_children(m_zhandle, m_broker_ids_path.c_str(), 0, &brokerids); if (ret != ZOK) { LERROR << "Get children error" << ", path: " << m_broker_ids_path << ", error: " << zerror(ret); return false; } else { ids.clear(); for (int i = 0; i < brokerids.count; ++i) { ids.push_back(brokerids.data[i]); } deallocate_String_vector(&brokerids); return true; } }/*}}}*/ bool Zookeeper::getBrokerIpAndPort(const string& brokerid, string& host, string& port) {/*{{{*/ string brokerid_info_path = m_broker_ids_path + "/" + brokerid; string brokerinfo; if (!getZnodeData(brokerid_info_path, brokerinfo)) { LERROR << "Fail to get broker info"; return false; } /* 1. Parse a JSON text string to a document. */ Document document; if (document.Parse<0>(brokerinfo.c_str()).HasParseError()) { LERROR << "Json parsing failed, json: " << brokerinfo; return false; } /* 2. Access values in document. */ if (!document.IsObject()) { LERROR << "Document is not object, type: " << Json::TypeNames[document.GetType()]; return false; } try { Json::getValue(document, "host", host); int port_int; Json::getValue(document, "port", port_int); port = int2Str(port_int); } catch (const JsonErr &err) { LERROR << "Json error: " << err; return false; } return true; }/*}}}*/ string Zookeeper::getBrokerUrls() {/*{{{*/ ScopedLock l(m_broker_urls_mutex); return m_broker_urls; }/*}}}*/ bool Zookeeper::setLogState( const char *buf, int buflen, stat_completion_t completion) {/*{{{*/ ScopedLock l(m_zhandle_mutex); if (NULL == m_zhandle) { LWARNING << "Zookeeper handle is NULL"; return false; } int ret = ZOK; const char *client_path = m_client_logkafka_id_path.c_str(); char *path = strndup(client_path, strlen(client_path)); if (NULL == path) { LERROR << "Fail to strndup path " << client_path; return false; } /* NOTE: use zookeeper async set for not blocking the main loop */ if ((ret = zoo_aset(m_zhandle, client_path, buf, buflen, -1, completion, path)) != ZOK) { LERROR << "Fail to set znode, " << zerror(ret) << ", path: " << path << ", buf: " << buf << ", buflen: " << buflen; free(path); return false; } return true; }/*}}}*/ } // namespace logkafka
28.78979
126
0.579691
Qihoo360
b9a408b5a73d418cde13c85cfa8a4421adb1397f
21,551
cpp
C++
src/globals/tb2globalconstr.cpp
Pierre-Mont/toulbar2
623b92d593eab2dc1e21df9f853c28cc84626ed6
[ "MIT" ]
33
2018-08-16T18:14:35.000Z
2022-03-14T10:26:18.000Z
src/globals/tb2globalconstr.cpp
Pierre-Mont/toulbar2
623b92d593eab2dc1e21df9f853c28cc84626ed6
[ "MIT" ]
13
2018-08-09T06:53:08.000Z
2022-03-28T10:26:24.000Z
src/globals/tb2globalconstr.cpp
Pierre-Mont/toulbar2
623b92d593eab2dc1e21df9f853c28cc84626ed6
[ "MIT" ]
12
2018-06-06T15:19:46.000Z
2022-02-11T17:09:27.000Z
#include "tb2globalconstr.hpp" #include "core/tb2wcsp.hpp" #include "search/tb2clusters.hpp" GlobalConstraint::GlobalConstraint(WCSP* wcsp, EnumeratedVariable** scope_in, int arity_in, Cost defval) : AbstractGlobalConstraint(wcsp, scope_in, arity_in) , extendedCost(NULL) , projectedCost(0) , nonassigned(arity_in) , currentVar(-1) , needPropagateAC(false) , needPropagateDAC(false) , needPropagateEAC(false) , currentDepth(-1) , def(1) , mode(0) , count_nic(0) , count_gac(0) , count_fdac(0) , count_edac(0) , error(0) { deltaCost = new vector<StoreCost>[arity_]; for (int i = 0; i < arity_in; i++) { deltaCost[i] = vector<StoreCost>(scope_in[i]->getDomainInitSize(), StoreCost(0)); fill(deltaCost[i].begin(), deltaCost[i].end(), 0); } fullySupportedSet = new set<int>[arity_in]; preUnaryCosts.resize(arity_in); for (int i = 0; i < arity_in; i++) preUnaryCosts[i].resize(scope[i]->getDomainInitSize(), 0); } GlobalConstraint::~GlobalConstraint() { if (deltaCost != NULL) delete[] deltaCost; if (fullySupportedSet != NULL) delete[] fullySupportedSet; } void GlobalConstraint::init() { if (deconnected()) return; needPropagateAC = true; needPropagateDAC = true; needPropagateEAC = false; EACCost.clear(); for (int i = 0; i < arity_; i++) fullySupportedSet[i].clear(); /*if ((currentDepth == -1) || (currentDepth >= Store::getDepth())) { initStructure(); } else { vector<int> rmv; checkRemoved(rmv); } currentDepth = Store::getDepth();*/ initStructure(); propagate(); } void GlobalConstraint::print(ostream& os) { os << this << " " << getName() << "("; int unassigned_ = 0; for (int i = 0; i < arity(); i++) { if (scope[i]->unassigned()) unassigned_++; os << scope[i]->wcspIndex; if (i < arity_ - 1) os << ","; } // string smode = ""; // for (map<string,int>::iterator iter = modeEnum.begin(); iter != modeEnum.begin(); ++iter) { // if ((*iter).second == mode) { // smode = (*iter).first; // break; // } // } os << ") mode: " << mode << ",defcost: " << def << ","; os << " unassigned: " << unassigned_ << "/" << nonassigned << "/" << arity(); os << endl; if (ToulBar2::verbose >= 4) showCostProvidingPartition(); if (ToulBar2::verbose >= 5) { os << "projectedCost: " << projectedCost << endl; for (int i = 0; i < arity(); i++) { os << "deltaCost[" << i << "]:"; for (unsigned int j = 0; j < deltaCost[i].size(); j++) { os << " " << deltaCost[i][j]; } os << endl; // os << "extendedCost[" << i << "]:"; // for(unsigned int j = 0; j < extendedCost[i].size();j++) {os << " " << extendedCost[i][j];} // os << endl; } } if (ToulBar2::verbose >= 6) for (int i = 0; i < arity(); i++) os << *scope[i] << endl; } Cost GlobalConstraint::eval(const Tuple& s) { Cost tcost = evalOriginal(s); for (unsigned int i = 0; i < s.size(); i++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(i); if (tcost < wcsp->getUb()) { tcost -= deltaCost[i][x->toIndex(s[i])]; } } if (tcost < wcsp->getUb()) { tcost -= projectedCost; } assert(tcost >= 0); return tcost; } void GlobalConstraint::assign(int varIndex) { if (connected(varIndex)) { deconnect(varIndex); nonassigned = nonassigned - 1; if (nonassigned == 0) { deconnect(); Tuple t(arity_, 0); for (int i = 0; i < arity_; i++) { t[i] = ((EnumeratedVariable*)getVar(i))->toIndex(getVar(i)->getValue()); } wcsp->revise(this); projectLB(eval(t)); } else { pushAll(); if (ToulBar2::FullEAC) reviseEACGreedySolution(); } } } void GlobalConstraint::project(int index, Value value, Cost cost, bool delayed) { if (deconnected()) return; assert(ToulBar2::verbose < 4 || ((cout << "[" << Store::getDepth() << "] project(" << getName() << ", " << getVar(index)->getName() << ", " << value << ", " << cost << ")" << endl), true)); EnumeratedVariable* x = (EnumeratedVariable*)getVar(index); // hard binary constraint costs are not changed if (!CUT(cost + wcsp->getLb(), wcsp->getUb())) { TreeDecomposition* td = wcsp->getTreeDec(); if (td) td->addDelta(cluster, x, value, cost); deltaCost[index][x->toIndex(value)] += cost; // Warning! Possible overflow??? } x->project(value, cost, delayed); } void GlobalConstraint::extend(int index, Value value, Cost cost) { assert(ToulBar2::verbose < 4 || ((cout << "[" << Store::getDepth() << "] extend(" << getName() << "," << getVar(index)->getName() << "," << value << ", " << cost << ")" << endl), true)); EnumeratedVariable* x = (EnumeratedVariable*)getVar(index); TreeDecomposition* td = wcsp->getTreeDec(); if (td) td->addDelta(cluster, x, value, -cost); deltaCost[index][x->toIndex(value)] -= cost; // Warning! Possible overflow??? x->extend(value, cost); } // function used for propagation void GlobalConstraint::remove(int index) { //vector<int> rmv; currentVar = -1; needPropagateDAC = true; needPropagateAC = true; } void GlobalConstraint::projectFromZero(int index) { //vector<int> rmv; currentVar = -1; needPropagateDAC = true; } void GlobalConstraint::propagate() { for (int i = 0; connected() && i < arity_; i++) { if (getVar(i)->assigned()) assign(i); } if (deconnected()) return; needPropagateEAC = false; currentVar = -1; wcsp->revise(this); vector<int> rmv; for (int i = 0; i < arity_; i++) rmv.push_back(i); checkRemoved(rmv); switch (ToulBar2::LcLevel) { case LC_DAC: if (needPropagateDAC || needPropagateAC) { propagateDAC(); needPropagateDAC = false; needPropagateAC = false; } break; case LC_EDAC: propagateEAC(); // not implemented yet (uses isEAC and findFullSupportEAC instead) case LC_FDAC: if (needPropagateDAC) { propagateDAC(); needPropagateDAC = false; } case LC_AC: if (needPropagateAC) { propagateAC(); needPropagateAC = false; } break; case LC_SNIC: propagateStrongNIC(); break; default: break; } } void GlobalConstraint::propagateEAC() { //not done here but wait for variable's propagateEAC // vector<int> provide; // provide.resize(arity_); // vector<map<Value, Cost> > deltas(arity_); // for (int i=0;i<arity_;i++) { // EnumeratedVariable *x = (EnumeratedVariable*)getVar(i); // for (EnumeratedVariable::iterator v = x->begin();v != x->end();++v) { // provide[i] = i; // deltas[i][*v] = x->getCost(*v); // } // } // changeAfterExtend(provide, deltas); // // for (int i=0;i<arity_;i++) { // if (getVar(i)->unassigned()) { // map<Value, Cost> delta; // EnumeratedVariable *x = (EnumeratedVariable*)getVar(i); // findProjection(i, delta); // for (map<Value, Cost>::iterator p = delta.begin(); p != delta.end();p++) { // if (wcsp->getLb() + p->second >= wcsp->getUb()) { // x->remove(p->first); // } // } // } // } // //undoExtend(); // changeAfterProject(provide, deltas); } void GlobalConstraint::propagateDAC() { if (ToulBar2::verbose >= 3) cout << "propagateDAC for " << *this << endl; vector<map<Value, Cost>> deltas; vector<int> vars; vector<int> rmv; //checkRemoved(rmv); for (int ii = 0; ii < arity_; ii++) { EnumeratedVariable* x = scope_dac[ii]; int i = scope_inv[x->wcspIndex]; if (x->unassigned()) { map<Value, Cost> delta; for (EnumeratedVariable::iterator it = x->begin(); it != x->end(); ++it) { delta[*it] = x->getCost(*it); //deltaCost[i][x->toIndex(*it)] -= x->getCost(*it); preUnaryCosts[i][x->toIndex(*it)] = x->getCost(*it); } vars.push_back(i); deltas.push_back(delta); } } changeAfterExtend(vars, deltas); for (int ii = 0; ii < arity_; ii++) { EnumeratedVariable* x = scope_dac[ii]; int varindex = scope_inv[x->wcspIndex]; if (x->unassigned()) { //delta.clear(); map<Value, Cost> delta; findProjection(varindex, delta); for (map<Value, Cost>::iterator i = delta.begin(); i != delta.end(); i++) { //deltaCost[varindex][x->toIndex(i->first)] += preUnaryCosts[varindex][x->toIndex(i->first)]; Cost costDelta = i->second - preUnaryCosts[varindex][x->toIndex(i->first)]; if (costDelta > 0) { if (CUT(costDelta + wcsp->getLb(), wcsp->getUb())) { i->second = preUnaryCosts[varindex][x->toIndex(i->first)]; } project(varindex, i->first, costDelta, true); } else if (costDelta < 0) { extend(varindex, i->first, -costDelta); } } changeAfterProject(varindex, delta); x->findSupport(); rmv.clear(); rmv.push_back(varindex); checkRemoved(rmv); } } //vector<int> rmv; // /*for (int i=0;i<arity_;i++) { if (getVar(i)->unassigned()) { checkRemoved(rmv); findFullSupport(i); } }*/ } void GlobalConstraint::propagateAC() { vector<int> rmv; for (int i = 0; i < arity_; i++) { if (getVar(i)->unassigned()) { findSupport(i); rmv.clear(); rmv.push_back(i); checkRemoved(rmv); } } } void GlobalConstraint::propagateStrongNIC() { vector<int> rmv; checkRemoved(rmv); bool cont = false; do { cont = false; for (int varindex = 0; varindex < arity_; varindex++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(varindex); if (x->unassigned()) { unsigned int oldD = x->getDomainSize(); checkMinCost(varindex); if (oldD != x->getDomainSize()) cont = true; } } if (cont) checkRemoved(rmv); } while (cont); propagateNIC(); } void GlobalConstraint::propagateNIC() { if (deconnected()) return; //wcsp->revise(this); vector<int> rmv; checkRemoved(rmv); Cost mincost = getMinCost(); if (mincost - projectedCost > 0) { Cost diff = mincost - projectedCost; projectedCost += diff; wcsp->increaseLb(diff); } } /*void GlobalConstraint::getCostsWithUnary(int index, map<Value, Cost> &costs) { vector<int> rmv, support; checkRemoved(rmv); vector<map<Value, Cost> > deltas; for (set<int>::iterator i = fullySupportedSet[index].begin();i != fullySupportedSet[index].end();i++) { EnumeratedVariable *x = (EnumeratedVariable*)getVar(*i); if (x->unassigned() && (*i != index)) { support.push_back(*i); map<Value, Cost> delta; for (EnumeratedVariable::iterator v = x->begin();v != x->end();++v) delta[*v] = x->getCost(*v); deltas.push_back(delta); } } changeAfterExtend(support, deltas); map<Value, Cost> delta; EnumeratedVariable *x = (EnumeratedVariable*)getVar(index); findProjection(index, delta); for (map<Value, Cost>::iterator p = delta.begin(); p != delta.end();p++) { costs[p->first] += p->second; } undoExtend(); }*/ bool GlobalConstraint::isEAC(int index, Value a) { if (ToulBar2::FullEAC) reviseEACGreedySolution(index, a); if (currentVar != index) { currentVar = index; vector<int> rmv; for (int i = 0; i < arity_; i++) rmv.push_back(i); checkRemoved(rmv); vector<int> support; vector<map<Value, Cost>> deltas; for (set<int>::iterator i = fullySupportedSet[index].begin(); i != fullySupportedSet[index].end(); i++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(*i); if (x->unassigned() && (*i != index)) { support.push_back(*i); map<Value, Cost> delta; for (EnumeratedVariable::iterator v = x->begin(); v != x->end(); ++v) delta[*v] = x->getCost(*v); deltas.push_back(delta); } } changeAfterExtend(support, deltas); EACCost.clear(); findProjection(index, EACCost); //undoExtend(); changeAfterProject(support, deltas); } if (EACCost[a] < 0) { cout << "EAC error\n"; EACCost[a] = 0; } //if (EACCost[a] > 0) needPropagateEAC = true; return (EACCost[a] == 0); } void GlobalConstraint::fillEAC2(int varindex) { currentVar = -1; for (int index = 0; index < arity_; index++) { if (index != varindex) { EnumeratedVariable* var = (EnumeratedVariable*)getVar(index); if (var->unassigned()) var->queueEAC2(); } } } //TODO: applies DAC order when enumerating variables (fullySupportedSet does not preserve DAC order) void GlobalConstraint::findFullSupportEAC(int index) { if (ToulBar2::verbose >= 3) cout << "findFullSupportEAC for variable " << index << endl; currentVar = -1; //if (needPropagateEAC) { //needPropagateEAC = false; vector<map<Value, Cost>> deltas; vector<int> vars; vector<int> rmv; //vars.push_back(index); vars.push_back(index); for (set<int>::iterator i = fullySupportedSet[index].begin(); i != fullySupportedSet[index].end(); i++) { EnumeratedVariable* x = scope[*i]; if (x->unassigned() && (*i != index)) { vars.push_back(*i); } } for (vector<int>::iterator i = vars.begin(); i != vars.end(); ++i) { EnumeratedVariable* x = scope[*i]; map<Value, Cost> delta; for (EnumeratedVariable::iterator it = x->begin(); it != x->end(); ++it) { delta[*it] = x->getCost(*it); //deltaCost[i][x->toIndex(*it)] -= x->getCost(*it); preUnaryCosts[*i][x->toIndex(*it)] = x->getCost(*it); } //vars.push_back(*i); deltas.push_back(delta); } changeAfterExtend(vars, deltas); for (vector<int>::iterator it = vars.begin(); it != vars.end(); ++it) { int varindex = *it; EnumeratedVariable* x = scope[varindex]; if (x->unassigned()) { //delta.clear(); map<Value, Cost> delta; findProjection(varindex, delta); for (map<Value, Cost>::iterator i = delta.begin(); i != delta.end(); i++) { //deltaCost[varindex][x->toIndex(i->first)] += preUnaryCosts[varindex][x->toIndex(i->first)]; Cost costDelta = i->second - preUnaryCosts[varindex][x->toIndex(i->first)]; if (costDelta > 0) { if (CUT(costDelta + wcsp->getLb(), wcsp->getUb())) { i->second = preUnaryCosts[varindex][x->toIndex(i->first)]; } project(varindex, i->first, costDelta, true); } else if (costDelta < 0) { extend(varindex, i->first, -costDelta); } } changeAfterProject(varindex, delta); x->findSupport(); rmv.clear(); rmv.push_back(varindex); checkRemoved(rmv); } } } } // THIS CODE IS NEVER USED!!! //TODO: applies DAC order when enumerating variables void GlobalConstraint::findFullSupport(int varindex, vector<int>& support, bool isEAC) { if (ToulBar2::verbose >= 3) cout << "findFullSupport for variable " << varindex << endl; //wcsp->revise(this); EnumeratedVariable* var = (EnumeratedVariable*)getVar(varindex); vector<map<Value, Cost>> deltas(support.size()); int count = 0; for (vector<int>::iterator i = support.begin(); i != support.end(); i++, count++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(*i); for (EnumeratedVariable::iterator v = x->begin(); v != x->end(); ++v) { deltas[count][*v] = x->getCost(*v); } } changeAfterExtend(support, deltas); map<Value, Cost> delta; findProjection(varindex, delta); map<Value, Cost> P; bool allzero = true; for (map<Value, Cost>::iterator i = delta.begin(); i != delta.end(); i++) { if (i->second > 0) { P[i->first] = i->second; allzero = false; } else if (i->second < 0) { P[i->first] = 0; cout << "projection error\n"; } } if (allzero) { //undoExtend(); changeAfterProject(support, deltas); return; } else { count_fdac++; } changeAfterProject(varindex, delta); // map<Value,Cost> *E = new map<Value, Cost>[support.size()]; vector<map<Value, Cost>> E; E.resize(support.size()); int index = 0; for (vector<int>::iterator i = support.begin(); i != support.end(); i++, index++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(*i); if (x->unassigned()) { delta.clear(); findProjection(*i, delta); for (map<Value, Cost>::iterator j = delta.begin(); j != delta.end(); j++) { E[index][j->first] = min(x->getCost(j->first) - j->second, x->getCost(j->first)); /*if (j->second < 0) { j->second = 0; }*/ //if (E[index][j->first] > 0) extendedCost[*i][j->first] += j->second; } changeAfterProject(*i, delta); } } index = 0; for (vector<int>::iterator i = support.begin(); i != support.end(); i++, index++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(*i); if (x->unassigned()) { for (map<Value, Cost>::iterator j = E[index].begin(); j != E[index].end(); j++) { if (j->second > 0) extend(*i, j->first, j->second); } } } index = 0; for (vector<int>::iterator i = support.begin(); i != support.end(); i++, index++) { EnumeratedVariable* x = (EnumeratedVariable*)getVar(*i); if (x->unassigned()) { bool supportbroken = false; for (map<Value, Cost>::iterator j = E[index].begin(); j != E[index].end(); j++) { if (j->second < 0) { if (j->first == x->getSupport()) supportbroken = true; project(*i, j->first, -j->second); } } if (supportbroken) x->findSupport(); } } bool supportbroken = false; for (map<Value, Cost>::iterator i = P.begin(); i != P.end(); i++) { if (i->second > 0) { if (i->first == var->getSupport()) supportbroken = true; project(varindex, i->first, i->second); } } if (supportbroken) var->findSupport(); // delete[] E; } void GlobalConstraint::findSupport(int varindex) { //wcsp->revise(this); if (ToulBar2::verbose >= 3) cout << "findSupport for variable " << varindex << endl; map<Value, Cost> delta; findProjection(varindex, delta); bool allzero = true; for (map<Value, Cost>::iterator i = delta.begin(); i != delta.end(); i++) { if (i->second > 0) allzero = false; } if (!allzero) { count_gac++; bool supportbroken = false; EnumeratedVariable* x = (EnumeratedVariable*)getVar(varindex); x->queueAC(); for (map<Value, Cost>::iterator i = delta.begin(); i != delta.end(); i++) { if (i->second > 0) { if (i->first == x->getSupport()) supportbroken = true; project(varindex, i->first, i->second); } } if (supportbroken) { x->findSupport(); } changeAfterProject(varindex, delta); } } void GlobalConstraint::checkMinCost(int varindex) { count_nic++; vector<Value> removed; EnumeratedVariable* x = (EnumeratedVariable*)getVar(varindex); map<Value, Cost> delta; findProjection(varindex, delta); for (EnumeratedVariable::iterator j = x->begin(); j != x->end(); ++j) { if (wcsp->getLb() + delta[*j] + x->getCost(*j) - projectedCost >= wcsp->getUb()) { removed.push_back(*j); } } for (vector<Value>::iterator i = removed.begin(); i != removed.end(); i++) { x->remove(*i); } if (!removed.empty()) x->queueAC(); } /* Local Variables: */ /* c-basic-offset: 4 */ /* tab-width: 4 */ /* indent-tabs-mode: nil */ /* c-default-style: "k&r" */ /* End: */
31.233333
193
0.525869
Pierre-Mont
b9a735d2a2dec18e68753353b32157e175c3777f
1,934
cpp
C++
dev/test/so_5/state/time_limit/reset_limit/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
272
2019-05-16T11:45:54.000Z
2022-03-28T09:32:14.000Z
dev/test/so_5/state/time_limit/reset_limit/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
40
2019-10-29T18:19:18.000Z
2022-03-30T09:02:49.000Z
dev/test/so_5/state/time_limit/reset_limit/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
29
2019-05-16T12:05:32.000Z
2022-03-19T12:28:33.000Z
/* * A test case for reseting time limit for a state. */ #include <iostream> #include <so_5/all.hpp> #include <test/3rd_party/various_helpers/time_limited_execution.hpp> class a_test_t final : public so_5::agent_t { state_t first{ this, "first" }; state_t second{ this, "second" }; struct sig_1 : public so_5::signal_t {}; struct sig_2 : public so_5::signal_t {}; struct finish : public so_5::signal_t {}; public : a_test_t( context_t ctx ) : so_5::agent_t{ ctx } { first .on_enter( []{ std::cout << "first on_enter" << std::endl; } ) .on_exit( [this] { std::cout << "first on_exit" << std::endl; so_5::send< finish >( *this ); } ) .time_limit( std::chrono::milliseconds{100}, second ) .event( [this](mhood_t< sig_1 >) { std::cout << "first sig_1, dropping time_limit" << std::endl; first.drop_time_limit(); so_5::send_delayed< sig_2 >( *this, std::chrono::milliseconds{200} ); } ) .event( [this](mhood_t< sig_2 >) { std::cout << "first sig_2, resetting time_limit" << std::endl; first.time_limit( std::chrono::milliseconds{50}, second ); } ); second .on_enter( []{ std::cout << "second on_enter" << std::endl; } ) .event( [this](mhood_t< finish >) { so_deregister_agent_coop_normally(); } ); } virtual void so_evt_start() override { this >>= first; so_5::send< sig_1 >( *this ); } }; int main() { try { run_with_time_limit( []() { so_5::launch( []( so_5::environment_t & env ) { env.introduce_coop( []( so_5::coop_t & coop ) { coop.make_agent< a_test_t >(); } ); }, []( so_5::environment_params_t & params ) { params.message_delivery_tracer( so_5::msg_tracing::std_cout_tracer() ); } ); }, 20, "test for resetting state's time_limit" ); } catch( const std::exception & ex ) { std::cerr << "Error: " << ex.what() << std::endl; return 1; } return 0; }
22.229885
73
0.601861
ZaMaZaN4iK
b9ab8c184956b997d0be4fc5a8ea3dade13ede8d
2,858
hpp
C++
ql/experimental/credit/onefactorgaussiancopula.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/experimental/credit/onefactorgaussiancopula.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/experimental/credit/onefactorgaussiancopula.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Roland Lichters This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file onefactorgaussiancopula.hpp \brief One-factor Gaussian copula */ #ifndef quantlib_one_factor_gaussian_copula_hpp #define quantlib_one_factor_gaussian_copula_hpp #include <ql/experimental/credit/onefactorcopula.hpp> #include <ql/math/distributions/normaldistribution.hpp> namespace QuantLib { //! One-factor Gaussian Copula /*! The copula model \f[ Y_i = a_i\,M+\sqrt{1-a_i^2}\:Z_i \f] is specified here by setting the desnity function for all variables, \f$ M, Z,\f$ and also \f$ Y \f$ to the standard normal distribution \f$ \phi(x) = \exp(-x^2/2) / \sqrt{2\pi}. \f$ */ class OneFactorGaussianCopula : public OneFactorCopula { public: OneFactorGaussianCopula (const Handle<Quote>& correlation, Real maximum = 5, Size integrationSteps = 50) : OneFactorCopula (correlation, maximum, integrationSteps) { registerWith(correlation_); } Real density (Real m) const; Real cumulativeZ (Real z) const; /*! overrides the base class implementation based on table data */ Real cumulativeY (Real y) const; Real testCumulativeY (Real y) const; /*! overrides the base class implementation based on table data */ Real inverseCumulativeY (Real p) const; private: // nothing to be done when correlation changes void performCalculations () const {} NormalDistribution density_; CumulativeNormalDistribution cumulative_; InverseCumulativeNormal inverseCumulative_; }; inline Real OneFactorGaussianCopula::density (Real m) const { return density_(m); } inline Real OneFactorGaussianCopula::cumulativeZ (Real z) const { return cumulative_(z); } inline Real OneFactorGaussianCopula::cumulativeY (Real y) const { return cumulative_(y); } inline Real OneFactorGaussianCopula::inverseCumulativeY (Real p) const { return inverseCumulative_(p); } } #endif
34.433735
79
0.687194
zhengyuzhang1
b9ac5b7a6d11f4b5284e01c4a13e96820221283b
46,157
cpp
C++
Microsoft.WindowsAzure.Storage/tests/cloud_page_blob_test.cpp
JasonDictos/azure-storage-cpp
8accecace59ad631cd7686f9e11fa7498fe717ac
[ "Apache-2.0" ]
null
null
null
Microsoft.WindowsAzure.Storage/tests/cloud_page_blob_test.cpp
JasonDictos/azure-storage-cpp
8accecace59ad631cd7686f9e11fa7498fe717ac
[ "Apache-2.0" ]
null
null
null
Microsoft.WindowsAzure.Storage/tests/cloud_page_blob_test.cpp
JasonDictos/azure-storage-cpp
8accecace59ad631cd7686f9e11fa7498fe717ac
[ "Apache-2.0" ]
null
null
null
// ----------------------------------------------------------------------------------------- // <copyright file="cloud_page_blob_test.cpp" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- #include "stdafx.h" #include "blob_test_base.h" #include "check_macros.h" #pragma region Fixture void page_blob_test_base::check_page_ranges_equal(const std::vector<azure::storage::page_range>& page_ranges) { auto downloaded_page_ranges = m_blob.download_page_ranges(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(page_ranges.size(), downloaded_page_ranges.size()); for (size_t i = 0; i < page_ranges.size(); ++i) { CHECK_EQUAL(page_ranges[i].start_offset(), downloaded_page_ranges[i].start_offset()); CHECK_EQUAL(page_ranges[i].end_offset(), downloaded_page_ranges[i].end_offset()); } } static std::string ACTIVE_LEASE_ERROR_MESSAGE = "There is currently a lease on the blob and no lease ID was specified in the request."; #pragma endregion SUITE(Blob) { TEST_FIXTURE(page_blob_test_base, page_blob_create) { auto same_blob = m_container.get_page_blob_reference(m_blob.name()); CHECK(!same_blob.exists(azure::storage::blob_request_options(), m_context)); m_blob.create(1024, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); CHECK_EQUAL(1024, m_blob.properties().size()); CHECK_EQUAL(0, same_blob.properties().size()); CHECK(same_blob.exists(azure::storage::blob_request_options(), m_context)); CHECK_EQUAL(1024, same_blob.properties().size()); m_blob.delete_blob(azure::storage::delete_snapshots_option::none, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK(!same_blob.exists(azure::storage::blob_request_options(), m_context)); CHECK_EQUAL(1024, same_blob.properties().size()); m_blob.create(2048, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); CHECK_EQUAL(2048, m_blob.properties().size()); CHECK_EQUAL(1024, same_blob.properties().size()); CHECK(same_blob.exists(azure::storage::blob_request_options(), m_context)); CHECK_EQUAL(2048, same_blob.properties().size()); } TEST_FIXTURE(page_blob_test_base, page_blob_resize) { m_blob.properties().set_content_language(_XPLATSTR("tr,en")); m_blob.create(1024, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); CHECK_EQUAL(1024, m_blob.properties().size()); m_blob.properties().set_content_language(_XPLATSTR("en")); m_blob.resize(2048, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(2048, m_blob.properties().size()); CHECK_UTF8_EQUAL(_XPLATSTR("en"), m_blob.properties().content_language()); m_blob.download_attributes(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_UTF8_EQUAL(_XPLATSTR("tr,en"), m_blob.properties().content_language()); } TEST_FIXTURE(page_blob_test_base, page_blob_sequence_number) { m_blob.properties().set_content_language(_XPLATSTR("tr,en")); m_blob.create(512, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); CHECK_EQUAL(512, m_blob.properties().size()); CHECK_EQUAL(0, m_blob.properties().page_blob_sequence_number()); m_blob.properties().set_content_language(_XPLATSTR("en")); m_blob.set_sequence_number(azure::storage::sequence_number::update(5), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(5, m_blob.properties().page_blob_sequence_number()); m_blob.set_sequence_number(azure::storage::sequence_number::maximum(7), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(7, m_blob.properties().page_blob_sequence_number()); m_blob.set_sequence_number(azure::storage::sequence_number::maximum(3), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(7, m_blob.properties().page_blob_sequence_number()); m_blob.set_sequence_number(azure::storage::sequence_number::increment(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(8, m_blob.properties().page_blob_sequence_number()); CHECK_UTF8_EQUAL(_XPLATSTR("en"), m_blob.properties().content_language()); m_blob.download_attributes(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_UTF8_EQUAL(_XPLATSTR("tr,en"), m_blob.properties().content_language()); CHECK_EQUAL(8, m_blob.properties().page_blob_sequence_number()); m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_equal_condition(8), azure::storage::blob_request_options(), m_context); m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_less_than_or_equal_condition(8), azure::storage::blob_request_options(), m_context); m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_less_than_or_equal_condition(9), azure::storage::blob_request_options(), m_context); m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_less_than_condition(9), azure::storage::blob_request_options(), m_context); CHECK_THROW(m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_equal_condition(7), azure::storage::blob_request_options(), m_context), azure::storage::storage_exception); CHECK_THROW(m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_less_than_or_equal_condition(7), azure::storage::blob_request_options(), m_context), azure::storage::storage_exception); CHECK_THROW(m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_less_than_or_equal_condition(7), azure::storage::blob_request_options(), m_context), azure::storage::storage_exception); CHECK_THROW(m_blob.clear_pages(0, 512, azure::storage::access_condition::generate_if_sequence_number_less_than_condition(7), azure::storage::blob_request_options(), m_context), azure::storage::storage_exception); } TEST_FIXTURE(page_blob_test_base, page_blob_create_with_sequence_number) { int64_t seq = get_random_int64() & 0x7FFFFFFFFFFFFFFFllu; m_blob.create(512, seq, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); m_blob.set_sequence_number(azure::storage::sequence_number::increment(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(seq + 1, m_blob.properties().page_blob_sequence_number()); } TEST_FIXTURE(page_blob_test_base, page_upload) { std::vector<uint8_t> buffer; buffer.resize(512); azure::storage::blob_request_options options; std::vector<azure::storage::page_range> pages; utility::string_t md5_header; m_context.set_sending_request([&md5_header] (web::http::http_request& request, azure::storage::operation_context) { if (!request.headers().match(web::http::header_names::content_md5, md5_header)) { md5_header.clear(); } }); m_blob.create(12 * 1024 * 1024, 0, azure::storage::access_condition(), options, m_context); check_blob_no_stale_property(m_blob); options.set_use_transactional_md5(false); for (int i = 0; i < 3; ++i) { fill_buffer_and_get_md5(buffer); auto stream = concurrency::streams::bytestream::open_istream(buffer); azure::storage::page_range range(i * 1024, i * 1024 + buffer.size() - 1); pages.push_back(range); m_blob.upload_pages(stream, range.start_offset(), utility::string_t(), azure::storage::access_condition(), options, m_context); CHECK_UTF8_EQUAL(utility::string_t(), md5_header); } check_page_ranges_equal(pages); options.set_use_transactional_md5(false); for (int i = 3; i < 6; ++i) { auto md5 = fill_buffer_and_get_md5(buffer); auto stream = concurrency::streams::bytestream::open_istream(buffer); azure::storage::page_range range(i * 1536, i * 1536 + buffer.size() - 1); pages.push_back(range); m_blob.upload_pages(stream, range.start_offset(), md5, azure::storage::access_condition(), options, m_context); CHECK_UTF8_EQUAL(md5, md5_header); } check_page_ranges_equal(pages); options.set_use_transactional_md5(true); for (int i = 6; i < 9; ++i) { auto md5 = fill_buffer_and_get_md5(buffer); auto stream = concurrency::streams::bytestream::open_istream(buffer); azure::storage::page_range range(i * 2048, i * 2048 + buffer.size() - 1); pages.push_back(range); m_blob.upload_pages(stream, range.start_offset(), utility::string_t(), azure::storage::access_condition(), options, m_context); CHECK_UTF8_EQUAL(md5, md5_header); } options.set_use_transactional_md5(false); { // upload a page range of max_page_size std::vector<uint8_t> big_buffer; big_buffer.resize(azure::storage::protocol::max_page_size); auto md5 = fill_buffer_and_get_md5(big_buffer); auto stream = concurrency::streams::bytestream::open_istream(big_buffer); azure::storage::page_range range(4 * 1024 * 1024, 4 * 1024 * 1024 + azure::storage::protocol::max_page_size - 1); pages.push_back(range); m_blob.upload_pages(stream, range.start_offset(), md5, azure::storage::access_condition(), options, m_context); CHECK_UTF8_EQUAL(md5, md5_header); } check_page_ranges_equal(pages); options.set_use_transactional_md5(true); { fill_buffer_and_get_md5(buffer); auto stream = concurrency::streams::bytestream::open_istream(buffer); CHECK_THROW(m_blob.upload_pages(stream, 0, dummy_md5, azure::storage::access_condition(), options, m_context), azure::storage::storage_exception); CHECK_UTF8_EQUAL(dummy_md5, md5_header); } // trying upload page ranges bigger than max_page_size { buffer.resize(azure::storage::protocol::max_page_size + 1); fill_buffer_and_get_md5(buffer); azure::storage::page_range range(8 * 1024 * 1024, 8 * 1024 * 1024 + azure::storage::protocol::max_page_size -1); auto stream = concurrency::streams::bytestream::open_istream(buffer); CHECK_THROW(m_blob.upload_pages(stream, range.start_offset(), utility::string_t(), azure::storage::access_condition(), options, m_context), std::invalid_argument); } check_page_ranges_equal(pages); m_context.set_sending_request(std::function<void(web::http::http_request &, azure::storage::operation_context)>()); } TEST_FIXTURE(page_blob_test_base, page_clear) { std::vector<uint8_t> buffer; buffer.resize(16 * 1024); azure::storage::blob_request_options options; fill_buffer_and_get_md5(buffer); auto stream = concurrency::streams::bytestream::open_istream(buffer); m_blob.upload_from_stream(stream, 0, azure::storage::access_condition(), options, m_context); std::vector<azure::storage::page_range> pages; pages.push_back(azure::storage::page_range(0, 512 - 1)); pages.push_back(azure::storage::page_range(512 * 2, 10 * 1024 - 1)); pages.push_back(azure::storage::page_range(13 * 1024, buffer.size() - 1)); for (size_t i = 1; i < pages.size(); i++) { int64_t start_offset = pages[i - 1].end_offset() + 1; int64_t length = pages[i].start_offset() - start_offset; m_blob.clear_pages(start_offset, length, azure::storage::access_condition(), options, m_context); } check_page_ranges_equal(pages); } TEST_FIXTURE(page_blob_test_base, page_blob_upload) { const size_t size = 6 * 1024 * 1024; azure::storage::blob_request_options options; options.set_use_transactional_md5(true); check_parallelism(upload_and_download(m_blob, size, 0, 0, true, options, 3, false), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_store_blob_content_md5(true); check_parallelism(upload_and_download(m_blob, size, 0, 0, true, options, 4, true), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_store_blob_content_md5(false); options.set_stream_write_size_in_bytes(1 * 1024 * 1024); check_parallelism(upload_and_download(m_blob, size, 0, 0, true, options, 7, false), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_parallelism_factor(4); check_parallelism(upload_and_download(m_blob, size, 0, 0, true, options, 7, false), 4); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_parallelism_factor(8); options.set_store_blob_content_md5(true); check_parallelism(upload_and_download(m_blob, size, 0, 0, true, options, 8, true), 6); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); } TEST_FIXTURE(page_blob_test_base, page_blob_upload_with_nonseekable) { const size_t size = 6 * 1024 * 1024; azure::storage::blob_request_options options; CHECK_THROW(upload_and_download(m_blob, size, 0, 0, false, options, 3, false), std::logic_error); } TEST_FIXTURE(page_blob_test_base, page_blob_upload_with_size) { const size_t buffer_size = 6 * 1024 * 1024; const size_t blob_size = 4 * 1024 * 1024; azure::storage::blob_request_options options; options.set_use_transactional_md5(true); const size_t buffer_offsets[2] = { 0, 1024 }; for (auto buffer_offset : buffer_offsets) { options.set_stream_write_size_in_bytes(blob_size); options.set_store_blob_content_md5(false); options.set_parallelism_factor(1); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, true, options, 2, false), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_store_blob_content_md5(true); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, true, options, 3, true), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_stream_write_size_in_bytes(1 * 1024 * 1024); options.set_store_blob_content_md5(false); options.set_parallelism_factor(4); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, true, options, 5, false), 4); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_parallelism_factor(8); options.set_store_blob_content_md5(true); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, true, options, 6, true), 4); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); } } TEST_FIXTURE(page_blob_test_base, page_blob_upload_with_size_with_nonseekable) { const size_t buffer_size = 6 * 1024 * 1024; const size_t blob_size = 4 * 1024 * 1024; azure::storage::blob_request_options options; options.set_use_transactional_md5(true); const size_t buffer_offsets[2] = { 0, 1024 }; for (auto buffer_offset : buffer_offsets) { options.set_stream_write_size_in_bytes(blob_size); options.set_store_blob_content_md5(false); options.set_parallelism_factor(1); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, false, options, 2, false), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_store_blob_content_md5(true); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, false, options, 3, true), 1); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_stream_write_size_in_bytes(1 * 1024 * 1024); options.set_store_blob_content_md5(false); options.set_parallelism_factor(4); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, false, options, 5, false), 4); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); options.set_parallelism_factor(8); options.set_store_blob_content_md5(true); check_parallelism(upload_and_download(m_blob, buffer_size, buffer_offset, blob_size, false, options, 6, true), 4); m_blob.delete_blob(); m_blob.properties().set_content_md5(utility::string_t()); } } TEST_FIXTURE(page_blob_test_base, page_blob_upload_with_invalid_size) { const size_t buffer_size = 2 * 1024 * 1024; azure::storage::blob_request_options options; CHECK_THROW(upload_and_download(m_blob, buffer_size, 0, buffer_size + 1, true, options, 0, false), azure::storage::storage_exception); CHECK_THROW(upload_and_download(m_blob, buffer_size, 0, buffer_size + 1, false, options, 0, false), azure::storage::storage_exception); CHECK_THROW(upload_and_download(m_blob, buffer_size, 1024, buffer_size - 1023, true, options, 0, false), azure::storage::storage_exception); CHECK_THROW(upload_and_download(m_blob, buffer_size, 1024, buffer_size - 1023, false, options, 0, false), azure::storage::storage_exception); } TEST_FIXTURE(page_blob_test_base, page_blob_file_upload) { azure::storage::blob_request_options options; options.set_store_blob_content_md5(true); utility::string_t md5_header; m_context.set_sending_request([&md5_header] (web::http::http_request& request, azure::storage::operation_context) { if (!request.headers().match(_XPLATSTR("x-ms-blob-content-md5"), md5_header)) { md5_header.clear(); } }); temp_file invalid_file(1000); CHECK_THROW(m_blob.upload_from_file(invalid_file.path(), 0, azure::storage::access_condition(), options, m_context), azure::storage::storage_exception); temp_file file(1024); m_blob.upload_from_file(file.path(), 0, azure::storage::access_condition(), options, m_context); CHECK_UTF8_EQUAL(file.content_md5(), md5_header); m_context.set_sending_request(std::function<void(web::http::http_request &, azure::storage::operation_context)>()); temp_file file2(0); m_blob.download_to_file(file2.path(), azure::storage::access_condition(), options, m_context); concurrency::streams::container_buffer<std::vector<uint8_t>> original_file_buffer; auto original_file = concurrency::streams::file_stream<uint8_t>::open_istream(file.path()).get(); original_file.read_to_end(original_file_buffer).wait(); original_file.close().wait(); concurrency::streams::container_buffer<std::vector<uint8_t>> downloaded_file_buffer; auto downloaded_file = concurrency::streams::file_stream<uint8_t>::open_istream(file2.path()).get(); downloaded_file.read_to_end(downloaded_file_buffer).wait(); downloaded_file.close().wait(); CHECK_EQUAL(original_file_buffer.collection().size(), downloaded_file_buffer.collection().size()); CHECK_ARRAY_EQUAL(original_file_buffer.collection(), downloaded_file_buffer.collection(), (int)downloaded_file_buffer.collection().size()); m_blob.properties().set_content_md5(dummy_md5); m_blob.upload_properties(); options.set_retry_policy(azure::storage::no_retry_policy()); CHECK_THROW(m_blob.download_to_file(file2.path(), azure::storage::access_condition(), options, m_context), azure::storage::storage_exception); } TEST_FIXTURE(page_blob_test_base, page_blob_constructor) { m_blob.create(0, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); CHECK(!m_blob.properties().etag().empty()); azure::storage::cloud_page_blob blob1(m_blob.uri()); CHECK_UTF8_EQUAL(m_blob.name(), blob1.name()); CHECK_UTF8_EQUAL(m_blob.uri().primary_uri().to_string(), blob1.uri().primary_uri().to_string()); CHECK_UTF8_EQUAL(m_blob.uri().secondary_uri().to_string(), blob1.uri().secondary_uri().to_string()); CHECK(blob1.properties().etag().empty()); azure::storage::cloud_blob blob2(m_blob); CHECK_UTF8_EQUAL(m_blob.name(), blob2.name()); CHECK_UTF8_EQUAL(m_blob.uri().primary_uri().to_string(), blob2.uri().primary_uri().to_string()); CHECK_UTF8_EQUAL(m_blob.uri().secondary_uri().to_string(), blob2.uri().secondary_uri().to_string()); CHECK_UTF8_EQUAL(m_blob.properties().etag(), blob2.properties().etag()); azure::storage::cloud_page_blob blob3(blob2); CHECK_UTF8_EQUAL(m_blob.name(), blob3.name()); CHECK_UTF8_EQUAL(m_blob.uri().primary_uri().to_string(), blob3.uri().primary_uri().to_string()); CHECK_UTF8_EQUAL(m_blob.uri().secondary_uri().to_string(), blob3.uri().secondary_uri().to_string()); CHECK_UTF8_EQUAL(m_blob.properties().etag(), blob2.properties().etag()); } TEST_FIXTURE(page_blob_test_base, page_blob_create_with_metadata) { m_blob.metadata()[_XPLATSTR("key1")] = _XPLATSTR("value1"); m_blob.metadata()[_XPLATSTR("key2")] = _XPLATSTR("value2"); m_blob.create(0, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); auto same_blob = m_container.get_page_blob_reference(m_blob.name()); CHECK(same_blob.metadata().empty()); same_blob.download_attributes(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(2U, same_blob.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), same_blob.metadata()[_XPLATSTR("key1")]); CHECK_UTF8_EQUAL(_XPLATSTR("value2"), same_blob.metadata()[_XPLATSTR("key2")]); } TEST_FIXTURE(page_blob_test_base, page_blob_snapshot_metadata) { m_blob.metadata()[_XPLATSTR("key1")] = _XPLATSTR("value1"); m_blob.metadata()[_XPLATSTR("key2")] = _XPLATSTR("value2"); m_blob.create(0, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); check_blob_no_stale_property(m_blob); auto snapshot1 = m_blob.create_snapshot(azure::storage::cloud_metadata(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(2U, snapshot1.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), snapshot1.metadata()[_XPLATSTR("key1")]); CHECK_UTF8_EQUAL(_XPLATSTR("value2"), snapshot1.metadata()[_XPLATSTR("key2")]); azure::storage::cloud_page_blob snapshot1_clone(snapshot1.uri(), snapshot1.snapshot_time(), snapshot1.service_client().credentials()); CHECK(snapshot1_clone.metadata().empty()); snapshot1_clone.download_attributes(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(2U, snapshot1_clone.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), snapshot1_clone.metadata()[_XPLATSTR("key1")]); CHECK_UTF8_EQUAL(_XPLATSTR("value2"), snapshot1_clone.metadata()[_XPLATSTR("key2")]); azure::storage::cloud_metadata snapshot_metadata; snapshot_metadata[_XPLATSTR("key3")] = _XPLATSTR("value1"); snapshot_metadata[_XPLATSTR("key4")] = _XPLATSTR("value2"); auto snapshot2 = m_blob.create_snapshot(snapshot_metadata, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(2U, snapshot1.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), snapshot2.metadata()[_XPLATSTR("key3")]); CHECK_UTF8_EQUAL(_XPLATSTR("value2"), snapshot2.metadata()[_XPLATSTR("key4")]); azure::storage::cloud_page_blob snapshot2_clone(snapshot2.uri(), snapshot2.snapshot_time(), snapshot2.service_client().credentials()); CHECK(snapshot2_clone.metadata().empty()); snapshot2_clone.download_attributes(azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(2U, snapshot2_clone.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), snapshot2_clone.metadata()[_XPLATSTR("key3")]); CHECK_UTF8_EQUAL(_XPLATSTR("value2"), snapshot2_clone.metadata()[_XPLATSTR("key4")]); } TEST_FIXTURE(page_blob_test_base, page_blob_upload_maximum_execution_time) { std::chrono::seconds duration(10); std::vector<uint8_t> buffer; buffer.resize(2 * 1024 * 1024); azure::storage::blob_request_options options; options.set_maximum_execution_time(duration); options.set_stream_write_size_in_bytes(buffer.size() / 2); m_context.set_response_received([duration] (web::http::http_request&, const web::http::http_response&, azure::storage::operation_context) { std::this_thread::sleep_for(duration); }); CHECK_THROW(m_blob.upload_from_stream(concurrency::streams::bytestream::open_istream(std::move(buffer)), 0, azure::storage::access_condition(), options, m_context), azure::storage::storage_exception); CHECK_EQUAL(2U, m_context.request_results().size()); m_context.set_response_received(std::function<void(web::http::http_request &, const web::http::http_response&, azure::storage::operation_context)>()); } TEST_FIXTURE(page_blob_test_base, page_blob_prevsnapshot) { m_blob.create(2048, 0, azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); azure::storage::cloud_page_blob snapshot1 = m_blob.create_snapshot(azure::storage::cloud_metadata(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); auto diff = m_blob.download_page_ranges_diff(snapshot1.snapshot_time(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK(0 == diff.size()); { utility::string_t content(2048, _XPLATSTR('A')); auto utf8_body = utility::conversions::to_utf8string(content); auto stream = concurrency::streams::bytestream::open_istream(std::move(utf8_body)); m_blob.upload_pages(stream, 0, _XPLATSTR("")); diff = m_blob.download_page_ranges_diff(snapshot1.snapshot_time(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK(1 == diff.size()); CHECK_EQUAL(false, diff[0].is_cleared_rage()); CHECK(0 == diff[0].start_offset()); CHECK(2047 == diff[0].end_offset()); } azure::storage::cloud_page_blob snapshot2 = m_blob.create_snapshot(azure::storage::cloud_metadata(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); auto diff2 = snapshot2.download_page_ranges_diff(snapshot1.snapshot_time(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK_EQUAL(false, diff[0].is_cleared_rage()); CHECK(0 == diff[0].start_offset()); CHECK(2047 == diff[0].end_offset()); { utility::string_t content(512, _XPLATSTR('B')); auto utf8_body = utility::conversions::to_utf8string(content); auto stream = concurrency::streams::bytestream::open_istream(std::move(utf8_body)); m_blob.upload_pages(stream, 0, _XPLATSTR("")); m_blob.clear_pages(512, 512); diff = m_blob.download_page_ranges_diff(snapshot2.snapshot_time(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK(2 == diff.size()); if (diff[0].is_cleared_rage() == true) { auto temp = diff[0]; diff[0] = diff[1]; diff[1] = temp; } CHECK_EQUAL(false, diff[0].is_cleared_rage()); CHECK(0 == diff[0].start_offset()); CHECK(511 == diff[0].end_offset()); CHECK_EQUAL(true, diff[1].is_cleared_rage()); CHECK(512 == diff[1].start_offset()); CHECK(1023 == diff[1].end_offset()); } azure::storage::cloud_page_blob snapshot3 = m_blob.create_snapshot(azure::storage::cloud_metadata(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); auto diff3 = snapshot3.download_page_ranges_diff(snapshot2.snapshot_time(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK(2 == diff.size()); if (diff[0].is_cleared_rage() == true) { auto temp = diff[0]; diff[0] = diff[1]; diff[1] = temp; } CHECK_EQUAL(false, diff[0].is_cleared_rage()); CHECK(0 == diff[0].start_offset()); CHECK(511 == diff[0].end_offset()); CHECK_EQUAL(true, diff[1].is_cleared_rage()); CHECK(512 == diff[1].start_offset()); CHECK(1023 == diff[1].end_offset()); { utility::string_t content(2048, _XPLATSTR('A')); auto utf8_body = utility::conversions::to_utf8string(content); auto stream = concurrency::streams::bytestream::open_istream(std::move(utf8_body)); m_blob.upload_pages(stream, 0, _XPLATSTR("")); diff = m_blob.download_page_ranges_diff(snapshot1.snapshot_time(), azure::storage::access_condition(), azure::storage::blob_request_options(), m_context); CHECK(1 == diff.size()); CHECK_EQUAL(false, diff[0].is_cleared_rage()); CHECK(0 == diff[0].start_offset()); CHECK(2047 == diff[0].end_offset()); } } TEST_FIXTURE(page_blob_test_base, page_blob_incremental_copy) { // get sas token for test azure::storage::blob_shared_access_policy policy; policy.set_permissions(azure::storage::blob_shared_access_policy::permissions::read); policy.set_start(utility::datetime::utc_now() - utility::datetime::from_minutes(5)); policy.set_expiry(utility::datetime::utc_now() + utility::datetime::from_minutes(30)); auto sas_token = m_container.get_shared_access_signature(policy); // prepare data m_blob.metadata()[_XPLATSTR("key1")] = _XPLATSTR("value1"); m_blob.create(2048); azure::storage::cloud_page_blob source_snapshot; auto inc_copy = m_container.get_page_blob_reference(m_blob.name() + _XPLATSTR("_copy")); // Scenario: incremental copy to create destination page blob { // perform actions source_snapshot = m_blob.create_snapshot(); auto source_uri = azure::storage::storage_credentials(sas_token).transform_uri(source_snapshot.snapshot_qualified_uri().primary_uri()); auto copy_id = inc_copy.start_incremental_copy(source_uri); auto inc_copy_ref = m_container.get_page_blob_reference(inc_copy.name()); wait_for_copy(inc_copy_ref); // verify copy id is valid but abort copy operation is invalid. azure::storage::operation_context context; CHECK_THROW(inc_copy.abort_copy(copy_id, azure::storage::access_condition(), azure::storage::blob_request_options(), context), azure::storage::storage_exception); CHECK_EQUAL(1u, context.request_results().size()); CHECK_EQUAL(web::http::status_codes::Conflict, context.request_results().back().http_status_code()); // verify incremental copy related properties and metadata. CHECK_EQUAL(true, inc_copy_ref.properties().is_incremental_copy()); CHECK(inc_copy_ref.copy_state().destination_snapshot_time().is_initialized()); CHECK_EQUAL(1u, inc_copy_ref.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), inc_copy_ref.metadata()[_XPLATSTR("key1")]); // verify destination blob properties retrieved with list blobs and snapshots of destination blobs auto iter = m_container.list_blobs(inc_copy_ref.name(), true, azure::storage::blob_listing_details::snapshots, 10, azure::storage::blob_request_options(), azure::storage::operation_context()); auto dest_blobs = transform_if<azure::storage::list_blob_item_iterator, azure::storage::cloud_blob>(iter, [](const azure::storage::list_blob_item& item)->bool { return item.is_blob(); }, [](const azure::storage::list_blob_item& item)->azure::storage::cloud_blob { return item.as_blob(); }); CHECK_EQUAL(2u, dest_blobs.size()); auto dest_blob_it = std::find_if(dest_blobs.cbegin(), dest_blobs.cend(), [](const azure::storage::cloud_blob& blob)->bool { return blob.snapshot_time().empty(); }); CHECK(dest_blob_it != dest_blobs.end()); CHECK_EQUAL(true, dest_blob_it->properties().is_incremental_copy()); CHECK(dest_blob_it->copy_state().destination_snapshot_time().is_initialized()); auto dest_snapshot_it = std::find_if(dest_blobs.begin(), dest_blobs.end(), [](const azure::storage::cloud_blob& blob)->bool { return !blob.snapshot_time().empty(); }); CHECK(dest_snapshot_it != dest_blobs.end()); CHECK_EQUAL(true, dest_snapshot_it->properties().is_incremental_copy()); CHECK(dest_snapshot_it->copy_state().destination_snapshot_time().is_initialized()); CHECK(dest_blob_it->copy_state().destination_snapshot_time() == parse_datetime(dest_snapshot_it->snapshot_time(), utility::datetime::date_format::ISO_8601)); // verify readability of destination snapshot concurrency::streams::container_buffer<std::vector<uint8_t>> buff; CHECK_NOTHROW(dest_snapshot_it->download_to_stream(buff.create_ostream())); } // Scenario: incremental copy new snapshot to destination blob { // make some changes on source utility::string_t content(2048, _XPLATSTR('A')); auto utf8_body = utility::conversions::to_utf8string(content); auto stream = concurrency::streams::bytestream::open_istream(std::move(utf8_body)); m_blob.upload_pages(stream, 0, _XPLATSTR("")); // create new snapshot of source and incremental copy once again. source_snapshot = m_blob.create_snapshot(); auto source_uri = azure::storage::storage_credentials(sas_token).transform_uri(source_snapshot.snapshot_qualified_uri().primary_uri()); inc_copy.start_incremental_copy(source_uri); auto inc_copy_ref = m_container.get_page_blob_reference(inc_copy.name()); wait_for_copy(inc_copy_ref); // verify incremental copy related properties and metadata. CHECK_EQUAL(true, inc_copy_ref.properties().is_incremental_copy()); CHECK(inc_copy_ref.copy_state().destination_snapshot_time().is_initialized()); CHECK_EQUAL(1u, inc_copy_ref.metadata().size()); CHECK_UTF8_EQUAL(_XPLATSTR("value1"), inc_copy_ref.metadata()[_XPLATSTR("key1")]); // verify snapshots of destination blobs auto iter = m_container.list_blobs(inc_copy_ref.name(), true, azure::storage::blob_listing_details::snapshots, 10, azure::storage::blob_request_options(), azure::storage::operation_context()); auto dest_blobs = transform_if<azure::storage::list_blob_item_iterator, azure::storage::cloud_blob>(iter, [](const azure::storage::list_blob_item& item)->bool { return item.is_blob(); }, [](const azure::storage::list_blob_item& item)->azure::storage::cloud_blob { return item.as_blob(); }); CHECK_EQUAL(3u, dest_blobs.size()); CHECK_EQUAL(2, std::count_if(dest_blobs.begin(), dest_blobs.end(), [](const azure::storage::cloud_blob& b) -> bool { return !b.snapshot_time().empty(); })); std::sort(dest_blobs.begin(), dest_blobs.end(), [](const azure::storage::cloud_blob& l, const azure::storage::cloud_blob& r) -> bool { return parse_datetime(l.snapshot_time(), utility::datetime::date_format::ISO_8601).to_interval() < parse_datetime(r.snapshot_time(), utility::datetime::date_format::ISO_8601).to_interval(); }); CHECK(inc_copy_ref.copy_state().destination_snapshot_time() == parse_datetime(dest_blobs.back().snapshot_time(), utility::datetime::date_format::ISO_8601)); } // Scenario: delete destination snapshot and perform incremental copy again { // verify the scenario CHECK_NOTHROW(inc_copy.delete_blob(azure::storage::delete_snapshots_option::delete_snapshots_only, azure::storage::access_condition(), azure::storage::blob_request_options(), azure::storage::operation_context())); auto source_uri = azure::storage::storage_credentials(sas_token).transform_uri(source_snapshot.snapshot_qualified_uri().primary_uri()); CHECK_NOTHROW(inc_copy.start_incremental_copy(source_uri)); auto inc_copy_ref = m_container.get_page_blob_reference(inc_copy.name()); wait_for_copy(inc_copy_ref); // verify snapshots of destination blob auto iter = m_container.list_blobs(inc_copy_ref.name(), true, azure::storage::blob_listing_details::snapshots, 10, azure::storage::blob_request_options(), azure::storage::operation_context()); auto dest_blobs = transform_if<azure::storage::list_blob_item_iterator, azure::storage::cloud_blob>(iter, [](const azure::storage::list_blob_item& item)->bool { return item.is_blob(); }, [](const azure::storage::list_blob_item& item)->azure::storage::cloud_blob { return item.as_blob(); }); CHECK_EQUAL(2u, dest_blobs.size()); } // Misc. verifications { azure::storage::operation_context context; // verify incremental copy same snapshot auto source_uri = azure::storage::storage_credentials(sas_token).transform_uri(source_snapshot.snapshot_qualified_uri().primary_uri()); CHECK_THROW(inc_copy.start_incremental_copy(source_uri, azure::storage::access_condition(), azure::storage::blob_request_options(), context), azure::storage::storage_exception); CHECK_EQUAL(1u, context.request_results().size()); CHECK_EQUAL(web::http::status_codes::Conflict, context.request_results().back().http_status_code()); // verify readability of destination blob concurrency::streams::container_buffer<std::vector<uint8_t>> buff; CHECK_THROW(inc_copy.download_to_stream(buff.create_ostream(), azure::storage::access_condition(), azure::storage::blob_request_options(), context), azure::storage::storage_exception); CHECK_EQUAL(2u, context.request_results().size()); CHECK_EQUAL(web::http::status_codes::Conflict, context.request_results().back().http_status_code()); // verify deletion of destination blob CHECK_NOTHROW(inc_copy.delete_blob(azure::storage::delete_snapshots_option::include_snapshots, azure::storage::access_condition(), azure::storage::blob_request_options(), context)); } } // Validate set standard blob tier for block blob on blob storage account. TEST_FIXTURE(premium_page_blob_test_base, page_blob_premium_tier) { // preparation azure::storage::blob_request_options options; // check default tier is p10 m_blob.create(1024); m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p10 == m_blob.properties().premium_blob_tier()); // check create page blob sets the tier to be p20 m_blob.create(1024, azure::storage::premium_blob_tier::p20, 0, azure::storage::access_condition(), options, azure::storage::operation_context()); CHECK(azure::storage::premium_blob_tier::p20 == m_blob.properties().premium_blob_tier()); m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p20 == m_blob.properties().premium_blob_tier()); // test can convert p20 to p30, p30 to p40. m_blob.set_premium_blob_tier(azure::storage::premium_blob_tier::p30, azure::storage::access_condition(), options, azure::storage::operation_context()); // validate local has been updated. CHECK(azure::storage::premium_blob_tier::p30 == m_blob.properties().premium_blob_tier()); // validate server has been updated m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p30 == m_blob.properties().premium_blob_tier()); m_blob.set_premium_blob_tier(azure::storage::premium_blob_tier::p40, azure::storage::access_condition(), options, azure::storage::operation_context()); // validate local has been updated. CHECK(azure::storage::premium_blob_tier::p40 == m_blob.properties().premium_blob_tier()); // validate server has been updated m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p40 == m_blob.properties().premium_blob_tier()); } TEST_FIXTURE(premium_page_blob_test_base, set_blob_tier_with_lease) { // preparation azure::storage::blob_request_options options; // check default tier is p10 m_blob.create(1024); m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p10 == m_blob.properties().premium_blob_tier()); // acquire a lease auto lease_id = m_blob.acquire_lease(azure::storage::lease_time(), _XPLATSTR("")); // set the acquired lease to access condition. azure::storage::access_condition condition; condition.set_lease_id(lease_id); // check create page blob sets the tier to be p20 m_blob.create(1024, azure::storage::premium_blob_tier::p20, 0, condition, options, azure::storage::operation_context()); CHECK(azure::storage::premium_blob_tier::p20 == m_blob.properties().premium_blob_tier()); m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p20 == m_blob.properties().premium_blob_tier()); // test can convert p20 to p30, p30 to p40. m_blob.set_premium_blob_tier(azure::storage::premium_blob_tier::p30, condition, options, azure::storage::operation_context()); // validate local has been updated. CHECK(azure::storage::premium_blob_tier::p30 == m_blob.properties().premium_blob_tier()); // validate server has been updated m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p30 == m_blob.properties().premium_blob_tier()); m_blob.set_premium_blob_tier(azure::storage::premium_blob_tier::p40, condition, options, azure::storage::operation_context()); // validate local has been updated. CHECK(azure::storage::premium_blob_tier::p40 == m_blob.properties().premium_blob_tier()); // validate server has been updated m_blob.download_attributes(); CHECK(azure::storage::premium_blob_tier::p40 == m_blob.properties().premium_blob_tier()); // validate no lease id would report failure. CHECK_STORAGE_EXCEPTION(m_blob.set_premium_blob_tier(azure::storage::premium_blob_tier::p30, azure::storage::access_condition(), options, azure::storage::operation_context()), ACTIVE_LEASE_ERROR_MESSAGE); CHECK(azure::storage::premium_blob_tier::p40 == m_blob.properties().premium_blob_tier()); } }
58.132242
229
0.683428
JasonDictos
b9acae4d08f40a3853a7d812b2cb2f6f49f02732
797
cpp
C++
remote_test/yosupo/math/convolution_mod.2.test.cpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
7
2021-07-20T15:25:00.000Z
2022-03-13T11:58:25.000Z
remote_test/yosupo/math/convolution_mod.2.test.cpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
10
2021-03-11T16:08:22.000Z
2022-03-13T08:40:36.000Z
remote_test/yosupo/math/convolution_mod.2.test.cpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
null
null
null
#define PROBLEM "https://judge.yosupo.jp/problem/convolution_mod" #include <iostream> #include <vector> #include "math/formal_power_series/relaxed_convolution.hpp" #include "modint/Montgomery_modint.hpp" int main() { #ifdef LOCAL std::freopen("in", "r", stdin), std::freopen("out", "w", stdout); #endif std::ios::sync_with_stdio(false); std::cin.tie(0); using mint = lib::MontModInt<998244353>; int n, m; std::cin >> n >> m; std::vector<mint> A(n), B(m), C, D; for (auto &i : A) std::cin >> i; for (auto &i : B) std::cin >> i; lib::RelaxedConvolution<mint> rc(C, D); for (int i = 0; i < n + m - 1; ++i) { C.emplace_back(i < n ? A[i] : mint(0)); D.emplace_back(i < m ? B[i] : mint(0)); std::cout << rc.next() << ' '; } return 0; }
28.464286
68
0.580928
hly1204
b9ae74999466c5857c3a3ca37a3bcadd45aacffd
192
cpp
C++
old/Codeforces/112/A.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
old/Codeforces/112/A.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
old/Codeforces/112/A.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "template.hpp" int main() { string a, b; cin >> a >> b; for (char& c : a) c = tolower(c); for (char& c : b) c = tolower(c); cout << (a < b ? -1 : a > b ? 1 : 0) << endl; }
19.2
47
0.463542
not522
b9aee9434e218a09125111ac635c39c7ec06fcc3
2,059
cc
C++
impl/browser/vibration/vibration_message_filter.cc
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
9
2015-04-09T20:22:08.000Z
2021-03-17T08:34:56.000Z
impl/browser/vibration/vibration_message_filter.cc
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
2
2015-02-04T13:41:12.000Z
2015-05-25T14:00:40.000Z
impl/browser/vibration/vibration_message_filter.cc
isabella232/chromium-efl
db2d09aba6498fb09bbea1f8440d071c4b0fde78
[ "BSD-3-Clause" ]
14
2015-02-12T16:20:47.000Z
2022-01-20T10:36:26.000Z
// Copyright 2013 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "browser/vibration/vibration_message_filter.h" #include <algorithm> #include "base/numerics/safe_conversions.h" #include "base/memory/ref_counted.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_thread.h" #include "browser/vibration/vibration_provider_client.h" #include "third_party/WebKit/public/platform/WebVibration.h" // Minimum duration of a vibration is 1 millisecond. const int64 kMinimumVibrationDurationMs = 1; VibrationMessageFilter::VibrationMessageFilter() : BrowserMessageFilter(ViewMsgStart) { } void VibrationMessageFilter::OverrideThreadForMessage( const IPC::Message& message, content::BrowserThread::ID* thread) { switch (message.type()) { case ViewHostMsg_Vibrate::ID : case ViewHostMsg_CancelVibration::ID : *thread = content::BrowserThread::UI; break; } } bool VibrationMessageFilter::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(VibrationMessageFilter, message) IPC_MESSAGE_HANDLER(ViewHostMsg_Vibrate, OnVibrate) IPC_MESSAGE_HANDLER(ViewHostMsg_CancelVibration, OnCancelVibration) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void VibrationMessageFilter::OnVibrate(int64 milliseconds) { // Though the Blink implementation already sanitizes vibration times, don't // trust any values passed from the renderer. milliseconds = std::max(kMinimumVibrationDurationMs, std::min(milliseconds, base::checked_cast<int64>(blink::kVibrationDurationMax))); VibrationProviderClient* vibration_provider = VibrationProviderClient::GetInstance(); vibration_provider->Vibrate(milliseconds); } void VibrationMessageFilter::OnCancelVibration() { VibrationProviderClient* vibration_provider = VibrationProviderClient::GetInstance(); vibration_provider->CancelVibration(); }
36.122807
87
0.78679
Jabawack
b9b06e589bbe8895ac5bd67aa404c8e462bfe00e
2,146
cpp
C++
src/medCore/gui/commonWidgets/medSlider.cpp
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
1
2020-11-16T13:55:45.000Z
2020-11-16T13:55:45.000Z
src/medCore/gui/commonWidgets/medSlider.cpp
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
null
null
null
src/medCore/gui/commonWidgets/medSlider.cpp
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2014. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "medSlider.h" #include "medSettingsManager.h" void medSlider::addTick(int position) { if( (ticksList.isEmpty()) || !ticksList.contains(position)) { ticksList.append(position); } } int medSlider::tickCount() { if (!ticksList.isEmpty()) { return ticksList.count(); } return 0; } void medSlider::removeTick(int position) { if (!ticksList.isEmpty()) { ticksList.removeAll(position); } } void medSlider::removeAllTicks() { if (!ticksList.isEmpty()) { ticksList.clear(); } } void medSlider::paintEvent(QPaintEvent *ev) { QSlider::paintEvent(ev); QPainter painter(this); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); for(int i = 0; i<tickCount(); i++) { int position = QStyle::sliderPositionFromValue(minimum(), maximum(), ticksList.at(i), width()); painter.setPen(this->getTickColor()); painter.drawLine(position, 0, position, height()); } } QColor medSlider::getTickColor() { // CSS QVariant themeChosen = medSettingsManager::instance()->value("startup","theme"); int themeIndex = themeChosen.toInt(); switch (themeIndex) { case 0: default: return QColor("cyan"); // Dark Theme break; case 1: return QColor("blue"); // Light Theme break; } } void medSlider::mousePressEvent(QMouseEvent *event) { QSlider::mousePressEvent(event); setValue(QStyle::sliderValueFromPosition(minimum(), maximum(), event->x(), width())); event->accept(); }
23.075269
89
0.550792
nebatmusic
b9b448a26cc3f215a4894162aa545efe91906da2
3,622
cpp
C++
Code/Engine/RendererCore/AnimationSystem/AnimGraph/AnimNodes/MathAnimNodes.cpp
katehuratakeshi220/ezEngine
19fe98b5850172e67c37490ab0cee1b2d96fd220
[ "MIT" ]
5
2020-06-02T02:29:40.000Z
2021-07-28T15:20:51.000Z
Code/Engine/RendererCore/AnimationSystem/AnimGraph/AnimNodes/MathAnimNodes.cpp
jayrulez/ezEngine
49881480fef984b02fe3f550dd9ace932a05b86f
[ "MIT" ]
null
null
null
Code/Engine/RendererCore/AnimationSystem/AnimGraph/AnimNodes/MathAnimNodes.cpp
jayrulez/ezEngine
49881480fef984b02fe3f550dd9ace932a05b86f
[ "MIT" ]
null
null
null
#include <RendererCore/RendererCorePCH.h> #include <RendererCore/AnimationSystem/AnimGraph/AnimGraph.h> #include <RendererCore/AnimationSystem/AnimGraph/AnimNodes/MathAnimNodes.h> // clang-format off EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezMathExpressionAnimNode, 1, ezRTTIDefaultAllocator<ezMathExpressionAnimNode>) { EZ_BEGIN_PROPERTIES { EZ_ACCESSOR_PROPERTY("Expression", GetExpression, SetExpression)->AddAttributes(new ezDefaultValueAttribute("a*a + (b-c) / abs(d)")), EZ_MEMBER_PROPERTY("a", m_ValueAPin)->AddAttributes(new ezHiddenAttribute), EZ_MEMBER_PROPERTY("b", m_ValueBPin)->AddAttributes(new ezHiddenAttribute), EZ_MEMBER_PROPERTY("c", m_ValueCPin)->AddAttributes(new ezHiddenAttribute), EZ_MEMBER_PROPERTY("d", m_ValueDPin)->AddAttributes(new ezHiddenAttribute), EZ_MEMBER_PROPERTY("Result", m_ResultPin)->AddAttributes(new ezHiddenAttribute), } EZ_END_PROPERTIES; EZ_BEGIN_ATTRIBUTES { new ezCategoryAttribute("Math"), new ezColorAttribute(ezColor::DarkOliveGreen), new ezTitleAttribute("= {Expression}"), } EZ_END_ATTRIBUTES; } EZ_END_DYNAMIC_REFLECTED_TYPE; // clang-format on ezMathExpressionAnimNode::ezMathExpressionAnimNode() = default; ezMathExpressionAnimNode::~ezMathExpressionAnimNode() = default; void ezMathExpressionAnimNode::SetExpression(const char* sz) { m_Expression.Reset(sz); } const char* ezMathExpressionAnimNode::GetExpression() const { return m_Expression.GetExpressionString(); } ezResult ezMathExpressionAnimNode::SerializeNode(ezStreamWriter& stream) const { stream.WriteVersion(1); EZ_SUCCEED_OR_RETURN(SUPER::SerializeNode(stream)); stream << m_Expression.GetExpressionString(); EZ_SUCCEED_OR_RETURN(m_ValueAPin.Serialize(stream)); EZ_SUCCEED_OR_RETURN(m_ValueBPin.Serialize(stream)); EZ_SUCCEED_OR_RETURN(m_ValueCPin.Serialize(stream)); EZ_SUCCEED_OR_RETURN(m_ValueDPin.Serialize(stream)); EZ_SUCCEED_OR_RETURN(m_ResultPin.Serialize(stream)); return EZ_SUCCESS; } ezResult ezMathExpressionAnimNode::DeserializeNode(ezStreamReader& stream) { stream.ReadVersion(1); EZ_SUCCEED_OR_RETURN(SUPER::DeserializeNode(stream)); ezStringBuilder tmp; stream >> tmp; m_Expression.Reset(tmp); EZ_SUCCEED_OR_RETURN(m_ValueAPin.Deserialize(stream)); EZ_SUCCEED_OR_RETURN(m_ValueBPin.Deserialize(stream)); EZ_SUCCEED_OR_RETURN(m_ValueCPin.Deserialize(stream)); EZ_SUCCEED_OR_RETURN(m_ValueDPin.Deserialize(stream)); EZ_SUCCEED_OR_RETURN(m_ResultPin.Deserialize(stream)); return EZ_SUCCESS; } void ezMathExpressionAnimNode::Initialize(ezAnimGraph& graph, const ezSkeletonResource* pSkeleton) { if (!m_Expression.IsValid() && m_ResultPin.IsConnected()) { ezLog::Error("Math expression '{}' is invalid.", m_Expression.GetExpressionString()); } } static ezHashedString s_sA = ezMakeHashedString("a"); static ezHashedString s_sB = ezMakeHashedString("b"); static ezHashedString s_sC = ezMakeHashedString("c"); static ezHashedString s_sD = ezMakeHashedString("d"); void ezMathExpressionAnimNode::Step(ezAnimGraph& graph, ezTime tDiff, const ezSkeletonResource* pSkeleton, ezGameObject* pTarget) { if (!m_Expression.IsValid()) { m_ResultPin.SetNumber(graph, 0); return; } ezMathExpression::Input inputs[] = { {s_sA, static_cast<float>(m_ValueAPin.GetNumber(graph))}, {s_sB, static_cast<float>(m_ValueBPin.GetNumber(graph))}, {s_sC, static_cast<float>(m_ValueCPin.GetNumber(graph))}, {s_sD, static_cast<float>(m_ValueDPin.GetNumber(graph))}, }; float result = m_Expression.Evaluate(inputs); m_ResultPin.SetNumber(graph, result); }
33.229358
137
0.77968
katehuratakeshi220
b9ba92789601ca164c319229a11ad91992b027bd
953
hpp
C++
CaWE/MaterialBrowser/FilterSettings.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/MaterialBrowser/FilterSettings.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/MaterialBrowser/FilterSettings.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_FILTER_SETTINGS_HPP_INCLUDED #define CAFU_FILTER_SETTINGS_HPP_INCLUDED #include "wx/wx.h" namespace MaterialBrowser { class DialogT; class FilterSettingsT : public wxPanel { public: FilterSettingsT(DialogT* Parent); wxString GetNameFilterValue() const; void SetNameFilterValue(const wxString& s); bool OnlyShowUsed() const { return m_OnlyShowUsedCheckbox && m_OnlyShowUsedCheckbox->IsChecked(); } bool OnlyShowEditorMats() const { return m_OnlyShowEditorMaterials && m_OnlyShowEditorMaterials->IsChecked(); } private: DialogT* m_Parent; wxComboBox* m_NameFilterCombobox; wxCheckBox* m_OnlyShowUsedCheckbox; wxCheckBox* m_OnlyShowEditorMaterials; }; } #endif
23.243902
119
0.703043
dns
b9bbbcccf6cb8c868f2e5a95a691c0659a38127e
1,739
cpp
C++
Visual Mercutio/zModel/PSS_DocObserverMsg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModel/PSS_DocObserverMsg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModel/PSS_DocObserverMsg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_DocObserverMsg --------------------------------------------------* **************************************************************************** * Description : Provides a document observer message * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_DocObserverMsg.h" // processsoft #include "PSS_Symbol.h" #include "PSS_ProcessGraphModelDoc.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // Dynamic creation //--------------------------------------------------------------------------- IMPLEMENT_DYNAMIC(PSS_DocObserverMsg, PSS_ObserverMsg) //--------------------------------------------------------------------------- // PSS_DocObserverMsg //--------------------------------------------------------------------------- PSS_DocObserverMsg::PSS_DocObserverMsg(IEActionType actionType, PSS_ProcessGraphModelDoc* pDoc, PSS_ProcessGraphModelMdl* pModel, CODSymbolComponent* pElement) : PSS_ObserverMsg(), m_ActionType(actionType), m_pDoc(pDoc), m_pModel(pModel), m_pElement(pElement) {} //--------------------------------------------------------------------------- PSS_DocObserverMsg::~PSS_DocObserverMsg() {} //---------------------------------------------------------------------------
41.404762
78
0.343301
Jeanmilost
b9bd164f262c9f350def4a9ff8627740d5f1785e
23,870
hpp
C++
include/kanaval/inputs.hpp
LTLA/kanaval
60ef46c749ff073830b430e002a25d2685988b40
[ "MIT" ]
null
null
null
include/kanaval/inputs.hpp
LTLA/kanaval
60ef46c749ff073830b430e002a25d2685988b40
[ "MIT" ]
null
null
null
include/kanaval/inputs.hpp
LTLA/kanaval
60ef46c749ff073830b430e002a25d2685988b40
[ "MIT" ]
null
null
null
#ifndef KANAVAL_INPUTS_HPP #define KANAVAL_INPUTS_HPP #include "H5Cpp.h" #include "utils.hpp" #include <stdexcept> #include <vector> #include <string> #include <numeric> #include <unordered_set> #include <unordered_map> /** * @file inputs.hpp * * @brief Validate input contents. */ namespace kanaval { namespace inputs { /** * @brief Details about the dataset. */ struct Details { /** * Available modalities in the dataset. * Currently, this may contain `"RNA"` and/or `"ADT"`. */ std::vector<std::string> modalities; /** * Number of features for each modality listed in `modalities`. * For datasets containing multiple samples, each entry contains the number of features in the intersection of feature spaces across all samples. */ std::vector<int> num_features; /** * Number of cells. * For multi-sample datasets, this considers the total number of cells in all samples. */ int num_cells; /** * Number of samples. * Note that a single matrix may contain multiple samples. */ int num_samples; }; /** * @cond */ struct ParamDump { int num_matrices; bool multi_matrix; bool multi_sample; }; inline ParamDump validate_parameters(const H5::Group& handle, bool embedded, int version) { auto phandle = utils::check_and_open_group(handle, "parameters"); ParamDump output; // Formats can either be a scalar... or not. std::vector<std::string> formats; output.multi_matrix = false; { auto fhandle = utils::check_and_open_dataset(phandle, "format", H5T_STRING); auto fspace = fhandle.getSpace(); if (fspace.getSimpleExtentNdims() == 0) { formats.push_back(utils::load_string(fhandle)); } else { if (version < 1001000) { throw std::runtime_error("'format' should be a scalar string in version 1.0"); } output.multi_matrix = true; formats = utils::load_string_vector(fhandle); } } output.num_matrices = formats.size(); auto fihandle = utils::check_and_open_group(phandle, "files"); auto nfiles = fihandle.getNumObjs(); // Checking the runs. std::vector<int> runs; if (output.multi_matrix) { runs = utils::load_integer_vector(phandle, "sample_groups"); if (runs.size() != formats.size()) { throw std::runtime_error("'sample_groups' and 'format' should have the same length"); } int total_files = std::accumulate(runs.begin(), runs.end(), 0); if (total_files != static_cast<int>(nfiles)) { throw std::runtime_error("sum of 'sample_groups' is not equal to the length of 'files'"); } // Checking that everyone has unique groups. auto names = utils::load_string_vector(phandle, "sample_names"); if (names.size() != formats.size()) { throw std::runtime_error("'sample_names' and 'format' should have the same length"); } std::unordered_set<std::string> stuff; for (auto s : names) { if (stuff.find(s) != stuff.end()) { throw std::runtime_error("duplicated sample name '" + s + "' in 'sample_names'"); } stuff.insert(s); } } else { runs.push_back(nfiles); } // Checking the files. int sofar = 0; std::vector<std::pair<hsize_t, hsize_t> > bytes; for (size_t r = 0; r < runs.size(); ++r) { auto curf = formats[r]; std::vector<std::string> types; for (int s = 0; s < runs[r]; ++s, ++sofar) { std::string current = std::to_string(sofar); try { auto curfihandle = utils::check_and_open_group(fihandle, current); utils::check_and_open_dataset(curfihandle, "name", H5T_STRING, {}); types.push_back(utils::load_string(curfihandle, "type")); if (embedded) { bytes.emplace_back( utils::load_integer_scalar<hsize_t>(curfihandle, "offset"), utils::load_integer_scalar<hsize_t>(curfihandle, "size") ); } else { utils::check_and_open_dataset(curfihandle, "id", H5T_STRING, {}); } } catch (std::exception& e) { throw utils::combine_errors(e, "failed to retrieve information for file " + current); } } if (curf == "MatrixMarket") { std::unordered_map<std::string, int> expected; expected["mtx"] = 0; expected["genes"] = 0; expected["annotations"] = 0; for (auto t : types) { auto it = expected.find(t); if (it == expected.end()) { throw std::runtime_error("unknown file type '" + t + "' when format is 'MatrixMarket'"); } ++(it->second); } if (expected["mtx"] != 1) { throw std::runtime_error("expected exactly one 'mtx' file when format is 'MatrixMarket'"); } if (expected["genes"] > 1) { throw std::runtime_error("expected no more than one 'genes' file when format is 'MatrixMarket'"); } if (expected["annotations"] > 1) { throw std::runtime_error("expected no more than one 'annotation' file when format is 'MatrixMarket'"); } } else if (curf == "10X") { if (types.size() != 1 || types.front() != "h5") { throw std::runtime_error("expected exactly one 'h5' file when format is '10X'"); } } else if (curf == "H5AD") { if (types.size() != 1 || types.front() != "h5") { throw std::runtime_error("expected exactly one 'h5' file when format is 'H5AD'"); } } } // Checking the files make sense. if (embedded) { hsize_t sofar = 0; for (const auto& b : bytes) { if (b.first != sofar) { throw std::runtime_error("offsets and sizes of 'files' are not sorted and contiguous"); } sofar += b.second; } } // Checking if there's a batch variable. if (!output.multi_matrix && phandle.exists("sample_factor")) { utils::check_and_open_dataset(phandle, "sample_factor", H5T_STRING, {}); output.multi_sample = true; } else { output.multi_sample = output.multi_matrix; } return output; } inline Details validate_results(const H5::Group& handle, const ParamDump& param_info, int version) { auto rhandle = utils::check_and_open_group(handle, "results"); Details output; // Pulling out the dimensions and modalities. if (version < 2000000) { output.modalities.push_back("RNA"); auto dims = utils::load_integer_vector<int>(rhandle, "dimensions"); if (dims.size() != 2) { throw std::runtime_error("'dimensions' should be a dataset of length 2"); } if (dims[0] < 0 || dims[1] < 0) { throw std::runtime_error("'dimensions' should contain non-negative integers"); } output.num_features.push_back(dims[0]); output.num_cells = dims[1]; } else { output.num_cells = utils::load_integer_scalar<>(rhandle, "num_cells"); auto fhandle = utils::check_and_open_group(rhandle, "num_features"); size_t nmodals = fhandle.getNumObjs(); if (nmodals == 0) { throw std::runtime_error("number of modalities should be positive"); } for (hsize_t idx = 0; idx < nmodals; ++idx) { std::string modality = fhandle.getObjnameByIdx(idx); output.modalities.push_back(modality); output.num_features.push_back(utils::load_integer_scalar<>(fhandle, modality)); } } // Checking the number of samples. output.num_samples = 1; if (rhandle.exists("num_samples")) { output.num_samples = utils::load_integer_scalar<int>(rhandle, "num_samples"); } if (param_info.multi_matrix) { if (output.num_samples != param_info.num_matrices) { throw std::runtime_error("'num_samples' should be equal to the number of matrices"); } } else { if (!param_info.multi_sample && output.num_samples != 1) { throw std::runtime_error("'num_samples' should be 1 for single matrix inputs without 'sample_factor'"); } } auto check_unique = [](const std::vector<int>& idx, const std::string& msg) -> void { std::unordered_set<int> used; used.reserve(idx.size()); for (auto i : idx) { if (i < 0) { throw std::runtime_error(msg + " contains negative values"); } else if (used.find(i) != used.end()) { throw std::runtime_error(msg + " contains duplicate values"); } used.insert(i); } }; if (version >= 2000000) { auto ihandle = utils::check_and_open_group<>(rhandle, "identities"); for (size_t m = 0; m < output.modalities.size(); ++m) { auto idx = utils::load_integer_vector<int>(ihandle, output.modalities[m]); if (idx.size() != static_cast<size_t>(output.num_features[m])) { throw std::runtime_error("'identities' for modality '" + output.modalities[m] + "' should have length equal to its number of features"); } check_unique(idx, "'identities' for modality '" + output.modalities[m] + "'"); } } else if (version >= 1002000) { auto idx = utils::load_integer_vector<int>(rhandle, "identities"); if (idx.size() != static_cast<size_t>(output.num_features[0])) { throw std::runtime_error("'identities' should have length equal to the number of genes"); } check_unique(idx, "'identities'"); } else { if (param_info.multi_matrix) { auto idx = utils::load_integer_vector<int>(rhandle, "indices"); if (idx.size() != static_cast<size_t>(output.num_features[0])) { throw std::runtime_error("'indices' should have length equal to the number of genes"); } check_unique(idx, "'indices'"); } else { auto perms = utils::load_integer_vector<int>(rhandle, "permutation"); if (perms.size() != static_cast<size_t>(output.num_features[0])) { throw std::runtime_error("'permutation' should have length equal to the number of genes"); } // Note that the code below implies that all consecutive entries are present, // otherwise we would see duplicates. std::vector<unsigned char> used(perms.size()); for (auto p : perms) { if (p < 0 || static_cast<size_t>(p) >= perms.size()) { throw std::runtime_error("'permutation' contains out-of-range values"); } else if (used[p]) { throw std::runtime_error("duplicated index in 'permutation'"); } used[p] = 1; } } } return output; } /** * @endcond */ /** * Check contents for the input step. * Contents are stored inside an `inputs` HDF5 group at the root of the file. * The `inputs` group itself contains the `parameters` and `results` subgroups. * * In this section, a "matrix" refers to one or more files describing a single (count) matrix. * This should be exactly one file for HDF5-based formats, or multiple files for MatrixMarket formats, e.g., to include feature information - see below for details. * Multiple matrices may be supplied, in which case each matrix is assumed to contain data for one sample. * Alternatively, a single matrix may contain data for one or more samples as partitioned by a sample factor. * * The loaded dataset refers to the in-memory representation of the matrix (for single matrix inputs) or the combined matrices (for multiple inputs). * The identities of the rows of the loaded dataset may be a permutation or subset of the rows in the input matrices. * This is especially true for multiple inputs where the loaded dataset only contains the intersection of features across inputs. * * <HR> * `parameters` should contain: * * - `format`: a scalar string specifying the file format for a single matrix. * This is usually either `"MatrixMarket"`, for a MatrixMarket file with possible feature/barcode annotations; * `"10X"`, for the 10X Genomics HDF5 matrix format; * or `"H5AD"`, for the H5AD format. * Other values are allowed but their interpretation is implementation-defined (e.g., for custom resources). * For multiple matrices, `format` should instead be a 1-dimensional string dataset of length equal to the number of uploads. * Each element of the dataset is usually one of `"MatrixMarket"`, `"10X"` or `"H5AD"`; * different values can be present for mixed input formats. * - `files`: a group of groups representing an array of input file information. * Each inner group is named by their positional index in the array and contains information about a file in an upload. * Each inner group should contain: * - `type`: a scalar string specifying the type of the file. * For multiple matrices, the constraints below apply to all files corresponding to a single matrix. * - If `format = "MatrixMarket"`, there should be exactly one `type = "mtx"` corresponding to the (possibly Gzipped) `*.mtx` file. * There may be zero or one `type = "genes"`, containing a (possibly Gzipped) TSV file with the Ensembl and gene symbols for each row. * There may be zero or one `type = "annotations"`, containing a (possibly Gzipped) TSV file with the annotations for each column. * - If `format = "10X"` or `"H5AD"`, there should be exactly one `type = "h5"`. * - For other `format`s, any `type` can be used, typically for custom resources. * - `name`: a scalar string specifying the file name as it was provided to **kana**. * * If `embedded = true`, we additionally expect: * - `offset`: a scalar integer specifying where the file starts as an offset from the start of the remaining bytes section. * The offset for the first file should be zero, and entries in `files` should be ordered by increasing `offset`. * - `size`: a non-negative scalar integer specifying the number of bytes in the file. * The offset of each file should be equal to the sum of `size` and `offset` for the preceding file. * * If `embedded = false`, we expect: * - `id`: a scalar string containing some unique identifier for this file. * The interpretation of `id` is application-specific but usually refers to some cache or database. * * For multiple matrices, `parameters` should also contain: * * - `sample_groups`: an integer dataset of length equal to the number of samples. * Each entry specifies the number of files in `files` that belong to a sample. * (All files from the same sample are assumed to be contiguous in the array represented by `files`; * so a `sample_groups` of `[3, 2, 1]` would mean that the first three files belong to the first sample, * the next 2 files belong to the second sample, and the last file belongs to the third sample.) * - `sample_names`: a string dataset of length equal to the number of samples, containing the sample name. * * For single matrix inputs, `parameters` may also contain: * * - `sample_factor`: a string scalar specifying the field in the per-cell annotation that contains the sample blocking factor. * If present, it is assumed that the matrix contains data for multiple samples. * * <DIV style="color:blue"> * <details> * <summary>For version 1.0</summary> * `parameters` should contain: * * - `format`: a scalar string specifying the file format for a single matrix. * This is usually either `"MatrixMarket"`, for a MatrixMarket file with possible feature/barcode annotations; * `"10X"`, for the 10X Genomics HDF5 matrix format; * or `"H5AD"`, for the H5AD format. * Other values are allowed but their interpretation is implementation-defined (e.g., for custom resources). * For multiple matrices, `format` should instead be a 1-dimensional string dataset of length equal to the number of uploads. * Each element of the dataset is usually one of `"MatrixMarket"`, `"10X"` or `"H5AD"`; * different values can be present for mixed input formats.} * - `files`: a group of groups representing an array of input file information. * Each inner group is named by their positional index in the array and contains information about a file in an upload. * Each inner group should contain: * - `type`: a scalar string specifying the type of the file. * - If `format = "MatrixMarket"`, there should be exactly one `type = "mtx"` corresponding to the (possibly Gzipped) `*.mtx` file. * There may be zero or one `type = "genes"`, containing a (possibly Gzipped) TSV file with the Ensembl and gene symbols for each row. * There may be zero or one `type = "annotations"`, containing a (possibly Gzipped) TSV file with the annotations for each column. * - If `format = "10X"` or `"H5AD"`, there should be exactly one `type = "h5"`. * - For other `format`s, any `type` can be used, typically for custom resources. * - `name`: a scalar string specifying the file name as it was provided to **kana**. * * If `embedded = true`, we additionally expect: * - `offset`: a scalar integer specifying where the file starts as an offset from the start of the remaining bytes section. * The offset for the first file should be zero, and entries in `files` should be ordered by increasing `offset`. * - `size`: a non-negative scalar integer specifying the number of bytes in the file. * The offset of each file should be equal to the sum of `size` and `offset` for the preceding file. * * If `embedded = false`, we expect: * - `id`: a scalar string containing some unique identifier for this file. * The interpretation of `id` is application-specific but usually refers to some cache or database. * </details> * </DIV> * * <HR> * `results` should contain: * * - `num_cells`: an integer scalar specifying the number of cells in the loaded dataset. * - `num_features`: a group containing integer scalar datasets, each named after a modality (typically `"RNA"` and/or `"ADT"`). * Each dataset contains the number of features for its named modality. * When dealing with multiple matrix inputs, the number of features is defined as the intersection across all matrices. * - `identities`: a group containin 1-dimensional integer datasets, each named after a modality in `num_features`. * Each dataset is of length equal to the number of features listed in its corresponding `num_features` dataset. * Each dataset contains the identities of the rows in the loaded dataset corresponding to its named modality. * If a single input was provided, `identities` identifies each row in terms of its index in the "original" input matrix (i.e., if it were loaded without any modification). * If multiple inputs were provided, `identities` contains the intersection of features across inputs, and each value refers to the row index in the original matrix of the _first_ input. * Row identities are parallel to the per-feature results in subsequent analysis steps. * * <DIV style="color:blue"> * <details> * <summary>For version 1.2</summary> * `results` should contain: * * - `dimensions`: an integer dataset of length 2, * containing the number of features and the number of cells in the loaded dataset. * When dealing with multiple matrix inputs, the first entry is instead defined as the size of the intersection of features across all matrices. * - `identities`: a 1-dimensional integer dataset of length equal to the first entry of `dimensions`, containing the identity of each row in the loaded dataset. * If a single input was provided, `identities` identifies each row in terms of its index in the "original" input matrix (i.e., if it were loaded without any modification). * If multiple inputs were provided, `identities` contains the intersection of features across inputs, and each value refers to the row index in the original matrix of the _first_ input. * Row identities are parallel to the per-gene results in subsequent analysis steps. * * `results` may also contain: * * - `num_samples`: an integer scalar dataset specifying the number of samples. * If absent, this is assumed to be 1. * For multiple matrices, the value listed here should be consistent with the number of samples specified in the paramaters. * </details> * * <details> * <summary>For version 1.1</summary> * `results` should contain: * * - `dimensions`: an integer dataset of length 2, * containing the number of features and the number of cells in the loaded dataset. * When dealing with multiple matrix inputs, the first entry is instead defined as the size of the intersection of features across all matrices. * * `results` may also contain: * * - `num_samples`: an integer scalar dataset specifying the number of samples. * If absent, this is assumed to be 1. * For multiple matrices, the value listed here should be consistent with the number of samples specified in the paramaters. * * If there is only a single matrix, `results` should also contain: * * - `permutation`: an integer dataset of length equal to the number of cells, * describing the permutation to be applied to the per-gene results to recover the original row order. * * If there are multiple matrices, `results` should instead contain: * * - `indices`: an integer dataset containing the row index of each feature in the intersection. * For each entry, the gene is defined as the indexed row in the first sample _without permutation_. * The `indices` are parallel to the per-gene results. * </details> * * <details> * <summary>For version 1.0</summary> * `results` should contain: * * - `dimensions`: an integer dataset of length 2, * containing the number of features and the number of cells in the loaded dataset. * - `permutation`: an integer dataset of length equal to the number of cells, * describing the permutation to be applied to the per-gene results to recover the original row order. * </details> * </DIV> * * All steps that generate per-gene results should use `identities` (or, for older formats, `permutation` or `indices`) to identify the genes corresponding to the statistics. * See the documentation for the functions listed below: * * - `feature_selection::validate()` * - `marker_detection::validate()` * - `custom_selections::validate()` * * <HR> * @param handle An open HDF5 file handle. * @param embedded Whether the data files are embedded or linked. * @param version Version of the state file. * * @return Details about the dataset. * If the format is invalid, an error is raised instead. */ inline Details validate(const H5::Group& handle, bool embedded, int version) { auto ihandle = utils::check_and_open_group(handle, "inputs"); ParamDump dump; try { dump = validate_parameters(ihandle, embedded, version); } catch (std::exception& e) { throw utils::combine_errors(e, "failed to retrieve parameters from 'inputs'"); } Details output; try { output = validate_results(ihandle, dump, version); } catch (std::exception& e) { throw utils::combine_errors(e, "failed to retrieve results from 'inputs'"); } return output; } } } #endif
45.815739
188
0.650691
LTLA
b9bd5a3dc9c9dd809815ff4ffb516fc7cdba74f4
5,476
cc
C++
src/Geometry/GradientField.cc
kwisniew/devsim
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
[ "Apache-2.0" ]
null
null
null
src/Geometry/GradientField.cc
kwisniew/devsim
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
[ "Apache-2.0" ]
null
null
null
src/Geometry/GradientField.cc
kwisniew/devsim
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
[ "Apache-2.0" ]
null
null
null
/*** DEVSIM Copyright 2013 Devsim 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. ***/ #include "GradientField.hh" #include "DenseMatrix.hh" #include "Region.hh" #include "NodeModel.hh" #include "dsAssert.hh" #include "Triangle.hh" #include "Tetrahedron.hh" #include "Node.hh" GradientField::~GradientField() { for (std::vector<dsMath::RealDenseMatrix *>::iterator it = dense_mats_.begin(); it != dense_mats_.end(); ++it) { delete *it; } } GradientField::GradientField(const Region *r) : myregion_(r) { } void GradientField::CalcMatrices2d() const { dsAssert(GetRegion().GetDimension() == 2, "UNEXPECTED"); //// TODO:Check for FPE's //// Assert dimension is 2! //// Assert fields exist ConstNodeModelPtr ux = myregion_->GetNodeModel("x"); ConstNodeModelPtr uy = myregion_->GetNodeModel("y"); dsAssert(ux.get(), "UNEXPECTED"); dsAssert(uy.get(), "UNEXPECTED"); const NodeScalarList &xvec = ux->GetScalarValues(); const NodeScalarList &yvec = uy->GetScalarValues(); const ConstTriangleList &tlist = myregion_->GetTriangleList(); dense_mats_.resize(tlist.size()); for (ConstTriangleList::const_iterator ti = tlist.begin(); ti != tlist.end(); ++ti) { const Triangle &triangle = **ti; const size_t triangleIndex = triangle.GetIndex(); dsMath::RealDenseMatrix *dmp = new dsMath::RealDenseMatrix(3); dsMath::RealDenseMatrix &M = *dmp; const std::vector<ConstNodePtr> &nl = triangle.GetNodeList(); const size_t ni0 = nl[0]->GetIndex(); const double x0 = xvec[ni0]; const double y0 = yvec[ni0]; for (size_t r = 1; r < 3; ++r) { const size_t nir = nl[r]->GetIndex(); const double xr = xvec[nir] - x0; const double yr = yvec[nir] - y0; M(r, 0) = xr; M(r, 1) = yr; M(r, 2) = 1.0; } M(0, 2) = 1.0; M.LUFactor(); dense_mats_[triangleIndex] = dmp; } } void GradientField::CalcMatrices3d() const { dsAssert(GetRegion().GetDimension() == 3, "UNEXPECTED"); //// TODO:Check for FPE's //// Assert dimension is 2! //// Assert fields exist ConstNodeModelPtr ux = myregion_->GetNodeModel("x"); ConstNodeModelPtr uy = myregion_->GetNodeModel("y"); ConstNodeModelPtr uz = myregion_->GetNodeModel("y"); dsAssert(ux.get(), "UNEXPECTED"); dsAssert(uy.get(), "UNEXPECTED"); dsAssert(uz.get(), "UNEXPECTED"); const NodeScalarList &xvec = ux->GetScalarValues(); const NodeScalarList &yvec = uy->GetScalarValues(); const NodeScalarList &zvec = uz->GetScalarValues(); const ConstTetrahedronList &tlist = myregion_->GetTetrahedronList(); dense_mats_.resize(tlist.size()); for (ConstTetrahedronList::const_iterator ti = tlist.begin(); ti != tlist.end(); ++ti) { const Tetrahedron &tetrahedron = **ti; const size_t tetrahedronIndex = tetrahedron.GetIndex(); dsMath::RealDenseMatrix *dmp = new dsMath::RealDenseMatrix(3); dsMath::RealDenseMatrix &M = *dmp; const std::vector<ConstNodePtr> &nl = tetrahedron.GetNodeList(); const size_t ni0 = nl[0]->GetIndex(); const double x0 = xvec[ni0]; const double y0 = yvec[ni0]; const double z0 = zvec[ni0]; for (size_t r = 1; r < 4; ++r) { const size_t nir = nl[r]->GetIndex(); const double xr = xvec[nir] - x0; const double yr = yvec[nir] - y0; const double zr = zvec[nir] - z0; M(r-1, 0) = xr; M(r-1, 1) = yr; M(r-1, 2) = zr; } M.LUFactor(); dense_mats_[tetrahedronIndex] = dmp; } } Vector GradientField::GetGradient(const Triangle &triangle, const NodeModel &nm) const { if (dense_mats_.empty()) { CalcMatrices2d(); } const NodeScalarList &nvals = nm.GetScalarValues(); const size_t triangleIndex = triangle.GetIndex(); dsMath::RealDenseMatrix &M = *dense_mats_[triangleIndex]; const std::vector<ConstNodePtr> &nl = triangle.GetNodeList(); static std::vector<double> B(3); for (size_t i = 0; i < 3; ++i) { B[i] = nvals[nl[i]->GetIndex()]; } bool info = M.Solve(B); if (info) { return Vector(B[0], B[1], B[2]); } else { return Vector(0,0,0); //// This is due to the inf result from a bad factorization } } // TODO:"REVIEW, TEST 3D CODE" Vector GradientField::GetGradient(const Tetrahedron &tetrahedron, const NodeModel &nm) const { if (dense_mats_.empty()) { CalcMatrices3d(); } const NodeScalarList &nvals = nm.GetScalarValues(); const size_t tetrahedronIndex = tetrahedron.GetIndex(); dsMath::RealDenseMatrix &M = *dense_mats_[tetrahedronIndex]; const std::vector<ConstNodePtr> &nl = tetrahedron.GetNodeList(); static std::vector<double> B(3); const double nv0 = nvals[nl[0]->GetIndex()]; for (size_t i = 1; i < 4; ++i) { const double nvr = nvals[nl[i]->GetIndex()] - nv0; B[i-1] = nvr; } bool info = M.Solve(B); if (info) { return Vector(B[0], B[1], B[2]); } else { return Vector(0,0,0); //// This is due to the inf result from a bad factorization } }
25.70892
112
0.655771
kwisniew
b9c6f26b76ae199986960cd4183bfbd5b2237bf4
43,144
cpp
C++
src/Test/TestHogLite.cpp
Erensu/Simd
8a69dc56d8fb8d3f0faba2fa69ee3e088288b83a
[ "MIT" ]
null
null
null
src/Test/TestHogLite.cpp
Erensu/Simd
8a69dc56d8fb8d3f0faba2fa69ee3e088288b83a
[ "MIT" ]
null
null
null
src/Test/TestHogLite.cpp
Erensu/Simd
8a69dc56d8fb8d3f0faba2fa69ee3e088288b83a
[ "MIT" ]
1
2020-01-31T03:16:34.000Z
2020-01-31T03:16:34.000Z
/* * Tests for Simd Library (http://ermig1979.github.io/Simd). * * Copyright (c) 2011-2018 Yermalayeu Ihar. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Test/TestUtils.h" #include "Test/TestPerformance.h" #include "Test/TestData.h" namespace Test { void FillCircle(View & view) { assert(view.format == View::Gray8); Point c = view.Size() / 2; ptrdiff_t r2 = Simd::Square(Simd::Min(view.width, view.height) / 4); for (size_t y = 0; y < view.height; ++y) { ptrdiff_t y2 = Simd::Square(y - c.y); uint8_t * data = view.data + view.stride*y; for (size_t x = 0; x < view.width; ++x) { ptrdiff_t x2 = Simd::Square(x - c.x); data[x] = x2 + y2 < r2 ? 255 : 0; } } } namespace { struct FuncHLEF { typedef void(*FuncPtr)(const uint8_t * src, size_t srcStride, size_t width, size_t height, size_t cell, float * features, size_t featuresStride); FuncPtr func; String description; FuncHLEF(const FuncPtr & f, const String & d) : func(f), description(d) {} FuncHLEF(const FuncHLEF & f, size_t c) : func(f.func), description(f.description + "[" + ToString(c) + "]") {} void Call(const View & src, size_t cell, View & dst) const { TEST_PERFORMANCE_TEST(description); func(src.data, src.stride, src.width, src.height, cell, (float*)dst.data, dst.stride/sizeof(float)); } }; } #define FUNC_HLEF(function) FuncHLEF(function, #function) #define ARGS_HLEF(cell, f1, f2) cell, FuncHLEF(f1, cell), FuncHLEF(f2, cell) bool HogLiteExtractFeaturesAutoTest(size_t A, size_t width, size_t height, size_t size, size_t cell, const FuncHLEF & f1, const FuncHLEF & f2) { bool result = true; width = std::max(3 * cell, width); height = std::max(3 * cell, height); if ((width / cell - 1)*cell < A) return result; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << width << ", " << height << "]."); View src(width, height, View::Gray8, NULL, TEST_ALIGN(width)); FillRandom(src); size_t dstX = width / cell - 2; size_t dstY = height / cell - 2; View dst1(dstX*size, dstY, View::Float, NULL, TEST_ALIGN(width)); View dst2(dstX*size, dstY, View::Float, NULL, TEST_ALIGN(width)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, cell, dst1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, cell, dst2)); result = result && Compare(dst1, dst2, EPS, true, 64); return result; } bool HogLiteExtractFeaturesAutoTest(size_t A, const FuncHLEF & f1, const FuncHLEF & f2) { bool result = true; result = result && HogLiteExtractFeaturesAutoTest(A, W, H, 16, ARGS_HLEF(4, f1, f2)); result = result && HogLiteExtractFeaturesAutoTest(A, W + O, H - O, 16, ARGS_HLEF(4, f1, f2)); result = result && HogLiteExtractFeaturesAutoTest(A, W, H, 16, ARGS_HLEF(8, f1, f2)); result = result && HogLiteExtractFeaturesAutoTest(A, W + O, H - O, 16, ARGS_HLEF(8, f1, f2)); return result; } bool HogLiteExtractFeaturesAutoTest() { bool result = true; result = result && HogLiteExtractFeaturesAutoTest(1, FUNC_HLEF(Simd::Base::HogLiteExtractFeatures), FUNC_HLEF(SimdHogLiteExtractFeatures)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteExtractFeaturesAutoTest(Simd::Sse41::A, FUNC_HLEF(Simd::Sse41::HogLiteExtractFeatures), FUNC_HLEF(SimdHogLiteExtractFeatures)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteExtractFeaturesAutoTest(Simd::Avx2::A, FUNC_HLEF(Simd::Avx2::HogLiteExtractFeatures), FUNC_HLEF(SimdHogLiteExtractFeatures)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && HogLiteExtractFeaturesAutoTest(1, FUNC_HLEF(Simd::Avx512bw::HogLiteExtractFeatures), FUNC_HLEF(SimdHogLiteExtractFeatures)); #endif return result; } namespace { struct FuncHLFF { typedef void(*FuncPtr)(const float * src, size_t srcStride, size_t srcWidth, size_t srcHeight, size_t featureSize, const float * filter, size_t filterWidth, size_t filterHeight, const uint32_t * mask, size_t maskStride, float * dst, size_t dstStride); FuncPtr func; String description; FuncHLFF(const FuncPtr & f, const String & d) : func(f), description(d) {} void Update(size_t filterWidth, size_t filterHeight, size_t featureSize, int useMask) { std::stringstream ss; ss << description; ss << "[" << filterWidth << "-" << filterHeight << "-" << featureSize << "-" << useMask << "]"; description = ss.str(); } FuncHLFF(const FuncHLFF & f, size_t fis, size_t fes, int um) : func(f.func), description(f.description + "[" + ToString(fis) + "x" + ToString(fes) + "-" + ToString(um) + "]") {} void Call(const View & src, size_t featureSize, const View & filter, const View & mask, View & dst) const { TEST_PERFORMANCE_TEST(description); func((float*)src.data, src.stride / sizeof(float), src.width / featureSize, src.height, featureSize, (float*)filter.data, filter.width / featureSize, filter.height, (uint32_t*)mask.data, mask.stride / sizeof(uint32_t), (float*)dst.data, dst.stride / sizeof(float)); } }; } #define FUNC_HLFF(function) FuncHLFF(function, #function) void FillCorrelatedMask(View & mask, int range) { uint8_t * data = mask.data; size_t size = mask.DataSize(); while (size) { size_t length = std::min<size_t>(Random(range)*mask.PixelSize(), size); memset(data, Random(2) ? 0xFF : 0x00, length); size -= length; data += length; } } bool HogLiteFilterFeaturesAutoTest(size_t srcWidth, size_t srcHeight, size_t filterWidth, size_t filterHeight, size_t featureSize, int useMask, FuncHLFF f1, FuncHLFF f2) { bool result = true; f1.Update(filterWidth, filterHeight, featureSize, useMask); f2.Update(filterWidth, filterHeight, featureSize, useMask); TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << srcWidth << ", " << srcHeight << "]."); View filter(filterWidth*featureSize, filterHeight, View::Float, NULL, featureSize*sizeof(float)); FillRandom32f(filter, 0.5f, 1.5f); View src(srcWidth*featureSize, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize*sizeof(float))); FillRandom32f(src, 0.5f, 1.5f); size_t dstWidth = srcWidth - filterWidth + 1; size_t dstHeight = srcHeight - filterHeight + 1; View mask; if (useMask) { mask.Recreate(dstWidth, dstHeight, View::Int32, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(uint32_t))); FillCorrelatedMask(mask, 16); } View dst1(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dst2(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, featureSize, filter, mask, dst1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, featureSize, filter, mask, dst2)); result = result && Compare(dst1, dst2, EPS, true, 64); return result; } bool HogLiteFilterFeaturesAutoTest(size_t filterWidth, size_t filterHeight, size_t featureSize, int useMask, const FuncHLFF & f1, const FuncHLFF & f2) { bool result = true; result = result && HogLiteFilterFeaturesAutoTest(W / featureSize, H, filterWidth, filterHeight, featureSize, useMask, f1, f2); result = result && HogLiteFilterFeaturesAutoTest((W + O)/ featureSize, H - O, filterWidth, filterHeight, featureSize, useMask, f1, f2); return result; } bool HogLiteFilterFeaturesAutoTest(const FuncHLFF & f1, const FuncHLFF & f2) { bool result = true; result = result && HogLiteFilterFeaturesAutoTest(8, 8, 16, 1, f1, f2); result = result && HogLiteFilterFeaturesAutoTest(8, 8, 8, 1, f1, f2); result = result && HogLiteFilterFeaturesAutoTest(8, 8, 16, 0, f1, f2); result = result && HogLiteFilterFeaturesAutoTest(8, 8, 8, 0, f1, f2); result = result && HogLiteFilterFeaturesAutoTest(5, 7, 16, 0, f1, f2); result = result && HogLiteFilterFeaturesAutoTest(9, 5, 8, 1, f1, f2); result = result && HogLiteFilterFeaturesAutoTest(5, 5, 8, 0, f1, f2); return result; } bool HogLiteFilterFeaturesAutoTest() { bool result = true; result = result && HogLiteFilterFeaturesAutoTest(FUNC_HLFF(Simd::Base::HogLiteFilterFeatures), FUNC_HLFF(SimdHogLiteFilterFeatures)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteFilterFeaturesAutoTest(FUNC_HLFF(Simd::Sse41::HogLiteFilterFeatures), FUNC_HLFF(SimdHogLiteFilterFeatures)); #endif #ifdef SIMD_AVX_ENABLE if (Simd::Avx::Enable) result = result && HogLiteFilterFeaturesAutoTest(FUNC_HLFF(Simd::Avx::HogLiteFilterFeatures), FUNC_HLFF(SimdHogLiteFilterFeatures)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteFilterFeaturesAutoTest(FUNC_HLFF(Simd::Avx2::HogLiteFilterFeatures), FUNC_HLFF(SimdHogLiteFilterFeatures)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && HogLiteFilterFeaturesAutoTest(FUNC_HLFF(Simd::Avx512bw::HogLiteFilterFeatures), FUNC_HLFF(SimdHogLiteFilterFeatures)); #endif return result; } namespace { struct FuncHLRF { typedef void(*FuncPtr)(const float * src, size_t srcStride, size_t srcWidth, size_t srcHeight, size_t featureSize, float * dst, size_t dstStride, size_t dstWidth, size_t dstHeight); FuncPtr func; String description; FuncHLRF(const FuncPtr & f, const String & d) : func(f), description(d) {} FuncHLRF(const FuncHLRF & f, size_t fs) : func(f.func), description(f.description + "[" + ToString(fs) + "]") {} void Call(const View & src, size_t featureSize, View & dst) const { TEST_PERFORMANCE_TEST(description); func((float*)src.data, src.stride / sizeof(float), src.width / featureSize, src.height, featureSize, (float*)dst.data, dst.stride / sizeof(float), dst.width / featureSize, dst.height); } }; } #define FUNC_HLRF(function) FuncHLRF(function, #function) #define ARGS_HLRF(fs, f1, f2) fs, FuncHLRF(f1, fs), FuncHLRF(f2, fs) bool HogLiteResizeFeaturesAutoTest(size_t srcWidth, size_t srcHeight, double k, size_t featureSize, const FuncHLRF & f1, const FuncHLRF & f2) { bool result = true; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << srcWidth << ", " << srcHeight << "]."); View src(srcWidth*featureSize, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); FillRandom32f(src, 0.5f, 1.5f); size_t dstWidth = size_t(srcWidth*k); size_t dstHeight = size_t(srcHeight*k); View dst1(dstWidth*featureSize, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dst2(dstWidth*featureSize, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, featureSize, dst1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, featureSize, dst2)); result = result && Compare(dst1, dst2, EPS, true, 64); return result; } bool HogLiteResizeFeaturesAutoTest(double k, size_t featureSize, const FuncHLRF & f1, const FuncHLRF & f2) { bool result = true; result = result && HogLiteResizeFeaturesAutoTest(W / featureSize, H, k, featureSize, f1, f2); result = result && HogLiteResizeFeaturesAutoTest((W + O) / featureSize, H - O, k, featureSize, f1, f2); return result; } bool HogLiteResizeFeaturesAutoTest(const FuncHLRF & f1, const FuncHLRF & f2) { bool result = true; result = result && HogLiteResizeFeaturesAutoTest(0.7, ARGS_HLRF(16, f1, f2)); result = result && HogLiteResizeFeaturesAutoTest(0.7, ARGS_HLRF(8, f1, f2)); return result; } bool HogLiteResizeFeaturesAutoTest() { bool result = true; result = result && HogLiteResizeFeaturesAutoTest(FUNC_HLRF(Simd::Base::HogLiteResizeFeatures), FUNC_HLRF(SimdHogLiteResizeFeatures)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteResizeFeaturesAutoTest(FUNC_HLRF(Simd::Sse41::HogLiteResizeFeatures), FUNC_HLRF(SimdHogLiteResizeFeatures)); #endif #ifdef SIMD_AVX_ENABLE if (Simd::Avx::Enable) result = result && HogLiteResizeFeaturesAutoTest(FUNC_HLRF(Simd::Avx::HogLiteResizeFeatures), FUNC_HLRF(SimdHogLiteResizeFeatures)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteResizeFeaturesAutoTest(FUNC_HLRF(Simd::Avx2::HogLiteResizeFeatures), FUNC_HLRF(SimdHogLiteResizeFeatures)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && HogLiteResizeFeaturesAutoTest(FUNC_HLRF(Simd::Avx512bw::HogLiteResizeFeatures), FUNC_HLRF(SimdHogLiteResizeFeatures)); #endif return result; } namespace { struct FuncHLCF { static const size_t SRC_FEATURE_SIZE = 16; static const size_t DST_FEATURE_SIZE = 8; typedef void(*FuncPtr)(const float * src, size_t srcStride, size_t width, size_t height, const float * pca, float * dst, size_t dstStride); FuncPtr func; String description; FuncHLCF(const FuncPtr & f, const String & d) : func(f), description(d) {} void Call(const View & src, const View & pca, View & dst) const { TEST_PERFORMANCE_TEST(description); func((float*)src.data, src.stride / sizeof(float), src.width / SRC_FEATURE_SIZE, src.height, (float*)pca.data, (float*)dst.data, dst.stride / sizeof(float)); } }; } #define FUNC_HLCF(function) FuncHLCF(function, #function) bool HogLiteCompressFeaturesAutoTest(size_t width, size_t height, const FuncHLCF & f1, const FuncHLCF & f2) { bool result = true; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << width << ", " << height << "]."); View src(width*FuncHLCF::SRC_FEATURE_SIZE, height, View::Float, NULL, TEST_ALIGN(width*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); FillRandom32f(src, 0.5f, 1.5f); View pca(FuncHLCF::SRC_FEATURE_SIZE*FuncHLCF::SRC_FEATURE_SIZE, 1, View::Float, NULL, TEST_ALIGN(FuncHLCF::SRC_FEATURE_SIZE*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); FillRandom32f(pca, 0.5f, 1.5f); View dst1(width*FuncHLCF::DST_FEATURE_SIZE, height, View::Float, NULL, TEST_ALIGN(width*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); View dst2(width*FuncHLCF::DST_FEATURE_SIZE, height, View::Float, NULL, TEST_ALIGN(width*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, pca, dst1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, pca, dst2)); result = result && Compare(dst1, dst2, EPS, true, 64); return result; } bool HogLiteCompressFeaturesAutoTest(const FuncHLCF & f1, const FuncHLCF & f2) { bool result = true; result = result && HogLiteCompressFeaturesAutoTest(W / FuncHLCF::SRC_FEATURE_SIZE, H, f1, f2); result = result && HogLiteCompressFeaturesAutoTest((W + O) / FuncHLCF::SRC_FEATURE_SIZE, H - O, f1, f2); return result; } bool HogLiteCompressFeaturesAutoTest() { bool result = true; result = result && HogLiteCompressFeaturesAutoTest(FUNC_HLCF(Simd::Base::HogLiteCompressFeatures), FUNC_HLCF(SimdHogLiteCompressFeatures)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteCompressFeaturesAutoTest(FUNC_HLCF(Simd::Sse41::HogLiteCompressFeatures), FUNC_HLCF(SimdHogLiteCompressFeatures)); #endif #ifdef SIMD_AVX_ENABLE if (Simd::Avx::Enable) result = result && HogLiteCompressFeaturesAutoTest(FUNC_HLCF(Simd::Avx::HogLiteCompressFeatures), FUNC_HLCF(SimdHogLiteCompressFeatures)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteCompressFeaturesAutoTest(FUNC_HLCF(Simd::Avx2::HogLiteCompressFeatures), FUNC_HLCF(SimdHogLiteCompressFeatures)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && HogLiteCompressFeaturesAutoTest(FUNC_HLCF(Simd::Avx512bw::HogLiteCompressFeatures), FUNC_HLCF(SimdHogLiteCompressFeatures)); #endif return result; } namespace { struct FuncHLFS { typedef void(*FuncPtr)(const float * src, size_t srcStride, size_t srcWidth, size_t srcHeight, size_t featureSize, const float * hFilter, size_t hSize, const float * vFilter, size_t vSize, float * dst, size_t dstStride, int add); FuncPtr func; String description; FuncHLFS(const FuncPtr & f, const String & d) : func(f), description(d) {} FuncHLFS(const FuncHLFS & f, size_t hs, size_t vs, size_t fs, int add) : func(f.func), description(f.description + "[" + ToString(hs) + "x" + ToString(vs) + "x" + ToString(fs) + "-" + ToString(add) + "]") {} void Call(const View & src, size_t featureSize, const View & hFilter, const View & vFilter, const View & dstSrc, View & dstDst, int add) const { Simd::Copy(dstSrc, dstDst); TEST_PERFORMANCE_TEST(description); func((float*)src.data, src.stride / sizeof(float), src.width / featureSize, src.height, featureSize, (float*)hFilter.data, hFilter.width / featureSize, (float*)vFilter.data, vFilter.width, (float*)dstDst.data, dstDst.stride / sizeof(float), add); } }; } #define FUNC_HLFS(function) FuncHLFS(function, #function) #define ARGS_HLFS(wm, hs, vs, fs, add, f1, f2) wm, hs, vs, fs, add, FuncHLFS(f1, hs, vs, fs, add), FuncHLFS(f2, hs, vs, fs, add) bool HogLiteFilterSeparableAutoTest(size_t srcWidth, size_t srcHeight, size_t hSize, size_t vSize, size_t featureSize, int add, const FuncHLFS & f1, const FuncHLFS & f2) { bool result = true; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << srcWidth << ", " << srcHeight << "]."); View hFilter(hSize*featureSize, 1, View::Float, NULL, featureSize * sizeof(float)); FillRandom32f(hFilter, 0.5f, 1.5f); View vFilter(vSize, 1, View::Float, NULL, sizeof(float)); FillRandom32f(vFilter, 0.5f, 1.5f); View src(srcWidth*featureSize, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); FillRandom32f(src, 0.5f, 1.5f); size_t dstWidth = srcWidth - hSize + 1; size_t dstHeight = srcHeight - vSize + 1; View dstSrc(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); FillRandom32f(dstSrc, 0.5f, 1.5f); View dstDst1(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dstDst2(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, featureSize, hFilter, vFilter, dstSrc, dstDst1, add)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, featureSize, hFilter, vFilter, dstSrc, dstDst2, add)); result = result && Compare(dstDst1, dstDst2, EPS, true, 64); return result; } bool HogLiteFilterSeparableAutoTest(size_t wMin, size_t hSize, size_t vSize, size_t featureSize, int add, const FuncHLFS & f1, const FuncHLFS & f2) { bool result = true; if (W / featureSize < hSize - 1 + wMin) return result; result = result && HogLiteFilterSeparableAutoTest(W / featureSize, H, hSize, vSize, featureSize, add, f1, f2); result = result && HogLiteFilterSeparableAutoTest((W + O) / featureSize, H - O, hSize, vSize, featureSize, add, f1, f2); return result; } bool HogLiteFilterSeparableAutoTest(size_t wMin, const FuncHLFS & f1, const FuncHLFS & f2) { bool result = true; result = result && HogLiteFilterSeparableAutoTest(ARGS_HLFS(wMin, 8, 8, 16, 1, f1, f2)); result = result && HogLiteFilterSeparableAutoTest(ARGS_HLFS(wMin, 8, 8, 16, 0, f1, f2)); result = result && HogLiteFilterSeparableAutoTest(ARGS_HLFS(wMin, 8, 8, 8, 1, f1, f2)); result = result && HogLiteFilterSeparableAutoTest(ARGS_HLFS(wMin, 6, 6, 16, 1, f1, f2)); result = result && HogLiteFilterSeparableAutoTest(ARGS_HLFS(wMin, 6, 6, 8, 1, f1, f2)); return result; } bool HogLiteFilterSeparableAutoTest() { bool result = true; result = result && HogLiteFilterSeparableAutoTest(1, FUNC_HLFS(Simd::Base::HogLiteFilterSeparable), FUNC_HLFS(SimdHogLiteFilterSeparable)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteFilterSeparableAutoTest(Simd::Sse41::F, FUNC_HLFS(Simd::Sse41::HogLiteFilterSeparable), FUNC_HLFS(SimdHogLiteFilterSeparable)); #endif #ifdef SIMD_AVX_ENABLE if (Simd::Avx::Enable) result = result && HogLiteFilterSeparableAutoTest(Simd::Avx::F, FUNC_HLFS(Simd::Avx::HogLiteFilterSeparable), FUNC_HLFS(SimdHogLiteFilterSeparable)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteFilterSeparableAutoTest(Simd::Avx::F, FUNC_HLFS(Simd::Avx2::HogLiteFilterSeparable), FUNC_HLFS(SimdHogLiteFilterSeparable)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && HogLiteFilterSeparableAutoTest(1, FUNC_HLFS(Simd::Avx512bw::HogLiteFilterSeparable), FUNC_HLFS(SimdHogLiteFilterSeparable)); #endif return result; } namespace { struct FuncHLFM { typedef void(*FuncPtr)(const float * a, size_t aStride, const float * b, size_t bStride, size_t height, float * value, size_t * col, size_t * row); FuncPtr func; String description; FuncHLFM(const FuncPtr & f, const String & d) : func(f), description(d) {} void Call(const View & a, const View & b, View & value, View & row, View & col) const { TEST_PERFORMANCE_TEST(description); for(size_t i = 0; i < value.width; ++i) func((float*)a.data + i, a.stride / sizeof(float), (float*)b.data + i, b.stride / sizeof(float), a.height, (float*)value.data + i, (size_t*)((uint64_t*)col.data + i), (size_t*)((uint64_t*)row.data + i)); } }; } #define FUNC_HLFM(function) FuncHLFM(function, #function) bool HogLiteFindMax7x7AutoTest(size_t number, const FuncHLFM & f1, const FuncHLFM & f2) { bool result = true; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << number << "]."); View a(number + 6, 7, View::Float, NULL, TEST_ALIGN(number)); FillRandom32f(a, 0.5f, 1.5f); View b(number + 6, 7, View::Float, NULL, TEST_ALIGN(number)); FillRandom32f(b, 0.5f, 1.5f); View value1(number, 1, View::Float, NULL, TEST_ALIGN(number)); View col1(number, 1, View::Int64, NULL, TEST_ALIGN(number)); View row1(number, 1, View::Int64, NULL, TEST_ALIGN(number)); View value2(number, 1, View::Float, NULL, TEST_ALIGN(number)); View col2(number, 1, View::Int64, NULL, TEST_ALIGN(number)); View row2(number, 1, View::Int64, NULL, TEST_ALIGN(number)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(a, b, value1, col1, row1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(a, b, value2, col2, row2)); result = result && Compare(value1, value2, EPS, true, 64, "value"); result = result && Compare(col1, col2, 0, true, 64, 0, "col"); result = result && Compare(row1, row2, 0, true, 64, 0, "row"); return result; } bool HogLiteFindMax7x7AutoTest() { bool result = true; result = result && HogLiteFindMax7x7AutoTest(W, FUNC_HLFM(Simd::Base::HogLiteFindMax7x7), FUNC_HLFM(SimdHogLiteFindMax7x7)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteFindMax7x7AutoTest(W, FUNC_HLFM(Simd::Sse41::HogLiteFindMax7x7), FUNC_HLFM(SimdHogLiteFindMax7x7)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteFindMax7x7AutoTest(W, FUNC_HLFM(Simd::Avx2::HogLiteFindMax7x7), FUNC_HLFM(SimdHogLiteFindMax7x7)); #endif return result; } namespace { struct FuncHLCM { typedef void(*FuncPtr)(const float * src, size_t srcStride, size_t srcWidth, size_t srcHeight, const float * threshold, size_t scale, size_t size, uint32_t * dst, size_t dstStride); FuncPtr func; String description; FuncHLCM(const FuncPtr & f, const String & d) : func(f), description(d) {} FuncHLCM(const FuncHLCM & f, size_t si, size_t sc, float th) : func(f.func), description(f.description + "[" + ToString(si) + "x" + ToString(sc) + "-" + ToString((double)th, 1, true) + "]") {} void Call(const View & src, float threshold, size_t scale, size_t size, View & dst) const { TEST_PERFORMANCE_TEST(description); func((float*)src.data, src.stride / sizeof(float), src.width, src.height, &threshold, scale, size, (uint32_t*)dst.data, dst.stride / sizeof(uint32_t)); } }; } #define FUNC_HLCM(function) FuncHLCM(function, #function) #define ARGS_HLCM(si, sc, th, f1, f2) si, sc, th, FuncHLCM(f1, si, sc, th), FuncHLCM(f2, si, sc, th) bool HogLiteCreateMaskAutoTest(size_t srcWidth, size_t srcHeight, size_t size, size_t scale, float threshold, const FuncHLCM & f1, const FuncHLCM & f2) { bool result = true; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << srcWidth << ", " << srcHeight << "]."); View src(srcWidth, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*sizeof(float))); FillRandom32f(src, 0.0f, 1.0f); size_t dstWidth = srcWidth*scale + size - scale; size_t dstHeight = srcHeight*scale + size - scale; View dst1(dstWidth, dstHeight, View::Int32, NULL, TEST_ALIGN(srcWidth * sizeof(float))); View dst2(dstWidth, dstHeight, View::Int32, NULL, TEST_ALIGN(srcWidth * sizeof(float))); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(src, threshold, scale, size, dst1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(src, threshold, scale, size, dst2)); result = result && Compare(dst1, dst2, 0, true, 64); return result; } bool HogLiteCreateMaskAutoTest(const FuncHLCM & f1, const FuncHLCM & f2) { bool result = true; result = result && HogLiteCreateMaskAutoTest(W, H, ARGS_HLCM(7, 1, 0.9f, f1, f2)); result = result && HogLiteCreateMaskAutoTest(W, H, ARGS_HLCM(7, 1, 0.5f, f1, f2)); result = result && HogLiteCreateMaskAutoTest(W, H, ARGS_HLCM(7, 2, 0.9f, f1, f2)); result = result && HogLiteCreateMaskAutoTest(W, H, ARGS_HLCM(7, 2, 0.5f, f1, f2)); result = result && HogLiteCreateMaskAutoTest(W + O, H - O, ARGS_HLCM(7, 2, 0.9f, f1, f2)); return result; } bool HogLiteCreateMaskAutoTest() { bool result = true; result = result && HogLiteCreateMaskAutoTest(FUNC_HLCM(Simd::Base::HogLiteCreateMask), FUNC_HLCM(SimdHogLiteCreateMask)); #ifdef SIMD_SSE41_ENABLE if (Simd::Sse41::Enable) result = result && HogLiteCreateMaskAutoTest(FUNC_HLCM(Simd::Sse41::HogLiteCreateMask), FUNC_HLCM(SimdHogLiteCreateMask)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable) result = result && HogLiteCreateMaskAutoTest(FUNC_HLCM(Simd::Avx2::HogLiteCreateMask), FUNC_HLCM(SimdHogLiteCreateMask)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && HogLiteCreateMaskAutoTest(FUNC_HLCM(Simd::Avx512bw::HogLiteCreateMask), FUNC_HLCM(SimdHogLiteCreateMask)); #endif return result; } //----------------------------------------------------------------------- bool HogLiteExtractFeaturesDataTest(bool create, size_t cell, size_t size, int width, int height, const FuncHLEF & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << width << ", " << height << "]."); View src(width, height, View::Gray8, NULL, TEST_ALIGN(width)); size_t dstX = width / cell - 2; size_t dstY = height / cell - 2; View dst1(dstX*size, dstY, View::Float, NULL, TEST_ALIGN(width)); View dst2(dstX*size, dstY, View::Float, NULL, TEST_ALIGN(width)); if (create) { FillRandom(src); TEST_SAVE(src); f.Call(src, cell, dst1); TEST_SAVE(dst1); } else { TEST_LOAD(src); TEST_LOAD(dst1); f.Call(src, cell, dst2); TEST_SAVE(dst2); result = result && Compare(dst1, dst2, EPS, true, 64); } return result; } bool HogLiteExtractFeaturesDataTest(bool create) { return HogLiteExtractFeaturesDataTest(create, 8, 16, DW, DH, FUNC_HLEF(SimdHogLiteExtractFeatures)); } bool HogLiteFilterFeaturesDataTest(bool create, size_t srcWidth, size_t srcHeight, size_t filterSize, size_t featureSize, const FuncHLFF & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << srcWidth << ", " << srcHeight << "]."); View filter(filterSize*featureSize, filterSize, View::Float, NULL, featureSize * sizeof(float)); View src(srcWidth*featureSize, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); size_t dstWidth = srcWidth - filterSize + 1; size_t dstHeight = srcHeight - filterSize + 1; View mask(dstWidth, dstHeight, View::Int32, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(uint32_t))); View dst1(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dst2(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); if (create) { FillRandom32f(src); FillRandom32f(filter); FillCorrelatedMask(mask, 16); TEST_SAVE(src); TEST_SAVE(filter); TEST_SAVE(mask); f.Call(src, featureSize, filter, mask, dst1); TEST_SAVE(dst1); } else { TEST_LOAD(src); TEST_LOAD(filter); TEST_LOAD(mask); TEST_LOAD(dst1); f.Call(src, featureSize, filter, mask, dst2); TEST_SAVE(dst2); result = result && Compare(dst1, dst2, EPS, true, 64); } return result; } bool HogLiteFilterFeaturesDataTest(bool create) { return HogLiteFilterFeaturesDataTest(create, DW, DH, 8, 16, FUNC_HLFF(SimdHogLiteFilterFeatures)); } bool HogLiteResizeFeaturesDataTest(bool create, size_t srcWidth, size_t srcHeight, double k, size_t featureSize, const FuncHLRF & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << srcWidth << ", " << srcHeight << "]."); View src(srcWidth*featureSize, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); size_t dstWidth = size_t(srcWidth*k); size_t dstHeight = size_t(srcHeight*k); View dst1(dstWidth*featureSize, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dst2(dstWidth*featureSize, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); if (create) { FillRandom32f(src); TEST_SAVE(src); f.Call(src, featureSize, dst1); TEST_SAVE(dst1); } else { TEST_LOAD(src); TEST_LOAD(dst1); f.Call(src, featureSize, dst2); TEST_SAVE(dst2); result = result && Compare(dst1, dst2, EPS, true, 64); } return result; } bool HogLiteResizeFeaturesDataTest(bool create) { return HogLiteResizeFeaturesDataTest(create, DW / 16, DH, 0.7, 16, FUNC_HLRF(SimdHogLiteResizeFeatures)); } bool HogLiteCompressFeaturesDataTest(bool create, size_t width, size_t height, const FuncHLCF & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << width << ", " << height << "]."); View src(width*FuncHLCF::SRC_FEATURE_SIZE, height, View::Float, NULL, TEST_ALIGN(width*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); View pca(FuncHLCF::SRC_FEATURE_SIZE*FuncHLCF::SRC_FEATURE_SIZE, 1, View::Float, NULL, TEST_ALIGN(FuncHLCF::SRC_FEATURE_SIZE*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); View dst1(width*FuncHLCF::DST_FEATURE_SIZE, height, View::Float, NULL, TEST_ALIGN(width*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); View dst2(width*FuncHLCF::DST_FEATURE_SIZE, height, View::Float, NULL, TEST_ALIGN(width*FuncHLCF::SRC_FEATURE_SIZE * sizeof(float))); if (create) { FillRandom32f(src); FillRandom32f(pca); TEST_SAVE(src); TEST_SAVE(pca); f.Call(src, pca, dst1); TEST_SAVE(dst1); } else { TEST_LOAD(src); TEST_LOAD(pca); TEST_LOAD(dst1); f.Call(src, pca, dst2); TEST_SAVE(dst2); result = result && Compare(dst1, dst2, EPS, true, 64); } return result; } bool HogLiteCompressFeaturesDataTest(bool create) { return HogLiteCompressFeaturesDataTest(create, DW / FuncHLCF::SRC_FEATURE_SIZE, DH, FUNC_HLCF(SimdHogLiteCompressFeatures)); } bool HogLiteFilterSeparableDataTest(bool create, size_t srcWidth, size_t srcHeight, size_t hSize, size_t vSize, size_t featureSize, int add, const FuncHLFS & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << srcWidth << ", " << srcHeight << "]."); View hFilter(hSize*featureSize, 1, View::Float, NULL, featureSize * sizeof(float)); View vFilter(vSize, 1, View::Float, NULL, sizeof(float)); View src(srcWidth*featureSize, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); size_t dstWidth = srcWidth - hSize + 1; size_t dstHeight = srcHeight - vSize + 1; View dstSrc(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dstDst1(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); View dstDst2(dstWidth, dstHeight, View::Float, NULL, TEST_ALIGN(srcWidth*featureSize * sizeof(float))); if (create) { FillRandom32f(hFilter, 0.5f, 1.5f); FillRandom32f(vFilter, 0.5f, 1.5f); FillRandom32f(src); FillRandom32f(dstSrc); TEST_SAVE(hFilter); TEST_SAVE(vFilter); TEST_SAVE(src); TEST_SAVE(dstSrc); f.Call(src, featureSize, hFilter, vFilter, dstSrc, dstDst1, add); TEST_SAVE(dstDst1); } else { TEST_LOAD(hFilter); TEST_LOAD(vFilter); TEST_LOAD(src); TEST_LOAD(dstSrc); TEST_LOAD(dstDst1); f.Call(src, featureSize, hFilter, vFilter, dstSrc, dstDst2, add); TEST_SAVE(dstDst2); result = result && Compare(dstDst1, dstDst2, EPS, true, 64); } return result; } bool HogLiteFilterSeparableDataTest(bool create) { return HogLiteFilterSeparableDataTest(create, DW, DH, 8, 8, 16, 1, FUNC_HLFS(SimdHogLiteFilterSeparable)); } bool HogLiteFindMax7x7DataTest(bool create, size_t number, const FuncHLFM & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << number << "]."); View a(number + 6, 7, View::Float, NULL, TEST_ALIGN(number)); View b(number + 6, 7, View::Float, NULL, TEST_ALIGN(number)); View value1(number, 1, View::Float, NULL, TEST_ALIGN(number)); View col1(number, 1, View::Int64, NULL, TEST_ALIGN(number)); View row1(number, 1, View::Int64, NULL, TEST_ALIGN(number)); View value2(number, 1, View::Float, NULL, TEST_ALIGN(number)); View col2(number, 1, View::Int64, NULL, TEST_ALIGN(number)); View row2(number, 1, View::Int64, NULL, TEST_ALIGN(number)); if (create) { FillRandom32f(a, 0.5f, 1.5f); FillRandom32f(b, 0.5f, 1.5f); TEST_SAVE(a); TEST_SAVE(b); f.Call(a, b, value1, col1, row1); TEST_SAVE(value1); TEST_SAVE(col1); TEST_SAVE(row1); } else { TEST_LOAD(a); TEST_LOAD(b); TEST_LOAD(value1); TEST_LOAD(col1); TEST_LOAD(row1); f.Call(a, b, value2, col2, row2); TEST_SAVE(value2); TEST_SAVE(col2); TEST_SAVE(row2); result = result && Compare(value1, value2, EPS, true, 64, "value"); result = result && Compare(col1, col2, 0, true, 64, 0, "col"); result = result && Compare(row1, row2, 0, true, 64, 0, "row"); } return result; } bool HogLiteFindMax7x7DataTest(bool create) { return HogLiteFindMax7x7DataTest(create, DW, FUNC_HLFM(SimdHogLiteFindMax7x7)); } bool HogLiteCreateMaskDataTest(bool create, size_t srcWidth, size_t srcHeight, size_t size, size_t scale, float threshold, const FuncHLCM & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << srcWidth << ", " << srcHeight << "]."); View src(srcWidth, srcHeight, View::Float, NULL, TEST_ALIGN(srcWidth * sizeof(float))); size_t dstWidth = srcWidth*scale + size - scale; size_t dstHeight = srcHeight*scale + size - scale; View dst1(dstWidth, dstHeight, View::Int32, NULL, TEST_ALIGN(srcWidth * sizeof(float))); View dst2(dstWidth, dstHeight, View::Int32, NULL, TEST_ALIGN(srcWidth * sizeof(float))); if (create) { FillRandom32f(src, 0.0f, 1.0f); TEST_SAVE(src); f.Call(src, threshold, scale, size, dst1); TEST_SAVE(dst1); } else { TEST_LOAD(src); TEST_LOAD(dst1); f.Call(src, threshold, scale, size, dst2); TEST_SAVE(dst2); result = result && Compare(dst1, dst2, 0, true, 64); } return result; } bool HogLiteCreateMaskDataTest(bool create) { return HogLiteCreateMaskDataTest(create, DW, DH, 7, 2, 0.5f, FUNC_HLCM(SimdHogLiteCreateMask)); } }
39.509158
264
0.610977
Erensu
b9ca6ea5ee58d713fd2c40adb8c326cdc5f2c20a
241
hpp
C++
taint/src/riscv/types.hpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
taint/src/riscv/types.hpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
taint/src/riscv/types.hpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
#ifndef _RISCV__TYPES_HPP_ #define _RISCV__TYPES_HPP_ #include <cstdint> namespace riscv { #if __riscv_xlen == 32 #error "only support rv64" #endif typedef uint32_t insn_t; typedef uint64_t addr_t; typedef uint64_t rlen_t; } #endif
13.388889
30
0.767635
ClasSun9
844df9e7409f26c78908c9d64bdb41ea9fc81d57
10,538
cpp
C++
Graphics/GraphicsEngineD3D12/src/DeviceMemoryD3D12Impl.cpp
tombish/DiligentCore
77cc297dd6848837fa5b0ed5c4161d7d0127a64a
[ "Apache-2.0" ]
398
2016-04-21T03:38:50.000Z
2022-03-23T15:27:31.000Z
Graphics/GraphicsEngineD3D12/src/DeviceMemoryD3D12Impl.cpp
tombish/DiligentCore
77cc297dd6848837fa5b0ed5c4161d7d0127a64a
[ "Apache-2.0" ]
275
2017-12-27T04:11:55.000Z
2022-03-30T07:35:11.000Z
Graphics/GraphicsEngineD3D12/src/DeviceMemoryD3D12Impl.cpp
tombish/DiligentCore
77cc297dd6848837fa5b0ed5c4161d7d0127a64a
[ "Apache-2.0" ]
139
2017-09-13T06:19:49.000Z
2022-03-28T15:01:20.000Z
/* * Copyright 2019-2021 Diligent Graphics 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "DeviceMemoryD3D12Impl.hpp" #include "RenderDeviceD3D12Impl.hpp" #include "DeviceContextD3D12Impl.hpp" #include "TextureD3D12Impl.hpp" #include "BufferD3D12Impl.hpp" #include "D3D12TypeConversions.hpp" #include "GraphicsAccessories.hpp" namespace Diligent { namespace { D3D12_HEAP_FLAGS GetD3D12HeapFlags(ID3D12Device* pd3d12Device, IDeviceObject** ppResources, Uint32 NumResources, bool& AllowMSAA, bool& UseNVApi) noexcept(false) { AllowMSAA = false; UseNVApi = false; // NB: D3D12_RESOURCE_HEAP_TIER_1 hardware requires exactly one of the // flags below left unset when creating a heap. constexpr auto D3D12_HEAP_FLAG_DENY_ALL = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; auto HeapFlags = D3D12_HEAP_FLAG_DENY_ALL; D3D12_FEATURE_DATA_D3D12_OPTIONS d3d12Features{}; if (SUCCEEDED(pd3d12Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &d3d12Features, sizeof(d3d12Features)))) { if (d3d12Features.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1) { if (NumResources == 0) { LOG_ERROR_AND_THROW("D3D12_RESOURCE_HEAP_TIER_1 hardware requires that at least one comptaible resource is provided. " "See SPARSE_RESOURCE_CAP_FLAG_MIXED_RESOURCE_TYPE_SUPPORT capability."); } } else if (d3d12Features.ResourceHeapTier >= D3D12_RESOURCE_HEAP_TIER_2) { // D3D12_RESOURCE_HEAP_TIER_2 hardware allows any combination of resources // to be placed in the heap HeapFlags = D3D12_HEAP_FLAG_NONE; } } if (NumResources == 0) return HeapFlags; Uint32 UsingNVApiCount = 0; Uint32 NotUsingNVApiCount = 0; static_assert(BIND_FLAGS_LAST == 1u << 11u, "Did you add a new bind flag? You may need to update the logic below."); for (Uint32 res = 0; res < NumResources; ++res) { auto* pResource = ppResources[res]; if (pResource == nullptr) continue; if (RefCntAutoPtr<ITextureD3D12> pTexture{pResource, IID_TextureD3D12}) { const auto* pTexD3D12Impl = pTexture.RawPtr<const TextureD3D12Impl>(); const auto& TexDesc = pTexD3D12Impl->GetDesc(); if (TexDesc.Usage != USAGE_SPARSE) LOG_ERROR_AND_THROW("Resource must be created with USAGE_SPARSE"); if (TexDesc.SampleCount > 1) AllowMSAA = true; if (pTexD3D12Impl->IsUsingNVApi()) ++UsingNVApiCount; else ++NotUsingNVApiCount; if (TexDesc.BindFlags & (BIND_RENDER_TARGET | BIND_DEPTH_STENCIL)) HeapFlags &= ~D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES; if (TexDesc.BindFlags & (BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS | BIND_INPUT_ATTACHMENT)) HeapFlags &= ~D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; if (TexDesc.BindFlags & BIND_UNORDERED_ACCESS) HeapFlags |= D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; } else if (RefCntAutoPtr<IBufferD3D12> pBuffer{pResource, IID_BufferD3D12}) { const auto& BuffDesc = pBuffer.RawPtr<const BufferD3D12Impl>()->GetDesc(); if (BuffDesc.Usage != USAGE_SPARSE) LOG_ERROR_AND_THROW("Resource must be created with USAGE_SPARSE"); HeapFlags &= ~D3D12_HEAP_FLAG_DENY_BUFFERS; if (BuffDesc.BindFlags & BIND_UNORDERED_ACCESS) HeapFlags |= D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; } else { UNEXPECTED("unsupported resource type"); } } if (d3d12Features.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1) { const auto NumDenyFlags = PlatformMisc::CountOneBits(static_cast<Uint32>(HeapFlags & D3D12_HEAP_FLAG_DENY_ALL)); if (NumDenyFlags != 2) { LOG_ERROR_AND_THROW("On D3D12_RESOURCE_HEAP_TIER_1 hadrware, only single resource usage for the heap is allowed: " "buffers, RT_DS_TEXTURES (BIND_RENDER_TARGET, BIND_DEPTH_STENCIL), or NON_RT_DS_TEXTURES " "(BIND_SHADER_RESOURCE, BIND_UNORDERED_ACCESS, BIND_INPUT_ATTACHMENT). " "See SPARSE_RESOURCE_CAP_FLAG_MIXED_RESOURCE_TYPE_SUPPORT capability."); } } if (UsingNVApiCount > 0) UseNVApi = true; if (UseNVApi && NotUsingNVApiCount > 0) LOG_ERROR_AND_THROW("Resources that use NVApi are incompatible with the resources that don't"); return HeapFlags; } inline CComPtr<ID3D12Heap> CreateD3D12Heap(RenderDeviceD3D12Impl* pDevice, const D3D12_HEAP_DESC& d3d12HeapDesc, bool UseNVApi) { auto* const pd3d12Device = pDevice->GetD3D12Device(); CComPtr<ID3D12Heap> pd3d12Heap; #ifdef DILIGENT_ENABLE_D3D_NVAPI if (UseNVApi) { if (NvAPI_D3D12_CreateHeap(pd3d12Device, &d3d12HeapDesc, IID_PPV_ARGS(&pd3d12Heap)) != NVAPI_OK) { LOG_ERROR_MESSAGE("Failed to create D3D12 heap using NVApi"); return {}; } } else #endif { if (FAILED(pd3d12Device->CreateHeap(&d3d12HeapDesc, IID_PPV_ARGS(&pd3d12Heap)))) { LOG_ERROR_MESSAGE("Failed to create D3D12 heap"); return {}; } } return pd3d12Heap; } } // namespace DeviceMemoryD3D12Impl::DeviceMemoryD3D12Impl(IReferenceCounters* pRefCounters, RenderDeviceD3D12Impl* pDeviceD3D11, const DeviceMemoryCreateInfo& MemCI) : TDeviceMemoryBase{pRefCounters, pDeviceD3D11, MemCI} { m_d3d12HeapFlags = GetD3D12HeapFlags(m_pDevice->GetD3D12Device(), MemCI.ppCompatibleResources, MemCI.NumResources, m_AllowMSAA, m_UseNVApi); if (!Resize(MemCI.InitialSize)) LOG_ERROR_AND_THROW("Failed to allocate device memory"); } DeviceMemoryD3D12Impl::~DeviceMemoryD3D12Impl() { m_pDevice->SafeReleaseDeviceObject(std::move(m_Pages), m_Desc.ImmediateContextMask); } IMPLEMENT_QUERY_INTERFACE(DeviceMemoryD3D12Impl, IID_DeviceMemoryD3D12, TDeviceMemoryBase) Bool DeviceMemoryD3D12Impl::Resize(Uint64 NewSize) { DvpVerifyResize(NewSize); D3D12_HEAP_DESC d3d12HeapDesc{}; d3d12HeapDesc.SizeInBytes = m_Desc.PageSize; d3d12HeapDesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; d3d12HeapDesc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; d3d12HeapDesc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; d3d12HeapDesc.Properties.CreationNodeMask = 1; d3d12HeapDesc.Properties.VisibleNodeMask = 1; d3d12HeapDesc.Alignment = m_AllowMSAA ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; d3d12HeapDesc.Flags = m_d3d12HeapFlags; const auto NewPageCount = StaticCast<size_t>(NewSize / m_Desc.PageSize); m_Pages.reserve(NewPageCount); while (m_Pages.size() < NewPageCount) { if (auto pHeap = CreateD3D12Heap(m_pDevice, d3d12HeapDesc, m_UseNVApi)) m_Pages.emplace_back(std::move(pHeap)); else return false; } while (m_Pages.size() > NewPageCount) { m_pDevice->SafeReleaseDeviceObject(std::move(m_Pages.back()), m_Desc.ImmediateContextMask); m_Pages.pop_back(); } return true; } Uint64 DeviceMemoryD3D12Impl::GetCapacity() const { return m_Desc.PageSize * m_Pages.size(); } Bool DeviceMemoryD3D12Impl::IsCompatible(IDeviceObject* pResource) const { try { bool AllowMSAA = false; bool UseNVApi = false; auto d3d12RequiredHeapFlags = GetD3D12HeapFlags(m_pDevice->GetD3D12Device(), &pResource, 1, AllowMSAA, UseNVApi); return ((m_d3d12HeapFlags & d3d12RequiredHeapFlags) == d3d12RequiredHeapFlags) && (!AllowMSAA || m_AllowMSAA) && (UseNVApi == m_UseNVApi); } catch (...) { return false; } } DeviceMemoryRangeD3D12 DeviceMemoryD3D12Impl::GetRange(Uint64 Offset, Uint64 Size) const { const auto PageIdx = static_cast<size_t>(Offset / m_Desc.PageSize); DeviceMemoryRangeD3D12 Range{}; if (PageIdx >= m_Pages.size()) { DEV_ERROR("DeviceMemoryD3D12Impl::GetRange(): Offset is out of bounds of allocated space"); return Range; } const auto OffsetInPage = Offset % m_Desc.PageSize; if (OffsetInPage + Size > m_Desc.PageSize) { DEV_ERROR("DeviceMemoryD3D12Impl::GetRange(): Offset and Size must be inside a single page"); return Range; } Range.Offset = OffsetInPage; Range.pHandle = m_Pages[PageIdx]; Range.Size = std::min(m_Desc.PageSize - OffsetInPage, Size); return Range; } } // namespace Diligent
36.846154
159
0.665307
tombish
84507a5d5dddb321e65cb454d045cc7912bcf42d
1,860
cpp
C++
backups/test3.cpp
charlesw1234/densityxx
22b2a0e7a8d3f7343352a7d402823cbb3476f44a
[ "BSD-3-Clause" ]
9
2016-02-21T15:02:23.000Z
2020-04-19T13:26:19.000Z
backups/test3.cpp
charlesw1234/densityxx
22b2a0e7a8d3f7343352a7d402823cbb3476f44a
[ "BSD-3-Clause" ]
null
null
null
backups/test3.cpp
charlesw1234/densityxx
22b2a0e7a8d3f7343352a7d402823cbb3476f44a
[ "BSD-3-Clause" ]
null
null
null
#include "densityxx/file_buffer.hpp" #include "densityxx/block.hpp" #include "densityxx/lion.hpp" static void exit_error(density::buffer_state_t buffer_state) { fprintf(stderr, "%s\n", density::buffer_state_render(buffer_state).c_str()); exit(-1); } int main(void) { uint_fast64_t read; density::context_t context; density::encode_state_t encode_state; density::buffer_state_t buffer_state; FILE *rfp = fopen("sharcxx.exe.c3", "rb"); FILE *wfp = fopen("sharcxx.exe.c3.sharc", "wb"); density::file_buffer_t<1 << 19, 1 << 19> buffer(rfp, wfp); density::block_encode_t<density::lion_encode_t> block_encode; buffer.init(density::compression_mode_lion_algorithm, density::block_type_default, context); block_encode.init(context); if ((buffer_state = buffer.action(NULL, density::encode_state_stall_on_input, context))) exit_error(buffer_state); while ((encode_state = context.write_header())) if ((buffer_state = buffer.action(NULL, encode_state, context))) exit_error(buffer_state); while ((encode_state = context.after(block_encode.continue_(context.before())))) if ((buffer_state = buffer.action(&read, encode_state, context))) exit_error(buffer_state); else if (read < (1 << 19)) break; while ((encode_state = context.after(block_encode.finish(context.before())))) if ((buffer_state = buffer.action(NULL, encode_state, context))) exit_error(buffer_state); while ((encode_state = context.write_footer(block_encode.read_bytes()))) if ((buffer_state = buffer.action(NULL, encode_state, context))) exit_error(buffer_state); if ((buffer_state = buffer.action(NULL, density::encode_state_stall_on_output, context))) exit_error(buffer_state); fclose(rfp); fclose(wfp); return 0; }
41.333333
96
0.694624
charlesw1234
84529e002a900733cadafdb3f8674d22295ef754
3,260
cpp
C++
code/engine/xrGame/alife_simulator_base2.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
58
2016-11-20T19:14:35.000Z
2021-12-27T21:03:35.000Z
code/engine/xrGame/alife_simulator_base2.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
59
2016-09-10T10:44:20.000Z
2018-09-03T19:07:30.000Z
code/engine/xrGame/alife_simulator_base2.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
39
2017-02-05T13:35:37.000Z
2022-03-14T11:00:12.000Z
//////////////////////////////////////////////////////////////////////////// // Module : alife_simulator_base2.cpp // Created : 25.12.2002 // Modified : 12.05.2004 // Author : Dmitriy Iassenev // Description : ALife Simulator base class //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "alife_simulator_base.h" //#include "relation_registry.h" //#include "alife_registry_wrappers.h" #include "xrServer_Objects_ALife_Items.h" #include "alife_graph_registry.h" #include "alife_object_registry.h" #include "alife_story_registry.h" #include "alife_schedule_registry.h" #include "alife_smart_terrain_registry.h" #include "alife_group_registry.h" using namespace ALife; void CALifeSimulatorBase::register_object(CSE_ALifeDynamicObject* object, bool add_object) { object->on_before_register(); if (add_object) objects().add(object); graph().update(object); scheduled().add(object); story_objects().add(object->m_story_id, object); smart_terrains().add(object); groups().add(object); setup_simulator(object); CSE_ALifeInventoryItem* item = smart_cast<CSE_ALifeInventoryItem*>(object); if (item && item->attached()) { CSE_ALifeDynamicObject* II = objects().object(item->base()->ID_Parent); #ifdef DEBUG if (std::find(II->children.begin(), II->children.end(), item->base()->ID) != II->children.end()) { Msg("[LSS] Specified item [%s][%d] is already attached to the specified object " "[%s][%d]", item->base()->name_replace(), item->base()->ID, II->name_replace(), II->ID); FATAL("[LSS] Cannot recover from the previous error!"); } #endif II->children.push_back(item->base()->ID); II->attach(item, true, false); } if (can_register_objects()) object->on_register(); } void CALifeSimulatorBase::unregister_object(CSE_ALifeDynamicObject* object, bool alife_query) { object->on_unregister(); CSE_ALifeInventoryItem* item = smart_cast<CSE_ALifeInventoryItem*>(object); if (item && item->attached()) graph().detach(*objects().object(item->base()->ID_Parent), item, objects().object(item->base()->ID_Parent)->m_tGraphID, alife_query); objects().remove(object->ID); story_objects().remove(object->m_story_id); smart_terrains().remove(object); groups().remove(object); if (!object->m_bOnline) { graph().remove(object, object->m_tGraphID); scheduled().remove(object); } else if (object->ID_Parent == 0xffff) { // if (object->used_ai_locations()) graph().level().remove(object, !object->used_ai_locations()); } } void CALifeSimulatorBase::on_death(CSE_Abstract* killed, CSE_Abstract* killer) { typedef CSE_ALifeOnlineOfflineGroup::MEMBER GROUP_MEMBER; CSE_ALifeCreatureAbstract* creature = smart_cast<CSE_ALifeCreatureAbstract*>(killed); if (creature) creature->on_death(killer); GROUP_MEMBER* member = smart_cast<GROUP_MEMBER*>(killed); if (!member) return; if (member->m_group_id == 0xffff) return; groups().object(member->m_group_id).notify_on_member_death(member); }
33.608247
95
0.638344
InNoHurryToCode
845bfcc4e8e3c80f81ddfff66e484304f7e30683
12,863
cc
C++
firestore/src/android/query_android.cc
tupleapp/firebase-cpp-sdk
b49f62267c897d9012fc536ea1491bfb51562ae3
[ "Apache-2.0" ]
null
null
null
firestore/src/android/query_android.cc
tupleapp/firebase-cpp-sdk
b49f62267c897d9012fc536ea1491bfb51562ae3
[ "Apache-2.0" ]
null
null
null
firestore/src/android/query_android.cc
tupleapp/firebase-cpp-sdk
b49f62267c897d9012fc536ea1491bfb51562ae3
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC #include "firestore/src/android/query_android.h" #include "app/meta/move.h" #include "app/src/assert.h" #include "firestore/src/android/direction_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/event_listener_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/firestore_android.h" #include "firestore/src/android/lambda_event_listener.h" #include "firestore/src/android/listener_registration_android.h" #include "firestore/src/android/metadata_changes_android.h" #include "firestore/src/android/promise_android.h" #include "firestore/src/android/source_android.h" #include "firestore/src/include/firebase/firestore.h" #include "firestore/src/jni/array.h" #include "firestore/src/jni/array_list.h" #include "firestore/src/jni/env.h" #include "firestore/src/jni/loader.h" #include "firestore/src/jni/task.h" namespace firebase { namespace firestore { namespace { using jni::Array; using jni::ArrayList; using jni::Env; using jni::Local; using jni::Method; using jni::Object; using jni::Task; constexpr char kClassName[] = PROGUARD_KEEP_CLASS "com/google/firebase/firestore/Query"; Method<Object> kEqualTo( "whereEqualTo", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kNotEqualTo( "whereNotEqualTo", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kLessThan( "whereLessThan", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kLessThanOrEqualTo( "whereLessThanOrEqualTo", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kGreaterThan( "whereGreaterThan", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kGreaterThanOrEqualTo( "whereGreaterThanOrEqualTo", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kArrayContains( "whereArrayContains", "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kArrayContainsAny( "whereArrayContainsAny", "(Lcom/google/firebase/firestore/FieldPath;Ljava/util/List;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kIn("whereIn", "(Lcom/google/firebase/firestore/FieldPath;Ljava/util/List;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kNotIn( "whereNotIn", "(Lcom/google/firebase/firestore/FieldPath;Ljava/util/List;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kOrderBy("orderBy", "(Lcom/google/firebase/firestore/FieldPath;" "Lcom/google/firebase/firestore/Query$Direction;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kLimit("limit", "(J)Lcom/google/firebase/firestore/Query;"); Method<Object> kLimitToLast("limitToLast", "(J)Lcom/google/firebase/firestore/Query;"); Method<Object> kStartAtSnapshot( "startAt", "(Lcom/google/firebase/firestore/DocumentSnapshot;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kStartAt( "startAt", "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"); Method<Object> kStartAfterSnapshot( "startAfter", "(Lcom/google/firebase/firestore/DocumentSnapshot;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kStartAfter( "startAfter", "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"); Method<Object> kEndBeforeSnapshot( "endBefore", "(Lcom/google/firebase/firestore/DocumentSnapshot;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kEndBefore( "endBefore", "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"); Method<Object> kEndAtSnapshot( "endAt", "(Lcom/google/firebase/firestore/DocumentSnapshot;)" "Lcom/google/firebase/firestore/Query;"); Method<Object> kEndAt( "endAt", "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"); Method<Task> kGet("get", "(Lcom/google/firebase/firestore/Source;)" "Lcom/google/android/gms/tasks/Task;"); Method<Object> kAddSnapshotListener( "addSnapshotListener", "(Ljava/util/concurrent/Executor;" "Lcom/google/firebase/firestore/MetadataChanges;" "Lcom/google/firebase/firestore/EventListener;)" "Lcom/google/firebase/firestore/ListenerRegistration;"); } // namespace void QueryInternal::Initialize(jni::Loader& loader) { loader.LoadClass( kClassName, kEqualTo, kNotEqualTo, kLessThan, kLessThanOrEqualTo, kGreaterThan, kGreaterThanOrEqualTo, kArrayContains, kArrayContainsAny, kIn, kNotIn, kOrderBy, kLimit, kLimitToLast, kStartAtSnapshot, kStartAt, kStartAfterSnapshot, kStartAfter, kEndBeforeSnapshot, kEndBefore, kEndAtSnapshot, kEndAt, kGet, kAddSnapshotListener); } Firestore* QueryInternal::firestore() { FIREBASE_ASSERT(firestore_->firestore_public() != nullptr); return firestore_->firestore_public(); } Query QueryInternal::WhereEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, kEqualTo, value); } Query QueryInternal::WhereNotEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, kNotEqualTo, value); } Query QueryInternal::WhereLessThan(const FieldPath& field, const FieldValue& value) const { return Where(field, kLessThan, value); } Query QueryInternal::WhereLessThanOrEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, kLessThanOrEqualTo, value); } Query QueryInternal::WhereGreaterThan(const FieldPath& field, const FieldValue& value) const { return Where(field, kGreaterThan, value); } Query QueryInternal::WhereGreaterThanOrEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, kGreaterThanOrEqualTo, value); } Query QueryInternal::WhereArrayContains(const FieldPath& field, const FieldValue& value) const { return Where(field, kArrayContains, value); } Query QueryInternal::WhereArrayContainsAny( const FieldPath& field, const std::vector<FieldValue>& values) const { return Where(field, kArrayContainsAny, values); } Query QueryInternal::WhereIn(const FieldPath& field, const std::vector<FieldValue>& values) const { return Where(field, kIn, values); } Query QueryInternal::WhereNotIn(const FieldPath& field, const std::vector<FieldValue>& values) const { return Where(field, kNotIn, values); } Query QueryInternal::OrderBy(const FieldPath& field, Query::Direction direction) const { Env env = GetEnv(); Local<Object> java_field = FieldPathConverter::Create(env, field); Local<Object> java_direction = DirectionInternal::Create(env, direction); Local<Object> query = env.Call(obj_, kOrderBy, java_field.get(), java_direction.get()); return firestore_->NewQuery(env, query); } Query QueryInternal::Limit(int32_t limit) const { Env env = GetEnv(); // Although the backend only supports int32, the Android client SDK uses long // as parameter type. auto java_limit = static_cast<jlong>(limit); Local<Object> query = env.Call(obj_, kLimit, java_limit); return firestore_->NewQuery(env, query); } Query QueryInternal::LimitToLast(int32_t limit) const { Env env = GetEnv(); // Although the backend only supports int32, the Android client SDK uses long // as parameter type. auto java_limit = static_cast<jlong>(limit); Local<Object> query = env.Call(obj_, kLimitToLast, java_limit); return firestore_->NewQuery(env, query); } Query QueryInternal::StartAt(const DocumentSnapshot& snapshot) const { return WithBound(kStartAtSnapshot, snapshot); } Query QueryInternal::StartAt(const std::vector<FieldValue>& values) const { return WithBound(kStartAt, values); } Query QueryInternal::StartAfter(const DocumentSnapshot& snapshot) const { return WithBound(kStartAfterSnapshot, snapshot); } Query QueryInternal::StartAfter(const std::vector<FieldValue>& values) const { return WithBound(kStartAfter, values); } Query QueryInternal::EndBefore(const DocumentSnapshot& snapshot) const { return WithBound(kEndBeforeSnapshot, snapshot); } Query QueryInternal::EndBefore(const std::vector<FieldValue>& values) const { return WithBound(kEndBefore, values); } Query QueryInternal::EndAt(const DocumentSnapshot& snapshot) const { return WithBound(kEndAtSnapshot, snapshot); } Query QueryInternal::EndAt(const std::vector<FieldValue>& values) const { return WithBound(kEndAt, values); } Future<QuerySnapshot> QueryInternal::Get(Source source) { Env env = GetEnv(); Local<Object> java_source = SourceInternal::Create(env, source); Local<Task> task = env.Call(obj_, kGet, java_source); return promises_.NewFuture<QuerySnapshot>(env, AsyncFn::kGet, task); } Query QueryInternal::Where(const FieldPath& field, const Method<Object>& method, const FieldValue& value) const { Env env = GetEnv(); Local<Object> java_field = FieldPathConverter::Create(env, field); Local<Object> query = env.Call(obj_, method, java_field, ToJava(value)); return firestore_->NewQuery(env, query); } Query QueryInternal::Where(const FieldPath& field, const Method<Object>& method, const std::vector<FieldValue>& values) const { Env env = GetEnv(); size_t size = values.size(); Local<ArrayList> java_values = ArrayList::Create(env, size); for (size_t i = 0; i < size; ++i) { java_values.Add(env, ToJava(values[i])); } Local<Object> java_field = FieldPathConverter::Create(env, field); Local<Object> query = env.Call(obj_, method, java_field, java_values); return firestore_->NewQuery(env, query); } Query QueryInternal::WithBound(const Method<Object>& method, const DocumentSnapshot& snapshot) const { Env env = GetEnv(); Local<Object> query = env.Call(obj_, method, snapshot.internal_->ToJava()); return firestore_->NewQuery(env, query); } Query QueryInternal::WithBound(const Method<Object>& method, const std::vector<FieldValue>& values) const { Env env = GetEnv(); Local<Array<Object>> java_values = ConvertFieldValues(env, values); Local<Object> query = env.Call(obj_, method, java_values); return firestore_->NewQuery(env, query); } ListenerRegistration QueryInternal::AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const QuerySnapshot&, Error, const std::string&)> callback) { auto* listener = new LambdaEventListener<QuerySnapshot>(firebase::Move(callback)); return AddSnapshotListener(metadata_changes, listener, /*passing_listener_ownership=*/true); } ListenerRegistration QueryInternal::AddSnapshotListener( MetadataChanges metadata_changes, EventListener<QuerySnapshot>* listener, bool passing_listener_ownership) { Env env = GetEnv(); Local<Object> java_listener = EventListenerInternal::Create(env, firestore_, listener); Local<Object> java_metadata = MetadataChangesInternal::Create(env, metadata_changes); Local<Object> java_registration = env.Call(obj_, kAddSnapshotListener, firestore_->user_callback_executor(), java_metadata, java_listener); if (!env.ok()) return {}; return ListenerRegistration(new ListenerRegistrationInternal( firestore_, listener, passing_listener_ownership, java_registration)); } Local<Array<Object>> QueryInternal::ConvertFieldValues( Env& env, const std::vector<FieldValue>& field_values) const { size_t size = field_values.size(); Local<Array<Object>> result = env.NewArray(size, Object::GetClass()); for (size_t i = 0; i < size; ++i) { result.Set(env, i, ToJava(field_values[i])); } return result; } bool operator==(const QueryInternal& lhs, const QueryInternal& rhs) { Env env = FirestoreInternal::GetEnv(); return Object::Equals(env, lhs.ToJava(), rhs.ToJava()); } } // namespace firestore } // namespace firebase
37.721408
80
0.709477
tupleapp
84622c95e8307a5de6589799cb15e748a55174a4
285
cpp
C++
test/homework_test/04_iteration_test/04_iteration_tests.cpp
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-PastranoAlejandro
2fd6ec041cb75d176f9be9db8c9a1dcdc0eec2be
[ "MIT" ]
null
null
null
test/homework_test/04_iteration_test/04_iteration_tests.cpp
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-PastranoAlejandro
2fd6ec041cb75d176f9be9db8c9a1dcdc0eec2be
[ "MIT" ]
null
null
null
test/homework_test/04_iteration_test/04_iteration_tests.cpp
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-PastranoAlejandro
2fd6ec041cb75d176f9be9db8c9a1dcdc0eec2be
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include"dna.h" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("TEST GC content function") { REQUIRE(.375== get_gc_content("AGCTATAG")); }
25.909091
97
0.719298
acc-cosc-1337-spring-2022
8464450d998cb432119809f2afa8cd4de0d42a1c
1,823
cc
C++
proxy/plugin_image_data.cc
phisixersai/ppapi
a4d4a5a249d3f369903be3e1fa1a1dfd16de82e0
[ "BSD-3-Clause" ]
1
2015-07-03T13:18:34.000Z
2015-07-03T13:18:34.000Z
proxy/plugin_image_data.cc
rise-worlds/ppapi
a4d4a5a249d3f369903be3e1fa1a1dfd16de82e0
[ "BSD-3-Clause" ]
null
null
null
proxy/plugin_image_data.cc
rise-worlds/ppapi
a4d4a5a249d3f369903be3e1fa1a1dfd16de82e0
[ "BSD-3-Clause" ]
1
2020-01-16T01:46:31.000Z
2020-01-16T01:46:31.000Z
// Copyright (c) 2010 The Native Client 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 "ppapi/proxy/plugin_image_data.h" #include <stdio.h> #include <string.h> #include "native_client/src/include/portability.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "ppapi/c/ppb_image_data.h" #include "ppapi/proxy/generated/ppb_rpc_client.h" #include "ppapi/proxy/plugin_globals.h" #include "ppapi/proxy/utility.h" namespace ppapi_proxy { namespace { PP_ImageDataFormat GetNativeImageDataFormat() { return PP_IMAGEDATAFORMAT_BGRA_PREMUL; } bool IsImageDataFormatSupported(PP_ImageDataFormat format) { return format == PP_IMAGEDATAFORMAT_BGRA_PREMUL; } PP_Resource Create(PP_Module module, PP_ImageDataFormat format, const struct PP_Size* size, bool init_to_zero) { UNREFERENCED_PARAMETER(module); UNREFERENCED_PARAMETER(format); UNREFERENCED_PARAMETER(size); UNREFERENCED_PARAMETER(init_to_zero); return kInvalidResourceId; } bool IsImageData(PP_Resource resource) { UNREFERENCED_PARAMETER(resource); return false; } bool Describe(PP_Resource resource, struct PP_ImageDataDesc* desc) { UNREFERENCED_PARAMETER(resource); UNREFERENCED_PARAMETER(desc); return false; } void* Map(PP_Resource resource) { UNREFERENCED_PARAMETER(resource); return NULL; } void Unmap(PP_Resource resource) { UNREFERENCED_PARAMETER(resource); } } // namespace const PPB_ImageData* PluginImageData::GetInterface() { static const PPB_ImageData intf = { GetNativeImageDataFormat, IsImageDataFormatSupported, Create, IsImageData, Describe, Map, Unmap, }; return &intf; } } // namespace ppapi_proxy
24.306667
73
0.744926
phisixersai
846461a3b1b6ed6078f2f7964939d83171db547d
700
cpp
C++
src/AST_Implementaciones/UnarioPositivo.cpp
AlejandroRM94/Compilador_C_minimo
6c69987749233876c9f7fc0cde9c479f0d3ba531
[ "MIT" ]
null
null
null
src/AST_Implementaciones/UnarioPositivo.cpp
AlejandroRM94/Compilador_C_minimo
6c69987749233876c9f7fc0cde9c479f0d3ba531
[ "MIT" ]
null
null
null
src/AST_Implementaciones/UnarioPositivo.cpp
AlejandroRM94/Compilador_C_minimo
6c69987749233876c9f7fc0cde9c479f0d3ba531
[ "MIT" ]
null
null
null
#include "../AST_Tipos.h" UnarioPositivo::UnarioPositivo( Expresion* exp ) { this->exp = exp; } UnarioPositivo::~UnarioPositivo( ) { delete exp; } TipoDato UnarioPositivo::analizarTipo() { return exp->analizarTipo(); } string UnarioPositivo::toString() { stringstream ss; ss << "<UNARIO_POSITIVO>" << endl; if( exp != nullptr ) { ss << exp->toString( ); } ss << "</UNARIO_POSITIVO>" << endl; return ss.str(); } string UnarioPositivo::generarCodigo(){ stringstream ss; ss << exp->generarCodigo(); return ss.str(); } bool UnarioPositivo::analizarTipoConstante() { return true; } int UnarioPositivo::evaluar() { return exp->evaluar(); }
17.948718
50
0.634286
AlejandroRM94
8465576fa255b2a8124b76511d21b1adabc7f8ab
11,853
cpp
C++
Source/GameplayAbilitiesEditor/Private/SGameplayAttributeWidget.cpp
praisesolek/up-to-date-GAS
5f159cae5ac5b2748fb99670ffce6b507a7fd869
[ "Unlicense" ]
null
null
null
Source/GameplayAbilitiesEditor/Private/SGameplayAttributeWidget.cpp
praisesolek/up-to-date-GAS
5f159cae5ac5b2748fb99670ffce6b507a7fd869
[ "Unlicense" ]
null
null
null
Source/GameplayAbilitiesEditor/Private/SGameplayAttributeWidget.cpp
praisesolek/up-to-date-GAS
5f159cae5ac5b2748fb99670ffce6b507a7fd869
[ "Unlicense" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. #include "SGameplayAttributeWidget.h" #include "UObject/UnrealType.h" #include "Widgets/Layout/SSeparator.h" #include "Widgets/Layout/SBox.h" #include "Widgets/Views/STableViewBase.h" #include "Widgets/Views/STableRow.h" #include "Widgets/Views/SListView.h" #include "Widgets/Input/SComboBox.h" #include "AttributeSet.h" #include "Widgets/Input/SSearchBox.h" #include "UObject/UObjectHash.h" #include "UObject/UObjectIterator.h" #include "AbilitySystemComponent.h" #include "Misc/TextFilter.h" #include "SlateOptMacros.h" #define LOCTEXT_NAMESPACE "K2Node" DECLARE_DELEGATE_OneParam(FOnAttributePicked, FProperty*); BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION struct FAttributeViewerNode { public: FAttributeViewerNode(FProperty* InAttribute, FString InAttributeName) { Attribute = InAttribute; AttributeName = MakeShareable(new FString(InAttributeName)); } /** The displayed name for this node. */ TSharedPtr<FString> AttributeName; FProperty* Attribute; }; /** The item used for visualizing the attribute in the list. */ class SAttributeItem : public SComboRow< TSharedPtr<FAttributeViewerNode> > { public: SLATE_BEGIN_ARGS(SAttributeItem) : _HighlightText() , _TextColor(FLinearColor(1.0f, 1.0f, 1.0f, 1.0f)) {} /** The text this item should highlight, if any. */ SLATE_ARGUMENT(FText, HighlightText) /** The color text this item will use. */ SLATE_ARGUMENT(FSlateColor, TextColor) /** The node this item is associated with. */ SLATE_ARGUMENT(TSharedPtr<FAttributeViewerNode>, AssociatedNode) SLATE_END_ARGS() /** * Construct the widget * * @param InArgs A declaration from which to construct the widget */ void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& InOwnerTableView) { AssociatedNode = InArgs._AssociatedNode; this->ChildSlot [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(0.0f, 3.0f, 6.0f, 3.0f) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text(FText::FromString(*AssociatedNode->AttributeName.Get())) .HighlightText(InArgs._HighlightText) .ColorAndOpacity(this, &SAttributeItem::GetTextColor) .IsEnabled(true) ] ]; TextColor = InArgs._TextColor; STableRow< TSharedPtr<FAttributeViewerNode> >::ConstructInternal( STableRow::FArguments() .ShowSelection(true), InOwnerTableView ); } /** Returns the text color for the item based on if it is selected or not. */ FSlateColor GetTextColor() const { const TSharedPtr< ITypedTableView< TSharedPtr<FAttributeViewerNode> > > OwnerWidget = OwnerTablePtr.Pin(); const TSharedPtr<FAttributeViewerNode>* MyItem = OwnerWidget->Private_ItemFromWidget(this); const bool bIsSelected = OwnerWidget->Private_IsItemSelected(*MyItem); if (bIsSelected) { return FSlateColor::UseForeground(); } return TextColor; } private: /** The text color for this item. */ FSlateColor TextColor; /** The Attribute Viewer Node this item is associated with. */ TSharedPtr< FAttributeViewerNode > AssociatedNode; }; class SAttributeListWidget : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SAttributeListWidget) { } SLATE_ARGUMENT(FString, FilterMetaData) SLATE_ARGUMENT(FOnAttributePicked, OnAttributePickedDelegate) SLATE_END_ARGS() /** * Construct the widget * * @param InArgs A declaration from which to construct the widget */ void Construct(const FArguments& InArgs); virtual ~SAttributeListWidget(); private: typedef TTextFilter< const FProperty& > FAttributeTextFilter; /** Called by Slate when the filter box changes text. */ void OnFilterTextChanged(const FText& InFilterText); /** Creates the row widget when called by Slate when an item appears on the list. */ TSharedRef< ITableRow > OnGenerateRowForAttributeViewer(TSharedPtr<FAttributeViewerNode> Item, const TSharedRef< STableViewBase >& OwnerTable); /** Called by Slate when an item is selected from the tree/list. */ void OnAttributeSelectionChanged(TSharedPtr<FAttributeViewerNode> Item, ESelectInfo::Type SelectInfo); /** Updates the list of items in the dropdown menu */ TSharedPtr<FAttributeViewerNode> UpdatePropertyOptions(); /** Delegate to be called when an attribute is picked from the list */ FOnAttributePicked OnAttributePicked; /** The search box */ TSharedPtr<SSearchBox> SearchBoxPtr; /** Holds the Slate List widget which holds the attributes for the Attribute Viewer. */ TSharedPtr<SListView<TSharedPtr< FAttributeViewerNode > >> AttributeList; /** Array of items that can be selected in the dropdown menu */ TArray<TSharedPtr<FAttributeViewerNode>> PropertyOptions; /** Filters needed for filtering the assets */ TSharedPtr<FAttributeTextFilter> AttributeTextFilter; /** Filter for meta data */ FString FilterMetaData; }; SAttributeListWidget::~SAttributeListWidget() { if (OnAttributePicked.IsBound()) { OnAttributePicked.Unbind(); } } void SAttributeListWidget::Construct(const FArguments& InArgs) { struct Local { static void AttributeToStringArray(const FProperty& Property, OUT TArray< FString >& StringArray) { UClass* Class = Property.GetOwnerClass(); if ((Class->IsChildOf(UAttributeSet::StaticClass()) && !Class->ClassGeneratedBy) || (Class->IsChildOf(UAbilitySystemComponent::StaticClass()) && !Class->ClassGeneratedBy)) { StringArray.Add(FString::Printf(TEXT("%s.%s"), *Class->GetName(), *Property.GetName())); } } }; FilterMetaData = InArgs._FilterMetaData; OnAttributePicked = InArgs._OnAttributePickedDelegate; // Setup text filtering AttributeTextFilter = MakeShareable(new FAttributeTextFilter(FAttributeTextFilter::FItemToStringArray::CreateStatic(&Local::AttributeToStringArray))); UpdatePropertyOptions(); TSharedPtr< SWidget > ClassViewerContent; SAssignNew(ClassViewerContent, SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SAssignNew(SearchBoxPtr, SSearchBox) .HintText(NSLOCTEXT("Abilities", "SearchBoxHint", "Search Attributes")) .OnTextChanged(this, &SAttributeListWidget::OnFilterTextChanged) .DelayChangeNotificationsWhileTyping(true) ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SSeparator) .Visibility(EVisibility::Collapsed) ] + SVerticalBox::Slot() .FillHeight(1.0f) [ SAssignNew(AttributeList, SListView<TSharedPtr< FAttributeViewerNode > >) .Visibility(EVisibility::Visible) .SelectionMode(ESelectionMode::Single) .ListItemsSource(&PropertyOptions) // Generates the actual widget for a tree item .OnGenerateRow(this, &SAttributeListWidget::OnGenerateRowForAttributeViewer) // Find out when the user selects something in the tree .OnSelectionChanged(this, &SAttributeListWidget::OnAttributeSelectionChanged) ]; ChildSlot [ ClassViewerContent.ToSharedRef() ]; } TSharedRef< ITableRow > SAttributeListWidget::OnGenerateRowForAttributeViewer(TSharedPtr<FAttributeViewerNode> Item, const TSharedRef< STableViewBase >& OwnerTable) { TSharedRef< SAttributeItem > ReturnRow = SNew(SAttributeItem, OwnerTable) .HighlightText(SearchBoxPtr->GetText()) .TextColor(FLinearColor(1.0f, 1.0f, 1.0f, 1.f)) .AssociatedNode(Item); return ReturnRow; } TSharedPtr<FAttributeViewerNode> SAttributeListWidget::UpdatePropertyOptions() { PropertyOptions.Empty(); TSharedPtr<FAttributeViewerNode> InitiallySelected = MakeShareable(new FAttributeViewerNode(nullptr, "None")); PropertyOptions.Add(InitiallySelected); // Gather all UAttribute classes for (TObjectIterator<UClass> ClassIt; ClassIt; ++ClassIt) { UClass *Class = *ClassIt; if (Class->IsChildOf(UAttributeSet::StaticClass()) && !Class->ClassGeneratedBy) { // Allow entire classes to be filtered globally if (Class->HasMetaData(TEXT("HideInDetailsView"))) { continue; } for (TFieldIterator<FProperty> PropertyIt(Class, EFieldIteratorFlags::ExcludeSuper); PropertyIt; ++PropertyIt) { FProperty *Property = *PropertyIt; // if we have a search string and this doesn't match, don't show it if (AttributeTextFilter.IsValid() && !AttributeTextFilter->PassesFilter(*Property)) { continue; } // don't show attributes that are filtered by meta data if (!FilterMetaData.IsEmpty() && Property->HasMetaData(*FilterMetaData)) { continue; } // Allow properties to be filtered globally (never show up) if (Property->HasMetaData(TEXT("HideInDetailsView"))) { continue; } TSharedPtr<FAttributeViewerNode> SelectableProperty = MakeShareable(new FAttributeViewerNode(Property, FString::Printf(TEXT("%s.%s"), *Class->GetName(), *Property->GetName()))); PropertyOptions.Add(SelectableProperty); } } // UAbilitySystemComponent can add 'system' attributes if (Class->IsChildOf(UAbilitySystemComponent::StaticClass()) && !Class->ClassGeneratedBy) { for (TFieldIterator<FProperty> PropertyIt(Class, EFieldIteratorFlags::ExcludeSuper); PropertyIt; ++PropertyIt) { FProperty* Property = *PropertyIt; // SystemAttributes have to be explicitly tagged if (Property->HasMetaData(TEXT("SystemGameplayAttribute")) == false) { continue; } // if we have a search string and this doesn't match, don't show it if (AttributeTextFilter.IsValid() && !AttributeTextFilter->PassesFilter(*Property)) { continue; } TSharedPtr<FAttributeViewerNode> SelectableProperty = MakeShareable(new FAttributeViewerNode(Property, FString::Printf(TEXT("%s.%s"), *Class->GetName(), *Property->GetName()))); PropertyOptions.Add(SelectableProperty); } } } return InitiallySelected; } void SAttributeListWidget::OnFilterTextChanged(const FText& InFilterText) { AttributeTextFilter->SetRawFilterText(InFilterText); SearchBoxPtr->SetError(AttributeTextFilter->GetFilterErrorText()); UpdatePropertyOptions(); } void SAttributeListWidget::OnAttributeSelectionChanged(TSharedPtr<FAttributeViewerNode> Item, ESelectInfo::Type SelectInfo) { OnAttributePicked.ExecuteIfBound(Item->Attribute); } void SGameplayAttributeWidget::Construct(const FArguments& InArgs) { FilterMetaData = InArgs._FilterMetaData; OnAttributeChanged = InArgs._OnAttributeChanged; SelectedProperty = InArgs._DefaultProperty; // set up the combo button SAssignNew(ComboButton, SComboButton) .OnGetMenuContent(this, &SGameplayAttributeWidget::GenerateAttributePicker) .ContentPadding(FMargin(2.0f, 2.0f)) .ToolTipText(this, &SGameplayAttributeWidget::GetSelectedValueAsString) .ButtonContent() [ SNew(STextBlock) .Text(this, &SGameplayAttributeWidget::GetSelectedValueAsString) ]; ChildSlot [ ComboButton.ToSharedRef() ]; } void SGameplayAttributeWidget::OnAttributePicked(FProperty* InProperty) { if (OnAttributeChanged.IsBound()) { OnAttributeChanged.Execute(InProperty); } // Update the selected item for displaying SelectedProperty = InProperty; // close the list ComboButton->SetIsOpen(false); } TSharedRef<SWidget> SGameplayAttributeWidget::GenerateAttributePicker() { FOnAttributePicked OnPicked(FOnAttributePicked::CreateRaw(this, &SGameplayAttributeWidget::OnAttributePicked)); return SNew(SBox) .WidthOverride(280) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .MaxHeight(500) [ SNew(SAttributeListWidget) .OnAttributePickedDelegate(OnPicked) .FilterMetaData(FilterMetaData) ] ]; } FText SGameplayAttributeWidget::GetSelectedValueAsString() const { if (SelectedProperty) { UClass* Class = SelectedProperty->GetOwnerClass(); FString PropertyString = FString::Printf(TEXT("%s.%s"), *Class->GetName(), *SelectedProperty->GetName()); return FText::FromString(PropertyString); } return FText::FromString(TEXT("None")); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION #undef LOCTEXT_NAMESPACE
28.699758
181
0.752046
praisesolek
84672bfca11190f51db23a3d2a94dab8189a95c5
5,551
cpp
C++
StarLight/randomgenerator.cpp
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StarLight/randomgenerator.cpp
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
StarLight/randomgenerator.cpp
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // // Copyright 2010 // // This file is part of starlight. // // starlight 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. // // starlight 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 starlight. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////////// // // File and Version Information: // $Rev:: $: revision of last commit // $Author: jwebb $: author of last commit // $Date: 2014/11/07 18:44:19 $: date of last commit // // Description: // // // /////////////////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <cmath> #include "randomgenerator.h" #include "StarGenerator/UTIL/StarRandom.h" using namespace std; //USED IN ROOT under TRANDOM3 // Random number generator class based on // M. Matsumoto and T. Nishimura, // Mersenne Twistor: A 623-diminsionally equidistributed // uniform pseudorandom number generator // ACM Transactions on Modeling and Computer Simulation, // Vol. 8, No. 1, January 1998, pp 3--30. // // For more information see the Mersenne Twistor homepage // http://www.math.keio.ac.jp/~matumoto/emt.html // // Advantage: large period 2**19937-1 // relativly fast // (only two times slower than TRandom, but // two times faster than TRandom2) // Drawback: a relative large internal state of 624 integers // // // Aug.99 ROOT implementation based on CLHEP by P.Malzacher // // the original code contains the following copyright notice: /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Library General Public */ /* License as published by the Free Software Foundation; either */ /* version 2 of the License, or (at your option) any later */ /* version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* See the GNU Library General Public License for more details. */ /* You should have received a copy of the GNU Library General */ /* Public License along with this library; if not, write to the */ /* Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA */ /* 02111-1307 USA */ /* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */ /* When you use this, send an email to: matumoto@math.keio.ac.jp */ /* with an appropriate reference to your work. */ ///////////////////////////////////////////////////////////////////// extern "C" { double rndm_(float a); }; void randomGenerator::SetSeed(unsigned int seed) { #if 0 // Set the random generator sequence // if seed is 0 (default value) a TUUID is generated and used to fill // the first 8 integers of the seed array. // In this case the seed is guaranteed to be unique in space and time. // Use upgraded seeding procedure to fix a known problem when seeding with values // with many zero in the bit pattern (like 2**28). // see http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html _count624 = 624; int i,j; _Mt[0] = seed; j = 1; // use multipliers from Knuth's "Art of Computer Programming" Vol. 2, 3rd Ed. p.106 for(i=j; i<624; i++) { _Mt[i] = (1812433253 * ( _Mt[i-1] ^ ( _Mt[i-1] >> 30)) + i); } #endif } double randomGenerator::Rndom(int) { //return rndm_(1.0f); // Use STARSIM random number generator return StarRandom::Instance().flat(); #if 0 // Machine independent random number generator. // Produces uniformly-distributed floating points in ]0,1] // Method: Mersenne Twistor unsigned int y; const int kM = 397; const int kN = 624; const unsigned int kTemperingMaskB = 0x9d2c5680; const unsigned int kTemperingMaskC = 0xefc60000; const unsigned int kUpperMask = 0x80000000; const unsigned int kLowerMask = 0x7fffffff; const unsigned int kMatrixA = 0x9908b0df; if (_count624 >= kN) { register int i; for (i=0; i < kN-kM; i++) { y = (_Mt[i] & kUpperMask) | (_Mt[i+1] & kLowerMask); _Mt[i] = _Mt[i+kM] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); } for ( ; i < kN-1 ; i++) { y = (_Mt[i] & kUpperMask) | (_Mt[i+1] & kLowerMask); _Mt[i] = _Mt[i+kM-kN] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); } y = (_Mt[kN-1] & kUpperMask) | (_Mt[0] & kLowerMask); _Mt[kN-1] = _Mt[kM-1] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); _count624 = 0; } y = _Mt[_count624++]; y ^= (y >> 11); y ^= ((y << 7 ) & kTemperingMaskB ); y ^= ((y << 15) & kTemperingMaskC ); y ^= (y >> 18); if (y) return ( (double) y * 2.3283064365386963e-10); // * Power(2,-32) return Rndom(); #endif }
34.69375
86
0.593407
klendathu2k
846751cb9ca2a5ad89eade2eb994ba1ad7b6883a
43
cpp
C++
master/core/comp/MyNet/ICombiner.cpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/comp/MyNet/ICombiner.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/comp/MyNet/ICombiner.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
#include "StdAfx.h" #include "icombiner.h"
14.333333
22
0.72093
importlib
846ade2d4f9573c81eada1bbfd5471cf8189755f
2,301
cpp
C++
src/wiztk/net/ip-address/private.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
37
2017-11-22T14:15:33.000Z
2021-11-25T20:39:39.000Z
src/wiztk/net/ip-address/private.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
3
2018-03-01T12:44:22.000Z
2021-01-04T23:14:41.000Z
src/wiztk/net/ip-address/private.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
10
2017-11-25T19:09:11.000Z
2020-12-02T02:05:47.000Z
/* * Copyright 2017 - 2018 The WizTK 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. */ #include "private.hpp" #include <cstring> namespace wiztk { namespace net { IPAddress::Private::Private(const Private &other) { Copy(other); } IPAddress::Private::~Private() { Reset(); } IPAddress::Private &IPAddress::Private::operator=(const Private &other) { Reset(); Copy(other); return *this; } void IPAddress::Private::Reset() { if (nullptr == socket_address) return;; switch (socket_address->sa_family) { case AF_INET: { // IPv4 auto *ipv4_address = reinterpret_cast<struct sockaddr_in *>(socket_address); delete ipv4_address; break; } case AF_INET6: { // IPv6 auto *ipv6_address = reinterpret_cast<struct sockaddr_in6 *>(socket_address); delete ipv6_address; break; } default: { // TODO: check the address type delete socket_address; break; } } socket_address = nullptr; } void IPAddress::Private::Copy(const Private &other) { Reset(); if (nullptr != other.socket_address) { switch (other.socket_address->sa_family) { case AF_INET: { auto *addr = new struct sockaddr_in; memcpy(addr, reinterpret_cast<struct sockaddr_in *>(other.socket_address), sizeof(struct sockaddr_in)); socket_address = reinterpret_cast<struct sockaddr *>(addr); break; } case AF_INET6: { auto *addr = new struct sockaddr_in6; memcpy(addr, reinterpret_cast<struct sockaddr_in6 *>(other.socket_address), sizeof(struct sockaddr_in6)); socket_address = reinterpret_cast<struct sockaddr *>(addr); break; } default:break; } } } } }
25.285714
83
0.653629
wiztk
846cf4e79cac6e37c67c76d33b11c513b8596e67
5,933
cpp
C++
cvs/objects/target_finder/source/emissions_stabalization_target.cpp
cmcormack/gcam-core
ccbe826dbfeb9ed85472977aac6d36dbbf763a23
[ "ECL-2.0" ]
157
2016-10-13T17:44:11.000Z
2022-03-30T09:34:50.000Z
cvs/objects/target_finder/source/emissions_stabalization_target.cpp
cmcormack/gcam-core
ccbe826dbfeb9ed85472977aac6d36dbbf763a23
[ "ECL-2.0" ]
190
2016-10-13T20:19:10.000Z
2022-03-25T19:17:05.000Z
cvs/objects/target_finder/source/emissions_stabalization_target.cpp
cmcormack/gcam-core
ccbe826dbfeb9ed85472977aac6d36dbbf763a23
[ "ECL-2.0" ]
95
2016-10-13T17:44:44.000Z
2022-03-28T02:10:52.000Z
/* * LEGAL NOTICE * This computer software was prepared by Battelle Memorial Institute, * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830 * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this * sentence must appear on any copies of this computer software. * * EXPORT CONTROL * User agrees that the Software will not be shipped, transferred or * exported into any country or used in any manner prohibited by the * United States Export Administration Act or any other applicable * export laws, restrictions or regulations (collectively the "Export Laws"). * Export of the Software may require some form of license or other * authority from the U.S. Government, and failure to obtain such * export control license may result in criminal liability under * U.S. laws. In addition, if the Software is identified as export controlled * items under the Export Laws, User represents and warrants that User * is not a citizen, or otherwise located within, an embargoed nation * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea) * and that User is not otherwise prohibited * under the Export Laws from receiving the Software. * * Copyright 2011 Battelle Memorial Institute. All Rights Reserved. * Distributed as open-source under the terms of the Educational Community * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php * * For further details, see: http://www.globalchange.umd.edu/models/gcam/ * */ /*! * \file emissions_stabalization_target.cpp * \ingroup Objects * \brief EmissionsStabalizationTarget class source file. * \author Josh Lurz */ #include "util/base/include/definitions.h" #include <cassert> #include <string> #include "containers/include/scenario.h" #include "util/base/include/model_time.h" #include "climate/include/iclimate_model.h" #include "target_finder/include/emissions_stabalization_target.h" #include "util/logger/include/ilogger.h" #include "util/base/include/configuration.h" #include "util/base/include/util.h" extern Scenario* scenario; using namespace std; /*! * \brief Constructor * \param aClimateModel The climate model. * \param aTargetValue The value of the target. * \param aFirstTaxYear The first tax year. */ EmissionsStabalizationTarget::EmissionsStabalizationTarget( const IClimateModel* aClimateModel, const double aTargetValue, const int aFirstTaxYear ): mClimateModel( aClimateModel ), mFirstTaxYear( aFirstTaxYear ) { // Store configuration variables. const Configuration* conf = Configuration::getInstance(); // FYI: the target gas read from the configuration appears to be // ignored in the rest of this class. mTargetGas = conf->getString( "concentration-target-gas", "CO2" ); } /*! * \brief Return the static name of the object. * \return The static name of the object. */ const string& EmissionsStabalizationTarget::getXMLNameStatic(){ static const string XML_NAME = "emissions-balance-target"; return XML_NAME; } double EmissionsStabalizationTarget::getStatus( const int aYear ) const { // Determine the total system emissions. NOTE: Net terrestrial uptake // includes land use emissions as a negative, so they are not added here as // that would double account. // NOTE: Assumes that net terrestrial uptake is not removed from industrial // emissions. // Make sure we are using the correct year. const int year = aYear == ITarget::getUseMaxTargetYearFlag() ? getYearOfMaxTargetValue() : aYear; /*! * \pre year must be greater than mFirstTaxYear otherwise we will have no * ability to change the status in that year. */ assert( year >= mFirstTaxYear ); // Note that mClimateModel->getEmissions will not contain values until GCAM // has solved for a given year. double totalEmissions = mClimateModel->getEmissions( "CO2", year ); // Year can be between two years double netOceanUp = mClimateModel->getNetOceanUptake( year ); double netTerrUp = mClimateModel->getNetTerrestrialUptake( year ); double totalNetUptake = netOceanUp + netTerrUp; // Determine how how far away from the target the current estimate is. double percentOff = objects::percentDiff( totalNetUptake, totalEmissions ); // Print an information message. ILogger& targetLog = ILogger::getLogger( "target_finder_log" ); targetLog.setLevel( ILogger::NOTICE ); targetLog << "Currently " << percentOff << " percent away from the stabilization target. " << "Emissions: " << totalEmissions << " Total net uptake: " << totalNetUptake << endl; return percentOff; } int EmissionsStabalizationTarget::getYearOfMaxTargetValue() const { // TODO: I think realistically this is always the last year. double minDiff = numeric_limits<double>::max(); const int finalYearToCheck = scenario->getModeltime()->getEndYear(); int minYear = mFirstTaxYear - 1; // Loop over possible year and find the min difference in emisssions and the // year it occurs in. for( int year = mFirstTaxYear; year <= finalYearToCheck; ++year ) { // Note that mClimateModel->getEmissions will not contain values until GCAM // has solved for a given year. double totalEmissions = mClimateModel->getEmissions( "CO2", year ); double netOceanUp = mClimateModel->getNetOceanUptake( year ); double netTerrUp = mClimateModel->getNetTerrestrialUptake( year ); double totalNetUptake = netOceanUp + netTerrUp; double percentOff = objects::percentDiff( totalNetUptake, totalEmissions ); if( percentOff < minDiff ) { minDiff = percentOff; minYear = year; } } return minYear; }
39.032895
92
0.72476
cmcormack
84757b18f3865bb2beb1229f2e1cc4aabb60142b
1,741
cpp
C++
6_lesson/6b_dynamic/6_dynamic.cpp
JonMuehlst/INTROCPP
5f394c58c66a873bafb11dce54207a1dd580c916
[ "MIT" ]
null
null
null
6_lesson/6b_dynamic/6_dynamic.cpp
JonMuehlst/INTROCPP
5f394c58c66a873bafb11dce54207a1dd580c916
[ "MIT" ]
null
null
null
6_lesson/6b_dynamic/6_dynamic.cpp
JonMuehlst/INTROCPP
5f394c58c66a873bafb11dce54207a1dd580c916
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> using namespace std; int main() { int arrSize; cout << "Please insert size of array: "; cin >> arrSize; //---------------------------------------------------------- // primitive dynamic array //---------------------------------------------------------- int* arr = new int[arrSize]; for (size_t i = 0; i < arrSize; ++i) { arr[i] = i; cout << arr[i] << " "; } cout << endl; delete[] arr; // must clean! otherwise leak of memory //---------------------------------------------------------- //---------------------------------------------------------- // modern dynamic array //---------------------------------------------------------- vector<int> vec(arrSize); for (size_t i = 0; i < vec.size(); ++i) { vec[i] = i; cout << vec[i] << " "; } cout << endl; vec.push_back(300); // can grow, primitives cannot for (auto v : vec) cout << v << " "; cout << endl; //---------------------------------------------------------- //---------------------------------------------------------- // modern dynamic array of arrays //---------------------------------------------------------- vector< vector<int> > vecOfVec = { { 2, 1, 3 }, { 30, 10 } }; for (auto& vec : vecOfVec) { for (auto& v : vec) { cout << v << "\t"; } cout << endl; } vector< vector<int> > vecOfVec2(arrSize, vector<int>(arrSize)); for (size_t i = 0; i < arrSize; ++i) { for (size_t j = 0; j < arrSize; ++j) { vecOfVec2[i][j] = i*j; } } for (auto& vec : vecOfVec2) { for (auto& v : vec) { cout << v << "\t"; } cout << endl; } //---------------------------------------------------------- return 0; }
25.602941
65
0.349799
JonMuehlst
8478479824d9c51296b55d4c0a4e2b83fcfb0e60
2,646
cpp
C++
test/test_audio_read_ogg.cpp
trazfr/alarm
ea511eb0f16945de2005d828f452c76fce9d77e7
[ "MIT" ]
null
null
null
test/test_audio_read_ogg.cpp
trazfr/alarm
ea511eb0f16945de2005d828f452c76fce9d77e7
[ "MIT" ]
null
null
null
test/test_audio_read_ogg.cpp
trazfr/alarm
ea511eb0f16945de2005d828f452c76fce9d77e7
[ "MIT" ]
null
null
null
#include "audio_read_ogg.hpp" #ifndef NO_AUDIO_READ_OGG #include <gtest/gtest.h> #include <fstream> #include <sstream> namespace { constexpr char kFilename[] = "test.ogg"; } // namespace class TestAudioReadOgg : public ::testing::Test { protected: FILEUnique createFile() { FILEUnique result{std::fopen(kFilename, "rb")}; EXPECT_TRUE(result); return result; } void SetUp() override { std::ostringstream str; AudioReadOgg::loadLib(str); ASSERT_TRUE(str.str().empty()); // generate the test file on the fly std::string commandLine = "ffmpeg -y -loglevel quiet -f lavfi -i sine=f=440 -t 1 -c:a libvorbis "; commandLine += kFilename; system(commandLine.c_str()); } void TearDown() override { AudioReadOgg::unloadLib(); unlink(kFilename); } }; TEST_F(TestAudioReadOgg, wrongExtension) { // there is a "fast" check to know if it is an OGG container, no check on extension auto file = createFile(); const auto audioNullOgg = AudioReadOgg::create(file, "weirdEntension"); EXPECT_TRUE(audioNullOgg); EXPECT_FALSE(file); } TEST_F(TestAudioReadOgg, nullFile) { FILEUnique file; const auto audioNullOgg = AudioReadOgg::create(file, "ogg"); EXPECT_FALSE(audioNullOgg); } TEST_F(TestAudioReadOgg, wrongContent) { // replace content std::ofstream{kFilename} << "dummy content"; auto file = createFile(); const auto audioNullOgg = AudioReadOgg::create(file, "ogg"); EXPECT_FALSE(audioNullOgg); EXPECT_TRUE(file); } TEST_F(TestAudioReadOgg, read) { auto file = createFile(); const auto audio = AudioReadOgg::create(file, "ogg"); EXPECT_FALSE(file); ASSERT_TRUE(audio); const int channels = audio->getChannels(); const int rate = audio->getRate(); const uint64_t samples = audio->getSamples(); EXPECT_EQ(1, channels); EXPECT_EQ(44100, rate); EXPECT_EQ(44100, samples); // read the full file #1 std::vector<char> bufferLoop1(channels * samples * 2); const size_t readLoop1 = audio->readBuffer(bufferLoop1.data(), bufferLoop1.size(), true); EXPECT_EQ(bufferLoop1.size(), readLoop1); // read the full file #2 std::vector<char> bufferLoop2(bufferLoop1.size()); const size_t readLoop2 = audio->readBuffer(bufferLoop2.data(), bufferLoop2.size(), true); EXPECT_EQ(bufferLoop2.size(), readLoop2); // the 2 reads should be equal EXPECT_EQ(bufferLoop1, bufferLoop2); std::ostringstream str; str << *audio; EXPECT_FALSE(str.str().empty()); } #endif // NO_AUDIO_READ_OGG
24.054545
106
0.663265
trazfr
8479129f6a7ad90aca9e8e535448d112392193cb
586
cpp
C++
LeetCode/17_14.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
1
2018-01-13T06:01:49.000Z
2018-01-13T06:01:49.000Z
LeetCode/17_14.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
null
null
null
LeetCode/17_14.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
null
null
null
// 设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。 // 示例: // 输入: arr = [1,3,5,7,2,4,6,8], k = 4 // 输出: [1,2,3,4] // 提示: // 0 <= len(arr) <= 100000 // 0 <= k <= min(100000, len(arr)) class Solution { public: vector<int> smallestK(vector<int> &arr, int k) { priority_queue<int> pq; vector<int> result; for (auto ele : arr) { pq.push(ele); if (pq.size() > k) pq.pop(); } while (!pq.empty()) { result.push_back(pq.top()); pq.pop(); } return result; } };
18.903226
50
0.438567
thewangcj
847ed136b883d118b5ad9439954b373117bdcee2
800
cpp
C++
example/count.cpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
2
2015-12-06T05:10:14.000Z
2021-09-05T21:48:27.000Z
example/count.cpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
null
null
null
example/count.cpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
1
2017-06-06T10:50:17.000Z
2017-06-06T10:50:17.000Z
/* @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/assert.hpp> #include <boost/hana/count.hpp> #include <boost/hana/equal.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/tuple.hpp> #include <boost/hana/type.hpp> namespace hana = boost::hana; int main() { constexpr auto ints = hana::tuple_c<int, 1, 2, 3, 2, 2, 4, 2>; BOOST_HANA_CONSTANT_CHECK(hana::count(ints, hana::int_c<2>) == hana::size_c<4>); static_assert(hana::count(ints, 2) == 4, ""); constexpr auto types = hana::tuple_t<int, char, long, short, char, double>; BOOST_HANA_CONSTANT_CHECK(hana::count(types, hana::type_c<char>) == hana::size_c<2>); }
32
89
0.70375
qicosmos
84810a1dbdf42476a57e3814463dac02838f30b1
8,673
cpp
C++
DeviceCode/Targets/Native/PXA271/DeviceCode/pxa271_intc/PXA271__AITC.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
4
2019-01-21T11:47:53.000Z
2020-06-09T02:14:15.000Z
DeviceCode/Targets/Native/PXA271/DeviceCode/pxa271_intc/PXA271__AITC.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
null
null
null
DeviceCode/Targets/Native/PXA271/DeviceCode/pxa271_intc/PXA271__AITC.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
6
2017-11-09T11:48:10.000Z
2020-05-24T09:43:07.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> //////////////////////////////////////////////////////////////////////////////// #undef TRACE_ALWAYS #define TRACE_ALWAYS 0x00000001 #undef DEBUG_TRACE #define DEBUG_TRACE (TRACE_ALWAYS) //////////////////////////////////////////////////////////////////////////////// #if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED) #pragma arm section rwdata = "s_IsrTable_PXA271" #endif #define DEFINE_IRQ(index, priority) { priority, { NULL, (void*)(size_t)index } } PXA271_AITC_Driver::IRQ_VECTORING __section(rwdata) PXA271_AITC_Driver::s_IsrTable[] = { DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_SSP_3 ,PXA271_AITC::c_IRQ_Priority_18 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_MSL ,PXA271_AITC::c_IRQ_Priority_19 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_USB_HOST_2 ,PXA271_AITC::c_IRQ_Priority_20 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_USB_HOST_1 ,PXA271_AITC::c_IRQ_Priority_21 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_KEYPAD_CTRL ,PXA271_AITC::c_IRQ_Priority_22 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_MEMORY_STICK ,PXA271_AITC::c_IRQ_Priority_23 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_PWR_I2C ,PXA271_AITC::c_IRQ_Priority_24 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_OS_TIMER ,PXA271_AITC::c_IRQ_Priority_13 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_GPIO0 ,PXA271_AITC::c_IRQ_Priority_14 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_GPIO1 ,PXA271_AITC::c_IRQ_Priority_15 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_GPIOx ,PXA271_AITC::c_IRQ_Priority_16 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_USB_CLIENT ,PXA271_AITC::c_IRQ_Priority_17 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_PMU ,PXA271_AITC::c_IRQ_Priority_25 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_I2S ,PXA271_AITC::c_IRQ_Priority_26 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_AC97 ,PXA271_AITC::c_IRQ_Priority_27 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_USIM ,PXA271_AITC::c_IRQ_Priority_28 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_SSP_2 ,PXA271_AITC::c_IRQ_Priority_12 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_LCD ,PXA271_AITC::c_IRQ_Priority_11 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_I2C ,PXA271_AITC::c_IRQ_Priority_10 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_INFRA_RED_COM ,PXA271_AITC::c_IRQ_Priority_29 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_STUART ,PXA271_AITC::c_IRQ_Priority_7 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_BTUART ,PXA271_AITC::c_IRQ_Priority_8 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_FFUART ,PXA271_AITC::c_IRQ_Priority_9 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_FLASH_CARD ,PXA271_AITC::c_IRQ_Priority_30 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_SSP_1 ,PXA271_AITC::c_IRQ_Priority_6 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_DMA_CTRL ,PXA271_AITC::c_IRQ_Priority_5 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_OS_TIMER0 ,PXA271_AITC::c_IRQ_Priority_0 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_OS_TIMER1 ,PXA271_AITC::c_IRQ_Priority_1 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_OS_TIMER2 ,PXA271_AITC::c_IRQ_Priority_2 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_OS_TIMER3 ,PXA271_AITC::c_IRQ_Priority_3 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_RTC_1HZ_TIC ,PXA271_AITC::c_IRQ_Priority_31 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_RTC_ALARM ,PXA271_AITC::c_IRQ_Priority_4 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_TRUSTED_PLFM ,PXA271_AITC::c_IRQ_Priority_32 ), DEFINE_IRQ( PXA271_AITC::c_IRQ_INDEX_QK_CAP ,PXA271_AITC::c_IRQ_Priority_33 ), DEFINE_IRQ( PXA271_AITC_Driver::c_VECTORING_GUARD ,PXA271_AITC::c_IRQ_Priority_34 ), }; #undef DEFINE_IRQ #if defined(ADS_LINKER_BUG__NOT_ALL_UNUSED_VARIABLES_ARE_REMOVED) #pragma arm section rwdata #endif //////////////////////////////////////////////////////////////////////////////// void PXA271_AITC_Driver::Initialize() { PXA271_AITC& AITC = PXA271::AITC(); // disable all interrupts AITC.ICMR = 0; AITC.ICMR2 = 0; // Only active interrupt will trigger the IRQ on idle AITC.ICCR = AITC.ICCR__DIM_OTHER; // set all priorities to the lowest IRQ_VECTORING* IsrVector = s_IsrTable; // set the priority level for each IRQ and stub the IRQ callback for (int i=0; i<c_VECTORING_GUARD;i++) { AITC.SetPriority(i, IsrVector[i].Priority ); IsrVector->Handler.Initialize( STUB_ISRVector, (void*)(size_t)IsrVector->Priority); } } BOOL PXA271_AITC_Driver::ActivateInterrupt( UINT32 Irq_Index, BOOL Fast, HAL_CALLBACK_FPN ISR, void* ISR_Param) { // figure out the interrupt IRQ_VECTORING* IsrVector = IRQToIRQVector( Irq_Index ); if(!IsrVector) return FALSE; { GLOBAL_LOCK(irq); PXA271_AITC& AITC = PXA271::AITC(); // disable this interrupt while we change it AITC.DisableInterrupt(Irq_Index); // set the correct type AITC.SetType( Irq_Index, Fast ); // set the vector IsrVector->Handler.Initialize( ISR, ISR_Param ); // enable the interrupt if we have a vector AITC.EnableInterrupt(Irq_Index); } return TRUE; } BOOL PXA271_AITC_Driver::DeactivateInterrupt( UINT32 Irq_Index ) { // figure out the interrupt IRQ_VECTORING* IsrVector = IRQToIRQVector( Irq_Index ); if(!IsrVector) return FALSE; { GLOBAL_LOCK(irq); PXA271_AITC& AITC = PXA271::AITC(); // disable this interrupt while we change it AITC.DisableInterrupt(Irq_Index); // as it is stub, just put the Priority to the ISR parameter IsrVector->Handler.Initialize( STUB_ISRVector, (void*)(size_t)IsrVector->Priority ); } return TRUE; } void __irq IRQ_Handler() { UINT32 index; PXA271_AITC& AITC = PXA271::AITC(); // set before jumping elsewhere or allowing other interrupts SystemState_SetNoLock( SYSTEM_STATE_ISR ); SystemState_SetNoLock( SYSTEM_STATE_NO_CONTINUATIONS ); while((index = AITC.NormalInterruptPending()) != AITC.c_MaxInterruptIndex) { PXA271_AITC_Driver::IRQ_VECTORING* IsrVector = &PXA271_AITC_Driver::s_IsrTable[ index ]; // In case the interrupt was forced, remove the flag. AITC.RemoveForcedInterrupt( index ); IsrVector->Handler.Execute(); } SystemState_ClearNoLock( SYSTEM_STATE_NO_CONTINUATIONS ); // nestable SystemState_ClearNoLock( SYSTEM_STATE_ISR ); // nestable } BOOL PXA271_AITC_Driver::InterruptEnable( UINT32 Irq_Index ) { if(Irq_Index >= c_VECTORING_GUARD ) return FALSE; PXA271_AITC& AITC = PXA271::AITC(); GLOBAL_LOCK(irq); BOOL WasEnabled = AITC.IsInterruptEnabled( Irq_Index ); AITC.EnableInterrupt(Irq_Index); return WasEnabled; } BOOL PXA271_AITC_Driver::InterruptDisable( UINT32 Irq_Index ) { if(Irq_Index >= c_VECTORING_GUARD ) return FALSE; PXA271_AITC& AITC = PXA271::AITC(); GLOBAL_LOCK(irq); BOOL WasEnabled = AITC.IsInterruptEnabled( Irq_Index ); AITC.DisableInterrupt(Irq_Index); return WasEnabled; } BOOL PXA271_AITC_Driver::InterruptEnableState( UINT32 Irq_Index ) { PXA271_AITC& AITC = PXA271::AITC(); return AITC.IsInterruptEnabled( Irq_Index ); } BOOL PXA271_AITC_Driver::InterruptState( UINT32 Irq_Index ) { PXA271_AITC& AITC = PXA271::AITC(); return AITC.GetInterruptState( Irq_Index ); } PXA271_AITC_Driver::IRQ_VECTORING* PXA271_AITC_Driver::IRQToIRQVector( UINT32 IRQ ) { IRQ_VECTORING* IsrVector = s_IsrTable; if (IRQ < c_VECTORING_GUARD) { return &IsrVector[IRQ]; } return NULL; } void PXA271_AITC_Driver::STUB_ISRVector( void* Param ) { lcd_printf( "\fSTUB_ISR %08x\r\n", (size_t)Param ); HARD_BREAKPOINT(); }
36.594937
201
0.638072
valoni
84819f7219e9a9f284213138f112e2c2c6481714
4,285
cpp
C++
lightclient/src/CommitteeSet.cpp
ultrain-os/ultrain-core-production
5d26bbe51033db183d3c069a30d87bcbe9cf736e
[ "MIT" ]
38
2019-08-15T08:38:15.000Z
2022-01-14T07:31:51.000Z
lightclient/src/CommitteeSet.cpp
sighttviewliu/ultrain-core-production
c2807d9310da8b5dc1408502866be59299a96c22
[ "MIT" ]
4
2019-08-19T13:07:10.000Z
2020-10-17T02:45:04.000Z
lightclient/src/CommitteeSet.cpp
sighttviewliu/ultrain-core-production
c2807d9310da8b5dc1408502866be59299a96c22
[ "MIT" ]
7
2019-08-15T11:11:09.000Z
2022-01-14T08:11:46.000Z
#include <lightclient/CommitteeSet.h> namespace ultrainio { CommitteeSet::CommitteeSet() {} CommitteeSet::CommitteeSet(const std::string& s) { init(s); } CommitteeSet::CommitteeSet(const std::vector<char>& vc) { init(std::string(vc.begin(), vc.end())); } void CommitteeSet::init(const std::string& s) { CommitteeInfo committeeInfo; size_t start = 0; size_t next = 0; while(committeeInfo.fromStrStream(s, start, next)) { m_committeeInfoV.push_back(committeeInfo); if (next == std::string::npos) { return; } start = next; } } CommitteeSet::CommitteeSet(const std::vector<CommitteeInfo>& committeeInfoV) : m_committeeInfoV(committeeInfoV) {} CommitteeSet::CommitteeSet(const std::vector<chain::role_base>& roleBaseVector) { for (auto e : roleBaseVector) { CommitteeInfo info; info.accountName = std::string(e.owner); info.blsPk = e.bls_key; info.pk = e.producer_key; m_committeeInfoV.push_back(info); } } bool CommitteeSet::verify(const BlsVoterSet& blsVoterSet) const { if (blsVoterSet.accountPool.size() < nextRoundThreshold()) { ilog("bls account pool less next round thresh : ${thresh}", ("thresh", nextRoundThreshold())); return false; } std::vector<std::string> blsPkV = getBlsPk(blsVoterSet.accountPool); return blsVoterSet.verifyBls(blsPkV); } std::vector<std::string> CommitteeSet::getBlsPk(const std::vector<AccountName>& accountV) const { std::vector<std::string> pkV; for (auto v : accountV) { for (auto info : m_committeeInfoV) { if (std::string(v) == info.accountName) { pkV.push_back(info.blsPk); break; } } } return pkV; } SHA256 CommitteeSet::committeeMroot() const { // MUST BE the same with StakeOverBase return SHA256::hash(toString()); } std::vector<char> CommitteeSet::toVectorChar() const { std::string res = toString(); std::vector<char> vc(res.size()); vc.assign(res.begin(), res.end()); return vc; } std::string CommitteeSet::toString() const { std::string s; for (int i = 0; i < m_committeeInfoV.size(); i++) { m_committeeInfoV[i].toStrStream(s); if (i != m_committeeInfoV.size() -1) { s.append(CommitteeInfo::kDelimiters); } } return s; } bool CommitteeSet::operator == (const CommitteeSet& rhs) const { if (this == &rhs) { return true; } return m_committeeInfoV == rhs.m_committeeInfoV; } bool CommitteeSet::operator != (const CommitteeSet& rhs) const { return !(*this == rhs); } CommitteeDelta CommitteeSet::diff(const CommitteeSet& pre) const { std::list<CommitteeInfo> addCommitteeInfo; std::list<CommitteeInfo> removedCommitteeInfo; for (auto itor = m_committeeInfoV.begin(); itor != m_committeeInfoV.end(); itor++) { addCommitteeInfo.push_front(*itor); } for (auto itor = pre.m_committeeInfoV.begin(); itor != pre.m_committeeInfoV.end(); itor++) { addCommitteeInfo.remove(*itor); removedCommitteeInfo.push_front(*itor); } for (auto itor = m_committeeInfoV.begin(); itor != m_committeeInfoV.end(); itor++) { removedCommitteeInfo.remove(*itor); } return CommitteeDelta(addCommitteeInfo, removedCommitteeInfo); } int CommitteeSet::nextRoundThreshold() const { // detail see StakeVoteRandom.cpp realGetNextRoundThreshold int kDesiredVoterNumber = 100; // sync with consensus config.h double kNextRoundThresholdRatio = 0.67; // sync with consensus config.h int voterSize = m_committeeInfoV.size() > kDesiredVoterNumber ? kDesiredVoterNumber : m_committeeInfoV.size(); return kNextRoundThresholdRatio * voterSize + 1; } bool CommitteeSet::empty() const { return m_committeeInfoV.empty(); } }
34.28
118
0.596033
ultrain-os
8483d6ad77c96e53f0d664a8ee40ebe74dda5fcc
1,525
cpp
C++
data_structures/stack_using_array.cpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
20,295
2016-07-17T06:29:04.000Z
2022-03-31T23:32:16.000Z
data_structures/stack_using_array.cpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
1,399
2017-06-02T05:59:45.000Z
2022-03-31T00:55:00.000Z
data_structures/stack_using_array.cpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
5,775
2016-10-14T08:10:18.000Z
2022-03-31T18:26:39.000Z
#include <iostream> int *stack; int stack_idx = 0, stack_size; void push(int x) { if (stack_idx == stack_size) { std::cout << "\nOverflow"; } else { stack[stack_idx++] = x; } } void pop() { if (stack_idx == 0) { std::cout << "\nUnderflow"; } else { std::cout << "\n" << stack[--stack_idx] << " deleted"; } } void show() { for (int i = 0; i < stack_idx; i++) { std::cout << stack[i] << "\n"; } } void topmost() { std::cout << "\nTopmost element: " << stack[stack_idx - 1]; } void bottom() { std::cout << "\nBottom element: " << stack[0]; } // If we need access to first element without using pop command int main() { std::cout << "\nEnter stack_size of stack : "; std::cin >> stack_size; stack = new int[stack_size]; int ch, x; do { std::cout << "\n0. Exit"; std::cout << "\n1. Push"; std::cout << "\n2. Pop"; std::cout << "\n3. Print"; std::cout << "\n4. Print topmost element:"; std::cout << "\n5. Print Bottom element:"; std::cout << "\nEnter Your Choice : "; std::cin >> ch; if (ch == 1) { std::cout << "\nInsert : "; std::cin >> x; push(x); } else if (ch == 2) { pop(); } else if (ch == 3) { show(); } else if (ch == 4) { topmost(); } else if(ch == 5) { bottom(); } } while (ch != 0); delete[] stack; return 0; }
24.206349
129
0.45377
icbdubey
849259e892e9de9aab62504007adccc9d41f8442
5,666
cpp
C++
RLTiles_CPP/RLTiles/RLTileMapRenderer.cpp
Julianiolo/raylibExtras
ce344ee4ee24a283e211467f32d6a2ff506dae4d
[ "Zlib" ]
69
2020-12-31T03:21:58.000Z
2022-03-07T20:11:18.000Z
RLTiles_CPP/RLTiles/RLTileMapRenderer.cpp
Julianiolo/raylibExtras
ce344ee4ee24a283e211467f32d6a2ff506dae4d
[ "Zlib" ]
7
2021-01-01T23:36:48.000Z
2021-07-04T11:17:40.000Z
RLTiles_CPP/RLTiles/RLTileMapRenderer.cpp
Julianiolo/raylibExtras
ce344ee4ee24a283e211467f32d6a2ff506dae4d
[ "Zlib" ]
41
2021-01-16T20:49:33.000Z
2022-01-07T23:53:21.000Z
/********************************************************************************************** * * raylibExtras * Utilities and Shared Components for Raylib * * RLTiles * Tiled map rendering * * LICENSE: MIT * * Copyright (c) 2020 Jeffery Myers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************/ #include "RLTileMapRenderer.h" Vector2 GetDisplayLocation(int x, int y, int TileWidth, int TileHeight, RLTiledMapTypes mapType) { if (mapType == RLTiledMapTypes::Orthographic) return Vector2{ static_cast<float>(x * TileWidth), static_cast<float>(y * TileHeight) }; float halfWidth = TileWidth * 0.5f; float halfHeight = TileHeight * 0.5f; float quarterHeight = TileHeight * 0.25f; return Vector2{ x * halfWidth - y * halfWidth - halfWidth, y * halfHeight + (x * halfHeight) }; } void RLTileRenderer::Setup() { TextureCache.clear(); for (std::map<int, RLTileSheet>::iterator sheet = TileMap.Sheets.begin(); sheet != TileMap.Sheets.end(); sheet++) { int start = sheet->second.StartFrame; int end = ((int)sheet->second.Tiles.size() - 1) + start; TextureCache[std::pair<int,int>(start,end)] = std::pair<Texture, RLTileSheet*>(LoadTexture(sheet->second.SheetSource.c_str()), (&sheet->second)); } RenderLayers.clear(); for (auto layer : TileMap.Layers) { RenderLayers.emplace(layer.first, RLTileRenderLayer()); RLTileRenderLayer& renderLayer = RenderLayers[layer.first]; renderLayer.TileSize.x = layer.second.TileWidth; renderLayer.TileSize.y = layer.second.TileHeight; for (int y = 0; y < layer.second.Height; ++y) { for (int x = 0; x < layer.second.Width; ++x) { RLTile tile = TileMap.GetTile(x, y, layer.first); auto itr = std::find_if(TextureCache.begin(), TextureCache.end(), [tile](const auto tx) { return (tile.TileID >= tx.first.first && tile.TileID <= tx.first.second); }); RLRenderTile tileInfo; if (itr != TextureCache.end()) { tileInfo.SourceTexture = &(itr->second.first); tileInfo.SourceRect = itr->second.second->GetFrame(tile.TileID); if (tileInfo.SourceRect.width == 0 || tileInfo.SourceRect.height == 0) tileInfo.SourceRect = Rectangle{ 0,0, (float)tileInfo.SourceTexture->width, (float)tileInfo.SourceTexture->height }; if (tile.FlipDiag) tileInfo.Rotate = true; if (tile.FlipX) tileInfo.SourceRect.width *= -1; if (tile.FilpY) tileInfo.SourceRect.height *= -1; tileInfo.DestinationPos = GetDisplayLocation(x, y, layer.second.TileWidth, layer.second.TileHeight, TileMap.MapType); } renderLayer.RenderTiles.emplace_back(tileInfo); } } } } bool RLTileRenderer::TileInView(RLRenderTile& tile) { if (tile.DestinationPos.x + tile.SourceRect.width < CurrentViewRect.x) return false; if (tile.DestinationPos.y + tile.SourceRect.height < CurrentViewRect.y) return false; if (tile.DestinationPos.x > CurrentViewRect.x + CurrentViewRect.width) return false; if (tile.DestinationPos.y > CurrentViewRect.y + CurrentViewRect.height) return false; return true; } void RLTileRenderer::Draw(Camera2D& camera) { CurrentViewRect.x = camera.target.x - (camera.offset.x / camera.zoom); CurrentViewRect.y = camera.target.y - (camera.offset.y / camera.zoom); CurrentViewRect.width = GetScreenWidth() / camera.zoom; CurrentViewRect.height = GetScreenHeight() / camera.zoom; for (auto layer : RenderLayers) { for (auto& tile : layer.second.RenderTiles) { if (tile.SourceTexture != nullptr && TileInView(tile)) { Vector2 origin = { layer.second.TileSize.x * 0.5f, layer.second.TileSize.y * 0.5f }; Rectangle dest = { tile.DestinationPos.x + origin.x,tile.DestinationPos.y + origin.y, layer.second.TileSize.x, layer.second.TileSize.y }; DrawTexturePro(*tile.SourceTexture, tile.SourceRect, dest, origin, tile.Rotate ? 90 : 0, WHITE); // Draw a part of a texture defined by a rectangle with 'pro' parameters } } } }
40.184397
191
0.611013
Julianiolo
8496b63d67ae320df8050d902ab3c21c5968b008
13,276
hpp
C++
include/GlobalNamespace/AvatarPoseRestrictions.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/AvatarPoseRestrictions.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/AvatarPoseRestrictions.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: AvatarPoseController class AvatarPoseController; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: Quaternion because it is already included! } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x50 #pragma pack(push, 1) // Autogenerated type: AvatarPoseRestrictions // [TokenAttribute] Offset: FFFFFFFF class AvatarPoseRestrictions : public UnityEngine::MonoBehaviour { public: // private System.Single _maxHeadSquareDistanceFromCenter // Size: 0x4 // Offset: 0x18 float maxHeadSquareDistanceFromCenter; // Field size check static_assert(sizeof(float) == 0x4); // private System.Single _minHeadYPos // Size: 0x4 // Offset: 0x1C float minHeadYPos; // Field size check static_assert(sizeof(float) == 0x4); // private System.Single _maxHeadYPos // Size: 0x4 // Offset: 0x20 float maxHeadYPos; // Field size check static_assert(sizeof(float) == 0x4); // [FormerlySerializedAsAttribute] Offset: 0xEAC36C // private System.Single _minHandXZSquareDistanceFromHeadCenter // Size: 0x4 // Offset: 0x24 float minHandXZSquareDistanceFromHeadCenter; // Field size check static_assert(sizeof(float) == 0x4); // [FormerlySerializedAsAttribute] Offset: 0xEAC3B8 // private System.Single _maxHandXZSquareDistanceFromHeadCenter // Size: 0x4 // Offset: 0x28 float maxHandXZSquareDistanceFromHeadCenter; // Field size check static_assert(sizeof(float) == 0x4); // private System.Single _minHandYDistanceFromHeadCenter // Size: 0x4 // Offset: 0x2C float minHandYDistanceFromHeadCenter; // Field size check static_assert(sizeof(float) == 0x4); // private System.Single _maxHandYDistanceFromHeadCenter // Size: 0x4 // Offset: 0x30 float maxHandYDistanceFromHeadCenter; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _forceHeadPosition // Size: 0x1 // Offset: 0x34 bool forceHeadPosition; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: forceHeadPosition and: centerHeadOffset char __padding7[0x3] = {}; // private UnityEngine.Vector3 _centerHeadOffset // Size: 0xC // Offset: 0x38 UnityEngine::Vector3 centerHeadOffset; // Field size check static_assert(sizeof(UnityEngine::Vector3) == 0xC); // Padding between fields: centerHeadOffset and: avatarPoseController char __padding8[0x4] = {}; // [InjectAttribute] Offset: 0xEAC444 // private readonly AvatarPoseController _avatarPoseController // Size: 0x8 // Offset: 0x48 GlobalNamespace::AvatarPoseController* avatarPoseController; // Field size check static_assert(sizeof(GlobalNamespace::AvatarPoseController*) == 0x8); // Creating value type constructor for type: AvatarPoseRestrictions AvatarPoseRestrictions(float maxHeadSquareDistanceFromCenter_ = {}, float minHeadYPos_ = {}, float maxHeadYPos_ = {}, float minHandXZSquareDistanceFromHeadCenter_ = {}, float maxHandXZSquareDistanceFromHeadCenter_ = {}, float minHandYDistanceFromHeadCenter_ = {}, float maxHandYDistanceFromHeadCenter_ = {}, bool forceHeadPosition_ = {}, UnityEngine::Vector3 centerHeadOffset_ = {}, GlobalNamespace::AvatarPoseController* avatarPoseController_ = {}) noexcept : maxHeadSquareDistanceFromCenter{maxHeadSquareDistanceFromCenter_}, minHeadYPos{minHeadYPos_}, maxHeadYPos{maxHeadYPos_}, minHandXZSquareDistanceFromHeadCenter{minHandXZSquareDistanceFromHeadCenter_}, maxHandXZSquareDistanceFromHeadCenter{maxHandXZSquareDistanceFromHeadCenter_}, minHandYDistanceFromHeadCenter{minHandYDistanceFromHeadCenter_}, maxHandYDistanceFromHeadCenter{maxHandYDistanceFromHeadCenter_}, forceHeadPosition{forceHeadPosition_}, centerHeadOffset{centerHeadOffset_}, avatarPoseController{avatarPoseController_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // Get instance field: private System.Single _maxHeadSquareDistanceFromCenter float _get__maxHeadSquareDistanceFromCenter(); // Set instance field: private System.Single _maxHeadSquareDistanceFromCenter void _set__maxHeadSquareDistanceFromCenter(float value); // Get instance field: private System.Single _minHeadYPos float _get__minHeadYPos(); // Set instance field: private System.Single _minHeadYPos void _set__minHeadYPos(float value); // Get instance field: private System.Single _maxHeadYPos float _get__maxHeadYPos(); // Set instance field: private System.Single _maxHeadYPos void _set__maxHeadYPos(float value); // Get instance field: private System.Single _minHandXZSquareDistanceFromHeadCenter float _get__minHandXZSquareDistanceFromHeadCenter(); // Set instance field: private System.Single _minHandXZSquareDistanceFromHeadCenter void _set__minHandXZSquareDistanceFromHeadCenter(float value); // Get instance field: private System.Single _maxHandXZSquareDistanceFromHeadCenter float _get__maxHandXZSquareDistanceFromHeadCenter(); // Set instance field: private System.Single _maxHandXZSquareDistanceFromHeadCenter void _set__maxHandXZSquareDistanceFromHeadCenter(float value); // Get instance field: private System.Single _minHandYDistanceFromHeadCenter float _get__minHandYDistanceFromHeadCenter(); // Set instance field: private System.Single _minHandYDistanceFromHeadCenter void _set__minHandYDistanceFromHeadCenter(float value); // Get instance field: private System.Single _maxHandYDistanceFromHeadCenter float _get__maxHandYDistanceFromHeadCenter(); // Set instance field: private System.Single _maxHandYDistanceFromHeadCenter void _set__maxHandYDistanceFromHeadCenter(float value); // Get instance field: private System.Boolean _forceHeadPosition bool _get__forceHeadPosition(); // Set instance field: private System.Boolean _forceHeadPosition void _set__forceHeadPosition(bool value); // Get instance field: private UnityEngine.Vector3 _centerHeadOffset UnityEngine::Vector3 _get__centerHeadOffset(); // Set instance field: private UnityEngine.Vector3 _centerHeadOffset void _set__centerHeadOffset(UnityEngine::Vector3 value); // Get instance field: private readonly AvatarPoseController _avatarPoseController GlobalNamespace::AvatarPoseController* _get__avatarPoseController(); // Set instance field: private readonly AvatarPoseController _avatarPoseController void _set__avatarPoseController(GlobalNamespace::AvatarPoseController* value); // protected System.Void Start() // Offset: 0x1F31DA8 void Start(); // private System.Void HandleAvatarPoseControllerPositionsWillBeSet(UnityEngine.Quaternion headRotation, UnityEngine.Vector3 headPosition, UnityEngine.Vector3 leftHandPosition, UnityEngine.Vector3 rightHandPosition, out UnityEngine.Vector3 newHeadPosition, out UnityEngine.Vector3 newLeftHandPosition, out UnityEngine.Vector3 newRightHandPosition) // Offset: 0x1F31E20 void HandleAvatarPoseControllerPositionsWillBeSet(UnityEngine::Quaternion headRotation, UnityEngine::Vector3 headPosition, UnityEngine::Vector3 leftHandPosition, UnityEngine::Vector3 rightHandPosition, ByRef<UnityEngine::Vector3> newHeadPosition, ByRef<UnityEngine::Vector3> newLeftHandPosition, ByRef<UnityEngine::Vector3> newRightHandPosition); // private UnityEngine.Vector3 LimitHandPositionRelativeToHead(UnityEngine.Vector3 handPosition, UnityEngine.Vector3 headCenter) // Offset: 0x1F321D8 UnityEngine::Vector3 LimitHandPositionRelativeToHead(UnityEngine::Vector3 handPosition, UnityEngine::Vector3 headCenter); // public System.Void .ctor() // Offset: 0x1F32424 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static AvatarPoseRestrictions* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::AvatarPoseRestrictions::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<AvatarPoseRestrictions*, creationType>())); } }; // AvatarPoseRestrictions #pragma pack(pop) static check_size<sizeof(AvatarPoseRestrictions), 72 + sizeof(GlobalNamespace::AvatarPoseController*)> __GlobalNamespace_AvatarPoseRestrictionsSizeCheck; static_assert(sizeof(AvatarPoseRestrictions) == 0x50); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::AvatarPoseRestrictions*, "", "AvatarPoseRestrictions"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::AvatarPoseRestrictions::Start // Il2CppName: Start template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AvatarPoseRestrictions::*)()>(&GlobalNamespace::AvatarPoseRestrictions::Start)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AvatarPoseRestrictions*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::AvatarPoseRestrictions::HandleAvatarPoseControllerPositionsWillBeSet // Il2CppName: HandleAvatarPoseControllerPositionsWillBeSet template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AvatarPoseRestrictions::*)(UnityEngine::Quaternion, UnityEngine::Vector3, UnityEngine::Vector3, UnityEngine::Vector3, ByRef<UnityEngine::Vector3>, ByRef<UnityEngine::Vector3>, ByRef<UnityEngine::Vector3>)>(&GlobalNamespace::AvatarPoseRestrictions::HandleAvatarPoseControllerPositionsWillBeSet)> { static const MethodInfo* get() { static auto* headRotation = &::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")->byval_arg; static auto* headPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; static auto* leftHandPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; static auto* rightHandPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; static auto* newHeadPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->this_arg; static auto* newLeftHandPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->this_arg; static auto* newRightHandPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AvatarPoseRestrictions*), "HandleAvatarPoseControllerPositionsWillBeSet", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{headRotation, headPosition, leftHandPosition, rightHandPosition, newHeadPosition, newLeftHandPosition, newRightHandPosition}); } }; // Writing MetadataGetter for method: GlobalNamespace::AvatarPoseRestrictions::LimitHandPositionRelativeToHead // Il2CppName: LimitHandPositionRelativeToHead template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector3 (GlobalNamespace::AvatarPoseRestrictions::*)(UnityEngine::Vector3, UnityEngine::Vector3)>(&GlobalNamespace::AvatarPoseRestrictions::LimitHandPositionRelativeToHead)> { static const MethodInfo* get() { static auto* handPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; static auto* headCenter = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AvatarPoseRestrictions*), "LimitHandPositionRelativeToHead", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{handPosition, headCenter}); } }; // Writing MetadataGetter for method: GlobalNamespace::AvatarPoseRestrictions::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
62.919431
997
0.766195
marksteward
8496ef3fbdfa8c1c60545d74e023cd37ed7997d9
104
cpp
C++
example-undistortion/src/main.cpp
danoli3/ofxCv
ac235abd6b0674d61a110ec21bbf9a87f927c9d9
[ "MIT" ]
34
2015-04-16T03:27:10.000Z
2021-12-29T07:24:33.000Z
Week12/example-background-contours/src/main.cpp
bakercp/ExperimentalMedia2013
b0e748104c327d14e2231a0a98282503712702ed
[ "MIT" ]
12
2015-04-02T13:54:51.000Z
2021-05-28T02:47:47.000Z
Week12/example-background-contours/src/main.cpp
bakercp/ExperimentalMedia2013
b0e748104c327d14e2231a0a98282503712702ed
[ "MIT" ]
14
2015-02-05T00:04:15.000Z
2020-06-04T13:56:37.000Z
#include "testApp.h" int main() { ofSetupOpenGL(640 * 2, 480, OF_WINDOW); ofRunApp(new testApp()); }
14.857143
40
0.663462
danoli3
8498ff62b9921dc08aa6297d807281abe45c247f
2,834
cpp
C++
src/org/apache/poi/ss/format/CellFormatter.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/format/CellFormatter.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/format/CellFormatter.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/format/CellFormatter.java #include <org/apache/poi/ss/format/CellFormatter.hpp> #include <java/lang/Class.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <java/lang/StringBuilder.hpp> #include <java/util/Locale.hpp> #include <java/util/logging/Logger.hpp> #include <org/apache/poi/util/LocaleUtil.hpp> template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::format::CellFormatter::CellFormatter(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::format::CellFormatter::CellFormatter(::java::lang::String* format) : CellFormatter(*static_cast< ::default_init_tag* >(0)) { ctor(format); } poi::ss::format::CellFormatter::CellFormatter(::java::util::Locale* locale, ::java::lang::String* format) : CellFormatter(*static_cast< ::default_init_tag* >(0)) { ctor(locale,format); } void poi::ss::format::CellFormatter::ctor(::java::lang::String* format) { ctor(::poi::util::LocaleUtil::getUserLocale(), format); } void poi::ss::format::CellFormatter::ctor(::java::util::Locale* locale, ::java::lang::String* format) { super::ctor(); this->locale = locale; this->format_ = format; } java::util::logging::Logger*& poi::ss::format::CellFormatter::logger() { clinit(); return logger_; } java::util::logging::Logger* poi::ss::format::CellFormatter::logger_; java::lang::String* poi::ss::format::CellFormatter::format(::java::lang::Object* value) { auto sb = new ::java::lang::StringBuffer(); formatValue(sb, value); return npc(sb)->toString(); } java::lang::String* poi::ss::format::CellFormatter::simpleFormat(::java::lang::Object* value) { auto sb = new ::java::lang::StringBuffer(); simpleValue(sb, value); return npc(sb)->toString(); } java::lang::String* poi::ss::format::CellFormatter::quote(::java::lang::String* str) { clinit(); return ::java::lang::StringBuilder().append(u'"')->append(str) ->append(u'"')->toString(); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::format::CellFormatter::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.format.CellFormatter", 38); return c; } void poi::ss::format::CellFormatter::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; logger_ = ::java::util::logging::Logger::getLogger(npc(CellFormatter::class_())->getName()); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::ss::format::CellFormatter::getClass0() { return class_(); }
26.485981
106
0.666902
pebble2015
84990fbdec75414459c2def3567849b8143c6aee
7,042
cpp
C++
src/plugin/torchNMSPlugin/torchNMSPlugin.cpp
mmeendez8/amirstan_plugin
35cdb3a4ff59e5203116550597bec2e16af16a64
[ "MIT" ]
null
null
null
src/plugin/torchNMSPlugin/torchNMSPlugin.cpp
mmeendez8/amirstan_plugin
35cdb3a4ff59e5203116550597bec2e16af16a64
[ "MIT" ]
null
null
null
src/plugin/torchNMSPlugin/torchNMSPlugin.cpp
mmeendez8/amirstan_plugin
35cdb3a4ff59e5203116550597bec2e16af16a64
[ "MIT" ]
null
null
null
#include "plugin/torchNMSPlugin/torchNMSPlugin.h" #include <assert.h> #include <chrono> #include "amirCommon.h" #include "amir_cuda_util/common_util.h" #include "amir_cuda_util/cuda_util.h" #include "common.h" #include "serialize.hpp" #include "torch_nms.h" namespace amirstan { namespace plugin { namespace { static const char *PLUGIN_VERSION{"1"}; static const char *PLUGIN_NAME{"TorchNMSPluginDynamic"}; } // namespace PluginFieldCollection TorchNMSPluginDynamicCreator::mFC{}; std::vector<PluginField> TorchNMSPluginDynamicCreator::mPluginAttributes( {PluginField("iou_threshold")}); TorchNMSPluginDynamic::TorchNMSPluginDynamic(const std::string &name, float iouThreshold) : mLayerName(name), mIouThreshold(iouThreshold) {} TorchNMSPluginDynamic::TorchNMSPluginDynamic(const std::string name, const void *data, size_t length) : mLayerName(name) { deserialize_value(&data, &length, &mIouThreshold); } nvinfer1::IPluginV2DynamicExt *TorchNMSPluginDynamic::clone() const { TorchNMSPluginDynamic *plugin = new TorchNMSPluginDynamic(mLayerName, mIouThreshold); plugin->setPluginNamespace(getPluginNamespace()); return plugin; } nvinfer1::DimsExprs TorchNMSPluginDynamic::getOutputDimensions( int outputIndex, const nvinfer1::DimsExprs *inputs, int nbInputs, nvinfer1::IExprBuilder &exprBuilder) { nvinfer1::DimsExprs ret = inputs[1]; return ret; } bool TorchNMSPluginDynamic::supportsFormatCombination( int pos, const nvinfer1::PluginTensorDesc *inOut, int nbInputs, int nbOutputs) { const auto *in = inOut; const auto *out = inOut + nbInputs; switch (pos) { case 0: return (in[0].type == nvinfer1::DataType::kFLOAT && in[0].format == nvinfer1::TensorFormat::kLINEAR); case 1: return (in[1].type == nvinfer1::DataType::kFLOAT && in[1].format == nvinfer1::TensorFormat::kLINEAR); case 2: return (out[0].type == nvinfer1::DataType::kINT32 && out[0].format == nvinfer1::TensorFormat::kLINEAR); } } void TorchNMSPluginDynamic::configurePlugin( const nvinfer1::DynamicPluginTensorDesc *inputs, int nbInputs, const nvinfer1::DynamicPluginTensorDesc *outputs, int nbOutputs) { // Validate input arguments } size_t TorchNMSPluginDynamic::getWorkspaceSize( const nvinfer1::PluginTensorDesc *inputs, int nbInputs, const nvinfer1::PluginTensorDesc *outputs, int nbOutputs) const { int num_bbox = inputs[1].dims.d[0]; auto data_type = inputs[1].type; size_t tmp_score_workspace = 0; size_t final_score_workspace = 0; size_t nms_workspace = 0; size_t index_workspace = amirstan::common::getAlignedSize(num_bbox * sizeof(int)); switch (data_type) { case nvinfer1::DataType::kFLOAT: tmp_score_workspace = num_bbox * sizeof(float); final_score_workspace = num_bbox * sizeof(float); nms_workspace = nms_workspace_size<float>(num_bbox) + 1; break; default: break; } tmp_score_workspace = amirstan::common::getAlignedSize(tmp_score_workspace); final_score_workspace = amirstan::common::getAlignedSize(final_score_workspace); nms_workspace = amirstan::common::getAlignedSize(nms_workspace); return tmp_score_workspace + final_score_workspace + index_workspace + nms_workspace; } int TorchNMSPluginDynamic::enqueue(const nvinfer1::PluginTensorDesc *inputDesc, const nvinfer1::PluginTensorDesc *outputDesc, const void *const *inputs, void *const *outputs, void *workSpace, cudaStream_t stream) { nvinfer1::Dims score_dims = inputDesc[1].dims; nvinfer1::Dims output_dims = outputDesc[0].dims; int num_boxes = score_dims.d[0]; auto data_type = inputDesc[1].type; switch (data_type) { case nvinfer1::DataType::kFLOAT: torch_nms<float>((int *)outputs[0], (float *)inputs[0], (float *)inputs[1], num_boxes, mIouThreshold, workSpace, stream); break; default: return 1; break; } return 0; } nvinfer1::DataType TorchNMSPluginDynamic::getOutputDataType( int index, const nvinfer1::DataType *inputTypes, int nbInputs) const { return nvinfer1::DataType::kINT32; } // IPluginV2 Methods const char *TorchNMSPluginDynamic::getPluginType() const { return PLUGIN_NAME; } const char *TorchNMSPluginDynamic::getPluginVersion() const { return PLUGIN_VERSION; } int TorchNMSPluginDynamic::getNbOutputs() const { return 1; } int TorchNMSPluginDynamic::initialize() { return 0; } void TorchNMSPluginDynamic::terminate() {} size_t TorchNMSPluginDynamic::getSerializationSize() const { return sizeof(mIouThreshold); } void TorchNMSPluginDynamic::serialize(void *buffer) const { serialize_value(&buffer, mIouThreshold); } void TorchNMSPluginDynamic::destroy() { // This gets called when the network containing plugin is destroyed delete this; } void TorchNMSPluginDynamic::setPluginNamespace(const char *libNamespace) { mNamespace = libNamespace; } const char *TorchNMSPluginDynamic::getPluginNamespace() const { return mNamespace.c_str(); } ////////////////////// creator ///////////////////////////// TorchNMSPluginDynamicCreator::TorchNMSPluginDynamicCreator() { mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } const char *TorchNMSPluginDynamicCreator::getPluginName() const { return PLUGIN_NAME; } const char *TorchNMSPluginDynamicCreator::getPluginVersion() const { return PLUGIN_VERSION; } const PluginFieldCollection *TorchNMSPluginDynamicCreator::getFieldNames() { return &mFC; } IPluginV2 *TorchNMSPluginDynamicCreator::createPlugin( const char *name, const PluginFieldCollection *fc) { float iou_threshold = 0.; for (int i = 0; i < fc->nbFields; i++) { if (fc->fields[i].data == nullptr) { continue; } std::string field_name(fc->fields[i].name); if (field_name.compare("iou_threshold") == 0) { iou_threshold = static_cast<const float *>(fc->fields[i].data)[0]; } } TorchNMSPluginDynamic *plugin = new TorchNMSPluginDynamic(name, iou_threshold); plugin->setPluginNamespace(getPluginNamespace()); return plugin; } IPluginV2 *TorchNMSPluginDynamicCreator::deserializePlugin( const char *name, const void *serialData, size_t serialLength) { // This object will be deleted when the network is destroyed, which will // call FCPluginDynamic::destroy() auto plugin = new TorchNMSPluginDynamic(name, serialData, serialLength); plugin->setPluginNamespace(getPluginNamespace()); return plugin; } void TorchNMSPluginDynamicCreator::setPluginNamespace( const char *libNamespace) { mNamespace = libNamespace; } const char *TorchNMSPluginDynamicCreator::getPluginNamespace() const { return mNamespace.c_str(); } } // namespace plugin } // namespace amirstan
30.885965
80
0.704913
mmeendez8
849a1dc18be5959fa2b4b67d275db677aff2e660
3,115
cpp
C++
MAze/Laberinto.cpp
IzaguirreYamile/MAze
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
[ "MIT" ]
1
2021-09-02T21:19:19.000Z
2021-09-02T21:19:19.000Z
MAze/Laberinto.cpp
IzaguirreYamile/MAze
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
[ "MIT" ]
null
null
null
MAze/Laberinto.cpp
IzaguirreYamile/MAze
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
[ "MIT" ]
null
null
null
#include "Laberinto.h" Laberinto::Laberinto() { } void Laberinto::Iniciar(Graphics^ g) { cols = 16; rows = 6; Celda* auxiliar; for (int j = 0; j < rows; j++) { for (int i = 0; i < cols; i++) { auxiliar = new Celda(i, j); grid.push_back(auxiliar); } } current = grid.at(0); } void Laberinto::Dibujar(Graphics^ g) { for (int i = 0; i < grid.size(); i++) { grid.at(i)->Dibujar(g); //g->DrawRectangle(Pens::Red, grid2[i]->Area()); } current->Cambiar_visitado(true); //PASO 1 Celda* next = Verificar_Vecino(current); if (next) { next->Cambiar_visitado(true); //PASO 2 stack.push_back(current); //PASE 3 Remover_Pared(current, next); //PASO 4 current = next; } else if ((stack.size() > 0)) { Celda* aux = stack.back(); stack.pop_back(); current = aux; } // Dibujar_Current(g); } Celda* Laberinto::colision(Rectangle per) { for (int i = 0; i < grid.size(); i++) { if (grid.at(i)->Area().IntersectsWith(per)) { return grid.at(i); } } } Celda* Laberinto::Rectornar_celda(int i) { if (grid.at(i) != nullptr) { return grid.at(i); } } Celda* Laberinto::Verificar_Vecino(Celda* celda) { srand(time(NULL)); int i = celda->retornar_i(); int j = celda->retornar_j(); /*Aca se toma de referencia el current arriba, derecha, abajo e izquierda representan los vecinos el indice que se obtiene por la funcion index */ vector<Celda*>vecinos; Celda* arriba = grid[index(i, j - 1)]; Celda* derecha = grid[index(i + 1, j)]; Celda* Abajo = grid[index(i, j + 1)]; Celda* Izquierda = grid[index(i - 1, j)]; // Si el vecino existe y no ha sido visitado aun pues se agrega al arreglo de vecinos if (arriba && (arriba->retornar_visitado() == false)) { vecinos.push_back(arriba); } if (derecha && (derecha->retornar_visitado() == false)) { vecinos.push_back(derecha); } if (Abajo && (Abajo->retornar_visitado() == false)) { vecinos.push_back(Abajo); } if (Izquierda && (Izquierda->retornar_visitado() == false)) { vecinos.push_back(Izquierda); } if (vecinos.size() > 0) { int r = rand() % (vecinos.size()); return vecinos[r]; //Si existe almenos un vecino, se escoge un vecino r que es aleatorio a el numero de vecinos /// pueden ir de 1 a 3 creo } else { //sino se retorna un undefinied return NULL; } } int Laberinto::index(int i, int j) { if (i < 0 || j < 0 || i> cols - 1 || j > rows - 1) { return NULL; } return i + j * cols; } void Laberinto::Remover_Pared(Celda* a, Celda* b) { int x = a->retornar_i() - b->retornar_i(); if (x == 1) { a->cambiar_pared(false, 3); b->cambiar_pared(false, 1); } else if (x == -1) { a->cambiar_pared(false, 1); b->cambiar_pared(false, 3); } int y = a->retornar_j() - b->retornar_j(); if (y == 1) { a->cambiar_pared(false, 0); b->cambiar_pared(false, 2); } else if (y == -1) { a->cambiar_pared(false, 2); b->cambiar_pared(false, 0); } } int Laberinto::retornar_cant() { return stack.size(); } void Laberinto::Dibujar_Current(Graphics^ g) { int x = current->retornar_i(); int y = current->retornar_j(); g->DrawRectangle(Pens::Blue, x * 70, y * 70, 70, 70); }
24.527559
95
0.625361
IzaguirreYamile
849dce8e4558c657810228f31cf3657fa7b514e7
42,724
cpp
C++
src/core/models/genotype/single_cell_model.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
null
null
null
src/core/models/genotype/single_cell_model.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
null
null
null
src/core/models/genotype/single_cell_model.cpp
gunjanbaid/octopus
b19e825d10c16bc14565338aadf4aee63c8fe816
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2019 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #include "single_cell_model.hpp" #include <utility> #include <cassert> #include <iterator> #include <algorithm> #include <numeric> #include <limits> #include "utils/k_medoids.hpp" #include "utils/select_top_k.hpp" #include "utils/maths.hpp" #include "utils/concat.hpp" #include "subclone_model.hpp" #include "population_model.hpp" #include "coalescent_population_prior_model.hpp" #include "genotype_prior_model.hpp" #include "individual_model.hpp" namespace octopus { namespace model { const UniformPopulationPriorModel SingleCellModel::default_population_prior_model_{}; namespace { auto get_vb_model_options(const SingleCellModel::AlgorithmParameters& config) { VariationalBayesMixtureMixtureModel::Options result {}; result.parallel_execution = config.execution_policy == ExecutionPolicy::par; return result; } } // namespace SingleCellModel::SingleCellModel(std::vector<SampleName> samples, SingleCellPriorModel prior_model, Parameters parameters, AlgorithmParameters config, boost::optional<const PopulationPriorModel&> population_prior_model) : samples_{std::move(samples)} , prior_model_{std::move(prior_model)} , posterior_model_ {get_vb_model_options(config)} , parameters_{std::move(parameters)} , config_{std::move(config)} , population_prior_model_{std::addressof(population_prior_model ? *population_prior_model : default_population_prior_model_)} {} const SingleCellPriorModel& SingleCellModel::prior_model() const { return prior_model_; } namespace { template <typename Range> bool all_same_ploidy(const Range& genotypes) { const static auto ploidy_not_equal = [] (const auto& lhs, const auto& rhs) { return lhs.ploidy() != rhs.ploidy(); }; return std::adjacent_find(std::cbegin(genotypes), std::cend(genotypes), ploidy_not_equal) == std::cend(genotypes); } template <typename T> std::vector<T> copy(const std::vector<T>& values, const std::vector<std::size_t>& indices) { std::vector<T> result {}; result.reserve(indices.size()); for (auto idx : indices) { assert(idx < values.size()); result.push_back(values[idx]); } return result; } } // namespace SingleCellModel::Inferences SingleCellModel::evaluate(const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { assert(all_same_ploidy(genotypes)); const auto num_clones = prior_model_.phylogeny().size(); assert(num_clones <= genotypes.size()); Inferences result {}; if (num_clones == 1) { evaluate(result, genotypes, haplotype_likelihoods); } else { const auto genotype_combinations = propose_genotype_combinations(genotypes, haplotype_likelihoods); evaluate(result, genotypes, genotype_combinations, haplotype_likelihoods); } return result; } SingleCellModel::Inferences SingleCellModel::evaluate(const PhylogenyNodePloidyMap& phylogeny_ploidies, const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { assert(phylogeny_ploidies.size() == prior_model_.phylogeny().size()); const auto num_clones = prior_model_.phylogeny().size(); assert(num_clones <= genotypes.size()); if (num_clones == 1) { return evaluate(genotypes, haplotype_likelihoods); } else { Inferences result {}; const auto genotype_combinations = propose_genotype_combinations(phylogeny_ploidies, genotypes, haplotype_likelihoods); evaluate(result, genotypes, genotype_combinations, haplotype_likelihoods); return result; } } // private methods std::vector<std::size_t> SingleCellModel::propose_genotypes(const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { assert(config_.max_genotype_combinations); const auto merged_likelihoods = haplotype_likelihoods.merge_samples(); const IndividualModel pooled_model {prior_model_.germline_prior_model()}; const auto pooled_model_inferences = pooled_model.evaluate(genotypes, merged_likelihoods); return select_top_k_indices(pooled_model_inferences.posteriors.genotype_log_probabilities, *config_.max_genotype_combinations); } namespace { auto log(std::size_t base, std::size_t x) { return std::log2(x) / std::log2(base); } auto num_combinations(const std::size_t num_genotypes, const std::size_t num_samples) { static constexpr auto max_combinations = std::numeric_limits<std::size_t>::max(); if (num_samples <= log(num_genotypes, max_combinations)) { return static_cast<std::size_t>(std::pow(num_genotypes, num_samples)); } else { return max_combinations; } } template <typename T> auto select(const std::vector<std::size_t>& indices, const std::vector<T>& data) { std::vector<T> result {}; result.reserve(indices.size()); for (auto idx : indices) result.push_back(data[idx]); return result; } auto l1_norm(const std::vector<double>& p, const std::vector<double>& q) noexcept { return std::inner_product(std::cbegin(p), std::cend(p), std::cbegin(q), 0.0, std::plus<> {}, [] (const auto a, const auto b) { return std::abs(a - b); }); } ClusterVector cluster_samples(const std::vector<PopulationModel::Latents::ProbabilityVector>& genotype_posteriors, const unsigned num_clusters) { ClusterVector result {}; KMediodsParameters params {}; params.initialisation = KMediodsParameters::InitialisationMode::max_distance; auto best_fit = k_medoids(genotype_posteriors, num_clusters, result, l1_norm, params).second; params.initialisation = KMediodsParameters::InitialisationMode::total_distance; ClusterVector tmp {}; auto fit = k_medoids(genotype_posteriors, num_clusters, tmp, l1_norm, params).second; if (fit < best_fit) { result = std::move(tmp); best_fit = fit; } params.initialisation = KMediodsParameters::InitialisationMode::random; for (int i {0}; i < 3; ++i) { tmp.clear(); fit = k_medoids(genotype_posteriors, num_clusters, tmp, l1_norm, params).second; if (fit < best_fit) { result = std::move(tmp); best_fit = fit; } } return result; } template <typename ForwardIterator> ForwardIterator unique_stable(const ForwardIterator first, const ForwardIterator last) { const auto n = static_cast<std::size_t>(std::distance(first, last)); using ValueTp = typename std::iterator_traits<ForwardIterator>::value_type; std::vector<std::pair<ValueTp, std::size_t>> indexed_values(n); std::size_t idx {0}; std::transform(std::make_move_iterator(first), std::make_move_iterator(last), std::begin(indexed_values), [&] (auto&& value) { return std::make_pair(std::move(value), idx++); }); std::sort(std::begin(indexed_values), std::end(indexed_values)); const static auto first_equal = [] (const auto& lhs, const auto& rhs) { return lhs.first == rhs.first; }; indexed_values.erase(std::unique(std::begin(indexed_values), std::end(indexed_values), first_equal), std::end(indexed_values)); const static auto index_less = [] (const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; }; std::sort(std::begin(indexed_values), std::end(indexed_values), index_less); return std::transform(std::make_move_iterator(std::begin(indexed_values)), std::make_move_iterator(std::end(indexed_values)), first, [] (auto&& p) { return std::move(p.first); }); } template <typename Range> void unique_stable_erase(Range& values) { values.erase(unique_stable(std::begin(values), std::end(values)), std::end(values)); } template <typename T1, typename T2> auto zip(std::vector<T1>&& lhs, std::vector<T2>&& rhs) { assert(lhs.size() == rhs.size()); std::vector<std::pair<T1, T2>> result {}; result.reserve(lhs.size()); std::transform(std::make_move_iterator(std::begin(lhs)), std::make_move_iterator(std::end(lhs)), std::make_move_iterator(std::begin(rhs)), std::back_inserter(result), [] (T1&& a, T2&& b) noexcept { return std::make_pair(std::move(a), std::move(b)); }); return result; } template <typename T1, typename T2> auto unzip(std::vector<std::pair<T1, T2>>&& zipped) { std::vector<T1> lhs {}; std::vector<T2> rhs {}; lhs.reserve(zipped.size()); rhs.reserve(zipped.size()); for (auto& p : zipped) { lhs.push_back(std::move(p.first)); rhs.push_back(std::move(p.second)); } return std::make_pair(std::move(lhs), std::move(rhs)); } void combine(const IndividualModel::Latents::ProbabilityVector& src, IndividualModel::Latents::ProbabilityVector& dst, const double src_weight = 1, const double dst_weight = 1) noexcept { assert(src.size() == dst.size()); const auto lhs_prob = src_weight / (src_weight + dst_weight); const auto rhs_prob = dst_weight / (src_weight + dst_weight); const auto combine_probs = [=] (auto lhs, auto rhs) noexcept { return lhs_prob * lhs + rhs_prob * rhs; }; std::transform(std::cbegin(src), std::cend(src), std::cbegin(dst), std::begin(dst), combine_probs); } template <typename T> std::vector<T> select(const std::vector<bool>& selectors, const std::vector<T>& values) { assert(selectors.size() == values.size()); std::vector<T> result {}; result.reserve(std::accumulate(std::cbegin(selectors), std::cend(selectors), 0)); std::size_t selector_idx {0}; const auto selector = [&] (const auto&) { return selectors[selector_idx++]; }; std::copy_if(std::cbegin(values), std::cend(values), std::back_inserter(result), selector); return result; } template <typename T> IndexTupleVector select_top_k_combinations(const std::vector<std::vector<T>>& values, const std::size_t k, const std::size_t n) { const auto tuples = select_top_k_tuples(values, k); if (values.size() <= n) { return tuples; } else { IndexTupleVector result {}; result.reserve(k); std::vector<bool> selectors(values.size()); std::fill_n(std::rbegin(selectors), n, 1); for (const auto& tuple : tuples) { do { if (result.size() < k) { result.push_back(select(selectors, tuple)); } else { return result; } } while (std::next_permutation(std::begin(selectors), std::end(selectors))); } return result; } } template <typename Range> auto sum_entropies(const std::vector<Range>& ranges) { const static auto add_entropy = [] (auto total, const auto& probs) { return maths::entropy2(probs); }; return std::accumulate(std::cbegin(ranges), std::cend(ranges), 0.0, add_entropy); } template <typename Range> auto max_entropy_idx(const std::vector<Range>& ranges) { std::size_t result {0}; double max {0}; for (std::size_t idx {0}; idx < ranges.size(); ++idx) { const auto entropy = maths::entropy(ranges[idx]); if (idx == 0 || max < entropy) { result = idx; max = entropy; } } return result; } template <typename T> void erase(std::vector<T>& values, const std::size_t idx) { values.erase(std::next(std::cbegin(values), idx)); } struct ClusterHelper { std::vector<std::size_t> sample_indices; std::vector<SampleName> samples; ProbabilityVector genotype_probabilities; double entropy; }; void sort_by_size_and_entropy(ClusterVector& clusters, std::vector<std::vector<SampleName>>& samples_by_cluster, std::vector<ProbabilityVector>& cluster_marginal_genotype_posteriors) { std::vector<ClusterHelper> tmp_clusters(clusters.size()); for (std::size_t k {0}; k < clusters.size(); ++k) { std::swap(tmp_clusters[k].sample_indices, clusters[k]); std::swap(tmp_clusters[k].samples, samples_by_cluster[k]); std::swap(tmp_clusters[k].genotype_probabilities, cluster_marginal_genotype_posteriors[k]); tmp_clusters[k].entropy = maths::entropy2(tmp_clusters[k].genotype_probabilities); } const static auto sorter = [] (const ClusterHelper& lhs, const ClusterHelper& rhs) { if (lhs.samples.size() == rhs.samples.size()) { return lhs.entropy < rhs.entropy; } else { return lhs.samples.size() > rhs.samples.size(); } }; std::sort(std::begin(tmp_clusters), std::end(tmp_clusters), sorter); for (std::size_t k {0}; k < clusters.size(); ++k) { std::swap(tmp_clusters[k].sample_indices, clusters[k]); std::swap(tmp_clusters[k].samples, samples_by_cluster[k]); std::swap(tmp_clusters[k].genotype_probabilities, cluster_marginal_genotype_posteriors[k]); } } void erase_combinations_with_duplicate_indices(std::vector<std::vector<std::size_t>>& combinations, const std::size_t max_index) { std::vector<int> counts(max_index); combinations.erase(std::remove_if(std::begin(combinations), std::end(combinations), [&counts] (const auto& indices) { std::fill(std::begin(counts), std::end(counts), 0); for (auto idx : indices) ++counts[idx]; return std::any_of(std::cbegin(counts), std::cend(counts), [] (auto count) { return count > 1; }); }), std::end(combinations)); } } // namespace SingleCellModel::GenotypeCombinationVector SingleCellModel::propose_genotype_combinations(const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { const auto num_groups = prior_model_.phylogeny().size(); const auto max_possible_combinations = num_combinations(genotypes.size(), num_groups); const auto max_genotype_combinations = config_.max_genotype_combinations ? *config_.max_genotype_combinations : max_possible_combinations; // 1. Run population model // 2. Cluster samples // 3. Run individual model on merged reads // 4. Select top combinations using cluster marginal posteriors PopulationModel::Options population_model_options {}; population_model_options.max_genotype_combinations = max_genotype_combinations; PopulationModel population_model {*population_prior_model_, population_model_options}; std::vector<PopulationModel::Latents::ProbabilityVector> population_genotype_posteriors; IndividualModel individual_model {prior_model_.germline_prior_model()}; std::vector<ProbabilityVector> cluster_marginal_genotype_posteriors {}; cluster_marginal_genotype_posteriors.reserve(samples_.size() / 2); const auto haplotypes = haplotype_likelihoods.haplotypes(); ClusterVector clusters {}; std::vector<std::vector<SampleName>> samples_by_cluster {}; while (clusters.empty() || clusters.size() > num_groups) { if (clusters.empty()) { auto population_inferences = population_model.evaluate(samples_, haplotypes, genotypes, haplotype_likelihoods); population_genotype_posteriors = std::move(population_inferences.posteriors.marginal_genotype_probabilities); clusters = cluster_samples(population_genotype_posteriors, std::max(samples_.size() / 4, 2 * num_groups)); } else if (clusters.size() > 2 * num_groups) { clusters = cluster_samples(cluster_marginal_genotype_posteriors, std::max(clusters.size() / 2, 2 * num_groups)); } else { auto num_effective_clusters = sum_entropies(cluster_marginal_genotype_posteriors); if ((clusters.size() == num_groups + 1 && num_effective_clusters < num_groups / 2) || (num_groups < 4 && clusters.size() <= num_groups + 2 && num_effective_clusters < 2)) { break; } sort_by_size_and_entropy(clusters, samples_by_cluster, cluster_marginal_genotype_posteriors); while (clusters.size() > num_groups && clusters.back().size() == 1 && maths::entropy2(cluster_marginal_genotype_posteriors.back()) > 1) { clusters.pop_back(); samples_by_cluster.pop_back(); cluster_marginal_genotype_posteriors.pop_back(); } if (clusters.size() <= num_groups + 1) break; num_effective_clusters = sum_entropies(cluster_marginal_genotype_posteriors); if (num_groups < 4 && clusters.size() <= num_groups + 2 && num_effective_clusters < 2) break; clusters = cluster_samples(cluster_marginal_genotype_posteriors, num_groups + 1); } cluster_marginal_genotype_posteriors.clear(); std::vector<std::vector<SampleName>> next_samples_by_cluster {}; next_samples_by_cluster.reserve(clusters.size()); for (const auto& cluster : clusters) { if (samples_by_cluster.empty()) { next_samples_by_cluster.push_back(select(cluster, samples_)); } else { next_samples_by_cluster.push_back(concat(select(cluster, samples_by_cluster))); } const auto pooled_likelihoods = haplotype_likelihoods.merge_samples(next_samples_by_cluster.back()); auto cluster_inferences = individual_model.evaluate(genotypes, pooled_likelihoods); cluster_marginal_genotype_posteriors.push_back(std::move(cluster_inferences.posteriors.genotype_probabilities)); } samples_by_cluster = std::move(next_samples_by_cluster); } GenotypeCombinationVector result {}; auto k = 10 * max_genotype_combinations; while (result.empty()) { result = select_top_k_combinations(cluster_marginal_genotype_posteriors, k, num_groups); // Remove combinations with duplicate genotypes as these are redundant according to model. erase_combinations_with_duplicate_indices(result, genotypes.size()); // Reorder the combinations, keeping only the most probable one under the prior std::vector<SingleCellPriorModel::GenotypeReference> combination_refs {}; combination_refs.reserve(num_groups); for (GenotypeCombination& combination : result) { std::sort(std::begin(combination), std::end(combination)); GenotypeCombination best_combination; auto max_prior = std::numeric_limits<double>::lowest(); do { for (auto idx : combination) combination_refs.emplace_back(genotypes[idx]); const auto prior = prior_model_.evaluate(combination_refs); combination_refs.clear(); if (prior > max_prior) { best_combination = combination; max_prior = prior; } } while (std::next_permutation(std::begin(combination), std::end(combination))); combination = std::move(best_combination); } unique_stable_erase(result); k *= 2; } if (result.size() > max_genotype_combinations) { result.resize(max_genotype_combinations); } return result; } SingleCellModel::GenotypeCombinationVector SingleCellModel::propose_all_genotype_combinations(const GenotypeVector& genotypes) const { const auto num_groups = prior_model_.phylogeny().size(); GenotypeCombinationVector result {}; result.reserve(num_combinations(genotypes.size(), num_groups)); GenotypeCombination tmp(num_groups); std::vector<bool> v(genotypes.size() * num_groups), hits(genotypes.size(), false); std::fill(std::begin(v), std::next(std::begin(v), num_groups), true); do { bool good {true}; for (std::size_t i {0}, k {0}; k < num_groups; ++i) { if (v[i]) { if (i / genotypes.size() == k) { tmp[k++] = i - genotypes.size() * (i / genotypes.size()); } else { good = false; k = num_groups; } } } if (good) { for (auto idx : tmp) { if (hits[idx]) { good = false; break; } else { hits[idx] = true; } } std::fill(std::begin(hits), std::end(hits), false); if (good) result.push_back(tmp); } } while (std::prev_permutation(std::begin(v), std::end(v))); return result; } namespace { auto max_ploidy(const SingleCellModel::GenotypeVector& genotypes) { const static auto ploidy_less = [] (const auto& lhs, const auto& rhs) { return lhs.ploidy() < rhs.ploidy(); }; return std::max_element(std::cbegin(genotypes), std::cend(genotypes), ploidy_less)->ploidy(); } auto segment_by_ploidy(const SingleCellModel::GenotypeVector& genotypes) { std::vector<SingleCellModel::GenotypeVector> result(max_ploidy(genotypes) + 1); for (auto& g : result) g.reserve(genotypes.size()); for (const auto& genotype : genotypes) result[genotype.ploidy()].push_back(genotype); return result; } bool valid_ploidies(const std::vector<std::size_t>& combination, const SingleCellModel::GenotypeVector& genotypes, const std::vector<unsigned>& required_ploidies) noexcept { assert(combination.size() == required_ploidies.size()); std::size_t idx {0}; const auto ploidy_equal = [&] (auto g) noexcept { return genotypes[g].ploidy() == required_ploidies[idx++]; }; return std::all_of(std::cbegin(combination), std::cend(combination), ploidy_equal); } template <typename T> auto get_leaf_labels(const Phylogeny<std::size_t, T>& phylogeny) { std::vector<std::size_t> result {}; result.reserve(phylogeny.size() - 1); for (std::size_t id {0}; id < phylogeny.size(); ++id) { if (phylogeny.num_descendants(id) == 0) { result.push_back(id); } } return result; } bool is_redundant_copy_change(const Genotype<IndexedHaplotype<>>& lhs, const Genotype<IndexedHaplotype<>>& rhs) { return lhs.ploidy() != rhs.ploidy() && have_same_elements(lhs, rhs); } void erase_combinations_with_redundant_copy_changes(std::vector<std::vector<std::size_t>>& combinations, const SingleCellModel::GenotypeVector& genotypes, const SingleCellPriorModel::CellPhylogeny& phylogeny) { const auto leafs = get_leaf_labels(phylogeny); std::vector<std::size_t> leaf_ancestors(leafs.size()); std::transform(std::cbegin(leafs), std::cend(leafs), std::begin(leaf_ancestors), [&] (auto leaf_id) { return phylogeny.ancestor(leaf_id).id; }); std::vector<std::vector<boost::optional<bool>>> have_same_elements_cache(genotypes.size(), std::vector<boost::optional<bool>>(genotypes.size())); combinations.erase(std::remove_if(std::begin(combinations), std::end(combinations), [&] (const auto& combination) { std::size_t leaf_idx {0}; return std::any_of(std::cbegin(leafs), std::cend(leafs), [&] (const auto leaf) { const auto child_index = combination[leaf]; const auto parent_index = combination[leaf_ancestors[leaf_idx++]]; auto& result = have_same_elements_cache[child_index][parent_index]; if (!result) result = is_redundant_copy_change(genotypes[child_index], genotypes[parent_index]); return *result; }); }), std::end(combinations)); } } // namespace class ZygosityGenotypePriorModel : public GenotypePriorModel { public: using GenotypePriorModel::LogProbability; ZygosityGenotypePriorModel(const GenotypePriorModel& base) : base_ {std::addressof(base)} {} virtual ~ZygosityGenotypePriorModel() = default; private: const GenotypePriorModel* base_; template <typename T> LogProbability do_evaluate_helper(const Genotype<T>& genotype) const { LogProbability result {(ploidy(genotype) - zygosity(genotype)) * std::log(0.1)}; if (base_) { result += base_->evaluate(genotype); } return result; } virtual LogProbability do_evaluate(const Genotype<Haplotype>& genotype) const override { return do_evaluate_helper(genotype);} virtual LogProbability do_evaluate(const Genotype<IndexedHaplotype<>>& genotype) const override { return do_evaluate_helper(genotype); } bool check_is_primed() const noexcept override { return true; } }; SingleCellModel::GenotypeCombinationVector SingleCellModel::propose_genotype_combinations(const PhylogenyNodePloidyMap& phylogeny_ploidies, const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { // First assign each sample to a ploidy const auto genotypes_by_ploidy = segment_by_ploidy(genotypes); std::vector<unsigned> sample_ploidies {}; sample_ploidies.reserve(samples_.size()); const ZygosityGenotypePriorModel zygosity_prior {prior_model_.germline_prior_model()}; const IndividualModel zygosity_individual_model {zygosity_prior}; for (const auto& sample : samples_) { haplotype_likelihoods.prime(sample); unsigned best_ploidy {1}; double max_log_evidence {}; for (unsigned ploidy {1}; ploidy < genotypes_by_ploidy.size(); ++ploidy) { const auto inferences = zygosity_individual_model.evaluate(genotypes_by_ploidy[ploidy], haplotype_likelihoods); if (ploidy == 1 || max_log_evidence < inferences.log_evidence) { best_ploidy = ploidy; max_log_evidence = inferences.log_evidence; } } sample_ploidies.push_back(best_ploidy); } PopulationModel::Options population_model_options {}; population_model_options.max_genotype_combinations = config_.max_genotype_combinations; PopulationModel population_model {*population_prior_model_, population_model_options}; std::vector<PopulationModel::Latents::ProbabilityVector> population_genotype_posteriors; const auto num_groups = prior_model_.phylogeny().size(); std::vector<ProbabilityVector> cluster_marginal_genotype_posteriors {}; const auto haplotypes = haplotype_likelihoods.haplotypes(); ClusterVector clusters {}; std::vector<std::vector<SampleName>> samples_by_cluster {}; while (clusters.empty() || clusters.size() > num_groups) { if (clusters.empty()) { auto population_inferences = population_model.evaluate(samples_, haplotypes, genotypes, haplotype_likelihoods); population_genotype_posteriors = std::move(population_inferences.posteriors.marginal_genotype_probabilities); clusters = cluster_samples(population_genotype_posteriors, std::max(samples_.size() / 4, 2 * num_groups)); } else if (clusters.size() > 2 * num_groups) { clusters = cluster_samples(cluster_marginal_genotype_posteriors, std::max(clusters.size() / 2, 2 * num_groups)); } else { auto num_effective_clusters = sum_entropies(cluster_marginal_genotype_posteriors); if ((clusters.size() == num_groups + 1 && num_effective_clusters < num_groups / 2) || (num_groups < 4 && clusters.size() <= num_groups + 2 && num_effective_clusters < 1)) { break; } sort_by_size_and_entropy(clusters, samples_by_cluster, cluster_marginal_genotype_posteriors); while (clusters.size() > num_groups && clusters.back().size() == 1 && maths::entropy2(cluster_marginal_genotype_posteriors.back()) > 1) { clusters.pop_back(); samples_by_cluster.pop_back(); cluster_marginal_genotype_posteriors.pop_back(); } if (clusters.size() <= num_groups + 1) break; clusters = cluster_samples(cluster_marginal_genotype_posteriors, num_groups + 1); } cluster_marginal_genotype_posteriors.clear(); std::vector<std::vector<SampleName>> next_samples_by_cluster {}; next_samples_by_cluster.reserve(clusters.size()); for (const auto& cluster : clusters) { if (samples_by_cluster.empty()) { next_samples_by_cluster.push_back(select(cluster, samples_)); } else { next_samples_by_cluster.push_back(concat(select(cluster, samples_by_cluster))); } const auto pooled_likelihoods = haplotype_likelihoods.merge_samples(next_samples_by_cluster.back()); auto cluster_inferences = zygosity_individual_model.evaluate(genotypes, pooled_likelihoods); cluster_marginal_genotype_posteriors.push_back(std::move(cluster_inferences.posteriors.genotype_probabilities)); } samples_by_cluster = std::move(next_samples_by_cluster); } std::vector<unsigned> required_ploidies(num_groups); for (std::size_t id {0}; id < num_groups; ++id) required_ploidies[id] = phylogeny_ploidies.at(id); GenotypeCombinationVector result {}; const auto k = config_.max_genotype_combinations ? 100 * *config_.max_genotype_combinations : std::numeric_limits<std::size_t>::max(); result = select_top_k_combinations(cluster_marginal_genotype_posteriors, k, num_groups); // Remove combinations with duplicate genotypes as these are redundant according to model. erase_combinations_with_duplicate_indices(result, genotypes.size()); // Reorder the combinations, keeping only the most probable one under the prior std::vector<SingleCellPriorModel::GenotypeReference> combination_refs {}; combination_refs.reserve(num_groups); result.erase(std::remove_if(std::begin(result), std::end(result), [&] (GenotypeCombination& combination) { std::sort(std::begin(combination), std::end(combination)); GenotypeCombination best_combination; auto max_prior = std::numeric_limits<double>::lowest(); bool has_valid_combination {false}; do { if (valid_ploidies(combination, genotypes, required_ploidies)) { for (auto idx : combination) combination_refs.emplace_back(genotypes[idx]); const auto prior = prior_model_.evaluate(combination_refs); combination_refs.clear(); if (prior > max_prior) { best_combination = combination; max_prior = prior; } has_valid_combination = true; } } while (std::next_permutation(std::begin(combination), std::end(combination))); combination = std::move(best_combination); return !has_valid_combination; }), std::end(result)); unique_stable_erase(result); erase_combinations_with_redundant_copy_changes(result, genotypes, prior_model_.phylogeny()); if (result.empty()) { throw NoViableGenotypeCombinationsError {}; } if (config_.max_genotype_combinations && result.size() > *config_.max_genotype_combinations) { result.resize(*config_.max_genotype_combinations); } return result; } void SingleCellModel::evaluate(Inferences& result, const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { SubcloneModel::Priors subclone_priors {prior_model_.germline_prior_model(), {}}; const auto ploidy = genotypes.front().ploidy(); for (const auto& sample : samples_) { subclone_priors.alphas.emplace(sample, SubcloneModel::Priors::GenotypeMixturesDirichletAlphas(ploidy,parameters_.dropout_concentration)); } SubcloneModel::AlgorithmParameters algo_params {}; algo_params.max_seeds = config_.max_seeds; algo_params.execution_policy = config_.execution_policy; SubcloneModel helper_model {samples_, std::move(subclone_priors)}; SubcloneModel::InferredLatents subclone_inferences; if (!config_.max_genotype_combinations || genotypes.size() <= *config_.max_genotype_combinations) { subclone_inferences = helper_model.evaluate(genotypes, haplotype_likelihoods); } else { const auto genotype_subset_indices = propose_genotypes(genotypes, haplotype_likelihoods); const auto genotype_subset = copy(genotypes, genotype_subset_indices); subclone_inferences = helper_model.evaluate(genotype_subset, haplotype_likelihoods); SubcloneModel::Latents::ProbabilityVector weighted_genotype_posteriors(genotypes.size()); for (std::size_t g {0}; g < genotype_subset.size(); ++g) { weighted_genotype_posteriors[genotype_subset_indices[g]] = subclone_inferences.weighted_genotype_posteriors[g]; } subclone_inferences.weighted_genotype_posteriors = std::move(weighted_genotype_posteriors); } Inferences::GroupInferences founder {}; founder.genotype_posteriors = std::move(subclone_inferences.weighted_genotype_posteriors); founder.sample_attachment_posteriors.assign(samples_.size(), 1.0); result.phylogeny.set_founder({0, std::move(founder)}); result.log_evidence = subclone_inferences.approx_log_evidence; } void SingleCellModel::evaluate(Inferences& result, const GenotypeVector& genotypes, const GenotypeCombinationVector& genotype_combinations, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { const auto genotype_combination_priors = calculate_genotype_priors(genotype_combinations, genotypes); const auto vb_haplotype_likelihoods = make_likelihood_matrix(genotype_combinations, genotypes, haplotype_likelihoods); auto seeds = propose_seeds(genotype_combinations, genotypes, genotype_combination_priors, haplotype_likelihoods); auto vb_inferences = evaluate_model(genotype_combination_priors, vb_haplotype_likelihoods, std::move(seeds)); for (std::size_t group_idx {0}; group_idx < prior_model_.phylogeny().size(); ++group_idx) { Inferences::GroupInferences group {}; group.sample_attachment_posteriors.resize(samples_.size()); for (std::size_t sample_idx {0}; sample_idx < samples_.size(); ++sample_idx) { group.sample_attachment_posteriors[sample_idx] = vb_inferences.weighted_group_responsibilities[sample_idx][group_idx]; } // Marginalise over genotypes group.genotype_posteriors.resize(genotypes.size()); for (std::size_t genotype_combo_idx {0}; genotype_combo_idx < genotype_combinations.size(); ++genotype_combo_idx) { group.genotype_posteriors[genotype_combinations[genotype_combo_idx][group_idx]] += vb_inferences.weighted_genotype_posteriors[genotype_combo_idx]; } if (group_idx == 0) { result.phylogeny.set_founder({group_idx, std::move(group)}); } else { const auto ancestor_idx = prior_model_.phylogeny().ancestor(group_idx).id; result.phylogeny.add_descendant({group_idx, std::move(group)}, ancestor_idx); } } result.log_evidence = vb_inferences.map.approx_log_evidence; } VariationalBayesMixtureMixtureModel::LogProbabilityVector SingleCellModel::calculate_genotype_priors(const GenotypeCombinationVector& genotype_combinations, const GenotypeVector& genotypes) const { std::vector<SingleCellPriorModel::GenotypeReference> combination_buffer {}; LogProbabilityVector result(genotype_combinations.size()); std::transform(std::cbegin(genotype_combinations), std::cend(genotype_combinations), std::begin(result), [&] (const auto& combination) { combination_buffer.clear(); combination_buffer.reserve(combination.size()); std::transform(std::cbegin(combination), std::cend(combination), std::back_inserter(combination_buffer), [&] (auto idx) { return std::cref(genotypes[idx]); }); return prior_model_.evaluate(combination_buffer); }); return result; } SingleCellModel::VBLikelihoodMatrix SingleCellModel::make_likelihood_matrix(const GenotypeCombinationVector& genotype_combinations, const GenotypeVector& genotypes, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { VBLikelihoodMatrix result {}; result.reserve(samples_.size()); for (const auto& sample : samples_) { haplotype_likelihoods.prime(sample); VariationalBayesMixtureMixtureModel::GenotypeCombinationLikelihoodVector vb_combination_likelihoods {}; vb_combination_likelihoods.reserve(genotype_combinations.size()); for (const auto& genotype_combination : genotype_combinations) { VariationalBayesMixtureMixtureModel::GenotypeLikelihoodVector vb_genotype_likelihoods {}; vb_genotype_likelihoods.reserve(genotype_combination.size()); for (const auto genotype_idx : genotype_combination) { VariationalBayesMixtureMixtureModel::HaplotypeLikelihoodVector vb_haplotype_likelihoods {}; vb_haplotype_likelihoods.reserve(genotypes[genotype_idx].ploidy()); for (const auto& haplotype : genotypes[genotype_idx]) { vb_haplotype_likelihoods.emplace_back(haplotype_likelihoods[haplotype]); } vb_genotype_likelihoods.push_back(std::move(vb_haplotype_likelihoods)); } vb_combination_likelihoods.push_back(std::move(vb_genotype_likelihoods)); } result.push_back(std::move(vb_combination_likelihoods)); } return result; } namespace { LogProbabilityVector log_uniform_dist(const std::size_t n) { return LogProbabilityVector(n, -std::log(static_cast<double>(n))); } auto make_point_seed(const std::size_t num_genotypes, const std::size_t idx, const double p = 0.9999) { LogProbabilityVector result(num_genotypes, num_genotypes > 1 ? std::log((1 - p) / (num_genotypes - 1)) : 0); if (num_genotypes > 1) result[idx] = std::log(p); return result; } void make_point_seeds(const std::size_t num_genotypes, const std::vector<std::size_t>& indices, std::vector<LogProbabilityVector>& result, const double p = 0.9999) { result.reserve(result.size() + indices.size()); std::transform(std::cbegin(indices), std::cend(indices), std::back_inserter(result), [=] (auto idx) { return make_point_seed(num_genotypes, idx, p); }); } auto make_range_seed(const std::size_t num_genotypes, const std::size_t begin, const std::size_t n, const double p = 0.9999999) { LogProbabilityVector result(num_genotypes, std::log((1 - p) / (num_genotypes - n))); std::fill_n(std::next(std::begin(result), begin), n, std::log(p / n)); return result; } } // namespace SingleCellModel::VBSeedVector SingleCellModel::propose_seeds(const GenotypeCombinationVector& genotype_combinations, const GenotypeVector& genotypes, const VariationalBayesMixtureMixtureModel::LogProbabilityVector& genotype_combination_priors, const HaplotypeLikelihoodArray& haplotype_likelihoods) const { VBSeedVector result {}; const auto num_genotypes = genotype_combinations.size(); result.push_back(log_uniform_dist(num_genotypes)); if (config_.max_seeds > 1 && num_genotypes > 100) result.push_back(make_range_seed(num_genotypes, 0, num_genotypes / 100)); if (config_.max_seeds > 2 && num_genotypes > 10) result.push_back(make_range_seed(num_genotypes, 0, num_genotypes / 10)); std::vector<std::size_t> top_indices(std::min(config_.max_seeds - result.size(), num_genotypes)); std::iota(std::begin(top_indices), std::end(top_indices), 0u); make_point_seeds(genotype_combinations.size(), top_indices, result); return result; } VariationalBayesMixtureMixtureModel::Inferences SingleCellModel::evaluate_model(const VariationalBayesMixtureMixtureModel::LogProbabilityVector& genotype_combination_priors, const VBLikelihoodMatrix& haplotype_likelihoods, VBSeedVector seeds) const { if (parameters_.group_priors) { if (parameters_.sample_dropout_concentrations.size() == samples_.size()) { return posterior_model_.evaluate(genotype_combination_priors, haplotype_likelihoods, *parameters_.group_priors, parameters_.group_concentration, parameters_.sample_dropout_concentrations, std::move(seeds)); } else { return posterior_model_.evaluate(genotype_combination_priors, haplotype_likelihoods, *parameters_.group_priors, parameters_.group_concentration, parameters_.dropout_concentration, std::move(seeds)); } } else { if (parameters_.sample_dropout_concentrations.size() == samples_.size()) { return posterior_model_.evaluate(genotype_combination_priors, haplotype_likelihoods, parameters_.group_concentration, parameters_.sample_dropout_concentrations, std::move(seeds)); } else { return posterior_model_.evaluate(genotype_combination_priors, haplotype_likelihoods, parameters_.group_concentration, parameters_.dropout_concentration, std::move(seeds)); } } } } // namespace model } // namespace octopus
47.156733
158
0.666862
gunjanbaid
84a0d58f3426e666efc31725f9e9d6a0a3c2492d
232
cpp
C++
test/stkwebapptest/StkWebAppTest1.cpp
s-takeuchi/YaizuComLib
de1c881a4b743bafec22f7ea2d263572c474cbfe
[ "MIT" ]
4
2017-02-21T23:25:23.000Z
2022-01-30T20:17:22.000Z
test/stkwebapptest/StkWebAppTest1.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
161
2015-05-16T14:26:36.000Z
2021-11-25T05:07:56.000Z
test/stkwebapptest/StkWebAppTest1.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
1
2019-12-06T10:24:45.000Z
2019-12-06T10:24:45.000Z
#include "StkWebAppTest1.h" StkObject* StkWebAppTest1::Execute(StkObject* ReqObj, int Method, wchar_t UrlPath[StkWebAppExec::URL_PATH_LENGTH], int* ResultCode, wchar_t* HttpHeader) { *ResultCode = 200; return ReqObj->Clone(); }
29
152
0.767241
s-takeuchi
84a5811aeb3db815d1c912b6b2134308ce430dd9
990
hpp
C++
src/Factory.hpp
ahfakt/DP
592284274363f1627e9a1d2b6ab68014e5763490
[ "MIT" ]
null
null
null
src/Factory.hpp
ahfakt/DP
592284274363f1627e9a1d2b6ab68014e5763490
[ "MIT" ]
null
null
null
src/Factory.hpp
ahfakt/DP
592284274363f1627e9a1d2b6ab68014e5763490
[ "MIT" ]
null
null
null
#include "DP/Factory.h" namespace DP { template <typename T, typename IDType, typename ... Args> Factory<T, IDType, Args ...>::Factory() noexcept { Factory::Registry; } template <typename T, typename IDType, typename ... Args> CreateInfo<T, Args ...> const& Factory<T, IDType, Args ...>::GetCreateInfo(TypeID const& TypeId) { if (auto i = Factory::Registry.find(TypeId.id); i != Factory::Registry.end()) return i->second; throw Exception("Unregistered Class ID"); } template <typename T, typename IDType, typename ... Args> T* Factory<T, IDType, Args ...>::Create(TypeID const& TypeId, Args&& ... args) { CreateInfo<T, Args ...> const& createInfo = Factory::GetCreateInfo(TypeId); return createInfo.create(::operator new(createInfo.size), std::forward<Args>(args) ...); } template <typename T, typename IDType, typename ... Args> template <typename DT, IDType typeID> Factory<T, IDType, Args ...>::Registrar<DT, typeID>::Registrar() { Registrar::IsRegistered; } }//namespace DP
30.9375
89
0.69899
ahfakt
84a60a737c7b8f8d0d5b2a4fb4ef18ae7f57846a
41,342
hpp
C++
Rx/v2/src/rxcpp/rx-subscriber.hpp
tcw165/RxCpp
677212214755dd282cc71c2263de87e1371f9293
[ "Apache-2.0" ]
null
null
null
Rx/v2/src/rxcpp/rx-subscriber.hpp
tcw165/RxCpp
677212214755dd282cc71c2263de87e1371f9293
[ "Apache-2.0" ]
null
null
null
Rx/v2/src/rxcpp/rx-subscriber.hpp
tcw165/RxCpp
677212214755dd282cc71c2263de87e1371f9293
[ "Apache-2.0" ]
null
null
null
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once #if !defined(RXCPP_RX_SUBSCRIBER_HPP) #define RXCPP_RX_SUBSCRIBER_HPP #include "rx-includes.hpp" namespace rxcpp { template<class T> struct subscriber_base : public observer_base<T>, public subscription_base { typedef tag_subscriber subscriber_tag; }; /*! \brief binds an observer that consumes values with a composite_subscription that controls lifetime. \ingroup group-core */ template<class T, class Observer = observer<T>> class subscriber : public subscriber_base<T> { static_assert(!is_subscriber<Observer>::value, "not allowed to nest subscribers"); static_assert(is_observer<Observer>::value, "subscriber must contain an observer<T, ...>"); typedef subscriber<T, Observer> this_type; typedef rxu::decay_t<Observer> observer_type; composite_subscription lifetime; observer_type destination; trace_id id; struct nextdetacher { ~nextdetacher() { trace_activity().on_next_return(*that); if (do_unsubscribe) { that->unsubscribe(); } } nextdetacher(const this_type* that) : that(that) , do_unsubscribe(true) { } template<class U> void operator()(U&& u) { trace_activity().on_next_enter(*that, u); RXCPP_TRY { that->destination.on_next(std::forward<U>(u)); do_unsubscribe = false; } RXCPP_CATCH(...) { auto ex = rxu::current_exception(); trace_activity().on_error_enter(*that, ex); that->destination.on_error(std::move(ex)); trace_activity().on_error_return(*that); } } const this_type* that; volatile bool do_unsubscribe; }; struct errordetacher { ~errordetacher() { trace_activity().on_error_return(*that); that->unsubscribe(); } errordetacher(const this_type* that) : that(that) { } inline void operator()(rxu::error_ptr ex) { trace_activity().on_error_enter(*that, ex); that->destination.on_error(std::move(ex)); } const this_type* that; }; struct completeddetacher { ~completeddetacher() { trace_activity().on_completed_return(*that); that->unsubscribe(); } completeddetacher(const this_type* that) : that(that) { } inline void operator()() { trace_activity().on_completed_enter(*that); that->destination.on_completed(); } const this_type* that; }; subscriber(); public: typedef typename composite_subscription::weak_subscription weak_subscription; subscriber(const this_type& o) : lifetime(o.lifetime) , destination(o.destination) , id(o.id) { } subscriber(this_type&& o) : lifetime(std::move(o.lifetime)) , destination(std::move(o.destination)) , id(std::move(o.id)) { } template<class U, class O> friend class subscriber; template<class O> subscriber( const subscriber<T, O>& o, typename std::enable_if< !std::is_same<O, observer<T>>::value && std::is_same<Observer, observer<T>>::value, void**>::type = nullptr) : lifetime(o.lifetime) , destination(o.destination.as_dynamic()) , id(o.id) { } template<class U> subscriber(trace_id id, composite_subscription cs, U&& o) : lifetime(std::move(cs)) , destination(std::forward<U>(o)) , id(std::move(id)) { static_assert(!is_subscriber<U>::value, "cannot nest subscribers"); static_assert(is_observer<U>::value, "must pass observer to subscriber"); trace_activity().create_subscriber(*this); } this_type& operator=(this_type o) { lifetime = std::move(o.lifetime); destination = std::move(o.destination); id = std::move(o.id); return *this; } const observer_type& get_observer() const { return destination; } observer_type& get_observer() { return destination; } const composite_subscription& get_subscription() const { return lifetime; } composite_subscription& get_subscription() { return lifetime; } trace_id get_id() const { return id; } subscriber<T> as_dynamic() const { return subscriber<T>(id, lifetime, destination.as_dynamic()); } // observer // template<class V> void on_next(V&& v) const { if (!is_subscribed()) { return; } nextdetacher protect(this); protect(std::forward<V>(v)); } void on_error(rxu::error_ptr e) const { if (!is_subscribed()) { return; } errordetacher protect(this); protect(std::move(e)); } void on_completed() const { if (!is_subscribed()) { return; } completeddetacher protect(this); protect(); } // composite_subscription // bool is_subscribed() const { return lifetime.is_subscribed(); } weak_subscription add(subscription s) const { return lifetime.add(std::move(s)); } template<class F> auto add(F f) const -> typename std::enable_if<detail::is_unsubscribe_function<F>::value, weak_subscription>::type { return lifetime.add(make_subscription(std::move(f))); } void remove(weak_subscription w) const { return lifetime.remove(std::move(w)); } void clear() const { return lifetime.clear(); } void unsubscribe() const { return lifetime.unsubscribe(); } }; template<class T, class Observer> auto make_subscriber( subscriber<T, Observer> o) -> subscriber<T, Observer> { return subscriber<T, Observer>(std::move(o)); } // observer // template<class T> auto make_subscriber() -> typename std::enable_if< detail::is_on_next_of<T, detail::OnNextEmpty<T>>::value, subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>>(trace_id::make_next_id_subscriber(), composite_subscription(), observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>(detail::OnNextEmpty<T>())); } template<class T, class I> auto make_subscriber( const observer<T, I>& o) -> subscriber<T, observer<T, I>> { return subscriber<T, observer<T, I>>(trace_id::make_next_id_subscriber(), composite_subscription(), o); } template<class T, class Observer> auto make_subscriber(const Observer& o) -> typename std::enable_if< is_observer<Observer>::value && !is_subscriber<Observer>::value, subscriber<T, Observer>>::type { return subscriber<T, Observer>(trace_id::make_next_id_subscriber(), composite_subscription(), o); } template<class T, class Observer> auto make_subscriber(const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { return subscriber<T, observer<T, Observer>>(trace_id::make_next_id_subscriber(), composite_subscription(), o); } template<class T, class OnNext> auto make_subscriber(const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(trace_id::make_next_id_subscriber(), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext>(on)); } template<class T, class OnNext, class OnError> auto make_subscriber(const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(trace_id::make_next_id_subscriber(), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); } template<class T, class OnNext, class OnCompleted> auto make_subscriber(const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(trace_id::make_next_id_subscriber(), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); } template<class T, class OnNext, class OnError, class OnCompleted> auto make_subscriber(const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(trace_id::make_next_id_subscriber(), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); } // explicit lifetime // template<class T> auto make_subscriber(const composite_subscription& cs) -> subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>> { return subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>(detail::OnNextEmpty<T>())); } template<class T, class I> auto make_subscriber(const composite_subscription& cs, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { return subscriber<T, observer<T, I>>(trace_id::make_next_id_subscriber(), cs, o); } template<class T, class I> auto make_subscriber(const composite_subscription& cs, const subscriber<T, I>& s) -> subscriber<T, I> { return subscriber<T, I>(trace_id::make_next_id_subscriber(), cs, s.get_observer()); } template<class T, class Observer> auto make_subscriber(const composite_subscription& cs, const Observer& o) -> typename std::enable_if< !is_subscriber<Observer>::value && is_observer<Observer>::value, subscriber<T, Observer>>::type { return subscriber<T, Observer>(trace_id::make_next_id_subscriber(), cs, o); } template<class T, class Observer> auto make_subscriber(const composite_subscription& cs, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { return subscriber<T, observer<T, Observer>>(trace_id::make_next_id_subscriber(), cs, make_observer<T>(o)); } template<class T, class OnNext> auto make_subscriber(const composite_subscription& cs, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext>(on)); } template<class T, class OnNext, class OnError> auto make_subscriber(const composite_subscription& cs, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); } template<class T, class OnNext, class OnCompleted> auto make_subscriber(const composite_subscription& cs, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); } template<class T, class OnNext, class OnError, class OnCompleted> auto make_subscriber(const composite_subscription& cs, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); } // explicit id // template<class T> auto make_subscriber(trace_id id) -> subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>> { return subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>>(std::move(id), composite_subscription(), observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>(detail::OnNextEmpty<T>())); } template<class T> auto make_subscriber(trace_id id, const composite_subscription& cs) -> subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>> { return subscriber<T, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, detail::OnNextEmpty<T>>(detail::OnNextEmpty<T>())); } template<class T, class I> auto make_subscriber(trace_id id, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { return subscriber<T, observer<T, I>>(std::move(id), composite_subscription(), o); } template<class T, class I> auto make_subscriber(trace_id id, const composite_subscription& cs, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { return subscriber<T, observer<T, I>>(std::move(id), cs, o); } template<class T, class Observer> auto make_subscriber(trace_id id, const Observer& o) -> typename std::enable_if< is_observer<Observer>::value, subscriber<T, Observer>>::type { return subscriber<T, Observer>(std::move(id), composite_subscription(), o); } template<class T, class Observer> auto make_subscriber(trace_id id, const composite_subscription& cs, const Observer& o) -> typename std::enable_if< is_observer<Observer>::value, subscriber<T, Observer>>::type { return subscriber<T, Observer>(std::move(id), cs, o); } template<class T, class Observer> auto make_subscriber(trace_id id, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { return subscriber<T, observer<T, Observer>>(std::move(id), composite_subscription(), o); } template<class T, class Observer> auto make_subscriber(trace_id id, const composite_subscription& cs, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { return subscriber<T, observer<T, Observer>>(std::move(id), cs, o); } template<class T, class OnNext> auto make_subscriber(trace_id id, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(std::move(id), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext>(on)); } template<class T, class OnNext> auto make_subscriber(trace_id id, const composite_subscription& cs, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext>(on)); } template<class T, class OnNext, class OnError> auto make_subscriber(trace_id id, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(std::move(id), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); } template<class T, class OnNext, class OnError> auto make_subscriber(trace_id id, const composite_subscription& cs, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); } template<class T, class OnNext, class OnCompleted> auto make_subscriber(trace_id id, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(std::move(id), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); } template<class T, class OnNext, class OnCompleted> auto make_subscriber(trace_id id, const composite_subscription& cs, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); } template<class T, class OnNext, class OnError, class OnCompleted> auto make_subscriber(trace_id id, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(std::move(id), composite_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); } template<class T, class OnNext, class OnError, class OnCompleted> auto make_subscriber(trace_id id, const composite_subscription& cs, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { return subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); } // chain defaults from subscriber // template<class T, class OtherT, class OtherObserver, class I> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { auto r = subscriber<T, observer<T, I>>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class I> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { auto r = subscriber<T, observer<T, I>>(std::move(id), scbr.get_subscription(), o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const Observer& o) -> typename std::enable_if< is_observer<Observer>::value, subscriber<T, Observer>>::type { auto r = subscriber<T, Observer>(std::move(id), scbr.get_subscription(), o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const Observer& o) -> typename std::enable_if< !is_subscription<Observer>::value && is_observer<Observer>::value, subscriber<T, Observer>>::type { auto r = subscriber<T, Observer>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { auto r = subscriber<T, observer<T, Observer>>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), make_observer<T>(o)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { auto r = subscriber<T, observer<T, Observer>>(std::move(id), scbr.get_subscription(), o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext>(on)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(std::move(id), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext>(on)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(std::move(id), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(std::move(id), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(trace_id::make_next_id_subscriber(), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(std::move(id), scbr.get_subscription(), observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class I> auto make_subscriber(const subscriber<OtherT, OtherObserver>& , const composite_subscription& cs, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { return subscriber<T, observer<T, I>>(trace_id::make_next_id_subscriber(), cs, o); } template<class T, class OtherT, class OtherObserver, class I> auto make_subscriber(const subscriber<OtherT, OtherObserver>&, trace_id id, const composite_subscription& cs, const observer<T, I>& o) -> subscriber<T, observer<T, I>> { return subscriber<T, observer<T, I>>(std::move(id), cs, o); } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const composite_subscription& cs, const Observer& o) -> typename std::enable_if< is_observer<Observer>::value, subscriber<T, Observer>>::type { auto r = subscriber<T, Observer>(trace_id::make_next_id_subscriber(), cs, o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const composite_subscription& cs, const Observer& o) -> typename std::enable_if< is_observer<Observer>::value, subscriber<T, Observer>>::type { auto r = subscriber<T, Observer>(std::move(id), cs, o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const composite_subscription& cs, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { auto r = subscriber<T, observer<T, Observer>>(trace_id::make_next_id_subscriber(), cs, o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class Observer> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const composite_subscription& cs, const Observer& o) -> typename std::enable_if< !detail::is_on_next_of<T, Observer>::value && !is_subscriber<Observer>::value && !is_subscription<Observer>::value && !is_observer<Observer>::value, subscriber<T, observer<T, Observer>>>::type { auto r = subscriber<T, observer<T, Observer>>(std::move(id), cs, o); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const composite_subscription& cs, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext>(on)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const composite_subscription& cs, const OnNext& on) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext>(on)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const composite_subscription& cs, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const composite_subscription& cs, const OnNext& on, const OnError& oe) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError>(on, oe)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const composite_subscription& cs, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const composite_subscription& cs, const OnNext& on, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext, detail::OnErrorEmpty, OnCompleted>(on, detail::OnErrorEmpty(), oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, const composite_subscription& cs, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(trace_id::make_next_id_subscriber(), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); trace_activity().connect(r, scbr); return r; } template<class T, class OtherT, class OtherObserver, class OnNext, class OnError, class OnCompleted> auto make_subscriber(const subscriber<OtherT, OtherObserver>& scbr, trace_id id, const composite_subscription& cs, const OnNext& on, const OnError& oe, const OnCompleted& oc) -> typename std::enable_if< detail::is_on_next_of<T, OnNext>::value && detail::is_on_error<OnError>::value && detail::is_on_completed<OnCompleted>::value, subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>>::type { auto r = subscriber<T, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>>(std::move(id), cs, observer<T, detail::stateless_observer_tag, OnNext, OnError, OnCompleted>(on, oe, oc)); trace_activity().connect(r, scbr); return r; } template<class T, class Observer> auto make_subscriber(const subscriber<T, Observer>& scbr, const composite_subscription& cs) -> subscriber<T, Observer> { auto r = subscriber<T, Observer>(scbr.get_id(), cs, scbr.get_observer()); trace_activity().connect(r, scbr); return r; } template<class T, class Observer> auto make_subscriber(const subscriber<T, Observer>& scbr, trace_id id, const composite_subscription& cs) -> subscriber<T, Observer> { auto r = subscriber<T, Observer>(std::move(id), cs, scbr.get_observer()); trace_activity().connect(r, scbr); return r; } template<class T, class Observer> auto make_subscriber(const subscriber<T, Observer>& scbr, trace_id id) -> subscriber<T, Observer> { auto r = subscriber<T, Observer>(std::move(id), scbr.get_subscription(), scbr.get_observer()); trace_activity().connect(r, scbr); return r; } } #endif
49.452153
178
0.67048
tcw165
84a87a2b9a2de1f6125bf1422ec80a49ac473d7d
1,947
cpp
C++
TFX/src/core/Logger.cpp
DCubix/TFX
537f512b1bcc48cbdb592c82ef50a281ca6f4e4a
[ "MIT" ]
null
null
null
TFX/src/core/Logger.cpp
DCubix/TFX
537f512b1bcc48cbdb592c82ef50a281ca6f4e4a
[ "MIT" ]
null
null
null
TFX/src/core/Logger.cpp
DCubix/TFX
537f512b1bcc48cbdb592c82ef50a281ca6f4e4a
[ "MIT" ]
null
null
null
#include "Logger.h" #include <fstream> #include <assert.h> #include "termcolor.hpp" namespace tfx { #ifdef TFX_DEBUG Logger Logger::logger = Logger(); std::ofstream& Logger::logFile = std::ofstream(); #else std::ofstream& Logger::logFile = std::ofstream("Log_" + Util::currentDateTimeNoFormat() + ".txt"); Logger Logger::logger = Logger(Logger::logFile); #endif Logger::Logger() : m_output(std::cout) { } Logger::Logger(std::ostream& output) : m_output(output) { if (m_output.bad()) { assert(false); } } Logger::~Logger() { m_output.flush(); static std::stringstream closed_flag; m_output.rdbuf(closed_flag.rdbuf()); if (logFile) { logFile.close(); } } void Logger::print(LogLevel level, const char* file, const char* function, int line, const String& msg) { // [12/12/2017 23:45] => [ERROR] [func@33] Test error! String prefx = "[" + Util::currentDateTime() + "] => "; String filen = file; filen = filen.replace(R"(\)", "/"); filen = filen.subStr(filen.lastIndexOf(String("/"))+1); #ifdef TFX_DEBUG m_output << termcolor::green << termcolor::dark; #endif m_output << prefx.str(); #ifdef TFX_DEBUG switch (level) { case LogLevel::Debug: m_output << termcolor::cyan; break; case LogLevel::Info: m_output << termcolor::blue; break; case LogLevel::Warning: m_output << termcolor::yellow; break; case LogLevel::Error: m_output << termcolor::red; break; case LogLevel::Fatal: m_output << termcolor::magenta; break; } #endif switch (level) { case LogLevel::Debug: m_output << "[DEBG]"; break; case LogLevel::Info: m_output << "[INFO]"; break; case LogLevel::Warning: m_output << "[WARN]"; break; case LogLevel::Error: m_output << "[ERROR]"; break; case LogLevel::Fatal: m_output << "[FATAL]"; break; } #ifdef TFX_DEBUG m_output << termcolor::reset; #endif m_output << " [" << filen << "(" << function << " @ " << line << ")] " << msg << std::endl; } }
27.041667
106
0.644068
DCubix
84a89b5d825f668a546c48f76858f9e5c6344d8d
2,590
cpp
C++
src/swift2d/audio/Sound.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/audio/Sound.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/audio/Sound.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2015 Simon Schneegans & Felix Lauer // // // // This software may be modified and distributed under the terms // // of the MIT license. See the LICENSE file for details. // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/audio/Sound.hpp> #include <sndfile.h> #include <vector> #include <array> namespace swift { //////////////////////////////////////////////////////////////////////////////// Sound::Sound() { FileName.on_change().connect([this](std::string const& file) { load_from_file(file); return true; }); } //////////////////////////////////////////////////////////////////////////////// void Sound::load_from_file(std::string const& file_name) { SF_INFO info; SNDFILE* file = sf_open(file_name.c_str(), SFM_READ, &info); int error(sf_error(file)); if (error) { LOG_WARNING << "Error loading audio file \"" << file_name << "\": " << sf_error_number(error) << std::endl; } std::vector<short> data(info.channels * info.frames); sf_readf_short(file, data.data(), info.frames); buffer_.Data(info.channels == 1 ? oalplus::DataFormat::Mono16 : oalplus::DataFormat::Stereo16, &data.front(), data.size() * sizeof(short), info.samplerate); sf_close(file); } //////////////////////////////////////////////////////////////////////////////// void Sound::load(oalplus::Source* source) { source->Buffer(buffer_); } //////////////////////////////////////////////////////////////////////////////// void Sound::unload(oalplus::Source* source) { source->DetachBuffers(); } //////////////////////////////////////////////////////////////////////////////// void Sound::accept(SavableObjectVisitor& visitor) { AudioBuffer::accept(visitor); visitor.add_member("FileName", FileName); } //////////////////////////////////////////////////////////////////////////////// }
35
80
0.360618
Simmesimme
84a8ad07b63e9345704aab5c53de3c6625546eaf
17,117
cc
C++
v11/runtime/node/devices.cc
InclusiveTechNU/v11
d32357bf52f5d6cf4ad3002235d1144f1f347d96
[ "Apache-2.0" ]
4
2020-04-26T10:19:45.000Z
2021-11-22T18:24:16.000Z
v11/runtime/node/devices.cc
InclusiveTechNU/v11
d32357bf52f5d6cf4ad3002235d1144f1f347d96
[ "Apache-2.0" ]
21
2020-01-08T12:23:00.000Z
2020-11-24T05:47:25.000Z
v11/runtime/node/devices.cc
InclusiveTechNU/v11
d32357bf52f5d6cf4ad3002235d1144f1f347d96
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Northwestern Inclusive Technology Lab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <functional> #include <vector> #include <string> #include "runtime/node/devices.h" #include "runtime/node/sound_utils.h" #include "runtime/node/utils.h" #include "core/system/system_instance.h" #include "core/system/system.h" #include "core/devices/sound/text2speech/voice.h" #include "core/devices/sound/text2speech/text2speech_synthesizer.h" #include "core/devices/sound/text2speech/text2speech_synthesizer_bridge.h" #include "core/devices/keyboard/keyboard_simulator.h" #include "core/devices/keyboard/keyboard_listener.h" #include "core/devices/keyboard/keyboard_event.h" #include "core/devices/keyboard/keycode.h" using utils::string_from_value; using utils::keyboard_event_to_object; using keyboard::keycode; using keyboard::KeyboardSimulator; using sound::voice::Text2SpeechSynthesizer; using sound::voice::Text2SpeechSynthesizerBridge; using sound::voice::Voice; using sound::voice::SpeechDidFinishCallback; using keyboard::KeyboardListener; using keyboard::event::event_type; using keyboard::event::KeyboardEvent; using devices::utils::sound::voice_to_object; using sys::SystemInstance; using sys::System; namespace devices { napi_status sound(napi_env env, napi_value exports) { napi_status status; // ***************************** // * Speech API Interface // ***************************** napi_value speech; status = napi_create_object(env, &speech); if (status != napi_ok) return status; // * speech.getVoices() -> Array<Object> // Returns a list of system voices as Voice class objects napi_value get_sys_voices; status = napi_create_function(env, nullptr, 0, [](napi_env env, napi_callback_info info) -> napi_value { napi_status status; napi_value system_voices; status = napi_create_array(env, &system_voices); if (status != napi_ok) return nullptr; // Fill system voices with mapped Voice class to JS Object std::vector<const Voice*> sys_voices = Voice::get_system_voices(); for (size_t i = 0; i < sys_voices.size(); i++) { // Create voice object and set to index of i const Voice* voice = sys_voices[i]; napi_value voice_object; status = napi_create_object(env, &voice_object); if (status != napi_ok) return nullptr; status = voice_to_object(env, voice, voice_object); if (status != napi_ok) return nullptr; status = napi_set_element(env, system_voices, i, voice_object); if (status != napi_ok) return nullptr; delete voice; } return system_voices; }, nullptr, &get_sys_voices); if (status != napi_ok) return status; status = napi_set_named_property(env, speech, "getVoices", get_sys_voices); if (status != napi_ok) return status; // * speech.getDefaultVoice() -> Object // Returns the default voice object of the system napi_value get_default_voice; status = napi_create_function(env, nullptr, 0, [](napi_env env, napi_callback_info info) -> napi_value { // Create a voice object from the default native system voice napi_status status; napi_value system_voice_object; const Voice* sys_voice = Voice::get_default_voice(); status = napi_create_object(env, &system_voice_object); if (status != napi_ok) return nullptr; status = voice_to_object(env, sys_voice, system_voice_object); delete sys_voice; return system_voice_object; }, nullptr, &get_default_voice); if (status != napi_ok) return status; status = napi_set_named_property(env, speech, "getDefaultVoice", get_default_voice); if (status != napi_ok) return status; // * speech.speak(text: string, voice_id: string) -> void // Calls the native speach synthesis API with the specific voice declared napi_value speak; status = napi_create_function(env, nullptr, 0, [](napi_env env, napi_callback_info info) -> napi_value { // TODO(tommymchugh): Evoke error on failed to collect arguments napi_status status; // Collect text and voice_id from info size_t args_count = 3; napi_value args[3]; status = napi_get_cb_info(env, info, &args_count, args, nullptr, 0); if (status != napi_ok) return nullptr; napi_value text_object = args[0]; napi_value voice_id_object = args[1]; char* text_ptr = string_from_value(env, text_object); char* voice_id_ptr = string_from_value(env, voice_id_object); if (!text_ptr || !voice_id_ptr) return nullptr; // TODO(tommymchugh): Figure out how to check for null for callback // Create async thread-safe callback function // Handle the threadsafe call by sending Notification into callback typedef napi_threadsafe_function_call_js ts_callback; ts_callback speech_cb = [](napi_env env, napi_value js_cb, void* context, void* data) { napi_value undefined; a_ok(napi_get_undefined(env, &undefined)); a_ok(napi_call_function(env, undefined, js_cb, 0, nullptr, nullptr)); }; napi_value listener_callback_object = args[2]; napi_threadsafe_function listener_callback; napi_value res_name; napi_create_string_utf8(env, "resource", NAPI_AUTO_LENGTH, &res_name); if (status != napi_ok) return nullptr; status = napi_create_threadsafe_function(env, listener_callback_object, nullptr, res_name, 0, 2, nullptr, nullptr, nullptr, speech_cb, &listener_callback); if (status != napi_ok) return nullptr; // Send speech request to the native core interface const Voice* speaking_voice = Voice::get_voice_by_id(voice_id_ptr); if (speaking_voice != nullptr) { Text2SpeechSynthesizer* speech_synth = new Text2SpeechSynthesizer(); Text2SpeechSynthesizerBridge* speech_bridge = speech_synth-> get_bridge(); /* SpeechDidFinishCallback* speech_callback = new SpeechDidFinishCallback([&]() { napi_acquire_threadsafe_function(listener_callback); napi_call_threadsafe_function(listener_callback, nullptr, napi_tsfn_blocking); delete speaking_voice; delete speech_synth; }); speech_bridge->set_callback(speech_callback);*/ speech_synth->speak(text_ptr, speaking_voice); } else { // TODO(tommymchugh): throw error for no speaking } return nullptr; }, nullptr, &speak); if (status != napi_ok) return status; status = napi_set_named_property(env, speech, "speak", speak); if (status != napi_ok) return status; // Declare and place speech api binding within v11.speech status = napi_set_named_property(env, exports, "speech", speech); if (status != napi_ok) return status; return status; } napi_status keyboard(napi_env env, napi_value exports) { napi_status status; napi_value keyboard; status = napi_create_object(env, &keyboard); if (status != napi_ok) return status; // ***************************** // * KEY SIM API Interface // ***************************** napi_value simulate; status = napi_create_object(env, &simulate); if (status != napi_ok) return status; napi_value hold_key; status = napi_create_function(env, nullptr, 0, [](napi_env env, napi_callback_info info) -> napi_value { // TODO(tommymchugh): Evoke error on failed to collect arguments napi_status status; // Collect character to hold size_t args_count = 1; napi_value args[1]; status = napi_get_cb_info(env, info, &args_count, args, nullptr, 0); if (status != napi_ok) return nullptr; napi_value key_to_press_obj = args[0]; int32_t key_code = 0; a_ok(napi_get_value_int32(env, key_to_press_obj, &key_code)); uint32_t conv_key_code = (uint32_t) key_code; KeyboardSimulator simulator = KeyboardSimulator(); simulator.press_key(keyboard::uint_to_keycode(conv_key_code)); return nullptr; }, nullptr, &hold_key); if (status != napi_ok) return status; status = napi_set_named_property(env, simulate, "holdKey", hold_key); if (status != napi_ok) return status; napi_value release_key; status = napi_create_function(env, nullptr, 0, [](napi_env env, napi_callback_info info) -> napi_value { // TODO(tommymchugh): Evoke error on failed to collect arguments napi_status status; // Collect character to release size_t args_count = 1; napi_value args[1]; status = napi_get_cb_info(env, info, &args_count, args, nullptr, 0); if (status != napi_ok) return nullptr; napi_value key_to_press_obj = args[0]; int32_t key_code = 0; a_ok(napi_get_value_int32(env, key_to_press_obj, &key_code)); uint32_t conv_key_code = (uint32_t) key_code; KeyboardSimulator simulator = KeyboardSimulator(); simulator.release_key(keyboard::uint_to_keycode(conv_key_code)); return nullptr; }, nullptr, &release_key); if (status != napi_ok) return status; status = napi_set_named_property(env, simulate, "releaseKey", release_key); if (status != napi_ok) return status; status = napi_set_named_property(env, keyboard, "simulation", simulate); if (status != napi_ok) return status; // ***************************** // * KEY LISTENER API Interface // ***************************** napi_value listener_key; status = napi_create_function(env, nullptr, 0, [](napi_env env, napi_callback_info info) -> napi_value { // Retrieve sys_ptr data napi_status status; void* sys_void_ptr = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, nullptr, &sys_void_ptr); if (!sys_void_ptr) { // TODO(tommymchugh): Faill on system pointer cannot be found return nullptr; } System* sys_ptr = reinterpret_cast<System*>(sys_void_ptr); // TODO(tommymchugh): Manage through system devices api KeyboardListener* keyboard_listener = new KeyboardListener; // TODO(tommymchugh): Evoke error on failed to collect arguments // Collect text and voice_id from info size_t args_count = 2; napi_value args[2]; status = napi_get_cb_info(env, info, &args_count, args, nullptr, 0); if (status != napi_ok) return nullptr; napi_value listener_type_object = args[0]; char* listener_type_ptr = string_from_value(env, listener_type_object); std::string listener_type_str = std::string(listener_type_ptr); delete listener_type_ptr; // TODO(tommymchugh): Figure out how to check for null for callback // Create async thread-safe callback function // Handle the threadsafe call by sending Notification into callback typedef napi_threadsafe_function_call_js ts_callback; ts_callback notification_cb = [](napi_env env, napi_value js_cb, void* context, void* data) { // Convert data to KeyboardEvent type KeyboardEvent* event = reinterpret_cast<KeyboardEvent*>(data); // TODO(tommymchugh): determine proper context not undef napi_value undefined, event_object; keyboard_event_to_object(env, event, &event_object); a_ok(napi_get_undefined(env, &undefined)); a_ok(napi_call_function(env, undefined, js_cb, 1, &event_object, nullptr)); delete event; }; napi_value listener_callback_object = args[1]; napi_threadsafe_function listener_callback; napi_value res_name; napi_create_string_utf8(env, "resource", NAPI_AUTO_LENGTH, &res_name); if (status != napi_ok) return nullptr; status = napi_create_threadsafe_function(env, listener_callback_object, nullptr, res_name, 0, 2, nullptr, nullptr, nullptr, notification_cb, &listener_callback); if (status != napi_ok) return nullptr; if (listener_type_str == "press") { keyboard_listener->add_event_listener(event_type::KEY_DOWN, [listener_callback] (KeyboardEvent* event) { napi_acquire_threadsafe_function(listener_callback); napi_call_threadsafe_function(listener_callback, reinterpret_cast<void*>(event), napi_tsfn_blocking); }); } else if (listener_type_str == "release") { keyboard_listener->add_event_listener(event_type::KEY_UP, [listener_callback] (KeyboardEvent* event) { napi_acquire_threadsafe_function(listener_callback); napi_call_threadsafe_function(listener_callback, reinterpret_cast<void*>(event), napi_tsfn_blocking); }); } else { // TODO(tommymchugh): Handle unknown listener type } return nullptr; }, SystemInstance::GetInstance(), &listener_key); if (status != napi_ok) return status; status = napi_set_named_property(env, keyboard, "addEventListener", listener_key); if (status != napi_ok) return status; // Declare and place keyboards apis binding within v11.keyboard status = napi_set_named_property(env, exports, "keyboard", keyboard); if (status != napi_ok) return status; return status; } // Initialize all variables and functions void init(napi_env env, napi_value exports) { napi_status sound_status = sound(env, exports); if (sound_status != napi_ok) { napi_throw_error(env, nullptr, "Failed to initialize devices/sound"); return; } napi_status keyboard_status = keyboard(env, exports); if (keyboard_status != napi_ok) { napi_throw_error(env, nullptr, "Failed to initialize devices/keyboard"); return; } } } // namespace devices
43.224747
79
0.573056
InclusiveTechNU
84a993efb1c3526dde6d068a92090975c21ebafd
383
cpp
C++
LAB 1 ASSIGNMENTS/Task_5 Lab_1.cpp
ZapeeoSheikh/Cppfactory
7bdf9c6dd8053a506f17fc4a0aa2093f06d2be70
[ "MIT" ]
null
null
null
LAB 1 ASSIGNMENTS/Task_5 Lab_1.cpp
ZapeeoSheikh/Cppfactory
7bdf9c6dd8053a506f17fc4a0aa2093f06d2be70
[ "MIT" ]
null
null
null
LAB 1 ASSIGNMENTS/Task_5 Lab_1.cpp
ZapeeoSheikh/Cppfactory
7bdf9c6dd8053a506f17fc4a0aa2093f06d2be70
[ "MIT" ]
null
null
null
//task_5(sales prediction) #include <iostream> using namespace std; main() { float total_sale,sale_of_year; total_sale = 0.62; sale_of_year= 680; cout<<"Percentage of total sale in decimal is: "<<total_sale <<endl; cout<<"Sale of this year is:"<< sale_of_year<<" million"<<endl; cout<<"Predicted sale is:"<<total_sale*sale_of_year; return 0; }
22.529412
71
0.660574
ZapeeoSheikh
84a9c08e981cb1f6e68f650472643971de32a9f5
969
cpp
C++
src/_PathMovetoRel.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
136
2015-07-15T12:49:36.000Z
2022-03-24T12:30:25.000Z
src/_PathMovetoRel.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
59
2015-12-28T21:40:37.000Z
2022-03-31T13:11:50.000Z
src/_PathMovetoRel.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
33
2015-12-04T08:00:07.000Z
2022-01-28T23:39:25.000Z
#include <boost/python.hpp> #include <boost/cstdint.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost::python; namespace { struct Magick_PathMovetoRel_Wrapper: Magick::PathMovetoRel { Magick_PathMovetoRel_Wrapper(PyObject* py_self_, const Magick::Coordinate& p0): Magick::PathMovetoRel(p0), py_self(py_self_) {} Magick_PathMovetoRel_Wrapper(PyObject* py_self_, const Magick::CoordinateList& p0): Magick::PathMovetoRel(p0), py_self(py_self_) {} Magick_PathMovetoRel_Wrapper(PyObject* py_self_, const Magick::PathMovetoRel& p0): Magick::PathMovetoRel(p0), py_self(py_self_) {} PyObject* py_self; }; } void __PathMovetoRel() { class_< Magick::PathMovetoRel, bases<Magick::VPathBase>, Magick_PathMovetoRel_Wrapper >("PathMovetoRel", init< const Magick::Coordinate& >()) .def(init< const Magick::CoordinateList& >()) .def(init< const Magick::PathMovetoRel& >()) ; }
25.5
145
0.712074
veryhappythings
84aa92c516286857f6916ebd1adb24b5273a2636
2,285
cpp
C++
test/case/intrusive_ptr_test.cpp
tangzhenquan/atframe_utils
94a41a89cbc65a62102a8ac0f98b4b340b2bb8ef
[ "MIT" ]
null
null
null
test/case/intrusive_ptr_test.cpp
tangzhenquan/atframe_utils
94a41a89cbc65a62102a8ac0f98b4b340b2bb8ef
[ "MIT" ]
null
null
null
test/case/intrusive_ptr_test.cpp
tangzhenquan/atframe_utils
94a41a89cbc65a62102a8ac0f98b4b340b2bb8ef
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstring> #include <cstring> #include <ctime> #include <memory> #include <sstream> #include "frame/test_macros.h" #include "std/smart_ptr.h" struct intrusive_ptr_test_clazz { int ref_count; int *del_count; intrusive_ptr_test_clazz(int *dc) : ref_count(0), del_count(dc) {} ~intrusive_ptr_test_clazz() { ++(*del_count); } friend void intrusive_ptr_add_ref(intrusive_ptr_test_clazz *p) { CASE_EXPECT_NE(p, NULL); if (NULL != p) { ++p->ref_count; } } friend void intrusive_ptr_release(intrusive_ptr_test_clazz *p) { CASE_EXPECT_NE(p, NULL); if (NULL != p) { --p->ref_count; if (0 == p->ref_count) { delete p; } } } }; CASE_TEST(smart_ptr, intrusive_ptr_int) { typedef std::intrusive_ptr<intrusive_ptr_test_clazz> ptr_t; int delete_count = 0; { ptr_t p = ptr_t(new intrusive_ptr_test_clazz(&delete_count)); CASE_EXPECT_EQ(p->ref_count, 1); { ptr_t p2(p); CASE_EXPECT_EQ(p->ref_count, 2); } CASE_EXPECT_EQ(p->ref_count, 1); #if defined(UTIL_CONFIG_COMPILER_CXX_RVALUE_REFERENCES) && UTIL_CONFIG_COMPILER_CXX_RVALUE_REFERENCES { ptr_t p2(p); CASE_EXPECT_EQ(p->ref_count, 2); ptr_t prv(std::move(p2)); CASE_EXPECT_EQ(p->ref_count, 2); CASE_EXPECT_EQ(p2.get(), NULL); CASE_EXPECT_NE(prv.get(), NULL); } { ptr_t p2(p); CASE_EXPECT_EQ(p->ref_count, 2); ptr_t prv; prv = std::move(p2); CASE_EXPECT_EQ(p->ref_count, 2); CASE_EXPECT_EQ(p2.get(), NULL); CASE_EXPECT_NE(prv.get(), NULL); } #endif { ptr_t p2(p); CASE_EXPECT_EQ(p->ref_count, 2); p2.reset(NULL); CASE_EXPECT_EQ(p->ref_count, 1); CASE_EXPECT_EQ(p2.get(), NULL); CASE_EXPECT_TRUE(p); CASE_EXPECT_FALSE(p2); } CASE_EXPECT_EQ(delete_count, 0); } CASE_EXPECT_EQ(delete_count, 1); }
25.674157
102
0.538731
tangzhenquan
84b10283525bfd0571d906787216e039f6a913ae
4,271
cpp
C++
src/accounting/UserConversionRates.cpp
vimofthevine/UnderBudget
5711be8e5da3cb7a78da007fe43cf1ce1b796493
[ "Apache-2.0" ]
2
2016-07-17T02:12:44.000Z
2016-11-22T14:04:55.000Z
src/accounting/UserConversionRates.cpp
vimofthevine/UnderBudget
5711be8e5da3cb7a78da007fe43cf1ce1b796493
[ "Apache-2.0" ]
null
null
null
src/accounting/UserConversionRates.cpp
vimofthevine/UnderBudget
5711be8e5da3cb7a78da007fe43cf1ce1b796493
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 Kyle Treubig * * 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. */ // Qt include(s) #include <QtCore> #include <QtSql> // UnderBudget include(s) #include "accounting/UserConversionRates.hpp" namespace ub { //------------------------------------------------------------------------------ const QString UserConversionRates::connection = "UserConversionRates"; const QString UserConversionRates::createTableQuery = "CREATE TABLE IF NOT EXISTS rates " "(id INTEGER PRIMARY KEY, source TEXT, target TEXT, rate REAL);"; const QString UserConversionRates::createIndexQuery = "CREATE UNIQUE INDEX IF NOT EXISTS source_target ON rates " "(source, target);"; const QString UserConversionRates::insertConversionQuery = "INSERT OR REPLACE INTO rates (source, target, rate) " "VALUES(:source, :target, :rate);"; const QString UserConversionRates::removeConversionQuery = "DELETE FROM rates WHERE source=:source AND target=:target;"; const QString UserConversionRates::retrieveConversionQuery = "SELECT rate FROM rates WHERE source=:source AND target=:target;"; //------------------------------------------------------------------------------ void UserConversionRates::open(const QString& filename) { // make sure connection is registered QSqlDatabase db = QSqlDatabase::database(connection, false); if ( ! db.isValid()) { db = QSqlDatabase::addDatabase("QSQLITE", connection); } // make sure previous database is closed if (db.isOpen()) { // if any other database instances exist right at this moment, // they also will be closed and their queries invalidated db.close(); } // open database file db.setDatabaseName(filename); if ( ! db.open()) { qWarning() << "Unable to open conversion rates file, " << filename; } else { QSqlQuery createQuery(createTableQuery, db); createQuery.exec(); if (createQuery.lastError().isValid()) { qWarning() << "Error creating conversion rates table: " << createQuery.lastError(); } else { QSqlQuery indexQuery(createIndexQuery, db); indexQuery.exec(); if (indexQuery.lastError().isValid()) { qWarning() << "Error creating unique index: " << indexQuery.lastError(); } } } } //------------------------------------------------------------------------------ void UserConversionRates::add(const QString& source, const QString& target, double rate) { QSqlQuery insertQuery(QSqlDatabase::database(connection)); insertQuery.prepare(insertConversionQuery); insertQuery.bindValue(":source", source); insertQuery.bindValue(":target", target); insertQuery.bindValue(":rate", rate); insertQuery.exec(); if (insertQuery.lastError().isValid()) { qWarning() << insertQuery.lastError(); } } //------------------------------------------------------------------------------ void UserConversionRates::remove(const QString& source, const QString& target) { QSqlQuery removeQuery(QSqlDatabase::database(connection)); removeQuery.prepare(removeConversionQuery); removeQuery.bindValue(":source", source); removeQuery.bindValue(":target", target); removeQuery.exec(); if (removeQuery.lastError().isValid()) { qWarning() << removeQuery.lastError(); } } //------------------------------------------------------------------------------ double UserConversionRates::get(const QString& source, const QString& target) const { // If no conversion necessary if (source == target) { return 1.0; } QSqlQuery retrieveQuery(QSqlDatabase::database(connection)); retrieveQuery.prepare(retrieveConversionQuery); retrieveQuery.bindValue(":source", source); retrieveQuery.bindValue(":target", target); retrieveQuery.exec(); if (retrieveQuery.next()) { return retrieveQuery.value(0).toDouble(); } else { return 1.0; } } }
28.66443
83
0.660969
vimofthevine
84b3f8d7c2fd894e56ab8fb4cc46f0769eeb959f
804
cpp
C++
src/Client/src/upload.cpp
wanderingThroughSpaceAndTime/Dropbox
d704a1c24f3d21571d9779bb8e5e61a8da9cc97f
[ "MIT" ]
null
null
null
src/Client/src/upload.cpp
wanderingThroughSpaceAndTime/Dropbox
d704a1c24f3d21571d9779bb8e5e61a8da9cc97f
[ "MIT" ]
null
null
null
src/Client/src/upload.cpp
wanderingThroughSpaceAndTime/Dropbox
d704a1c24f3d21571d9779bb8e5e61a8da9cc97f
[ "MIT" ]
null
null
null
#include "upload.h" #include "ui_upload.h" #include <QFileSystemModel> upload::upload(QWidget *parent) : QDialog(parent), ui(new Ui::upload) { ui->setupUi(this); QString path(getenv("HOME")); dirmodel = new QFileSystemModel(this); dirmodel->setFilter(QDir::NoDotAndDotDot | QDir::AllDirs); dirmodel->setRootPath(path); ui->treeView->setModel(dirmodel); filemodel = new QFileSystemModel(this); filemodel->setFilter(QDir::NoDotAndDotDot | QDir::Files); filemodel->setRootPath(path); ui->listView->setModel(filemodel); } upload::~upload() { delete ui; } void upload::on_treeView_clicked(const QModelIndex &index) { QString path = filemodel->fileInfo(index).absoluteFilePath(); ui->listView->setRootIndex(filemodel->setRootPath(path)); }
21.72973
65
0.69403
wanderingThroughSpaceAndTime
84b4c09d8f641a949a8ec4810ad51e53f8622ead
37,915
cpp
C++
native_addon/wj_image/image_win.cpp
SafeOnlineWorld/web_jsx
7ce26957e40c4e6658042d4f2e6f3d93a77b709f
[ "CC-BY-4.0" ]
2
2019-03-13T21:00:36.000Z
2019-04-10T22:44:38.000Z
native_addon/wj_image/image_win.cpp
SafeOnlineWorld/web_jsx
7ce26957e40c4e6658042d4f2e6f3d93a77b709f
[ "CC-BY-4.0" ]
2
2020-02-17T08:12:52.000Z
2020-09-21T14:33:29.000Z
native_addon/wj_image/image_win.cpp
SafeOnlineWorld/web_jsx
7ce26957e40c4e6658042d4f2e6f3d93a77b709f
[ "CC-BY-4.0" ]
2
2019-11-26T11:38:39.000Z
2019-12-17T17:12:01.000Z
/** * Copyright (c) 2018, SOW (https://www.safeonline.world). (https://github.com/RKTUXYN) All rights reserved. * @author {SOW} * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ //1:57 PM 1/16/2020 #if (defined(_WIN32)||defined(_WIN64)) # include "image_win.h" # include <web_jsx/web_jsx.h> # include <web_jsx/v8_util.h> # include <web_jsx/base64.h> # include <iostream> # include <string> # include <algorithm> # include <stdio.h> # include <windows.h> # include <winbase.h> # include <gdiplus.h> #pragma comment(lib,"gdiplus.lib") #if !defined(GMEM_MOVEABLE) # define GMEM_MOVEABLE 0x0002 #endif//!GMEM_MOVEABLE #if !defined(PixelFormat32bppRGB) # define PixelFormat32bppRGB (9 | (32 << 8) | PixelFormatGDI) #endif//!GMEM_MOVEABLE #ifndef FALSE # define FALSE 0 #endif #ifndef TRUE # define TRUE 1 #endif #pragma warning(disable:4996) wchar_t* ccr2ws(const char* s) { size_t len = strlen(s); wchar_t* buf = new wchar_t[len + sizeof(wchar_t)](); //mbstowcs_s(len, buf, len, s, len); mbsrtowcs(buf, &s, len, NULL); return buf; } enum image_format { BMP = 0x0000, PNG = 0x0001, JPEG = 0x0002, JPG = 0x0003, GIF = 0x0004, TIFF = 0x0005, TIF = 0x0006, NO_EXT = -1, UNKNOWN = -2 }; typedef struct { uint8_t a, r, g, b; } rgb32; enum _mood { UNKNOWN_ = 0x0000, READ = 0x0001, WRITE = 0x0002 }; void to_lower(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); }); } image_format get_image_format(const std::string& path_str) { size_t found = path_str.find_last_of("."); if (found == std::string::npos) return image_format::NO_EXT; std::string str_extension = path_str.substr(found + 1); to_lower(str_extension); if (str_extension == "jpg" || str_extension == "jpeg" || str_extension == "jfif" || str_extension == "pjpeg" || str_extension == "pjp" ) return image_format::JPEG; if (str_extension == "bmp") return image_format::BMP; if (str_extension == "gif") return image_format::GIF; if (str_extension == "png") return image_format::PNG; if (str_extension == "tif") return image_format::TIF; if (str_extension == "tiff") return image_format::TIFF; return image_format::UNKNOWN; } const char* get_mime_type(image_format format) { if (format == image_format::BMP)return "image/bmp"; if (format == image_format::PNG)return "image/png"; if (format == image_format::JPEG)return "image/jpeg"; if (format == image_format::JPG)return "image/jpeg"; if (format == image_format::GIF)return "image/gif"; if (format == image_format::TIFF)return "image/tiff"; if (format == image_format::TIF)return "image/tiff"; return NULL; } INT get_encoder_clsid(const WCHAR* format, CLSID* pClsid) { UINT num, size; Gdiplus::GetImageEncodersSize(&num, &size); Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size)); if (pImageCodecInfo == NULL) return -1; Gdiplus::Status st = Gdiplus::GetImageEncoders(num, size, pImageCodecInfo); if (st == Gdiplus::Ok) { for (UINT ix = 0; ix < num; ++ix) { if (0 == _wcsicmp(pImageCodecInfo[ix].MimeType, format) == 0) { *pClsid = pImageCodecInfo[ix].Clsid; free(pImageCodecInfo); return ix; } } } free(pImageCodecInfo); return -1; } const char* get_gdiplus_error_reason(Gdiplus::Status stat) { switch (stat) { case Gdiplus::Ok: return "Ok"; case Gdiplus::GenericError:return "GenericError"; case Gdiplus::InvalidParameter:return "InvalidParameter"; case Gdiplus::OutOfMemory:return "OutOfMemory"; case Gdiplus::ObjectBusy:return "ObjectBusy"; case Gdiplus::InsufficientBuffer:return "InsufficientBuffer"; case Gdiplus::NotImplemented:return "NotImplemented"; case Gdiplus::Win32Error:return "Win32Error"; case Gdiplus::WrongState:return "WrongState"; case Gdiplus::Aborted:return "Aborted"; case Gdiplus::FileNotFound:return "FileNotFound"; case Gdiplus::ValueOverflow:return "ValueOverflow"; case Gdiplus::AccessDenied:return "AccessDenied"; case Gdiplus::UnknownImageFormat:return "UnknownImageFormat"; case Gdiplus::FontFamilyNotFound:return "FontFamilyNotFound"; case Gdiplus::FontStyleNotFound:return "FontStyleNotFound"; case Gdiplus::NotTrueTypeFont:return "NotTrueTypeFont"; case Gdiplus::UnsupportedGdiplusVersion:return "UnsupportedGdiplusVersion"; case Gdiplus::GdiplusNotInitialized:return "GdiplusNotInitialized"; case Gdiplus::PropertyNotFound:return "PropertyNotFound"; case Gdiplus::PropertyNotSupported:return "PropertyNotSupported"; default:return "Unknown"; } } using namespace sow_web_jsx; class image { private: UINT _height; UINT _width; byte* _pixels; Gdiplus::BitmapData* _bitmap_data; Gdiplus::Bitmap* _bit_map; image_format _format; int _gd_is_init; ULONG_PTR _gdiplus_token; int _is_loaded; int _errc; int _is_copy; char* _internal_error; __forceinline int panic(const char* error, int code) { _free_char(_internal_error); size_t len = strlen(error); _internal_error = new char[len + 1]; strcpy_s(_internal_error, len, error); _errc = code < 0 ? code : code * -1; return _errc; } __forceinline int gd_init() { this->gdiplus_shutdown(); Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::Status stat; stat = GdiplusStartup(&_gdiplus_token, &gdiplusStartupInput, NULL); if (stat == Gdiplus::Ok) { _gd_is_init = TRUE; return TRUE; } std::string* err= new std::string("Unable to init GDI+. Error reason:"); err->append(get_gdiplus_error_reason(stat)); this->panic(err->c_str(), TRUE); _free_obj(err); return _errc; } public: __forceinline image() { _errc = FALSE; _is_loaded = FALSE; _internal_error = NULL; _pixels = NULL; _bit_map = NULL; _height = 0; _width = 0; _bitmap_data = NULL; _gd_is_init = FALSE; _format = image_format::UNKNOWN; _gdiplus_token = NULL; _is_copy = FALSE; } __forceinline ~image() { this->release_all(); } __forceinline void release_all() { this->free_memory(); if (_is_copy == TRUE)return; this->gdiplus_shutdown(); } __forceinline void gdiplus_shutdown() { if (_gdiplus_token != NULL) { Gdiplus::GdiplusShutdown(_gdiplus_token); _gdiplus_token = NULL; _gd_is_init = FALSE; } return; } __forceinline int load(const char* path) { this->release_all(); if (__file_exists(path) == false) { return panic("ERROR: File not found...", TRUE); } _format = get_image_format(path); if (_format == UNKNOWN || _format == NO_EXT) { return panic("ERROR: Unsupported image format...", TRUE); } int ret = this->gd_init(); if (is_error_code(ret) == TRUE)return ret; wchar_t* wpath = ::ccr2ws(path); _bit_map = new Gdiplus::Bitmap(const_cast<const wchar_t*>(wpath)); delete[]wpath; _height = _bit_map->GetHeight(); _width = _bit_map->GetWidth(); _is_loaded = TRUE; return TRUE; } //10:25 AM 1/19/2020 __forceinline int load_from_buff(char* buffer, ULONG size, image_format format = image_format::BMP) { this->release_all(); int ret = this->gd_init(); if (is_error_code(ret) == TRUE)return ret; IStream* pStream = NULL; if (::CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*)&pStream) == S_OK) { //ULONG ulBytesWrite; if (pStream->Write(buffer, size, NULL) == S_OK) { _bit_map = Gdiplus::Bitmap::FromStream(pStream); if (_bit_map != NULL) { Gdiplus::Status stat = _bit_map->GetLastStatus(); if (stat == Gdiplus::Ok) { _height = _bit_map->GetHeight(); _width = _bit_map->GetWidth(); _is_loaded = TRUE; _format = format; } else { std::string* err = new std::string("Unable to create Bitmap from stream. Error reason:"); err->append(get_gdiplus_error_reason(stat)); ret = this->panic(err->c_str(), TRUE); delete _bit_map; _free_obj(err); _bit_map = NULL; } } } else { ret = this->panic("Unable to write data to memmory stream.", TRUE); } pStream->Release(); } else { ret = this->panic("Unable to create memmory stream.", TRUE); } return ret; } __forceinline int load_from_base64(const char* data, image_format format = image_format::BMP) { std::string* out = new std::string(); if (::base64::to_decode_str(data, *out) == false) { _free_obj(out); return this->panic("Unablet to decode base64 data. Please try again.", TRUE); } int ret = this->load_from_buff(out->data(), static_cast<ULONG>(out->size()), format); _free_obj(out); return ret; } __forceinline int create_canvas(const INT width, const INT height) { this->release_all(); int ret = this->gd_init(); if (is_error_code(ret) == TRUE)return ret; _bit_map = new Gdiplus::Bitmap(width, height, PixelFormat32bppRGB); _is_loaded = TRUE; _height = height; _width = width; _format = image_format::BMP; this->reset_rgb(); return ret; } __forceinline void reset_rgb() { if (_is_loaded == FALSE)return; this->lock_bits(Gdiplus::ImageLockModeWrite); rgb32* in = new rgb32(); in->r = (uint8_t)(0xff); in->g = (uint8_t)(0xff); in->b = (uint8_t)(0xff); in->a = (uint8_t)(0xff); rgb32* out = reinterpret_cast<rgb32*>(_pixels); for (UINT i = 0; i < _height; ++i) { for (UINT j = 0; j < _width; ++j) { out->b = in->b; out->g = in->g; out->r = in->r; out->a = in->a; ++out; } } this->unlock_bits(); } __forceinline image_format get_format() const { return _format; } __forceinline void unlock_bits() { if (_bit_map == NULL)return; if (_bitmap_data == NULL)return; _bit_map->UnlockBits(_bitmap_data); ::DeleteObject(_bitmap_data); _bitmap_data = NULL; if (_pixels != NULL) { ::DeleteObject(_pixels); _pixels = NULL; } return; } __forceinline void dump_data() { this->lock_bits(Gdiplus::ImageLockModeRead); rgb32* out = reinterpret_cast<rgb32*>(_pixels); for (UINT i = 0; i < _height; ++i) { for (UINT j = 0; j < _width; ++j) { std::cout << "rgb(" << (int)out->b << "," << (int)out->g << "," << (int)out->r << ") "; ++out; } } this->unlock_bits(); } __forceinline int lock_bits(Gdiplus::ImageLockMode lock_mode = Gdiplus::ImageLockModeRead) { if (_is_loaded == FALSE)return this->panic("Please Load an Image than try again.", TRUE); this->unlock_bits(); _bitmap_data = new Gdiplus::BitmapData; Gdiplus::Rect rect(0, 0, _width, _height); // Lock a 5x3 rectangular portion of the bitmap for reading. _bit_map->LockBits(&rect, lock_mode, PixelFormat32bppARGB, _bitmap_data); if (_pixels != NULL) { ::DeleteObject(_pixels); _pixels = NULL; } _pixels = reinterpret_cast<byte*>(_bitmap_data->Scan0); return TRUE; } /* * Get the rgba color from your given x, y ratio of image * @return rgb32 || NULL */ __forceinline rgb32* get_pixel(INT x, INT y) const { if (_is_loaded == FALSE)return NULL; if (_pixels == NULL)return NULL; rgb32* pixel_color = reinterpret_cast<rgb32*>(_pixels); return &pixel_color[(_height - 1 - y) * _width + x]; } __forceinline int set_pixel(rgb32* pixel_color, INT x, INT y) { if (_is_loaded == FALSE)return FALSE; if (_pixels == NULL)return FALSE; rgb32* temp = reinterpret_cast<rgb32*>(_pixels); memcpy(&temp[(_height - 1 - y) * _width + x], pixel_color, sizeof(rgb32)); return TRUE; } __forceinline ULONG_PTR gdiplus_token()const { return _gdiplus_token; } __forceinline Gdiplus::Bitmap* get_data()const { Gdiplus::Rect rect(0, 0, _width, _height); return _bit_map->Clone(rect, PixelFormat32bppARGB); } /*Assignment operator creates a deep copy of the source image.*/ __forceinline image& operator = (const image& other) { if (other.is_loaded() == FALSE)return *this; this->free_memory(); this->_bit_map = other.get_data(); _width = other.get_width(); _height = other.get_height(); this->_gdiplus_token = other.gdiplus_token(); _is_loaded = TRUE; _format = other.get_format(); return *this; } __forceinline int resize(image& dest) { if (_is_loaded == FALSE)return this->panic("Please Load an Image than try again.", TRUE); this->lock_bits(Gdiplus::ImageLockModeRead); dest.lock_bits(Gdiplus::ImageLockModeWrite); INT new_width = dest.get_width(), new_height = dest.get_height(); double scale_width = static_cast<double>(new_width) / static_cast<double>(_width); double scale_height = static_cast<double>(new_height) / static_cast<double>(_height); for (INT y = 0; y < new_height; ++y) { for (INT x = 0; x < new_width; ++x) { rgb32* pixel_color = get_pixel(static_cast<INT>(x / scale_width), static_cast<INT>(y / scale_height)); dest.set_pixel(pixel_color, x, y); } } this->unlock_bits(); dest.unlock_bits(); return TRUE; } __forceinline int resize(INT width, INT height) { if (_is_loaded == FALSE)return this->panic("Please Load an Image than try again.", TRUE); if (width % 4 != 0) { return panic("There is a windows-imposed requirement on BMP that the width be a multiple of 4", TRUE); } image* img = new image(); int ret = img->create_canvas(width, height); if (is_error_code(ret) == TRUE) { panic(img->get_last_error(), ret); img->free_memory(); delete img; return ret; } ret = this->resize(*img); if (is_error_code(ret) != TRUE) { *this = *img; } img->free_memory(TRUE); delete img; return ret; } __forceinline int save(const char* path) { return this->save_as(path, _format); } __forceinline int save_as(const char* path, const image_format format) { if (_is_loaded == FALSE)return this->panic("Please Load an Image than try again.", TRUE); const char* cmime_type = get_mime_type(format); if (cmime_type == NULL) return this->panic("Unsupported Image format.\nSupported .bmp, .png, .jpeg, .jpg, .gif, .tiff, .tif", TRUE); CLSID encoder_clsid; wchar_t* mime_type = ::ccr2ws(cmime_type); int ret = ::get_encoder_clsid(const_cast<const wchar_t*>(mime_type), &encoder_clsid); delete[]mime_type; if (ret < 0)return this->panic("Unable to create mime type.", TRUE); wchar_t* wpath = ccr2ws(path); Gdiplus::Status stat; Gdiplus::EncoderParameters* encoder_parameters = NULL; if (format == image_format::JPEG || format == image_format::JPG) { encoder_parameters = new Gdiplus::EncoderParameters(); encoder_parameters->Count = 1; encoder_parameters->Parameter[0].Value = 0;// Save the image as a JPEG with quality level 0. encoder_parameters->Parameter[0].Guid = Gdiplus::EncoderQuality; encoder_parameters->Parameter[0].Type = Gdiplus::EncoderParameterValueTypeLong; encoder_parameters->Parameter[0].NumberOfValues = 1; } stat = _bit_map->Save(const_cast<const wchar_t*>(wpath), &encoder_clsid, encoder_parameters); delete[]wpath; if (encoder_parameters != NULL) { delete encoder_parameters; encoder_parameters = NULL; } if (stat == Gdiplus::Status::Ok)return TRUE; std::string* err = new std::string("Failed to save image. Error reason:"); err->append(get_gdiplus_error_reason(stat)); this->panic(err->c_str(), TRUE); _free_obj(err); return _errc; } //10:44 AM 1/20/2020 template<class _func> __forceinline int get_image_buff(_func cb, image_format format = image_format::BMP) { if (_is_loaded == FALSE) return this->panic("Please Load an Image than try again.", TRUE); if (_bit_map == NULL) return this->panic("Please Load an Image than try again.", TRUE); const char* cmime_type = get_mime_type(format); if (cmime_type == NULL) return this->panic("Unsupported Image format.\nSupported .bmp, .png, .jpeg, .jpg, .gif, .tiff, .tif", TRUE); IStream* oStream = NULL; if (::CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*)&oStream) != S_OK)return this->panic("Unable to create memmory stream.", TRUE); this->unlock_bits(); CLSID encoder_clsid; wchar_t* mime_type = ccr2ws(cmime_type); int ret = get_encoder_clsid(const_cast<const wchar_t*>(mime_type), &encoder_clsid); delete[]mime_type; if (ret < 0)return this->panic("Unable to create mime type.", TRUE); _bit_map->Save(oStream, &encoder_clsid); ULARGE_INTEGER ulnSize; LARGE_INTEGER lnOffset; lnOffset.QuadPart = 0; oStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize); oStream->Seek(lnOffset, STREAM_SEEK_SET, NULL); if (ulnSize.QuadPart <= 0) { oStream->Release(); return this->panic("No data found in Image Stream.", TRUE); } int eof = FALSE; ULONG ulBytesRead; unsigned int total_len = (unsigned int)ulnSize.QuadPart; const int chunk = 1024 * 2; unsigned read_len = 0; do { char* pBuff; if (total_len > chunk) { read_len = chunk; } else { read_len = total_len; } pBuff = new char[read_len]; oStream->Read(pBuff, (ULONG)read_len, &ulBytesRead); total_len -= ulBytesRead; if (total_len <= 0)eof = TRUE; cb(const_cast<const char*>(pBuff), static_cast<int>(ulBytesRead)); delete[]pBuff; } while (eof == FALSE); oStream->Release(); return TRUE; } //04:13 PM 1/19/2020 __forceinline int get_image_buff(std::string&out, image_format format = image_format::BMP) { if (_is_loaded == FALSE) return this->panic("Please Load an Image than try again.", TRUE); if (_bit_map == NULL) return this->panic("Please Load an Image than try again.", TRUE); const char* cmime_type = get_mime_type(format); if (cmime_type == NULL) return this->panic("Unsupported Image format.\nSupported .bmp, .png, .jpeg, .jpg, .gif, .tiff, .tif", TRUE); IStream* oStream = NULL; if (::CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*)& oStream) != S_OK)return this->panic("Unable to create memmory stream.", TRUE); this->unlock_bits(); CLSID encoder_clsid; wchar_t* mime_type = ccr2ws(cmime_type); int ret = get_encoder_clsid(const_cast<const wchar_t*>(mime_type), &encoder_clsid); delete[]mime_type; if (ret < 0)return this->panic("Unable to create mime type.", TRUE); _bit_map->Save(oStream, &encoder_clsid); ULARGE_INTEGER ulnSize; LARGE_INTEGER lnOffset; lnOffset.QuadPart = 0; oStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize); oStream->Seek(lnOffset, STREAM_SEEK_SET, NULL); if (ulnSize.QuadPart <= 0) { oStream->Release(); return this->panic("No data found in Image Stream.", TRUE); } char* pBuff = new char[(unsigned int)ulnSize.QuadPart]; ULONG ulBytesRead; oStream->Read(pBuff, (ULONG)ulnSize.QuadPart, &ulBytesRead); oStream->Release(); out = std::string(pBuff, ulBytesRead); delete[]pBuff; pBuff = NULL; return TRUE; } __forceinline int to_base64(std::string& out, image_format format = image_format::BMP) { std::string* data = new std::string(); int ret = this->get_image_buff(*data, format); if (is_error_code(ret) == FALSE) { ret = ::base64::to_encode_str(*data, out) == true ? TRUE : FALSE; } _free_obj(data); return ret; } __forceinline UINT get_width() const { return _width; } __forceinline UINT get_height() const { return _height; } __forceinline const char* get_last_error() const { if (_errc >= 0 || _internal_error == NULL) return "No Error Found!!!"; return const_cast<const char*>(_internal_error); } __forceinline int has_error() const { return _errc == TRUE || _errc < 0 ? TRUE : FALSE; } __forceinline int is_loaded() const { return _is_loaded; } __forceinline void free_memory(int is_copy = FALSE) { _is_copy = is_copy; if (_bitmap_data != NULL) { ::DeleteObject(_bitmap_data); _bitmap_data = NULL; } _free_char(_internal_error); if (_pixels != NULL) { ::DeleteObject(_pixels); _pixels = NULL; } if (_bit_map != NULL) { delete _bit_map; _bit_map = NULL; } _height = 0; _width = 0; _errc = FALSE; _is_loaded = FALSE; _format = image_format::UNKNOWN; return; } }; image* get_image_instance(js_method_args) { image* img = sow_web_jsx::unwrap<image>(args); if (img == NULL) { throw_js_error(args.GetIsolate(), "Image object disposed..."); return NULL; } return img; } void image_export(v8::Isolate* isolate, v8::Handle<v8::Object> target){ v8::Local<v8::FunctionTemplate> image_tpl = v8::FunctionTemplate::New(isolate, [](const v8::FunctionCallbackInfo<v8::Value>& args) { if (!args.IsConstructCall()) { throw_js_error(args.GetIsolate(), "Cannot call constructor as function!!!"); return; } v8::Isolate* isolate = args.GetIsolate(); image* img = new image(); v8::Local<v8::Object> obj = args.This(); obj->SetInternalField(0, v8::External::New(isolate, img)); v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>> pobj(isolate, obj); pobj.SetWeak<image*>(&img, [](const v8::WeakCallbackInfo<image*>& data) { delete[] data.GetParameter(); }, v8::WeakCallbackType::kParameter); }); image_tpl->SetClassName(v8_str(isolate, "Image")); image_tpl->InstanceTemplate()->SetInternalFieldCount(1); v8::Local<v8::ObjectTemplate> prototype = image_tpl->PrototypeTemplate(); set_prototype(isolate, prototype, "load", [](js_method_args) { if (!args[0]->IsString()) { throw_js_error(args.GetIsolate(), "File Path Required required...."); return; } image* img = get_image_instance(args); if (img == NULL)return; v8::Isolate* isolate = args.GetIsolate(); native_string utf_abs_path_str(isolate, args[0]); std::string* abspath = new std::string(utf_abs_path_str.c_str()); format__path(*abspath); int ret = img->load(abspath->c_str()); utf_abs_path_str.clear(); abspath->clear(); delete abspath; if (is_error_code(ret) == TRUE) { throw_js_error(isolate, img->get_last_error()); return; } args.GetReturnValue().Set(v8::Integer::New(isolate, ret)); }); set_prototype(isolate, prototype, "release", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; img->release_all(); delete img; img = NULL; args.Holder()->SetAlignedPointerInInternalField(0, nullptr); }); set_prototype(isolate, prototype, "reset", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } img->reset_rgb(); args.GetReturnValue().Set(args.Holder()); }); set_prototype(isolate, prototype, "release_mem", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; img->release_all(); args.GetReturnValue().Set(args.Holder()); }); set_prototype(isolate, prototype, "get_data", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } image_format format = image_format::BMP;//get_image_format(*abspath); if (args.Length() > 0) { if (args[0]->IsNumber()) { v8::Local<v8::Context>ctx = args.GetIsolate()->GetCurrentContext(); format = (image_format)args[0]->Int32Value(ctx).FromMaybe(0); } } std::string* out = new std::string(); int ret = img->get_image_buff(*out, format); if (is_error_code(ret) == TRUE) { throw_js_error(args.GetIsolate(), img->get_last_error()); } else { args.GetReturnValue().Set(v8_str(args.GetIsolate(), out->c_str())); } out->clear(); delete out; }); set_prototype(isolate, prototype, "get_datac", [](js_method_args) { if (!args[0]->IsFunction()) { throw_js_error(args.GetIsolate(), "Callback required..."); return; } image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } v8::Isolate* isolate = args.GetIsolate(); image_format format = image_format::BMP;//get_image_format(*abspath); if (args.Length() > 1) { if (args[1]->IsNumber()) { v8::Local<v8::Context>ctx = isolate->GetCurrentContext(); format = (image_format)args[1]->Int32Value(ctx).FromMaybe(0); } } v8::Persistent<v8::Function> cb; cb.Reset(isolate, v8::Local<v8::Function>::Cast(args[0])); v8::Local<v8::Function> callback = v8::Local<v8::Function>::New(isolate, cb); int ret = img->get_image_buff([&isolate, &callback](const char* buff, int len) { //v8_str(isolate, buff); v8::Local<v8::Value> argv[2] = { v8::String::NewFromUtf8(isolate, buff,v8::NewStringType::kNormal, len).ToLocalChecked(), v8::Integer::New(isolate, len) }; callback->Call(isolate->GetCurrentContext(), isolate->GetCurrentContext()->Global(), 2, argv); argv->Clear(); }, format); callback.Clear(); if (is_error_code(ret) == TRUE) { throw_js_error(args.GetIsolate(), img->get_last_error()); } else { args.GetReturnValue().Set(args.Holder()); } }); set_prototype(isolate, prototype, "to_base64", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } image_format format = image_format::BMP;//get_image_format(*abspath); if (args.Length() > 0) { if (args[0]->IsNumber()) { v8::Local<v8::Context>ctx = args.GetIsolate()->GetCurrentContext(); format = (image_format)args[0]->Int32Value(ctx).FromMaybe(0); } } std::string* out = new std::string(); int ret = img->to_base64(*out, format); if (is_error_code(ret) == TRUE) { throw_js_error(args.GetIsolate(), img->get_last_error()); } else { args.GetReturnValue().Set(v8_str(args.GetIsolate(), out->c_str())); } _free_obj(out); }); set_prototype(isolate, prototype, "load_from_data", [](js_method_args) { if (!args[0]->IsString()) { throw_js_error(args.GetIsolate(), "base64 Data required...."); return; } image* img = get_image_instance(args); if (img == NULL)return; v8::Isolate* isolate = args.GetIsolate(); image_format format = image_format::BMP; if (args.Length() > 1) { if (args[1]->IsNumber()) { v8::Local<v8::Context>ctx = args.GetIsolate()->GetCurrentContext(); format = (image_format)args[1]->Int32Value(ctx).FromMaybe(0); } } native_string utf_base64(isolate, args[0]); std::string* img_data = new std::string(utf_base64.c_str(), utf_base64.size()); int ret = img->load_from_buff(img_data->data(), static_cast<ULONG>(img_data->size()), format); utf_base64.clear(); _free_obj(img_data); if (is_error_code(ret) == TRUE) { throw_js_error(isolate, img->get_last_error()); return; } args.GetReturnValue().Set(v8::Integer::New(isolate, ret)); }); set_prototype(isolate, prototype, "load_from_base64", [](js_method_args) { if (!args[0]->IsString()) { throw_js_error(args.GetIsolate(), "base64 Data required...."); return; } image* img = get_image_instance(args); if (img == NULL)return; v8::Isolate* isolate = args.GetIsolate(); image_format format = image_format::BMP;//get_image_format(*abspath); if (args.Length() > 1) { if (args[1]->IsNumber()) { v8::Local<v8::Context>ctx = args.GetIsolate()->GetCurrentContext(); format = (image_format)args[1]->Int32Value(ctx).FromMaybe(0); } } native_string utf_base64(isolate, args[0]); int ret = img->load_from_base64(utf_base64.c_str(), format); utf_base64.clear(); if (is_error_code(ret) == TRUE) { throw_js_error(isolate, img->get_last_error()); return; } args.GetReturnValue().Set(v8::Integer::New(isolate, ret)); }); set_prototype(isolate, prototype, "save", [](js_method_args) { if (!args[0]->IsString()) { throw_js_error(args.GetIsolate(), "File Path required...."); return; } image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } v8::Isolate* isolate = args.GetIsolate(); native_string utf_abs_path_str(isolate, args[0]); std::string* abspath = new std::string(utf_abs_path_str.c_str()); format__path(*abspath); image_format format = get_image_format(*abspath); if (format == image_format::UNKNOWN || format == image_format::NO_EXT) { utf_abs_path_str.clear(); _free_obj(abspath); throw_js_error(args.GetIsolate(), "Unsupported Image format defined..."); return; } int ret = TRUE; ret = img->save_as(abspath->c_str(), format); utf_abs_path_str.clear(); _free_obj(abspath); if (is_error_code(ret) == TRUE) { throw_js_error(isolate, img->get_last_error()); return; } args.GetReturnValue().Set(v8::Integer::New(isolate, ret)); }); set_prototype(isolate, prototype, "get_width", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } UINT width = img->get_width(); args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), static_cast<int>(width))); }); set_prototype(isolate, prototype, "get_height", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } UINT height = img->get_height(); args.GetReturnValue().Set(v8::Integer::New(args.GetIsolate(), static_cast<int>(height))); }); set_prototype(isolate, prototype, "resize", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } if (args.Length() < 2) { throw_js_error(args.GetIsolate(), "Height and Width required..."); return; } if (!args[0]->IsNumber()) { throw_js_error(args.GetIsolate(), "Height required..."); return; } if (!args[1]->IsNumber()) { throw_js_error(args.GetIsolate(), "Width required..."); return; } v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Context>ctx = isolate->GetCurrentContext(); int width = args[0]->Int32Value(ctx).FromMaybe(0); int height = args[1]->Int32Value(ctx).FromMaybe(0); int ret = img->resize(width, height); if (is_error_code(ret) == TRUE) { throw_js_error(isolate, img->get_last_error()); } else { args.GetReturnValue().Set(args.Holder()); } }); set_prototype(isolate, prototype, "create_canvas", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (args.Length() < 2) { throw_js_error(args.GetIsolate(), "Height and Width required..."); return; } if (!args[0]->IsNumber()) { throw_js_error(args.GetIsolate(), "Height required..."); return; } if (!args[1]->IsNumber()) { throw_js_error(args.GetIsolate(), "Width required..."); return; } v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Context>ctx = isolate->GetCurrentContext(); int width = args[0]->Int32Value(ctx).FromMaybe(0); int height = args[1]->Int32Value(ctx).FromMaybe(0); int ret = img->create_canvas(width, height); if (is_error_code(ret) == TRUE) { throw_js_error(isolate, img->get_last_error()); } else { args.GetReturnValue().Set(args.Holder()); } }); set_prototype(isolate, prototype, "lock_bits", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } _mood mood = READ; if (args.Length() >= 1) { if (args[0]->IsNumber()) { v8::Local<v8::Context>ctx = args.GetIsolate()->GetCurrentContext(); mood = (_mood)args[0]->ToInteger(ctx).ToLocalChecked()->Value(); } } int ret = img->lock_bits(mood == READ ? Gdiplus::ImageLockModeRead : Gdiplus::ImageLockModeWrite); if (is_error_code(ret) == TRUE) { throw_js_error(args.GetIsolate(), img->get_last_error()); return; } args.GetReturnValue().Set(args.Holder()); }); set_prototype(isolate, prototype, "get_pixel", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } if (args.Length() < 2) { throw_js_error(args.GetIsolate(), "x y required..."); return; } if (!args[0]->IsNumber() || !args[1]->IsNumber()) { throw_js_error(args.GetIsolate(), "x y should be number..."); return; } v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Context>ctx = isolate->GetCurrentContext(); int x = args[0]->Int32Value(ctx).FromMaybe(0); int y = args[1]->Int32Value(ctx).FromMaybe(0); rgb32* pixel = img->get_pixel(x, y); if (pixel == NULL) { throw_js_error(args.GetIsolate(), "Unable to read pixel from image..."); return; } v8::Handle<v8::Object> v8_result = v8::Object::New(isolate); v8_result->Set(ctx, v8_str(isolate, "r"), v8::Integer::New(isolate, static_cast<int>(pixel->r))); v8_result->Set(ctx, v8_str(isolate, "g"), v8::Integer::New(isolate, static_cast<int>(pixel->g))); v8_result->Set(ctx, v8_str(isolate, "b"), v8::Integer::New(isolate, static_cast<int>(pixel->b))); v8_result->Set(ctx, v8_str(isolate, "a"), v8::Integer::New(isolate, static_cast<int>(pixel->a))); args.GetReturnValue().Set(v8_result); v8_result.Clear(); }); set_prototype(isolate, prototype, "set_pixel", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } if (args.Length() < 3) { throw_js_error(args.GetIsolate(), "rgba and x y required..."); return; } if (!args[0]->IsObject()) { throw_js_error(args.GetIsolate(), "rgba should be object..."); return; } if (!args[1]->IsNumber() || !args[2]->IsNumber()) { throw_js_error(args.GetIsolate(), "x y should be number..."); return; } v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> rgba = v8::Handle<v8::Object>::Cast(args[0]); v8::Local<v8::Context>ctx = isolate->GetCurrentContext(); rgb32* pixel = new rgb32(); int val = ::v8_object_get_number(isolate, ctx, rgba, "r"); if (val == -500) { delete pixel; return; } pixel->r = (uint8_t)val; val = ::v8_object_get_number(isolate, ctx, rgba, "g"); if (val == -500) { delete pixel; return; } pixel->g = (uint8_t)val; val = ::v8_object_get_number(isolate, ctx, rgba, "b"); if (val == -500) { delete pixel; return; } pixel->b = (uint8_t)val; val = ::v8_object_get_number(isolate, ctx, rgba, "a"); if (val == -500) { delete pixel; return; } pixel->a = (uint8_t)val; int x = args[1]->Int32Value(ctx).FromMaybe(0); int y = args[2]->Int32Value(ctx).FromMaybe(0); int ret = img->set_pixel(pixel, x, y); if (is_error_code(ret) == TRUE) { throw_js_error(isolate, "Unable to set your request pixel..."); } else { //std::cout << "rgb(" << (int)pixel->b << "," << (int)pixel->g << "," << (int)pixel->r << ") " << std::endl; args.GetReturnValue().Set(args.Holder()); } }); set_prototype(isolate, prototype, "unlock_bits", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } img->unlock_bits(); args.GetReturnValue().Set(args.Holder()); }); set_prototype(isolate, prototype, "dump_data", [](js_method_args) { image* img = get_image_instance(args); if (img == NULL)return; if (img->is_loaded() == FALSE) { throw_js_error(args.GetIsolate(), "Image does not loaded yet..."); return; } img->dump_data(); args.GetReturnValue().Set(args.Holder()); }); v8::Local<v8::Context>context = isolate->GetCurrentContext(); { v8::Local<v8::Object>image_format_object = v8::Object::New(isolate); image_format_object->Set(context, v8_str(isolate, "BMP"), v8::Integer::New(isolate, (int)image_format::BMP)); image_format_object->Set(context, v8_str(isolate, "PNG"), v8::Integer::New(isolate, (int)image_format::PNG)); image_format_object->Set(context, v8_str(isolate, "JPEG"), v8::Integer::New(isolate, (int)image_format::JPEG)); image_format_object->Set(context, v8_str(isolate, "JPG"), v8::Integer::New(isolate, (int)image_format::JPG)); image_format_object->Set(context, v8_str(isolate, "GIF"), v8::Integer::New(isolate, (int)image_format::GIF)); image_format_object->Set(context, v8_str(isolate, "TIFF"), v8::Integer::New(isolate, (int)image_format::TIFF)); image_format_object->Set(context, v8_str(isolate, "TIF"), v8::Integer::New(isolate, (int)image_format::TIF)); target->Set(context, v8_str(isolate, "image_format"), image_format_object); v8::Local<v8::Object>image_mood = v8::Object::New(isolate); image_mood->Set(context, v8_str(isolate, "READ"), v8::Integer::New(isolate, (int)_mood::READ)); image_mood->Set(context, v8_str(isolate, "WRITE"), v8::Integer::New(isolate, (int)_mood::WRITE)); target->Set(context, v8_str(isolate, "image_mood"), image_mood); } target->Set(context, v8_str(isolate, "Image"), image_tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()); } #endif//!_WIN32||_WIN64 //End 3:56 PM 1/18/2020
37.726368
135
0.661084
SafeOnlineWorld
84b89a5abb875476e86546a0c6a71261706a2b7c
852
hpp
C++
Core/Inc/CurrentSensor.hpp
TaiyouKomazawa/InteractiveMD
bdd967bfbf5d38b3175d106c0123049a9da45663
[ "BSD-3-Clause" ]
null
null
null
Core/Inc/CurrentSensor.hpp
TaiyouKomazawa/InteractiveMD
bdd967bfbf5d38b3175d106c0123049a9da45663
[ "BSD-3-Clause" ]
null
null
null
Core/Inc/CurrentSensor.hpp
TaiyouKomazawa/InteractiveMD
bdd967bfbf5d38b3175d106c0123049a9da45663
[ "BSD-3-Clause" ]
null
null
null
/* * CurrentSensor.hpp * * Created on: Jan 4, 2022 * Author: Taiyou Komazawa */ #ifndef INC_CURRENTSENSOR_HPP_ #define INC_CURRENTSENSOR_HPP_ #include "main.h" /** * @brief ADC式電流センサクラス */ class CurrentSensor { public: enum { /* ADCの分解能 */ ADC_RESOLUTION = 4096, }; /** * @brief センサのデータを格納する構造体型 */ typedef struct ADCDataType { /* 3回分の測定データ(平均フィルタ用) */ float data[3]; /* 電圧のオフセット値 */ float offset; }adc_data_t; CurrentSensor(ADC_HandleTypeDef *hadcx, uint8_t num_of_unit, float gain, uint16_t offset_count=100); ~CurrentSensor(); float get_current(int unit); void adc_get_offset(uint16_t offset_count); private: float get_raw_(uint8_t unit); ADC_HandleTypeDef *hadcx_; uint8_t num_of_unit_; float gain_; adc_data_t *adc_data_; uint16_t *adc_data_raw_; }; #endif /* INC_CURRENTSENSOR_HPP_ */
14.440678
101
0.705399
TaiyouKomazawa
84b954b45b428f7a8e1cd78b64dbd4ed695f3104
912
cpp
C++
DP/HouseRobberII_213.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
DP/HouseRobberII_213.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
DP/HouseRobberII_213.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: HouseRobberII_213.cpp > Author: zzy > Mail: 942744575@qq.com > Created Time: Thu 20 Sep 2018 08:47:58 PM CST ********************************************************************** */ /* * 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。 * 这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。 * 同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 * * 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 */ #include<vector> using std::vector; class Solution { public: int getRob(vector<int>& nums, int begin, int end) { if (end - begin == 2) { return std::max(nums[begin] + nums[end], nums[end-1]); } if (end - begin == 1) { return std::max(nums[begin], nums[end]); } return std::max(getRob(nums, begin, end -1) , getRob(nums, begin + 1, end)); } int rob(vector<int>& nums) { return getRob(nums, 0, nums.size()); } };
25.333333
78
0.554825
obviouskkk