blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
75796ba8f976fa7123db5a5f0c42f3673b287a57 | 800965a478f1c8d68c25d0837d1a3ffab75b50e9 | /Week-02/day-3/06.cpp | 4588e991003371d34c5b96273c87f7e8c764ded7 | [] | no_license | greenfox-zerda-sparta/Ak0s | 8ed1eea5a63249cabb58f5de8620884aea7a8503 | 2f37db6512f6aa7057048ed189ed2259e3ee48ba | refs/heads/master | 2021-01-12T18:15:08.523009 | 2017-02-13T18:06:12 | 2017-02-13T18:06:12 | 71,350,507 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | //============================================================================
// Name : 06.cpp
// Author : Ak0s
//============================================================================
// The "other_high_number_pointer" should point to the same memory address
// without using the "&" operator.
#include <iostream>
using namespace std;
int main() {
int high_number = 6655;
int low_number = 2;
int* high_number_pointer = &high_number;
int* other_high_number_pointer = high_number_pointer;
cout << "The memory address stored in 'high_number_pointer': " << high_number_pointer << endl;
cout << "The memory address stored in 'other_high_number_pointer': " << other_high_number_pointer;
return 0;
}
| [
"modis1akos@msn.com"
] | modis1akos@msn.com |
2951fbe7781342ec20383953b4dd3f34445bc2ff | 01b602a4a4d02d94aef887c2ba6951e42926655e | /dblLinkList.hpp | 9b35654353646c836f107de1067a22d0a54bdab3 | [] | no_license | klu428/fantasy-combat-tournament | 118ac7c3d3de042e5ddc34bc2272703cd9ca5528 | 452fe7df7d16b8e81f9fa628203eaa365e709463 | refs/heads/master | 2020-03-09T14:46:42.977787 | 2018-04-10T02:19:55 | 2018-04-10T02:19:55 | 128,842,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | hpp | /********************
** Author: Kelvin Lu
** Date: 10/31/2017
** Description: This is the specification file for the dblLinkList class, which contains the methods used to construct a double linked list.
********************/
#ifndef DBLLINKLIST_HPP
#define DBLLINKLIST_HPP
#include "Node.hpp"
#include <iostream>
#include <string>
#include <fstream>
class dblLinkList
{
private:
Node * front;
Node * back;
public:
//Constructor
dblLinkList();
//Check if the list is empty
bool isEmpty();
//Add node to the head of the list
void addFront(Character * input);
//Add node to the back of the list
void addBack(Character * input);
//Delete the first node in the list
void deleteFront();
//Delete the last node in the list
void deleteBack();
//Traverse the list and print each node's value
void traverseFront();
//Traverse the list in the reverse direction and print each node's value
void traverseBack();
//Get the front node's value
Character * getFront();
//Get the back node's value
Character * getBack();
//Delete a list
void deleteList();
//Destructor
~dblLinkList();
};
#endif | [
"noreply@github.com"
] | klu428.noreply@github.com |
46b67172f0aae0a66f4e197b8064bc5f8aded725 | 290b0be682afdd4388a520b0e26d286e64a56e88 | /winwizsrc/der_libs/statbar.h | 827e92b7af0075bef72efb28b3ba1c57f16c5b2c | [] | no_license | gondur/The-Wizard-s-Castle | abb0f35e6387b78c8ef92df79a73dfe20b29e5df | a3d38f01952328b89f7bc16b0497b719979d6afd | refs/heads/master | 2020-12-24T20:52:20.292730 | 2016-04-16T17:33:07 | 2016-04-16T17:33:07 | 56,396,735 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,915 | h | //*****************************************************************************
// Copyright (c) 2012-2013 Daniel D Miller
// Converting original statbar.cpp utility to a status-bar class
//
// This module, which has been entirely compiled from public-domain sources,
// is itself declared in the public domain.
//*****************************************************************************
// Class usage:
//
// static CStatusBar *MainStatusBar = NULL;
//
// // in WM_INITDIALOG
// MainStatusBar = new CStatusBar(hwnd) ;
// MainStatusBar->MoveToBottom(cxClient, cyClient) ;
//
// // re-position status-bar parts
// int sbparts[3];
// sbparts[0] = (int) (6 * cxClient / 10) ;
// sbparts[1] = (int) (8 * cxClient / 10) ;
// sbparts[2] = -1;
// MainStatusBar->SetParts(3, &sbparts[0]);
//
// // writing to status bar:
// //*******************************************************************
// static void status_message(char *msgstr)
// {
// MainStatusBar->show_message(msgstr);
// }
// //*******************************************************************
// static void status_message(uint idx, char *msgstr)
// {
// MainStatusBar->show_message(idx, msgstr);
// }
//*****************************************************************************
/*-------------------------------------------
* original code:
STATBAR.C -- Status bar helper functions.
(c) Paul Yao, 1996
-------------------------------------------*/
//lint -esym(1714, CStatusBar::show_message, CStatusBar::set_bgnd_color)
//lint -esym(1714, CStatusBar::set_statusbar_font, CStatusBar::height)
//lint -esym(1719, CStatusBar)
//lint -esym(1720, CStatusBar)
//lint -esym(1722, CStatusBar)
//lint -esym(1704, CStatusBar::CStatusBar)
// Info 1712: default constructor not defined for class 'CStatusBar'
//lint -esym(1712, CStatusBar)
class CStatusBar {
private:
HWND hwndParent ;
HWND hwndStatusBar ;
unsigned bar_height ;
HDC hdcSelf ; // used in conjunction with hfont
HFONT hfont ;
CStatusBar operator=(const CStatusBar src) ;
CStatusBar(const CStatusBar&);
// protected:
// unsigned cxChar ; // width of char
// unsigned cyChar ; // height of char
public:
CStatusBar(HWND hwndParent) ;
~CStatusBar();
bool IsStatusBarVisible(void);
unsigned MoveToBottom(unsigned cxClient, unsigned cyClient);
bool SetParts(int nParts, int *sbparts);
void show_message(TCHAR *msg);
void show_message(unsigned idx, TCHAR *msg);
void set_statusbar_font(char * szFaceName, int iDeciPtHeight, unsigned iAttributes);
void set_bgnd_color(COLORREF bgnd);
bool RebuildStatusBar (WORD wFlag);
void StatusBarMessage(WORD wMsg);
unsigned height(void) const
{ return bar_height ; } ;
} ;
//-------------------------------------------------------------------
// flags for RebuildStatusBar()
#define IDM_STAT_IGNORESIZE 600
#define IDM_STAT_SIZEGRIP 700
#define IDM_STAT_TOP 701
#define IDM_STAT_BOTTOM 702
#define IDM_STAT_NOMOVEY 703
#define IDM_STAT_NOPARENTALIGN 704
#define IDM_STAT_NORESIZE 705
// flags for StatusBarMessage()
#define IDM_ST_GETBORDERS 800
#define IDM_ST_GETPARTS 801
#define IDM_ST_SETTEXT 802
#define IDM_ST_SIMPLE 803
//-------------------------------------------------------------------------------
// Status Bar Helper Macros
// Note that none of these macros are usable within the context of this class,
// because they require access to the HWND, which is private data.
//-------------------------------------------------------------------------------
#define Status_GetBorders(hwnd, aBorders) \
(BOOL) SendMessageA((hwnd), SB_GETBORDERS, 0, (LPARAM) (LPINT) aBorders)
#define Status_GetParts(hwnd, nParts, aRightCoord) \
(int) SendMessageA((hwnd), SB_GETPARTS, (WPARAM) nParts, (LPARAM) (LPINT) aRightCoord)
#define Status_GetRect(hwnd, iPart, lprc) \
(BOOL) SendMessageA((hwnd), SB_GETRECT, (WPARAM) iPart, (LPARAM) (LPRECT) lprc)
#define Status_GetText(hwnd, iPart, szText) \
(DWORD)SendMessageA((hwnd), SB_GETTEXT, (WPARAM) iPart, (LPARAM) (LPSTR) szText)
#define Status_GetTextLength(hwnd, iPart) \
(DWORD)SendMessageA((hwnd), SB_GETTEXTLENGTH, (WPARAM) iPart, 0L)
#define Status_SetMinHeight(hwnd, minHeight) \
(void) SendMessageA((hwnd), SB_SETMINHEIGHT, (WPARAM) minHeight, 0L)
#define Status_SetParts(hwnd, nParts, aWidths) \
(BOOL) SendMessageA((hwnd), SB_SETPARTS, (WPARAM) nParts, (LPARAM) (LPINT) aWidths)
#define Status_SetText(hwnd, iPart, uType, szText) \
(BOOL) SendMessageA((hwnd), SB_SETTEXT, (WPARAM) (iPart | uType), (LPARAM) (LPSTR) szText)
#define Status_Simple(hwnd, fSimple) \
(BOOL) SendMessageA((hwnd), SB_SIMPLE, (WPARAM) (BOOL) fSimple, 0L)
| [
"hhhh@hotmail.com"
] | hhhh@hotmail.com |
fe5d64d28e87896db91ba7ac0a640f4e90ff3814 | 0b79f0a0ddadee7ef45755e8d74693e2cc609c52 | /main/src/jumpnrun/mover/bullet/Ball.cpp | 85fd1a70cb35c46464bcabc89900a58f339f3956 | [
"MIT"
] | permissive | wonderhorn/mkfj | ec98fdf82766d376d99f55659b413ad423608a90 | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | refs/heads/master | 2022-11-24T18:34:23.665540 | 2020-07-26T10:58:31 | 2020-07-26T10:58:31 | 276,013,519 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,299 | cpp | #include"jumpnrun/mover/bullet/Bubble.h"
#include"jumpnrun/mover/effect/Effect.h"
#include"jumpnrun/mover/effect/Circle.h"
#include"jumpnrun/mover/Barrier.h"
#include"jumpnrun/mover/bullet/Bullet.h"
#include"jumpnrun/system/Parmanent.h"
#include"jumpnrun/spell/Spell.h"
#include"jumpnrun/GRAPHICS.h"
using namespace jnr;
using namespace gfw;
using namespace gmtr;
#define $V Vector2D
RegisterMoverClass(Ball);
void Ball::initialize(int refx, int refy
, gmtr::Vector2D p, gmtr::Vector2D v, int power, OWNERHANDLE owner)
{
Bubble::initialize(refx, refy, p, v, power, owner);
phys.mass = 0;
interacting_with_stages = true;
interacting_with_blocks = false;
touch_and_dissapear = false;
this->hp = this->hp_max = 30;
phys.mass = 2;
wet = false;
smash_dimrate = 1.025;
v_target = v;
//this->Smash(v);
writeName("ball", name);
}
void Ball::run(jnr::JumpnRunData& data)
{
double vl2 = phys.v.l2();
if (vl2 <= 0.75)
{
this->owner = -1;
//return;
}
$V prev_v = phys.v;
Bubble::run(data);
if (fabs(this->v_reaction.x) >= 0.001)
{
this->owner = -1;
phys.v.x = -prev_v.x * 0.5;
v_target = $V(0, 0);
}
if (fabs(this->v_reaction.y) >= 0.001)
{
phys.v.y = -prev_v.y * 0.5;
v_target = $V(0, 0);
}
if (fabs(phys.v.x) < 0.25)
phys.v.x = 0;
if (phys.v.y < 0 && phys.v.y > -0.5)
phys.v.y = 0;
}
void Ball::drive(phsc::Physics& phys, jnr::JumpnRunData& data)
{
//drive and stop
if (v_target.x > 0)
{
phys.v.x += accel;
if (phys.v.x >= v_target.x)
phys.v.x = v_target.x;
}
else if (v_target.x < 0)
{
phys.v.x -= accel;
if (phys.v.x <= v_target.x)
phys.v.x = v_target.x;
}
else
{
if (phys.v.x > 0)
{
phys.v.x -= decel;
if (phys.v.x < 0)
phys.v.x = 0;
}
else if (phys.v.x < 0)
{
phys.v.x += decel;
if (phys.v.x > 0)
phys.v.x = 0;
}
}
}
void Ball::interact(jnr::Character& chara, jnr::JumpnRunData& data)
{
double vl2 = phys.v.l2();
if (vl2 <= 0.75)
{
return;
}
Bubble::interact(chara, data);
}
int Ball::damage(const Damage& d)
{
if (timer_invinc.moving())
return -1;
animation.reset(refx + width * 5, refy, d.stun_time, 1, width, height);
status = eStatus::Damaged;
v_target = $V(0, 0);
//this->Smash(d.smash);
this->phys.v = d.smash;
this->owner = d.owner;
hp -= d.power;
return d.power;
} | [
"https://twitter.com/Wonder_Horn"
] | https://twitter.com/Wonder_Horn |
99298b3126d1077bf6d3e09b2ec4bc153f761cec | 4b028d901bbb1bf5b4839d664176a03111c8c763 | /Multi-Level Inheritance.cpp | ecebe9e8d563a44dbdc222de2b2efa1bd2dad8e6 | [] | no_license | imsushant12/Inheritance-in-Cplusplus | 987e231e1397fb87c14fd53f12f8adb14d0793cb | d92bfa9092c2da5d539be966a180c8ffd7c1ff61 | refs/heads/main | 2023-01-08T09:06:20.542053 | 2020-11-04T03:12:36 | 2020-11-04T03:12:36 | 302,095,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | cpp | #include<bits/stdc++.h>
#include<iostream>
using namespace std;
class student
{
private: //can be protected as well
int id;
char name[20];
public:
void getstudent()
{
cout<<"\nEnter name : ";cin>>name;
cout<<"\nEnter id : ";cin>>id;
}
void putstudent()
{
cout<<"\nName is "<<name;
cout<<"\nID is "<<id;
}
};
class marks : public student
{
protected:
int m1,m2,m3;
public:
void getmarks()
{
cout<<"\nEnter marks of subject one : ";
cin>>m1;
cout<<"\nEnter marks of subject two : ";
cin>>m2;
cout<<"\nEnter marks of subject three : ";
cin>>m3;
}
};
class result : public marks
{
private:
int total;
float avg;
public:
void showdata()
{
total = m1+m2+m3;
cout<<"\nTotal marks = "<<total<<endl;
avg = (m1 + m2 + m3)/3;
cout<<"\nAverage marks = "<<avg<<endl;
}
};
int main()
{
result r;
r.getstudent();
r.getmarks();
r.putstudent();
r.showdata();
return 0;
}
| [
"noreply@github.com"
] | imsushant12.noreply@github.com |
7a16a09d297f6cef3c446ce23e83017124880220 | f400eaf8cb1b4772a8c1555d605c248e62bf9d12 | /2579 계단오르기/2579 계단오르기/main.cpp | c687cb8ab167d20dbfc56c5fda8e1ef15d74c5a6 | [] | no_license | dlrgy22/boj | cc7042a1ab3f3e127a12c0d35c92a194cd13ba89 | 7a58aaf15b9cd2deea5a0e450acd2e4ef638553f | refs/heads/master | 2020-12-09T18:58:02.149775 | 2020-03-17T06:12:25 | 2020-03-17T06:12:25 | 233,389,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int num;
cin>>num;
int stair[301],dp[301],i;
for(i=1;i<=num;i++){
cin>>stair[i];
}
dp[0]=0;
dp[1]=stair[1];
dp[2]=stair[2]+stair[1];
for(i=3;i<=num;i++){
dp[i]=max(stair[i]+dp[i-2],stair[i]+stair[i-1]+dp[i-3]);
}
cout<<dp[num];
}
| [
"jeong-ighyo@jeong-ighyoui-iMac.local"
] | jeong-ighyo@jeong-ighyoui-iMac.local |
3b208223498a05b3989a1a9248757559359e45ab | f0fed75abcf38c92193362b36d1fbf3aa30f0e73 | /android/frameworks/av/cmds/stagefright/ms12v1_3/ms12_user.cpp | f7dfb960c0d7a245f9e8786394da16699319fda9 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | jannson/BPI-1296-Android7 | b8229d0e7fa0da6e7cafd5bfe3ba18f5ec3c7867 | d377aa6e73ed42f125603961da0f009604c0754e | refs/heads/master | 2023-04-28T08:46:02.016267 | 2020-07-27T11:47:47 | 2020-07-27T11:47:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67,329 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "ms12_cmd.h"
#include "ms12_err.h"
#include "ms12_usage.h"
#define MS_EXTPCM_IN_SAMPLES 1536
#define MS_MAX_STR_LEN 1024
#define MS_MAJOR_VERSION "1"
#define MS_MINOR_VERSION "3"
#define MS_UPDATE_VERSION "1"
#define MS_DAP_MIN_VAL (-32767)
#define MS_DAP_MAX_VAL ( 32767)
/* Internal Function Declarations */
/** @brief This function retrieves the runtime dependant parameters from the parsed command line (or parsed command text file) */
static MS_RETVAL ms_get_runtime_params(MS_USE_CASE *p_use_case, MS_RUNTIME_PARAMS *p_runtime_params, DLB_GETPARAM_HANDLE h_getparam, int *err_code);
/** @brief This function retrieves the DAP parameters from the parsed command line (or parsed command text file) */
static MS_RETVAL ms_get_dap_params(dap_params_t *p_dap_params, DLB_GETPARAM_HANDLE h_getparam, int b_dap_vb_enable, int *err_code);
/** @brief Checks that the string has the specified suffix extension */
static MS_RETVAL ms_validate_extension(const char *param, const char *ext);
/** @brief Retrieves comma seperated integers from a string into an array */
static MS_RETVAL ms_get_int_array_from_str(char **p_csv_string, int num_el, int *p_vals);
/** @brief Retrieves integer from a string and returns address of next CSV integer */
static MS_RETVAL ms_get_int_from_str(char **p_csv_string, int *p_vals);
static MS_RETVAL set_int_check_gp_err(DLB_GETPARAM_RETVAL gp_err, int val, int *p_assign_val, int *err_code, int outofrange, int invalid);
static MS_RETVAL ms_validate_ac4trp(const char *param);
/*
* Documentation resides in header file only
*/
MS_RETVAL ms_parse_command_line(int argc, const char *argv[], MS_USE_CASE *p_use_case, MS_PARAMS *p_params, int *err_code)
{
/*** BEGIN VARIABLE DECLARATIONS ***/
/* Values read from switches */
const char *gp_string;
long int gp_value = 0;
DLB_GETPARAM_RETVAL gp_err;
int b_max_channels_set = 0;
/*** END VARIABLE DECLARATIONS ***/
/* Initialize GetParam */
if(argc > 1) {
gp_err = dlb_getparam_parse(p_params->h_getparam, argc, argv);
if (gp_err != DLB_GETPARAM_OK){
ms_show_banner();
ms_show_usage_brief();
return MS_HELPTEXT_REQUESTED;
}
}
else{
fprintf(stdout, "get input from textfile\n");
}
/* Detect the verbosity mode */
gp_err = dlb_getparam_int(p_params->h_getparam, "v", &gp_value, MS_MIN_VERBOSITY, MS_MAX_VERBOSITY);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_init_args.verbose_mode = (int16_t)gp_value;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
ms_show_banner();
*err_code = MS_ERR_INVALID_VERBOSE_MODE;
return MS_INVALID_PARAM;
}
if(p_params->ms_init_args.verbose_mode){
ms_show_banner();
}
/* Start by searching for the -h flag */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "h", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
if (strcmp(gp_string, "ddplus") == 0)
{
ms_show_usage_common_switches();
ms_show_usage_context_ddplus();
}
else if (strcmp(gp_string, "pcm") == 0)
{
ms_show_usage_common_switches();
ms_show_usage_context_pcm();
}
else if (strcmp(gp_string, "heaac") == 0)
{
ms_show_usage_common_switches();
ms_show_usage_context_heaac();
}
#ifdef MS12_AC4_SUPPORT
else if (strcmp(gp_string, "ac4") == 0)
{
ms_show_usage_common_switches();
ms_show_usage_context_ac4();
}
#endif
else if (strcmp(gp_string, "dap") == 0)
{
ms_show_usage_context_dap();
}
else if (strcmp(gp_string, "lc") == 0)
{
ms_show_usage_lc();
}
else if (strcmp(gp_string, "command.txt") == 0)
{
ms_show_usage_command_txt();
}
else
{
ms_show_usage_full();
}
*err_code = 0;
return MS_HELPTEXT_REQUESTED;
}
else if (gp_err == DLB_GETPARAM_NO_VALUE)
{
ms_show_usage_full();
*err_code = 0;
return MS_HELPTEXT_REQUESTED;
}
/* Check if the Processing Graph shall be initialized to low complexity mode */
gp_err = dlb_getparam_bool(p_params->h_getparam, "lc", &p_use_case->b_low_complexity);
if (gp_err != DLB_GETPARAM_OK)
{
return MS_INVALID_PARAM;
}
/* Check for input type indication */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "it", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
if (strcmp(gp_string, "DDP") == 0)
{
p_use_case->input_type = DOLBY_DIGITAL_PLUS;
}
else if (strcmp(gp_string, "AAC") == 0)
{
p_use_case->input_type = HE_AAC;
}
#ifdef MS12_AC4_SUPPORT
else if (strcmp(gp_string, "AC4") == 0)
{
p_use_case->input_type = AC4;
}
#endif
else if (strcmp(gp_string, "PCM") == 0)
{
p_use_case->input_type = EXTERNAL_PCM;
}
else
{
*err_code = MS_ERR_INVALID_INPUT_TYPE;
return MS_INVALID_PARAM;
}
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_INPUT_TYPE;
return MS_INVALID_PARAM;
}
/* Read the name of the main file */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "im", &p_params->ms_init_args.input_filename[0], MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_MISSING_INPUT_MAIN;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_OK)
{
*err_code = MS_ERR_INVALID_INPUT_FILE;
return MS_OPEN_FILE_ERROR;
}
else if (p_use_case->input_type == UNKNOWN)
{
/* Determine the extension and set the appropriate flag and use case */
if ( (ms_validate_extension(p_params->ms_init_args.input_filename[0], ".ec3") == 0) ||
(ms_validate_extension(p_params->ms_init_args.input_filename[0], ".ac3") == 0) )
{
p_use_case->input_type = DOLBY_DIGITAL_PLUS;
}
else if (ms_validate_extension(p_params->ms_init_args.input_filename[0], ".wav") == 0)
{
p_use_case->input_type = EXTERNAL_PCM;
}
else if ( (ms_validate_extension(p_params->ms_init_args.input_filename[0], "adts") == 0) ||
(ms_validate_extension(p_params->ms_init_args.input_filename[0], "loas") == 0) ||
(ms_validate_extension(p_params->ms_init_args.input_filename[0], ".mp4") == 0) )
{
p_use_case->input_type = HE_AAC;
}
#ifdef MS12_AC4_SUPPORT
else if ((ms_validate_extension(p_params->ms_init_args.input_filename[0], ".ac4") == 0)
|| (ms_validate_ac4trp(p_params->ms_init_args.input_filename[0]) == 0) )
{
p_use_case->input_type = AC4;
}
#endif
else
{
*err_code = MS_ERR_INVALID_INPUT_FILE_TYPE;
return MS_INVALID_PARAM;
}
}
if ((ms_validate_extension(p_params->ms_init_args.input_filename[0], ".mp4") == 0)
||(ms_validate_extension(p_params->ms_init_args.input_filename[0], ".trp") == 0) )
{
p_use_case->b_file_playback = 1;
}
if ( (p_use_case->input_type == HE_AAC) && p_use_case->b_low_complexity )
{
*err_code = MS_ERR_LC_UNSUPPORTED_HEAAC;
return MS_OPEN_FILE_ERROR;
}
/* Now, read the remaining common input and output parameters */
/* Associated input */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "ia", &p_params->ms_init_args.input_filename[1], MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM)
{
p_use_case->b_dual_input = 0;
}
else if (gp_err != DLB_GETPARAM_OK)
{
*err_code = MS_ERR_INVALID_INPUT_FILE;
return MS_OPEN_FILE_ERROR;
}
else if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_dual_input = 1;
if(p_use_case->b_low_complexity)
{
*err_code = MS_ERR_LC_UNSUPPORTED_ASSOC_MIX;
return MS_OPEN_FILE_ERROR;
}
/* Ensure that the main and associated inputs have the same file extensions */
if (p_use_case->input_type == DOLBY_DIGITAL_PLUS)
{
if ((ms_validate_extension(p_params->ms_init_args.input_filename[1], ".ec3") != 0) &&
(ms_validate_extension(p_params->ms_init_args.input_filename[1], ".ac3") != 0))
{
*err_code = MS_ERR_INCOMPATIBLE_INPUTS;
return MS_OPEN_FILE_ERROR;
}
}
else if (p_use_case->input_type == EXTERNAL_PCM)
{
/* no dual decoding for external PCM */
*err_code = MS_ERR_EXTPCM_ASSOCIATED_INPUT;
return MS_OPEN_FILE_ERROR;
}
else if ((p_use_case->input_type == HE_AAC) && (!p_use_case->b_file_playback))
{
if ((ms_validate_extension(p_params->ms_init_args.input_filename[1], "adts") != 0) &&
(ms_validate_extension(p_params->ms_init_args.input_filename[1], ".aac") != 0) &&
(ms_validate_extension(p_params->ms_init_args.input_filename[1], "loas") != 0))
{
*err_code = MS_ERR_INCOMPATIBLE_INPUTS;
return MS_OPEN_FILE_ERROR;
}
}
else if ((p_use_case->input_type == HE_AAC) && (p_use_case->b_file_playback))
{
if (ms_validate_extension(p_params->ms_init_args.input_filename[1], ".mp4") != 0)
{
*err_code = MS_ERR_INCOMPATIBLE_INPUTS;
return MS_OPEN_FILE_ERROR;
}
}
#ifdef MS12_AC4_SUPPORT
else if ((p_use_case->input_type == AC4) && (!p_use_case->b_file_playback))
{
if (ms_validate_extension(p_params->ms_init_args.input_filename[1], ".ac4") != 0)
{
*err_code = MS_ERR_INCOMPATIBLE_INPUTS;
return MS_OPEN_FILE_ERROR;
}
}
else if ((p_use_case->input_type == AC4) && (p_use_case->b_file_playback))
{
if ((ms_validate_extension(p_params->ms_init_args.input_filename[1], ".mp4") != 0)
&& (ms_validate_extension(p_params->ms_init_args.input_filename[1], ".trp") != 0) )
{
*err_code = MS_ERR_INCOMPATIBLE_INPUTS;
return MS_OPEN_FILE_ERROR;
}
}
#endif
}
/* 2nd main input instead of associated input */
if ( (p_use_case->input_type == DOLBY_DIGITAL_PLUS) /* 2nd main input is only available for DDP */
&& (p_use_case->b_dual_input == 0) /* 2nd main input and associate input cannot be specified together */
&& (p_use_case->b_low_complexity == 0) /* 2nd main input is not available in low complexity mode */
)
{
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "im2", &p_params->ms_init_args.input_filename[1], MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM)
{
/* no 2nd main input */
}
else if (gp_err != DLB_GETPARAM_OK)
{
*err_code = MS_ERR_INVALID_INPUT_FILE;
return MS_OPEN_FILE_ERROR;
}
else if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_dual_input = 1;
p_use_case->b_dual_main = 1;
/* Ensure that the 2nd main input has a DDP file extensions */
if ((ms_validate_extension(p_params->ms_init_args.input_filename[1], ".ec3") != 0) &&
(ms_validate_extension(p_params->ms_init_args.input_filename[1], ".ac3") != 0))
{
*err_code = MS_ERR_INCOMPATIBLE_INPUTS;
return MS_OPEN_FILE_ERROR;
}
}
}
/* System sounds input */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "is", &p_params->ms_init_args.input_filename[MS_SYSTEM_SOUNDS_IDX], MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM)
{
p_use_case->b_system_sounds = 0;
}
else if (gp_err != DLB_GETPARAM_OK)
{
*err_code = MS_ERR_INVALID_INPUT_FILE;
return MS_OPEN_FILE_ERROR;
}
else if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_system_sounds = 1;
if (ms_validate_extension(p_params->ms_init_args.input_filename[MS_SYSTEM_SOUNDS_IDX], ".wav") != 0)
{
*err_code = MS_ERR_INVALID_PCM_INPUT_FILE_EXT;
return MS_OPEN_FILE_ERROR;
}
}
/* Application sounds input */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "ias", &p_params->ms_init_args.input_filename[MS_APPLICATION_SOUNDS_IDX], MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM)
{
p_use_case->b_app_sounds = 0;
}
else if (gp_err != DLB_GETPARAM_OK)
{
*err_code = MS_ERR_INVALID_INPUT_FILE;
return MS_OPEN_FILE_ERROR;
}
else if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_app_sounds = 1;
if(p_use_case->b_low_complexity)
{
*err_code = MS_ERR_LC_UNSUPPORTED_APP_SOUND_IN;
return MS_OPEN_FILE_ERROR;
}
if (ms_validate_extension(p_params->ms_init_args.input_filename[MS_APPLICATION_SOUNDS_IDX], ".wav") != 0)
{
*err_code = MS_ERR_INVALID_PCM_INPUT_FILE_EXT;
return MS_OPEN_FILE_ERROR;
}
}
/* DD output */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "od", &p_params->ms_init_args.bitstream_output_filename[MS_DD_OUT_IDX], MS_MAX_STR_LEN);
if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_OK))
{
*err_code = MS_ERR_INVALID_DD_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
else if (gp_err == DLB_GETPARAM_OK)
{
if (p_use_case->b_low_complexity && (p_use_case->input_type == EXTERNAL_PCM))
{
*err_code = MS_ERR_LC_UNSUPPORTED_ENCODER;
return MS_INVALID_PARAM;
}
/* Ensure that the DD output file has the proper extension */
if (ms_validate_extension(p_params->ms_init_args.bitstream_output_filename[MS_DD_OUT_IDX], ".ac3") != 0)
{
*err_code = MS_ERR_INVALID_DD_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
}
/* DD+ output */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "odp", &p_params->ms_init_args.bitstream_output_filename[MS_DDP_OUT_IDX], MS_MAX_STR_LEN);
if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_OK))
{
*err_code = MS_ERR_INVALID_DDP_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
else if (gp_err == DLB_GETPARAM_OK)
{
if (p_use_case->b_low_complexity && (p_use_case->input_type == EXTERNAL_PCM))
{
*err_code = MS_ERR_LC_UNSUPPORTED_ENCODER;
return MS_INVALID_PARAM;
}
/* Ensure that the DD+ output file has the proper extension */
if (ms_validate_extension(p_params->ms_init_args.bitstream_output_filename[MS_DDP_OUT_IDX], ".ec3") != 0)
{
*err_code = MS_ERR_INVALID_DDP_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
}
if(p_params->ms_init_args.bitstream_output_filename[MS_DD_OUT_IDX] && p_params->ms_init_args.bitstream_output_filename[MS_DDP_OUT_IDX])
{
p_use_case->bs_output_mode = MS_BS_OUTPUT_MODE_SIM_DDP_DD;
}
else if(p_params->ms_init_args.bitstream_output_filename[MS_DD_OUT_IDX])
{
p_use_case->bs_output_mode = MS_BS_OUTPUT_MODE_DD;
}
else if(p_params->ms_init_args.bitstream_output_filename[MS_DDP_OUT_IDX])
{
p_use_case->bs_output_mode = MS_BS_OUTPUT_MODE_DDP;
}
else
{
p_use_case->bs_output_mode = MS_BS_OUTPUT_MODE_NONE;
}
/* 2-channel main output */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "oms", &p_params->ms_init_args.pcm_output_filename[MS_DOWNMIX_OUT_IDX], MS_MAX_STR_LEN);
if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_OK))
{
*err_code = MS_ERR_INVALID_2CH_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
else if (gp_err == DLB_GETPARAM_OK)
{
if (p_use_case->b_low_complexity && (p_use_case->input_type == EXTERNAL_PCM))
{
*err_code = MS_ERR_LC_UNSUPPORTED_DMX;
return MS_INVALID_PARAM;
}
/* Ensure that the 2-channel main output file has the proper extension */
if (ms_validate_extension(p_params->ms_init_args.pcm_output_filename[MS_DOWNMIX_OUT_IDX], ".wav") != 0)
{
*err_code = MS_ERR_INVALID_2CH_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
}
/* Output Parameter Text File */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "ot", &p_params->ms_init_args.pcmr_output_filename, MS_MAX_STR_LEN);
if (gp_err != DLB_GETPARAM_OK)
{
p_params->ms_init_args.pcmr_output_filename = NULL;
}
else if (p_use_case->b_low_complexity)
{
*err_code = MS_ERR_LC_UNSUPPORTED_TXT_OUT;
return MS_INVALID_PARAM;
}
if(p_use_case->input_type == DOLBY_DIGITAL_PLUS)
{
gp_err = dlb_getparam_int(p_params->h_getparam, "at", &gp_value, MS_MIN_ASSOC_SUBSTRM, MS_MAX_ASSOC_SUBSTRM);
if((gp_err == DLB_GETPARAM_UNDEFINED_PARAM) && !p_use_case->b_dual_input){
p_use_case->b_mainonly = 1;
}
else if(gp_err == DLB_GETPARAM_OK){
p_params->ms_runtime_args.ddplus_associated_substream = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ASSOCIATED_SUBSTREAM;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_ASSOCIATED_SUBSTREAM;
return MS_INVALID_PARAM;
}
}
#ifdef MS12_AC4_SUPPORT
/* Associated type selection - AC4 use-case only */
if(p_use_case->input_type == AC4)
{
p_params->ms_runtime_args.ac4_1st_pref_lang[0] = '\0';
p_params->ms_runtime_args.ac4_2nd_pref_lang[0] = '\0';
p_params->ms_runtime_args.ac4_pres_index[MS_MAIN_DECODER_IDX] = -1;
p_params->ms_runtime_args.ac4_pres_index[MS_ASSOC_DECODER_IDX] = -1;
p_params->ms_runtime_args.ac4_associated_type = 1;
p_params->ms_runtime_args.b_ac4_pref_assoc_type_over_lang = 1;
p_params->ms_runtime_args.ac4_prog_id_type = 0;
memset(p_params->ms_runtime_args.ac4_program_identifier_string, 0, sizeof(p_params->ms_runtime_args.ac4_program_identifier_string));
gp_err = dlb_getparam_int(p_params->h_getparam, "at", &gp_value, MS_MIN_AC4_ASSOC_TYPE, MS_MAX_AC4_ASSOC_TYPE);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_runtime_args.ac4_associated_type = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ASSOCIATED_TYPE;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_ASSOCIATED_TYPE;
return MS_INVALID_PARAM;
}
/* set default decoding mode depending on the number of input bitstreams. */
if(p_use_case->b_dual_input)
{
p_use_case->ac4_mode = AC4_MODE_DUAL_STREAM_DUAL_DECODE;
}
else
{
p_use_case->ac4_mode = AC4_MODE_SINGLE_STREAM_DUAL_DECODE_DUAL_INSTANCE;
}
gp_err = dlb_getparam_int(p_params->h_getparam, "ac4_mode", &gp_value, MS_MIN_AC4_MODE, MS_MAX_AC4_MODE);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->ac4_mode = (int)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_AC4_MODE;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_AC4_MODE;
return MS_INVALID_PARAM;
}
if ( ( p_use_case->b_dual_input && p_use_case->ac4_mode != AC4_MODE_DUAL_STREAM_DUAL_DECODE)
|| (!p_use_case->b_dual_input && p_use_case->ac4_mode == AC4_MODE_DUAL_STREAM_DUAL_DECODE))
{
*err_code = MS_ERR_INVALID_AC4_MODE;
return MS_INVALID_PARAM;
}
if(p_use_case->ac4_mode == AC4_MODE_SINGLE_STREAM_SINGLE_DECODE)
{
p_use_case->b_mainonly = 1;
}
/* Implement single PID dual decoding by reading from the main input bitstream twice */
if(p_use_case->ac4_mode == AC4_MODE_SINGLE_STREAM_DUAL_DECODE_DUAL_INSTANCE)
{
p_use_case->b_dual_input = 1;
p_params->ms_init_args.input_filename[1] = p_params->ms_init_args.input_filename[0];
}
/* associated is restricted to stereo */
p_use_case->b_restricted_ad = 1;
}
#endif
/* Main multichannel output */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "om", &p_params->ms_init_args.pcm_output_filename[MS_VIRTUALIZER_OUT_IDX], MS_MAX_STR_LEN);
if((gp_err != DLB_GETPARAM_OK) && (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_INVALID_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
else if(gp_err == DLB_GETPARAM_OK)
{
if(p_use_case->b_low_complexity)
{
*err_code = MS_ERR_LC_UNSUPPORTED_MC_OUT;
return MS_INVALID_PARAM;
}
/* Ensure that the main output file has the proper extension */
if (ms_validate_extension(p_params->ms_init_args.pcm_output_filename[MS_VIRTUALIZER_OUT_IDX], ".wav") != 0)
{
*err_code = MS_ERR_INVALID_OUTPUT_FILE_TYPE;
return MS_INVALID_PARAM;
}
}
/* DAP speaker output (2.1 channels) */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "o_dap_speaker", &p_params->ms_init_args.pcm_output_filename[MS_DAP_SPEAKER_OUT_IDX], MS_MAX_STR_LEN);
if((gp_err != DLB_GETPARAM_OK) && (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_INVALID_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
else if(gp_err == DLB_GETPARAM_OK)
{
p_params->ms_init_args.dap_output_mode |= MS_DAP_SPEAKER_OUT_ACTIVE;
/* Ensure that the DAP speaker output file has the proper extension */
if (ms_validate_extension(p_params->ms_init_args.pcm_output_filename[MS_DAP_SPEAKER_OUT_IDX], ".wav") != 0)
{
*err_code = MS_ERR_INVALID_OUTPUT_FILE_TYPE;
return MS_INVALID_PARAM;
}
}
/* DAP headphone output (2 channels) */
gp_err = dlb_getparam_maxlenstring(p_params->h_getparam, "o_dap_headphone", &p_params->ms_init_args.pcm_output_filename[MS_DAP_HEADPHONE_OUT_IDX], MS_MAX_STR_LEN);
if((gp_err != DLB_GETPARAM_OK) && (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_INVALID_OUTPUT_FILE;
return MS_INVALID_PARAM;
}
else if(gp_err == DLB_GETPARAM_OK)
{
p_params->ms_init_args.dap_output_mode |= MS_DAP_HEADPHONE_OUT_ACTIVE;
/* Ensure that the DAP headphone output file has the proper extension */
if (ms_validate_extension(p_params->ms_init_args.pcm_output_filename[MS_DAP_HEADPHONE_OUT_IDX], ".wav") != 0)
{
*err_code = MS_ERR_INVALID_OUTPUT_FILE_TYPE;
return MS_INVALID_PARAM;
}
}
/* Maximum number of channels in the processing chain */
gp_err = dlb_getparam_int(p_params->h_getparam, "max_channels", &gp_value, MS_MIN_MAX_CHANNEL, MS_MAX_MAX_CHANNEL);
if (gp_err == DLB_GETPARAM_OK)
{
if((int)gp_value == 7)
{
*err_code = MS_ERR_OUTOFRANGE_MAX_NUM_CHANNEL;
return MS_INVALID_PARAM;
}
p_params->ms_init_args.max_num_channels = (int)gp_value;
b_max_channels_set = 1;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_MAX_NUM_CHANNEL;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MAX_NUM_CHANNEL_VALUE;
return MS_INVALID_PARAM;
}
/* Encoder channel mode locking */
gp_err = dlb_getparam_int(p_params->h_getparam, "chmod_locking", &gp_value, MS_MIN_ENC_CHMOD_LOCK, MS_MAX_ENC_CHMOD_LOCK);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_init_args.enc_chmod_locking_mode = (int)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ENC_CHMOD_LOCK;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_ENC_CHMOD_LOCK_VALUE;
return MS_INVALID_PARAM;
}
if (p_use_case->b_low_complexity && (p_params->ms_init_args.max_num_channels > MS_LOW_COMPLEXITY_MAX_CHANNEL))
{
if(b_max_channels_set)
{
fprintf(stderr,"Warning: Low Complexity processing mode is limited to six channels. Parameter max_channels is set to six.\n");
}
p_params->ms_init_args.max_num_channels = MS_LOW_COMPLEXITY_MAX_CHANNEL;
}
#ifdef MS12_AC4_SUPPORT
if ( (p_use_case->input_type == AC4
)
&& (p_params->ms_init_args.max_num_channels > MS_AC4_MAX_CHANNEL)
)
{
if(b_max_channels_set)
{
fprintf(stderr,"Warning: AC4 decoding is limited to six output channels. Parameter max_channels is set to six.\n");
}
p_params->ms_init_args.max_num_channels = MS_AC4_MAX_CHANNEL;
}
#endif
/* downmix 7.1 to 5.1 for the multichannel PCM output */
gp_err = dlb_getparam_int(p_params->h_getparam, "mc_5_1_dmx", &gp_value, 0, 1);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_runtime_args.b_mc_5_1_dmx = (int)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_MC_5_1_DMX;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MC_5_1_DMX;
return MS_INVALID_PARAM;
}
/* Output WAV file bit-depth */
gp_err = dlb_getparam_int(p_params->h_getparam, "w", &gp_value, MS_MIN_WAVFILEBITDEPTH, MS_MAX_WAVFILEBITDEPTH);
if (gp_err == DLB_GETPARAM_OK)
{
if((int)gp_value % 8)
{
*err_code = MS_ERR_OUTOFRANGE_WAVFILEBITDEPTH;
return MS_INVALID_PARAM;
}
p_params->ms_init_args.wav_bit_depth = (int)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_WAVFILEBITDEPTH;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_WAVFILEBITDEPTH;
return MS_INVALID_PARAM;
}
/* precision of PCM data (SFRACT or LFRACT) */
gp_err = dlb_getparam_int(p_params->h_getparam, "p", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_init_args.b_high_risc_precision = (int)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_PCM_PREC_FLAG;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_PCM_PREC_FLAG;
return MS_INVALID_PARAM;
}
/* DAP mode */
gp_err = dlb_getparam_int(p_params->h_getparam, "dap_init_mode", &gp_value, MS_DAP_NO_PROC, MS_DAP_SI_PROC);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->dap_init_mode = (ms_dap_mode_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DAP_INIT_MODE;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DAP_INIT_MODE;
return MS_INVALID_PARAM;
}
else if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM && p_use_case->b_low_complexity)
{
p_use_case->dap_init_mode = MS_DAP_SI_PROC;
}
if (p_use_case->b_low_complexity && (p_use_case->dap_init_mode != MS_DAP_SI_PROC))
{
*err_code = MS_ERR_LC_UNSUPPORTED_DAP_INIT_MODE;
return MS_INVALID_PARAM;
}
/* DAP mode */
gp_err = dlb_getparam_int(p_params->h_getparam, "b_dap_vb_enable", &gp_value, 0, 1);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_dap_vb_enable = (ms_dap_mode_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DAP_VB_ENABLE;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DAP_VB_ENABLE;
return MS_INVALID_PARAM;
}
/* Read switches specific to external PCM reencoding */
if ((!p_use_case->b_dual_input) && (p_use_case->input_type == EXTERNAL_PCM))
{
gp_err = dlb_getparam_int(p_params->h_getparam, "rp", &gp_value, MS_MIN_COMP_PROF, MS_MAX_COMP_PROF);
if (gp_err == DLB_GETPARAM_OK)
{
if (p_use_case->b_low_complexity)
{
*err_code = MS_ERR_LC_UNSUPPORTED_ENCODER;
return MS_INVALID_PARAM;
}
p_params->ms_init_args.extpcm_compressor_profile = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_PCM_COMP_PROFILE;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_COMPRESSOR_PROFILE;
return MS_INVALID_PARAM;
}
}
/* Read switches specific to HE-AAC */
if (p_use_case->input_type == HE_AAC)
{
if (p_use_case->b_dual_input)
{
gp_err = dlb_getparam_int(p_params->h_getparam, "as", &gp_value, 0, 1);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_restricted_ad = (int)gp_value;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_ASSOCIATED_2CH_RESTRICT;
return MS_INVALID_PARAM;
}
}
gp_err = dlb_getparam_int(p_params->h_getparam, "dn", &gp_value, MS_MIN_DIALNORM, MS_MAX_DIALNORM);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_runtime_args.heaac_default_dialnorm = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_HEAAC_DIALNORM;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DIALNORM_VALUE;
return MS_INVALID_PARAM;
}
}
/* Detect the evaluation mode */
gp_err = dlb_getparam_int(p_params->h_getparam, "eval", &gp_value, 0, 1);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_eval_mode = (int16_t)gp_value;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_EVAL_MODE;
return MS_INVALID_PARAM;
}
/* Debug output mask */
gp_err = dlb_getparam_int(p_params->h_getparam, "dbgout", &gp_value, 0, 0x0FFFF);
if (gp_err == DLB_GETPARAM_OK)
{
p_params->ms_init_args.dbg_output_mask = (uint16_t)gp_value;
}
else if ((gp_err == DLB_GETPARAM_OUT_OF_RANGE) || (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_UNKNOWN_ERRCODE;
return MS_INVALID_PARAM;
}
#ifdef MS12_PLAYER_CMD_FOR_DDPENC_LISTENING_TEST
gp_err = dlb_getparam_int(p_params->h_getparam, "ddpenc_listen_acmod", &gp_value, 0, 21);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_system_sounds = (int)gp_value;
}
gp_err = dlb_getparam_int(p_params->h_getparam, "ddpenc_listen_datarate", &gp_value, 0, 1536);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_app_sounds = (int)gp_value;
}
gp_err = dlb_getparam_int(p_params->h_getparam, "ddpenc_listen_encodermode", &gp_value, 5, 13);
if (gp_err == DLB_GETPARAM_OK)
{
p_use_case->b_eval_mode = (int)gp_value;
}
#endif
return ms_get_runtime_params(p_use_case, &p_params->ms_runtime_args, p_params->h_getparam, err_code);
}
/*
* Documentation resides in declaration only
*/
static MS_RETVAL ms_get_runtime_params(MS_USE_CASE *p_use_case,
MS_RUNTIME_PARAMS *p_runtime_params,
DLB_GETPARAM_HANDLE h_getparam,
int *err_code)
{
DLB_GETPARAM_RETVAL gp_err;
long int gp_value;
const char *gp_string;
/* Dual-mono mode */
gp_err = dlb_getparam_int(h_getparam, "u", &gp_value, MS_MIN_DUALMONO, MS_MAX_DUALMONO);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->dual_mono = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DUALMONO;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DUALMONO_MODE;
return MS_INVALID_PARAM;
}
/* Boost factor - multi-channel */
gp_err = dlb_getparam_int(h_getparam, "b", &gp_value, MS_MIN_DRC_BOOST, MS_MAX_DRC_BOOST);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->drc_boost_fac_mc = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DRC_BOOST;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DRC_BOOST_FACTOR;
return MS_INVALID_PARAM;
}
/* Boost factor - 2-ch */
gp_err = dlb_getparam_int(h_getparam, "bs", &gp_value, MS_MIN_DRC_BOOST, MS_MAX_DRC_BOOST);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->drc_boost_fac_2ch = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DRC_BOOST;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DRC_BOOST_FACTOR;
return MS_INVALID_PARAM;
}
/* Cut factor - multi-channel */
gp_err = dlb_getparam_int(h_getparam, "c", &gp_value, MS_MIN_DRC_CUT, MS_MAX_DRC_CUT);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->drc_cut_fac_mc = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DRC_CUT;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DRC_CUT_FACTOR;
return MS_INVALID_PARAM;
}
/* Cut factor - 2-channel */
gp_err = dlb_getparam_int(h_getparam, "cs", &gp_value, MS_MIN_DRC_BOOST, MS_MAX_DRC_BOOST);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->drc_cut_fac_2ch = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DRC_CUT;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DRC_CUT_FACTOR;
return MS_INVALID_PARAM;
}
/* Channel configuration of the system sounds input */
gp_err = dlb_getparam_int(h_getparam, "chs", &gp_value, MS_MIN_SYS_SOUNDS_ACMOD, MS_MAX_SYS_SOUNDS_ACMOD);
if (gp_err == DLB_GETPARAM_OK)
{
if (p_use_case->b_low_complexity && (gp_value > 2))
{
*err_code = MS_ERR_LC_UNSUPPORTED_SYSSND_CHCFG;
return MS_INVALID_PARAM;
}
p_runtime_params->sys_sounds_channel_config.acmod = (uint16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_SYS_SOUNDS_ACMOD;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_SYS_SOUNDS_ACMOD;
return MS_INVALID_PARAM;
}
else if ((gp_err == DLB_GETPARAM_UNDEFINED_PARAM) && p_use_case->b_low_complexity)
{
p_runtime_params->sys_sounds_channel_config.acmod = 2;
}
/* LFE presence - system sounds input */
gp_err = dlb_getparam_int(h_getparam, "ls", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->sys_sounds_channel_config.b_lfe_present = (uint16_t)gp_value;
}
else if ((gp_err == DLB_GETPARAM_OUT_OF_RANGE) || (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_INVALID_LFE;
return MS_INVALID_PARAM;
}
else if (gp_err == DLB_GETPARAM_UNDEFINED_PARAM && p_use_case->b_low_complexity)
{
p_runtime_params->sys_sounds_channel_config.b_lfe_present = 0;
}
if (p_use_case->b_low_complexity && p_runtime_params->sys_sounds_channel_config.b_lfe_present)
{
*err_code = MS_ERR_LC_UNSUPPORTED_SYSSND_CHCFG;
return MS_INVALID_PARAM;
}
/* Channel configuration of the application sounds input */
gp_err = dlb_getparam_int(h_getparam, "chas", &gp_value, MS_MIN_APP_SOUNDS_ACMOD, MS_MAX_APP_SOUNDS_ACMOD);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->app_sounds_channel_config.acmod = (uint16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_APP_SOUNDS_ACMOD;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_APP_SOUNDS_ACMOD;
return MS_INVALID_PARAM;
}
/* LFE presence - application sounds input */
gp_err = dlb_getparam_int(h_getparam, "las", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->app_sounds_channel_config.b_lfe_present = (uint16_t)gp_value;
}
else if ((gp_err == DLB_GETPARAM_OUT_OF_RANGE) || (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_INVALID_LFE;
return MS_INVALID_PARAM;
}
/* Channel configuration of the external PCM input */
gp_err = dlb_getparam_int(h_getparam, "chp", &gp_value, MS_MIN_EXTPCM_ACMOD, MS_MAX_EXTPCM_ACMOD);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->extpcm_in_channel_config.acmod = (uint16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_EXTPCM_ACMOD;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_EXTPCM_ACMOD;
return MS_INVALID_PARAM;
}
/* LFE presence - external PCM input */
gp_err = dlb_getparam_int(h_getparam, "lp", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->extpcm_in_channel_config.b_lfe_present = (uint16_t)gp_value;
}
else if ((gp_err == DLB_GETPARAM_OUT_OF_RANGE) || (gp_err != DLB_GETPARAM_UNDEFINED_PARAM))
{
*err_code = MS_ERR_INVALID_LFE;
return MS_INVALID_PARAM;
}
/* Downmix mode */
gp_err = dlb_getparam_int(h_getparam, "dmx", &gp_value, MS_MIN_DMX, MS_MAX_DMX);
if (gp_err == DLB_GETPARAM_OK)
{
/* DD+ case: Only modes 0 (Lt/Rt) and 1 (Lo/Ro) are valid */
if ( ( (p_use_case->input_type == DOLBY_DIGITAL_PLUS)
)
&& ( (int16_t)gp_value == MS_DMX_TYPE_ARIB) )
{
*err_code = MS_ERR_INVALID_DDP_2CH_MODE;
return MS_INVALID_PARAM;
}
else if ((p_use_case->input_type == EXTERNAL_PCM) && ((int16_t)gp_value == MS_DMX_TYPE_ARIB))
{
*err_code = MS_ERR_INVALID_EXTPCM_2CH_MODE;
return MS_INVALID_PARAM;
}
else
{
p_runtime_params->downmix_type = (int16_t)gp_value;
}
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ST_DOWNMIX;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DMX_MODE;
return MS_INVALID_PARAM;
}
/* DRC mode */
gp_err = dlb_getparam_int(h_getparam, "drc", &gp_value, MS_MIN_DRC_MODE, MS_MAX_DRC_MODE);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->drc_mode = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_DRC_MODE;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_DRC_MODE;
return MS_INVALID_PARAM;
}
/* Associated substream selection - DD+ use-case only */
if(p_use_case->input_type == DOLBY_DIGITAL_PLUS)
{
/* only allow runtime switching of substream if we have substream selection used from the beginning */
if(p_runtime_params->ddplus_associated_substream)
{
gp_err = dlb_getparam_int(h_getparam, "at", &gp_value, MS_MIN_ASSOC_SUBSTRM, MS_MAX_ASSOC_SUBSTRM);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->ddplus_associated_substream = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ASSOCIATED_SUBSTREAM;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_ASSOCIATED_SUBSTREAM;
return MS_INVALID_PARAM;
}
}
}
#ifdef MS12_AC4_SUPPORT
/* Associated type selection - AC4 use-case only */
if(p_use_case->input_type == AC4)
{
gp_err = dlb_getparam_int(h_getparam, "at", &gp_value, MS_MIN_AC4_ASSOC_TYPE, MS_MAX_AC4_ASSOC_TYPE);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->ac4_associated_type = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ASSOCIATED_TYPE;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_ASSOCIATED_TYPE;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_int(h_getparam, "pat", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->b_ac4_pref_assoc_type_over_lang = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_PREFER_ASSOCIATED_TYPE;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_PREFER_ASSOCIATED_TYPE;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "lang", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
int n;
for(n=0; n<MS_AC4_LANG_MAX_STRLEN; n++)
{
p_runtime_params->ac4_1st_pref_lang[n] = gp_string[n];
if(gp_string[n] == '\0')
{
break;
}
}
p_runtime_params->ac4_1st_pref_lang[MS_AC4_LANG_MAX_STRLEN-1] = '\0';
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_MISSING_LANG_SELECTION;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "lang2", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
int n;
for(n=0; n<MS_AC4_LANG_MAX_STRLEN; n++)
{
p_runtime_params->ac4_2nd_pref_lang[n] = gp_string[n];
if(gp_string[n] == '\0')
{
break;
}
}
p_runtime_params->ac4_2nd_pref_lang[MS_AC4_LANG_MAX_STRLEN-1] = '\0';
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_MISSING_LANG_SELECTION;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_int(h_getparam, "ac4_de", &gp_value, MS_MIN_AC4_DE_GAIN, MS_MAX_AC4_DE_GAIN);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->ac4_de_gain = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_AC4_DE_GAIN;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_AC4_DE_GAIN;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_int(h_getparam, "ac4_main_pres_idx", &gp_value, MS_MIN_AC4_PRES_IDX, MS_MAX_AC4_PRES_IDX);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->ac4_pres_index[MS_MAIN_DECODER_IDX] = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_AC4_PRES_IDX;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_AC4_PRES_IDX;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_int(h_getparam, "ac4_assoc_pres_idx", &gp_value, MS_MIN_AC4_PRES_IDX, MS_MAX_AC4_PRES_IDX);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->ac4_pres_index[MS_ASSOC_DECODER_IDX] = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_AC4_PRES_IDX;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_AC4_PRES_IDX;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_int(h_getparam, "ac4_prog_id_type", &gp_value, MS_MIN_AC4_PROG_ID_TYPE, MS_MAX_AC4_PROG_ID_TYPE);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->ac4_prog_id_type = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_AC4_PROG_ID_TYPE;
return MS_INVALID_PARAM;
}
else if ((gp_err != DLB_GETPARAM_UNDEFINED_PARAM) && (gp_err != DLB_GETPARAM_ALREADY_GOT))
{
*err_code = MS_ERR_INVALID_AC4_PROG_ID_TYPE;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "ac4_prog_id", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
if(p_runtime_params->ac4_prog_id_type == 1)
{
long val = strtol(gp_string, NULL, 0);
if((val < MS_MIN_AC4_SHORT_PROG_ID) || (val > MS_MAX_AC4_SHORT_PROG_ID))
{
*err_code = MS_ERR_OUTOFRANGE_AC4_SHORT_PROG_ID;
return MS_INVALID_PARAM;
}
}
else if(p_runtime_params->ac4_prog_id_type == 2)
{
if(strlen(gp_string) != MS_PROGRAM_UUID_LEN_BYTES*2)
{
*err_code = MS_ERR_INVALID_UUID_PROG_ID;
return MS_INVALID_PARAM;
}
}
strncpy(p_runtime_params->ac4_program_identifier_string, gp_string, MS_PROGRAM_UUID_LEN_BYTES*2);
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
if(p_runtime_params->ac4_prog_id_type == 1)
{
*err_code = MS_ERR_INVALID_AC4_SHORT_PROG_ID;
}
else if(p_runtime_params->ac4_prog_id_type == 2)
{
*err_code = MS_ERR_INVALID_UUID_PROG_ID;
}
return MS_INVALID_PARAM;
}
}
#endif
p_runtime_params->b_sys_app_sound_mixing = 1; /* set mixing enabled as default */
gp_err = dlb_getparam_int(h_getparam, "xs", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->b_sys_app_sound_mixing = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_SYSSOUND_MIX;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_SYSSOUND_MIXING_VALUE;
return MS_INVALID_PARAM;
}
/* Associated program mixing and main/associated program user-balance - only for relevant use cases */
p_runtime_params->associated_audio_mixing = p_use_case->b_mainonly ? 0 : 1;
if ( ( (!p_use_case->b_mainonly && (p_use_case->input_type == DOLBY_DIGITAL_PLUS)) || p_use_case->b_dual_input )
&& !p_use_case->b_dual_main
)
{
gp_err = dlb_getparam_int(h_getparam, "xa", &gp_value, MS_MIN_BOOL_VAL, MS_MAX_BOOL_VAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->associated_audio_mixing = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_ASSOC_MIX;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_ASSOC_MIXING_VALUE;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_int(h_getparam, "xu", &gp_value, MS_MIN_USERBAL, MS_MAX_USERBAL);
if (gp_err == DLB_GETPARAM_OK)
{
p_runtime_params->user_balance_adjustment = (int16_t)gp_value;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = MS_ERR_OUTOFRANGE_USER_BALANCE;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_USER_BALANCE_VALUE;
return MS_INVALID_PARAM;
}
}
/* Mixer gains and fading ramps */
gp_err = dlb_getparam_maxlenstring(h_getparam, "main1_mixgain", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
char *tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_runtime_params->input_mix_input1.target_attenuation);
ms_get_int_from_str(&tmpstr, &p_runtime_params->input_mix_input1.duration_in_ms);
ms_get_int_from_str(&tmpstr, &p_runtime_params->input_mix_input1.type);
if ( (p_runtime_params->input_mix_input1.target_attenuation < -96) || (p_runtime_params->input_mix_input1.target_attenuation > 0)
|| (p_runtime_params->input_mix_input1.duration_in_ms < 0) || (p_runtime_params->input_mix_input1.duration_in_ms > 60000)
|| (p_runtime_params->input_mix_input1.type < 0) || (p_runtime_params->input_mix_input1.type > 2)
)
{
*err_code = MS_ERR_OUTOFRANGE_MIXER_FADE;
return MS_INVALID_PARAM;
}
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MIXER_FADE_VALUES;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "main2_mixgain", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
char *tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_runtime_params->input_mix_input2.target_attenuation);
ms_get_int_from_str(&tmpstr, &p_runtime_params->input_mix_input2.duration_in_ms);
ms_get_int_from_str(&tmpstr, &p_runtime_params->input_mix_input2.type);
if ( (p_runtime_params->input_mix_input2.target_attenuation < -96) || (p_runtime_params->input_mix_input2.target_attenuation > 0)
|| (p_runtime_params->input_mix_input2.duration_in_ms < 0) || (p_runtime_params->input_mix_input2.duration_in_ms > 60000)
|| (p_runtime_params->input_mix_input2.type < 0) || (p_runtime_params->input_mix_input2.type > 2)
)
{
*err_code = MS_ERR_OUTOFRANGE_MIXER_FADE;
return MS_INVALID_PARAM;
}
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MIXER_FADE_VALUES;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "sys_prim_mixgain", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
char *tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input1.target_attenuation);
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input1.duration_in_ms);
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input1.type);
if ( (p_runtime_params->syssound_mix_input1.target_attenuation < -96) || (p_runtime_params->syssound_mix_input1.target_attenuation > 0)
|| (p_runtime_params->syssound_mix_input1.duration_in_ms < 0) || (p_runtime_params->syssound_mix_input1.duration_in_ms > 60000)
|| (p_runtime_params->syssound_mix_input1.type < 0) || (p_runtime_params->syssound_mix_input1.type > 2)
)
{
*err_code = MS_ERR_OUTOFRANGE_MIXER_FADE;
return MS_INVALID_PARAM;
}
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MIXER_FADE_VALUES;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "sys_apps_mixgain", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
char *tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input2.target_attenuation);
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input2.duration_in_ms);
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input2.type);
if ( (p_runtime_params->syssound_mix_input2.target_attenuation < -96) || (p_runtime_params->syssound_mix_input2.target_attenuation > 0)
|| (p_runtime_params->syssound_mix_input2.duration_in_ms < 0) || (p_runtime_params->syssound_mix_input2.duration_in_ms > 60000)
|| (p_runtime_params->syssound_mix_input2.type < 0) || (p_runtime_params->syssound_mix_input2.type > 2)
)
{
*err_code = MS_ERR_OUTOFRANGE_MIXER_FADE;
return MS_INVALID_PARAM;
}
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MIXER_FADE_VALUES;
return MS_INVALID_PARAM;
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "sys_syss_mixgain", &gp_string, MS_MAX_STR_LEN);
if (gp_err == DLB_GETPARAM_OK)
{
char *tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input3.target_attenuation);
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input3.duration_in_ms);
ms_get_int_from_str(&tmpstr, &p_runtime_params->syssound_mix_input3.type);
if ( (p_runtime_params->syssound_mix_input3.target_attenuation < -96) || (p_runtime_params->syssound_mix_input3.target_attenuation > 0)
|| (p_runtime_params->syssound_mix_input3.duration_in_ms < 0) || (p_runtime_params->syssound_mix_input3.duration_in_ms > 60000)
|| (p_runtime_params->syssound_mix_input3.type < 0) || (p_runtime_params->syssound_mix_input3.type > 2)
)
{
*err_code = MS_ERR_OUTOFRANGE_MIXER_FADE;
return MS_INVALID_PARAM;
}
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = MS_ERR_INVALID_MIXER_FADE_VALUES;
return MS_INVALID_PARAM;
}
/* get DAP specific parameter */
if(ms_get_dap_params(&p_runtime_params->dap_parameter, h_getparam, p_use_case->b_dap_vb_enable, err_code))
{
return MS_INVALID_PARAM;
}
/* Now we are at the very end of command line parsing. Check for unhandled parameters */
if(dlb_getparam_left(h_getparam))
{
const char *name, *value;
dlb_getparam_nextremaining(h_getparam, &name, &value);
fprintf(stderr, "\n\nInapplicable or unsupported parameter - \"%s\"\n\n", name);
*err_code = MS_ERR_UNSUPPORTED_PARAMETER;
return MS_INVALID_PARAM;
}
return MS_OK;
}
static MS_RETVAL ms_get_dap_params(dap_params_t *p_dap_params, DLB_GETPARAM_HANDLE h_getparam, int b_dap_vb_enable, int *err_code)
{
/* Values read from switches */
const char *gp_string;
long int gp_value = 0;
DLB_GETPARAM_RETVAL gp_err;
char *tmpstr;
gp_err = dlb_getparam_int(h_getparam, "dap_calibration_boost", &gp_value, MS_DAP_MIN_VAL, MS_DAP_MAX_VAL);
if(set_int_check_gp_err(gp_err, gp_value, &p_dap_params->calibration_boost, err_code, MS_ERR_OUTOFRANGE_DAP_PARAM, MS_ERR_INVALID_DAP_VALUE))
return MS_INVALID_PARAM;
gp_err = dlb_getparam_int(h_getparam, "dap_surround_decoder_enable", &gp_value, 0, 1);
if(set_int_check_gp_err(gp_err, gp_value, &p_dap_params->surround_decoder_enable, err_code, MS_ERR_OUTOFRANGE_DAP_PARAM, MS_ERR_INVALID_DAP_VALUE))
return MS_INVALID_PARAM;
gp_err = dlb_getparam_int(h_getparam, "dap_dmx", &gp_value, MS_MIN_DAP_DMX_TYPE, MS_MAX_DAP_DMX_TYPE);
if(set_int_check_gp_err(gp_err, gp_value, &p_dap_params->dmx_type, err_code, MS_ERR_OUTOFRANGE_DAP_DMX_TYPE, MS_ERR_INVALID_DAP_DMX_TYPE))
return MS_INVALID_PARAM;
gp_err = dlb_getparam_int(h_getparam, "dap_drc", &gp_value, MS_MIN_DAP_DRC_TYPE, MS_MAX_DAP_DRC_TYPE);
if(set_int_check_gp_err(gp_err, gp_value, &p_dap_params->drc_type, err_code, MS_ERR_OUTOFRANGE_DAP_DRC_TYPE, MS_ERR_INVALID_DAP_DRC_TYPE))
return MS_INVALID_PARAM;
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_bass_enhancer", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->bass_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->bass_boost);
ms_get_int_from_str(&tmpstr, &p_dap_params->bass_cutoff);
ms_get_int_from_str(&tmpstr, &p_dap_params->bass_width);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_dialogue_enhancer", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->de_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->de_amount);
ms_get_int_from_str(&tmpstr, &p_dap_params->de_ducking);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_graphic_eq", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->eq_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->eq_nb_bands);
if(p_dap_params->eq_nb_bands > DAP_GEQ_MAX_BANDS)
{
*err_code = MS_ERR_DAP_GEQ_INVALID_NB_BANDS;
return MS_INVALID_PARAM;
}
ms_get_int_array_from_str(&tmpstr, p_dap_params->eq_nb_bands, &p_dap_params->a_geq_band_center[0]);
ms_get_int_array_from_str(&tmpstr, p_dap_params->eq_nb_bands, &p_dap_params->a_geq_band_target[0]);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_ieq", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->ieq_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->ieq_amount);
ms_get_int_from_str(&tmpstr, &p_dap_params->ieq_nb_bands);
if(p_dap_params->ieq_nb_bands > DAP_IEQ_MAX_BANDS)
{
*err_code = MS_ERR_DAP_IEQ_INVALID_NB_BANDS;
return MS_INVALID_PARAM;
}
ms_get_int_array_from_str(&tmpstr, p_dap_params->ieq_nb_bands, &p_dap_params->a_ieq_band_center[0]);
ms_get_int_array_from_str(&tmpstr, p_dap_params->ieq_nb_bands, &p_dap_params->a_ieq_band_target[0]);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_gains", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->postgain);
#ifdef DAP_PRE_AND_SYSTEM_GAIN_SUPPORTED
ms_get_int_from_str(&tmpstr, &p_dap_params->pregain);
ms_get_int_from_str(&tmpstr, &p_dap_params->systemgain);
#endif
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_leveler", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->leveler_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->leveler_amount);
ms_get_int_from_str(&tmpstr, &p_dap_params->leveler_ignore_il);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_mi_steering", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->mi_ieq_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->mi_dv_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->mi_de_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->mi_surround_enable);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_surround_virtualizer", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->virtualizer_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->headphone_reverb);
ms_get_int_from_str(&tmpstr, &p_dap_params->speaker_angle);
ms_get_int_from_str(&tmpstr, &p_dap_params->speaker_start);
ms_get_int_from_str(&tmpstr, &p_dap_params->surround_boost);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_optimizer", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
int ch;
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->optimizer_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->optimizer_nb_bands);
if(p_dap_params->optimizer_nb_bands > DAP_OPT_MAX_BANDS)
{
*err_code = MS_ERR_DAP_OPT_INVALID_NB_BANDS;
return MS_INVALID_PARAM;
}
ms_get_int_array_from_str(&tmpstr, p_dap_params->optimizer_nb_bands, &p_dap_params->a_opt_band_center_freq[0]);
for(ch=0; ch<DAP_MAX_CHANNELS; ch++)
{
if(!strncmp(tmpstr, "NULL", 4))
{
tmpstr += 5;
}
else
{
ms_get_int_array_from_str(&tmpstr, p_dap_params->optimizer_nb_bands, &p_dap_params->a_opt_band_gain[ch][0]);
}
}
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_regulator", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->regulator_enable);
ms_get_int_from_str(&tmpstr, &p_dap_params->regulator_mode);
ms_get_int_from_str(&tmpstr, &p_dap_params->regulator_overdrive);
ms_get_int_from_str(&tmpstr, &p_dap_params->regulator_timbre);
ms_get_int_from_str(&tmpstr, &p_dap_params->regulator_distortion);
ms_get_int_from_str(&tmpstr, &p_dap_params->reg_nb_bands);
if(p_dap_params->reg_nb_bands > DAP_REG_MAX_BANDS)
{
*err_code = MS_ERR_DAP_REG_INVALID_NB_BANDS;
return MS_INVALID_PARAM;
}
ms_get_int_array_from_str(&tmpstr, p_dap_params->reg_nb_bands, &p_dap_params->a_reg_band_center[0]);
ms_get_int_array_from_str(&tmpstr, p_dap_params->reg_nb_bands, &p_dap_params->a_reg_low_thresholds[0]);
ms_get_int_array_from_str(&tmpstr, p_dap_params->reg_nb_bands, &p_dap_params->a_reg_high_thresholds[0]);
ms_get_int_array_from_str(&tmpstr, p_dap_params->reg_nb_bands, &p_dap_params->a_reg_isolated_bands[0]);
}
gp_err = dlb_getparam_maxlenstring(h_getparam, "dap_virtual_bass", &gp_string, MS_MAX_STR_LEN);
if(gp_err == DLB_GETPARAM_OK)
{
if(b_dap_vb_enable)
{
tmpstr = (char *)gp_string;
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_mode);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_low_src_freq);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_high_src_freq);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_overall_gain);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_slope_gain);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_subgain[0]);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_subgain[1]);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_subgain[2]);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_mix_low_freq);
ms_get_int_from_str(&tmpstr, &p_dap_params->vb_mix_high_freq);
}
else
{
*err_code = MS_ERR_DAP_VB_NOT_ENABLED;
return MS_INVALID_PARAM;
}
}
return MS_OK;
}
static MS_RETVAL ms_init_dap_params(dap_params_t *p_dap_params)
{
memset(p_dap_params, MS_DAP_PARAM_NOT_SET, sizeof(dap_params_t));
return MS_OK;
}
/*
* Documentation resides in header file only
*/
void ms_init_params(MS_PARAMS *p_params)
{
/* set everything to 0 */
memset(&p_params->ms_init_args, 0, sizeof(p_params->ms_init_args));
memset(&p_params->ms_runtime_args, 0, sizeof(p_params->ms_runtime_args));
p_params->h_getparam = 0;
p_params->ms_init_args.max_num_channels = MS_MAX_MAX_CHANNEL;
p_params->ms_init_args.enc_chmod_locking_mode = 0;
p_params->ms_init_args.extpcm_compressor_profile = COMPPROF_FILMSTD;
p_params->ms_init_args.pcm_out_chans[MS_DOWNMIX_OUT_IDX] = 2;
p_params->ms_init_args.pcm_out_chans[MS_VIRTUALIZER_OUT_IDX] = MS_MAX_MAX_CHANNEL;
p_params->ms_init_args.pcm_out_chans[MS_DAP_SPEAKER_OUT_IDX] = 3;
p_params->ms_init_args.pcm_out_chans[MS_DAP_HEADPHONE_OUT_IDX] = 2;
p_params->ms_init_args.heaac_allow_partial_feed = 1;
p_params->ms_init_args.verbose_mode = 2;
p_params->ms_init_args.b_high_risc_precision = 1;
p_params->ms_runtime_args.heaac_default_dialnorm = 27*4; /* -27dB in dB/4 format */
p_params->ms_runtime_args.extpcm_num_in_samples = MS_EXTPCM_IN_SAMPLES;
p_params->ms_runtime_args.extpcm_in_channel_config.acmod = 7; /* DD_3_2 */
p_params->ms_runtime_args.extpcm_in_channel_config.b_lfe_present = 1;
p_params->ms_runtime_args.extpcm_in_channel_config.dsurmod = DSURMOD_NO_INDICATION;
p_params->ms_runtime_args.sys_sounds_num_in_samples = MS_EXTPCM_IN_SAMPLES;
p_params->ms_runtime_args.sys_sounds_channel_config.acmod = 2; /* DD_2_0 */
p_params->ms_runtime_args.sys_sounds_channel_config.b_lfe_present = 0;
p_params->ms_runtime_args.sys_sounds_channel_config.dsurmod = DSURMOD_NO_INDICATION;
p_params->ms_runtime_args.app_sounds_num_in_samples = MS_EXTPCM_IN_SAMPLES;
p_params->ms_runtime_args.app_sounds_channel_config.acmod = 7; /* DD_3_2 */
p_params->ms_runtime_args.app_sounds_channel_config.b_lfe_present = 1;
p_params->ms_runtime_args.app_sounds_channel_config.dsurmod = DSURMOD_NO_INDICATION;
p_params->ms_runtime_args.ddplus_outlfe = 1;
p_params->ms_runtime_args.ddplus_outmode = 7;
p_params->ms_runtime_args.drc_boost_fac_2ch = MS_MAX_DRC_BOOST;
p_params->ms_runtime_args.drc_boost_fac_mc = MS_MAX_DRC_BOOST;
p_params->ms_runtime_args.drc_cut_fac_2ch = MS_MAX_DRC_CUT;
p_params->ms_runtime_args.drc_cut_fac_mc = MS_MAX_DRC_CUT;
p_params->ms_runtime_args.heaac_mixing_mode = 1; /* blocking by default */
p_params->ms_runtime_args.multichannel_enable = 1; /* enable multichannel output per default */
p_params->ms_init_args.dbg_output_mask = 0;
ms_init_dap_params(&p_params->ms_runtime_args.dap_parameter);
}
/*
* Documentation resides in declaration only
*/
static MS_RETVAL ms_validate_extension(const char *param, const char *ext)
{
int counter = 0;
char temp[]="extn";
if (strlen(param) > MS_EXT_LENGTH)
{
for (counter = MS_EXT_LENGTH; counter > 0; counter--)
{
temp[MS_EXT_LENGTH-counter] = (char)tolower(param[strlen(param)-counter]);
}
}
if (strcmp(temp, ext) == 0)
return MS_OK;
else
return MS_INVALID_PARAM;
}
static MS_RETVAL ms_get_int_array_from_str(char **p_csv_string, int num_el, int *p_vals)
{
char *endstr;
int i;
for(i=0; i<num_el; i++)
{
p_vals[i] = strtol(*p_csv_string, &endstr, 0);
if(*p_csv_string == endstr)
{
return MS_INVALID_PARAM;
}
*p_csv_string = endstr+1;
}
return MS_OK;
}
static MS_RETVAL ms_get_int_from_str(char **p_csv_string, int *p_value)
{
char *endstr;
*p_value = strtol(*p_csv_string, &endstr, 0);
if(*p_csv_string == endstr)
{
return MS_INVALID_PARAM;
}
else
{
*p_csv_string = endstr+1;
return MS_OK;
}
}
static MS_RETVAL set_int_check_gp_err(DLB_GETPARAM_RETVAL gp_err, int val, int *p_assign_val, int *err_code, int outofrange, int invalid)
{
if(gp_err == DLB_GETPARAM_OK)
{
*p_assign_val = val;
}
else if (gp_err == DLB_GETPARAM_OUT_OF_RANGE)
{
*err_code = outofrange;
return MS_INVALID_PARAM;
}
else if (gp_err != DLB_GETPARAM_UNDEFINED_PARAM)
{
*err_code = invalid;
return MS_INVALID_PARAM;
}
return MS_OK;
}
static MS_RETVAL ms_validate_ac4trp(const char *param)
{
MS_RETVAL ret = MS_INVALID_PARAM;
char dst_extension[] = ".ac4.trp";
const int dst_length = strlen(dst_extension);
const int src_length = strlen(param);
if (src_length > dst_length)
{
const char *p_extension_begin = param + src_length - dst_length;
if (strncmp(p_extension_begin, dst_extension, dst_length) == 0)
{
ret = MS_OK;
}
}
return ret;
}
| [
"mingxin.android@gmail.com"
] | mingxin.android@gmail.com |
6e8b3a0f3aacecd144a3962a349498c1332d0075 | 82621767a8fffb6f5c1e0323879d4f2f7555e3b0 | /MicroAllocator/MicroAllocator.h | 338969c6aa35b499e91c9685f33349593ed9db2c | [
"Zlib"
] | permissive | abelianwang/malloc-survey | 40b46b1507ec8c5666157b53326d4a23e31ac88e | 6da5aca6aa2720d64bff709c111a5d8a5fa7a1be | refs/heads/master | 2023-03-18T09:16:13.401077 | 2016-07-06T15:11:27 | 2016-07-06T15:11:27 | 534,266,709 | 1 | 0 | Zlib | 2022-09-08T15:06:26 | 2022-09-08T15:06:26 | null | UTF-8 | C++ | false | false | 4,703 | h | #ifndef MICRO_ALLOCATOR_H
#define MICRO_ALLOCATOR_H
/*!
**
** Copyright (c) 2009 by John W. Ratcliff mailto:jratcliffscarab@gmail.com
**
** If you find this code useful or you are feeling particularily generous I would
** ask that you please go to http://www.amillionpixels.us and make a donation
** to Troy DeMolay.
**
** If you wish to contact me you can use the following methods:
**
** Skype ID: jratcliff63367
** email: jratcliffscarab@gmail.com
**
**
** The MIT license:
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is furnished
** to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// This code snippet provides a high speed micro-allocator.
//
// The concept is that you reserve an initial bank of memory for small allocations. Ideally a megabyte or two.
// The amount of memory reserved is equal to chunkSize*6
//
// All micro-allocations are split into 6 seperate pools.
// They are: 0-8 bytes
// 9-32 bytes
// 33-64 bytes
// 65-128 bytes
// 129-256 bytes
//
// On creation of the micro-allocation system you preserve a certiain amount of memory for each of these banks.
//
// The user provides a heap interface to callback for additional memory as needed.
//
// In most cases allocations are order-N and frees are order-N as well.
//
// The larger a buffer you provide, the closer to 'order-N' the allocator behaves.
//
// This kind of a micro-allocator is ideal for use with STL as it does many tiny allocations.
// All allocations are 16 byte aligned (with the exception of the 8 byte allocations, which are 8 byte aligned every other one).
//
namespace MICRO_ALLOCATOR
{
class HeapManager;
// creates a heap manager that uses micro-allocations for all allocations < 256 bytes and standard malloc/free for anything larger.
HeapManager * createHeapManager(size_t defaultChunkSize=32768);
void releaseHeapManager(HeapManager *heap);
// about 10% faster than using the virtual interface, inlines the functions as much as possible.
void * heap_malloc(HeapManager *hm,size_t size);
void heap_free(HeapManager *hm,void *p);
void * heap_realloc(HeapManager *hm,void *oldMem,size_t newSize);
}; // end of namespace
using namespace MICRO_ALLOCATOR;
// Jerry Coffin
//#pragma once
#include <stdlib.h>
#include <new>
#include <limits>
namespace micro {
template <class T>
struct allocator {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U> struct rebind { typedef allocator<U> other; };
allocator() throw() {}
allocator(const allocator&) throw() {}
template <class U> allocator(const allocator<U>&) throw(){}
~allocator() throw() {}
pointer address(reference x) const { return &x; }
const_pointer address(const_reference x) const { return &x; }
pointer allocate(size_type s, void const * = 0) {
if (0 == s)
return NULL;
pointer temp = (pointer)heap_malloc( get(), (s * sizeof(T)) );
if (temp == NULL)
throw std::bad_alloc();
return temp;
}
void deallocate(pointer p, size_type) {
heap_free( get(), p );
}
size_type max_size() const throw() {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
void construct(pointer p, const T& val) {
new((void *)p) T(val);
}
void destroy(pointer p) {
p->~T();
}
static HeapManager *get() {
static HeapManager *hmg = createHeapManager(5*1024*1024); // 4mb max for each heap when microallocating (<=1024 bytes)
return hmg;
}
};
}
#endif
| [
"rlyeh.nospam@gmail.com"
] | rlyeh.nospam@gmail.com |
8ca2f33793d778ae0599cfcd332376cfdea601f2 | 5e25ec6fcddb07eb7de490a353e92e14a7d357f2 | /inc/Resources/STB_Image_Loader.h | 730fe9bf929b500a9ed37d845ea3b8781b732ffe | [] | no_license | retrodump/vapor_engine | 13aaf8e763a2ef775922e11860579e619402baef | 1d462d4cfa33af057f3bea0ec87d07eb91daa168 | refs/heads/master | 2021-09-03T06:57:51.782716 | 2012-06-07T00:53:16 | 2012-06-07T00:53:16 | 116,496,920 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,183 | h | /************************************************************************
*
* vapor3D Engine © (2008-2010)
*
* <http://www.vapor3d.org>
*
************************************************************************/
#pragma once
#ifdef ENABLE_IMAGE_STB
#include "Resources/ResourceLoader.h"
#include "Resources/Image.h"
NAMESPACE_RESOURCES_BEGIN
//-----------------------------------//
/**
* This codec provides image decoding services using stb_image.
*/
REFLECT_DECLARE_CLASS(STB_Image_Loader)
class STB_Image_Loader : public ResourceLoader
{
REFLECT_DECLARE_OBJECT(STB_Image_Loader)
public:
STB_Image_Loader();
// Creates the resource with no data.
RESOURCE_LOADER_PREPARE(Image)
// Gets the class of the resource.
RESOURCE_LOADER_CLASS(Image)
// Decode an image file to a buffer.
virtual bool decode(ResourceLoadOptions&) OVERRIDE;
// Gets the name of this codec.
GETTER(Name, const String, "STB_IMAGE")
// Overrides this to return the right resource group.
GETTER(ResourceGroup, ResourceGroup::Enum, ResourceGroup::Images)
};
//-----------------------------------//
NAMESPACE_RESOURCES_END
#endif | [
"triton@e0e46c49-be69-4f5a-ad62-21024a331aea"
] | triton@e0e46c49-be69-4f5a-ad62-21024a331aea |
82ce01c6c37b00a7d2c4b2380df864ad3e4db518 | c456402dcc0a87a7a65c1efe4084638d9e0b3d96 | /lib/edd-dbg/src/windows/dbghelp.hpp | d2bed3dec8f8947b71146dbe7a775f24e6e2a8d5 | [
"MIT"
] | permissive | Try/OpenGothic | 059be5c346235f94942309e7ac07b80e8392e3cc | e70d3865887f316b458d33065fa428edf72c496e | refs/heads/master | 2023-08-29T19:04:30.564135 | 2023-08-21T22:19:42 | 2023-08-21T22:19:42 | 165,291,205 | 910 | 102 | MIT | 2023-09-08T14:16:46 | 2019-01-11T18:32:20 | C++ | UTF-8 | C++ | false | false | 4,296 | hpp | // Copyright Edd Dawson 2012
// 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 DBGHELP_HPP_0123_28082012
#define DBGHELP_HPP_0123_28082012
#include <windows.h>
extern "C"
{
// Some Windows types and structures not defined in the MinGW windows headers:
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680203%28v=vs.85%29.aspx
typedef struct _IMAGEHLP_SYMBOL64
{
DWORD SizeOfStruct;
DWORD64 Address;
DWORD Size;
DWORD Flags;
DWORD MaxNameLength;
CHAR Name[1]; // MSDN says this is a TCHAR[1]. It lies, even with ANSI/Unicode fudgery in effect.
}
IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms679272%28v=vs.85%29.aspx
enum ADDRESS_MODE
{
AddrMode1616,
AddrMode1632,
AddrModeReal,
AddrModeFlat
};
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms679272%28v=vs.85%29.aspx
typedef struct _tagADDRESS64
{
DWORD64 Offset;
WORD Segment;
ADDRESS_MODE Mode;
}
ADDRESS64, *LPADDRESS64;
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680346%28v=vs.85%29.aspx
typedef struct _KDHELP64
{
DWORD64 Thread;
DWORD ThCallbackStack;
DWORD ThCallbackBStore;
DWORD NextCallback;
DWORD FramePointer;
DWORD64 KiCallUserMode;
DWORD64 KeUserCallbackDispatcher;
DWORD64 SystemRangeStart;
DWORD64 KiUserExceptionDispatcher;
DWORD64 StackBase;
DWORD64 StackLimit;
DWORD64 Reserved[5];
}
KDHELP64, *PKDHELP64;
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680559%28v=vs.85%29.aspx
typedef BOOL (CALLBACK *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE, DWORD64, PVOID, DWORD, LPDWORD);
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms679354%28v=vs.85%29.aspx
typedef PVOID (CALLBACK *PFUNCTION_TABLE_ACCESS_ROUTINE64)(HANDLE, DWORD64);
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms679361%28v=vs.85%29.aspx
typedef DWORD64 (CALLBACK *PGET_MODULE_BASE_ROUTINE64)(HANDLE, DWORD64);
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms681399%28v=vs.85%29.aspx
typedef DWORD64 (CALLBACK *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE, HANDLE, LPADDRESS64);
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms680646%28v=vs.85%29.aspx
typedef struct _tagSTACKFRAME64
{
ADDRESS64 AddrPC;
ADDRESS64 AddrReturn;
ADDRESS64 AddrFrame;
ADDRESS64 AddrStack;
ADDRESS64 AddrBStore;
PVOID FuncTableEntry;
DWORD64 Params[4];
BOOL Far;
BOOL Virtual;
DWORD64 Reserved[3];
KDHELP64 KdHelp;
}
STACKFRAME64, *LPSTACKFRAME64;
}
namespace dbg
{
namespace ms
{
// Wrappers around functions from dbghelp.dll.
// They load the dll dynamically as required and take a lock
// internally to ensure proper threaded access as demanded by
// MSDN.
//
// Of course, some other code might be using dbghelp functions
// independently, but there's not a lot we can do synchronize
// correctly with that.
BOOL WINAPI SymInitialize(HANDLE, PCSTR, BOOL);
BOOL WINAPI SymCleanup(HANDLE) ;
DWORD64 WINAPI SymGetModuleBase64(HANDLE, DWORD64);
BOOL WINAPI SymGetSymFromAddr64(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
PVOID WINAPI SymFunctionTableAccess64(HANDLE, DWORD64);
BOOL WINAPI StackWalk64(DWORD,
HANDLE,
HANDLE,
LPSTACKFRAME64,
PVOID,
PREAD_PROCESS_MEMORY_ROUTINE64,
PFUNCTION_TABLE_ACCESS_ROUTINE64,
PGET_MODULE_BASE_ROUTINE64,
PTRANSLATE_ADDRESS_ROUTINE64);
} // ms
} // dbg
#endif // DBGHELP_HPP_0123_28082012
| [
"try9998@gmail.com"
] | try9998@gmail.com |
d13e85550ab17612c475f1297d2e3da08c899d9e | 97568959be7a920a86f75947f9ab661b20da300f | /samples/offscreenRendering/simpleWindow.h | c4dd918d9598f8d6c0f22ee37bf55281d2848812 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | kunitsyn/saiga | 73ae6db6bc37582076691e6ffd5af048ba77da2d | 0fa540f026007f7627b764e5bf2d5e1a33d4a5e1 | refs/heads/master | 2021-01-20T22:05:20.375569 | 2017-09-10T14:42:42 | 2017-09-10T14:42:42 | 101,798,210 | 0 | 0 | null | 2017-08-29T19:21:08 | 2017-08-29T19:21:07 | null | UTF-8 | C++ | false | false | 1,085 | h | /**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#pragma once
#include "saiga/rendering/renderer.h"
#include "saiga/world/proceduralSkybox.h"
#include "saiga/assets/all.h"
#include "saiga/assets/objAssetLoader.h"
#include "saiga/sdl/sdl_eventhandler.h"
#include "saiga/sdl/sdl_camera.h"
#include "saiga/sdl/sdl_window.h"
#include "saiga/rendering/lighting/directional_light.h"
using namespace Saiga;
class SimpleWindow : public Program
{
public:
SDLCamera<PerspectiveCamera> camera;
SimpleAssetObject cube1, cube2;
SimpleAssetObject groundPlane;
SimpleAssetObject sphere;
ProceduralSkybox skybox;
std::shared_ptr<DirectionalLight> sun;
SimpleWindow(OpenGLWindow* window);
~SimpleWindow();
void update(float dt) override;
void interpolate(float dt, float interpolation) override;
void render(Camera *cam) override;
void renderDepth(Camera *cam) override;
void renderOverlay(Camera *cam) override;
void renderFinal(Camera *cam) override;
};
| [
"darius.rueckert@fau.de"
] | darius.rueckert@fau.de |
6815dee25443f7cc663fe1c2f4ec7f034bb13fd5 | 2a2ab6381e0825574fcb93e1ed6748de12498ee8 | /include/tools/AssimpImporter.h | a87cc73b289f49d3df1057f5b07ad8375d91d827 | [
"MIT"
] | permissive | Ray1184/HPMSExtra | 9a88c1c8e2adb65b50d51918d3f32fda23579cf8 | 8e3d5415b6c6370b40e0dcd49a101fac3d8a8248 | refs/heads/master | 2023-01-20T09:08:36.576298 | 2020-11-30T19:06:48 | 2020-11-30T19:06:48 | 296,121,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,700 | h | /*!
* File AssimpImporter.h
*/
#pragma once
#include <string>
#include <sstream>
#include <assimp/scene.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <core/StdModelItem.h>
#include <core/AdvModelItem.h>
#include <core/Material.h>
#include <core/Mesh.h>
#include <common/Utils.h>
#define MAX_WEIGHTS 4
namespace hpms
{
struct Bone
{
size_t boneId;
std::string boneName;
glm::mat4 offsetMatrix;
Bone()
{}
Bone(size_t boneId, const std::string& boneName, const glm::mat4& offsetMatrix) : boneId(boneId),
boneName(boneName),
offsetMatrix(offsetMatrix)
{}
};
struct VertexWeight
{
unsigned int boneId;
unsigned int vertexId;
float weight;
VertexWeight()
{}
VertexWeight(unsigned int boneId, unsigned int vertexId, float weight) : boneId(boneId), vertexId(vertexId),
weight(weight)
{}
};
class AnimNode : public HPMSObject
{
private:
std::vector<AnimNode*> children;
std::vector<glm::mat4> transformations;
std::string name;
AnimNode* parent;
public:
AnimNode(std::string pname, AnimNode* pparent) : name(pname), parent(pparent)
{
}
~AnimNode()
{
for (AnimNode* child : children)
{
hpms::SafeDelete(child);
}
}
inline void AddTransform(const glm::mat4 mat)
{
transformations.push_back(mat);
}
inline const std::vector<AnimNode*>& GetChildren() const
{
return children;
}
inline void AddChild(AnimNode* node)
{
children.push_back(node);
}
inline void SetChildren(const std::vector<AnimNode*>& children)
{
AnimNode::children = children;
}
inline const std::vector<glm::mat4>& GetTransformations() const
{
return transformations;
}
inline void SetTransformations(const std::vector<glm::mat4>& transformations)
{
AnimNode::transformations = transformations;
}
inline const std::string& GetName() const
{
return name;
}
inline void SetName(const std::string& name)
{
AnimNode::name = name;
}
inline AnimNode* GetParent() const
{
return parent;
}
inline void SetParent(AnimNode* parent)
{
AnimNode::parent = parent;
}
inline const std::string Name() const override
{
return "AnimNode";
}
};
class AssimpImporter
{
public:
static AdvModelItem* LoadModelItem(std::string& path, std::string& textDirs);
private:
static void ProcessMaterial(aiMaterial* aiMat, std::vector<Material>& materials, std::string& textDirs);
static void ProcessMesh(aiMesh* aiMesh, std::vector<Mesh>& meshes, std::vector<Material>& materials,
std::vector<Bone>& bones);
static void
ProcessAnimations(const aiScene* aiScene, std::vector<Bone>& bones, AnimNode* rootNode, glm::mat4 rootTransform,
std::vector<hpms::Animation>& animations,
std::vector<std::string>& boneNames);
static void BuildAnimationFrames(std::vector<Bone>& bones, AnimNode* animRootNode, glm::mat4 rootTransform,
std::vector<hpms::Frame>& animationFrames,
std::vector<std::string>& boneNames);
inline static AnimNode* ProcessGraph(aiNode* aiNod, AnimNode* parent)
{
std::string nodeName = aiNod->mName.data;
//AnimNode* animNode = new AnimNode(nodeName, parent);
AnimNode* animNode = hpms::SafeNew<AnimNode>(nodeName, parent);
unsigned int numChildren = aiNod->mNumChildren;
for (int i = 0; i < numChildren; i++)
{
aiNode* aiChildNod = aiNod->mChildren[i];
AnimNode* childAnimNode = ProcessGraph(aiChildNod, animNode);
animNode->AddChild(childAnimNode);
}
return animNode;
}
inline static AnimNode* Find(const std::string& name, AnimNode* parent)
{
AnimNode* res = nullptr;
if (parent->GetName().compare(name) == 0)
{
res = parent;
} else
{
for (AnimNode* child : parent->GetChildren())
{
res = Find(name, child);
if (res != nullptr)
{
break;
}
}
}
return res;
}
inline static void BuildTransFormationMatrices(aiNodeAnim* aiNodAnim, AnimNode* animNode)
{
unsigned int numFrames = aiNodAnim->mNumPositionKeys;
aiVectorKey* posKeys = aiNodAnim->mPositionKeys;
aiVectorKey* scaleKeys = aiNodAnim->mScalingKeys;
aiQuatKey* rotKeys = aiNodAnim->mRotationKeys;
for (int i = 0; i < numFrames; i++)
{
aiVectorKey posKey = posKeys[i];
aiVector3D vec = posKey.mValue;
glm::mat4 transfMat(1.0);
transfMat = glm::translate(transfMat, glm::vec3(vec.x, vec.y, vec.z));
aiQuatKey quatKey = rotKeys[i];
aiQuaternion quat = quatKey.mValue;
glm::quat rot(quat.w, quat.x, quat.y, quat.z);
glm::mat4 rotMat = glm::mat4_cast(rot);
transfMat = transfMat * rotMat;
if (i < aiNodAnim->mNumScalingKeys)
{
posKey = scaleKeys[i];
vec = posKey.mValue;
transfMat = glm::scale(transfMat, glm::vec3(vec.x, vec.y, vec.z));
}
animNode->AddTransform(transfMat);
}
}
inline static unsigned int GetAnimationFrames(AnimNode* parent)
{
unsigned int numFrames = parent->GetTransformations().size();
for (AnimNode* child : parent->GetChildren())
{
unsigned int childFrames = GetAnimationFrames(child);
numFrames = std::max(numFrames, childFrames);
}
return numFrames;
}
inline static glm::mat4 GetParentTransforms(AnimNode* node, unsigned int framePos)
{
if (node == nullptr)
{
return glm::mat4(1.0);
}
glm::mat4 parentTransform = GetParentTransforms(node->GetParent(), framePos);
std::vector<glm::mat4> transformations = node->GetTransformations();
glm::mat4 nodeTransform(1.0);
unsigned int transfSize = transformations.size();
if (framePos < transfSize)
{
nodeTransform = transformations.at(framePos);
} else if (transfSize > 0)
{
nodeTransform = transformations.at(transfSize - 1);
}
glm::mat4 res = parentTransform * nodeTransform;
return res;
}
};
}
| [
"nickgreppi1184@gmail.com"
] | nickgreppi1184@gmail.com |
ac7761e65f791a9a0b6caec29b1c1469c3ea7964 | b18866e54d98b191a2c8af91e2e356533afce223 | /b5.cpp | 4503d14aed50546af217eca2c3e3dc5cf837f7b8 | [] | no_license | trongthanht3/baitapkithuatlaptrinhMTA | 49ab4e7fe1b23be62676e02dad13d7bb3b722ef9 | e2c9a825195d1c425a71e0aee58252fa1eb4d574 | refs/heads/master | 2020-07-14T04:15:06.258469 | 2019-12-31T15:00:28 | 2019-12-31T15:00:28 | 205,235,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | cpp | #include <iostream>
#include <conio.h>
using namespace std;
void kt_doixung(int a)
{
int goc = a;
int doi = 0;
while(goc > 0) {
doi = doi*10 + goc%10;
goc = goc/10;
}
if (doi == a)
cout << "doi xung" << endl;
else
cout << "khong doi" << endl;
}
int main()
{
int a;
char chk;
do {
cin >> a;
kt_doixung(a);
cout << "Press any key to continue. Esc to escape\n";
chk = getch();
} while (chk != 27);
return 0;
}
| [
"noreply@github.com"
] | trongthanht3.noreply@github.com |
0b1efcd293d3c5ecb2501f4be32995c4e9375e2d | 9b1b0c6d0543c46a9af4446bb73567452529adbb | /src/Serialize/test/LexerTest.cpp | b9ab9c4844fc42329fd968ff278bcebd8613047f | [
"MIT"
] | permissive | Loki-Astari/ThorsSerializer | cdc6a995e063b08de40685d164c25e177e1c7701 | 98b1495022c3961b34d558f7cec2cc295dde1ef9 | refs/heads/master | 2023-08-19T04:23:43.814659 | 2023-08-08T20:59:25 | 2023-08-08T20:59:25 | 4,123,363 | 298 | 78 | MIT | 2023-07-04T22:57:18 | 2012-04-24T10:10:30 | C++ | UTF-8 | C++ | false | false | 1,355 | cpp | #include "SerializeConfig.h"
#include "gtest/gtest.h"
#include "JsonManualLexer.h"
#include "JsonLexemes.h"
using ThorsAnvil::Serialize::JsonManualLexer;
TEST(LexerTest, JsonArrayTokens)
{
std::stringstream stream("[],");
JsonManualLexer lexer(stream);
EXPECT_EQ('[', lexer.yylex());
EXPECT_EQ(']', lexer.yylex());
EXPECT_EQ(',', lexer.yylex());
}
TEST(LexerTest, JsonMapTokens)
{
std::stringstream stream("{}:,");
JsonManualLexer lexer(stream);
EXPECT_EQ('{', lexer.yylex());
EXPECT_EQ('}', lexer.yylex());
EXPECT_EQ(':', lexer.yylex());
EXPECT_EQ(',', lexer.yylex());
}
TEST(LexerTest, JsonValueTokens)
{
std::stringstream stream(R"("Test" 456 789.123 true false null)");
JsonManualLexer lexer(stream);
EXPECT_EQ(ThorsAnvil::Serialize::JSON_STRING, lexer.yylex());
lexer.getRawString();
EXPECT_EQ(ThorsAnvil::Serialize::JSON_NUMBER, lexer.yylex());
lexer.getRawString();
EXPECT_EQ(ThorsAnvil::Serialize::JSON_NUMBER, lexer.yylex());
lexer.getRawString();
EXPECT_EQ(ThorsAnvil::Serialize::JSON_TRUE, lexer.yylex());
lexer.getRawString();
EXPECT_EQ(ThorsAnvil::Serialize::JSON_FALSE, lexer.yylex());
lexer.getRawString();
EXPECT_EQ(ThorsAnvil::Serialize::JSON_NULL, lexer.yylex());
lexer.getRawString();
}
| [
"Loki.Astari@gmail.com"
] | Loki.Astari@gmail.com |
e242a122cb52ec74aab147b580eed69ffe045e61 | 02a06f0ff931cd59dda969130f61d7f75fca7ff1 | /ESC Controller/ESC_Controller_CAN/ESC_Controller_CAN/ESC_Controller_CAN.ino | f62656a8d2e6140623d4381abd5b14b0c232534d | [] | no_license | UAlberta-EcoCar/MotorController_Firmware | 7657972870a6936a687539d56ecdde6a7be5c927 | 078715ac91d073945dd072018eb01a9fe74135c6 | refs/heads/master | 2020-04-15T15:22:46.501582 | 2016-05-14T21:06:11 | 2016-05-14T21:06:11 | 51,389,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,838 | ino | #include "esc_can.h"
#include "esc.h"
#include "sensors.h"
#include "hardware.h"
//Create objects for classes
Servo motor;
Can myCan;
Sensors mySensors;
Esc myEsc;
uint16_t curr_val = 0; // Translates voltage to current
uint16_t velocity; // Translates encoder values to speed
int enc1_val = 0; // Initiate variables to calculate speed
int enc_inc = 0;
int enc1_count = 0;
int enc1_avg = 0;
int count = 0;
int enc1_hold = 0;
uint16_t runtime = 0; // End speed calculation variables
uint16_t throttle = 0; // Analog value of gas pedal
uint16_t brake = 0; // Analog value of brake pedal
///////Testing variables///////
// uint16_t test_speed = 20; // To be used with testing motor without throttle values
bool test_flag = false;
/////End Testing Variables/////
void setup() {
Serial.begin(BR); // Initialize Serial Output
// while (!Serial); //holds program up until Serial is working
myEsc.begin(); // ONE
// myCan.begin(); // Initialize CAN - Currently does nothing, talk to Reagan
pinMode(CAN_INT, INPUT); // Initialize CAN pin
pinMode(enc1, INPUT); // Initialize Encoder pins
// pinMode(enc2, INPUT);
// pinMode(enc3, INPUT); // End Encoder pin initialization
pinMode(curr_sens_pin, INPUT); // Initialize Current Pin
pinMode(pinger_pin, INPUT); // Initialize Pinger Pin
}
void loop() {
/////////////////Check CAN////////////////////////
myCan.read(); //TWO
if(digitalRead(CAN_INT) == 0) //If there was a "message received interrupt"
{
digitalWrite(led1, !digitalRead(led1));
Serial.print("Read something");
Serial.println(millis());
}
//////////////Throttle and Brake//////////////
// if (myCan.throttle_available()) {
// throttle = myCan.throttle();
// Serial.print("Throttle: ");
// Serial.println(throttle);
// }
//
// if (myCan.brake_available()) {
// brake = myCan.brake();
// Serial.print("Brake: ");
// Serial.println(brake);
// }
//
// if (brake < 50) {
// myEsc.write(throttle);
// Serial.println("Throttle Value Deployed");
// }
// else {
// myEsc.write(0);
// Serial.println("Brake Deployed");
// }
// myEsc.test(test_speed); //Function used when testing motor without throttle values
/////////////////Current//////////////////////
// curr_val = mySensors.mcurrent(curr_sens_pin); // Attain current value
// Serial.print("Current Value: ");
// Serial.println(curr_val);
//
// myCan.send_mcurrent(curr_val); // Send current value via CAN
/////////////////Speed////////////////////////
// velocity = mySensors.mspeed(enc1_count, enc_inc, enc1_avg, enc1_val, enc1_hold, count, wheel_diam, gear_rat, runtime, speedtimer);
//
// myCan.send_mspeed(velocity);
/////////////////Pinger////////////////////////
// distance = mySensors.pinger(XX);
// myCan.send_pinger(distance);
}
| [
"bardwell@ualberta.ca"
] | bardwell@ualberta.ca |
591312caf06f382acda4c49ed292139b36d006cb | 53693584fcbddba5b348f993397aee66c2bfcea5 | /MustDo GFG/prefixSum.cpp | d42be0323e94130116a023a15f6994758ee041b9 | [] | no_license | dcesahil20/DSA-Cracker-Sahil | 34a83d8c9cbcd8e512c316301ec6a4652fd3445a | e86b19f1d26150f146bfd008eb82a9ee8b6d6c34 | refs/heads/main | 2023-04-13T23:38:44.837335 | 2021-05-04T15:53:01 | 2021-05-04T15:53:01 | 353,414,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | cpp | // prefixSumLeft[i] = prefixSumLeft[i-1] + arr[i]
// prefixSumRight[i] = prefixSumRight[i+1] + arr[i]
#include <iostream>
using namespace std;
void printArr(int arr[], int n){
for(int i=0; i<n; i++){
cout << arr[i] << " ";
}
}
int main(){
int input[] = {1,3,6,10,2,1,2,3,2};
int arrsize = sizeof(input)/sizeof(input[0]);
int preArrL[arrsize];
preArrL[0] = input[0];
for(int i=1; i<arrsize; i++){
preArrL[i] = preArrL[i-1] + input[i];
}
printArr(preArrL,arrsize);
cout << endl;
int preArrR[arrsize];
int end = arrsize-1;
preArrR[end] = input[end];
for (int i=end-1; i>=0; i--){
preArrR[i] = preArrR[i+1] + input[i];
}
printArr(preArrR, arrsize);
} | [
"sahil@innowatts.com"
] | sahil@innowatts.com |
9ae8b85355f2e7836511b5081e341dfdd831e6b4 | d23a545857f4cbf5a89bf1dd74aa885c0eee8630 | /src/google/protobuf/testing/zcgzip.cc | 5204cf5413799377678696d9a3cc3a9960e409d9 | [
"LicenseRef-scancode-protobuf"
] | permissive | chrisvana/protobuf_copy | be316d19535db57e82bb8ac03eb0027693e5d4d6 | 8888cdc45485deee2367ac112af22d77a085a24b | refs/heads/master | 2021-01-25T06:36:55.786139 | 2015-01-06T00:53:17 | 2015-01-06T00:53:17 | 13,333,902 | 0 | 0 | null | 2014-02-11T20:39:00 | 2013-10-04T20:22:32 | C++ | UTF-8 | C++ | false | false | 2,812 | cc | // Protocol Buffers - Google's data interchange format
// Copyright 2009 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: brianolson@google.com (Brian Olson)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// Test program to verify that GzipOutputStream is compatible with command line
// gzip or java.util.zip.GzipOutputStream
//
// Reads data on standard input and writes compressed gzip stream to standard
// output.
#include "third_party/protobuf/config.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <google/protobuf/io/gzip_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::GzipOutputStream;
int main(int argc, const char** argv) {
FileOutputStream fout(STDOUT_FILENO);
GzipOutputStream out(&fout);
int readlen;
while (true) {
void* outptr;
int outlen;
bool ok;
do {
ok = out.Next(&outptr, &outlen);
if (!ok) {
break;
}
} while (outlen <= 0);
readlen = read(STDIN_FILENO, outptr, outlen);
if (readlen <= 0) {
out.BackUp(outlen);
break;
}
if (readlen < outlen) {
out.BackUp(outlen - readlen);
}
}
return 0;
}
| [
"chris.vana@gmail.com"
] | chris.vana@gmail.com |
b0ba598ab42e7b455578d7cc5f216cb1f1839a6d | ddbebb14b892bb7baccacdb61035941dd3bf0d75 | /Labs/Lab11/priority_queue.h | caca1d104a49bf5f1a67fb7e12b60c3240b498df | [] | no_license | samuelbmarks/CSCI-1200 | 04d416943ec26611184bce8ea9069a7e6faf3b22 | b177a23a1eb7678557b0032e110073c55adc6206 | refs/heads/master | 2023-02-04T19:22:14.867935 | 2020-12-28T23:31:03 | 2020-12-28T23:31:03 | 312,116,135 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,703 | h | #ifndef priority_queue_h_
#define priority_queue_h_
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
template <class T>
class priority_queue {
private:
std::vector<T> m_heap;
public:
priority_queue() {}
priority_queue( std::vector<T> const& values )
{
m_heap = std::vector<T>(values.size()); //creating vectors of size of the the vector passed in
for (int i = values.size()-1; i >= 0; --i) //moving backwards through values, assgining values into m_heap
m_heap[i] = values[i];
for (int i = 0; i < values.size(); i++)
percolate_up(i);
}
const T& top() const
{
assert( !m_heap.empty() );
return m_heap[0];
}
void percolate_up(unsigned int i){
while (i != 0 && m_heap[i] < m_heap[(i-1)/2]){
swap(m_heap[i],m_heap[(i-1)/2]);
i = (i-1)/2; //checking that i is greater than zero (not the first index/top)
}
}
void push( const T& entry )
{
m_heap.push_back(entry); //adding entry
unsigned int i = m_heap.size()-1; //setting i to back of vector
percolate_up(i); //percolate up from i
}
void percolate_down(unsigned int i){
while(i <= m_heap.size()/2){ //while i is less than or equal to halfway point in heap
unsigned int j = 0;
if (2*i+2 < m_heap.size() && m_heap[2*i+2] < m_heap[2*i+1] ) //if right child is greater than left child
j = 2*i+2;
else
j = 2*i+1;
if(m_heap[j] < m_heap[i]){
T temp = m_heap[i];
m_heap[i] = m_heap[j];
m_heap[j] = temp;
i = j;
}
else
break;
}
}
void pop()
{
assert( !m_heap.empty() );
m_heap[0] = m_heap[m_heap.size()-1];
m_heap.pop_back();
percolate_down(0);
}
int size() { return m_heap.size(); }
bool empty() { return m_heap.empty(); }
// The following three functions are used for debugging.
// Check to see that internally the heap property is realized.
bool check_heap( )
{
return this->check_heap( this->m_heap );
}
// Check an external vector to see that the heap property is realized.
bool check_heap( const std::vector<T>& heap )
{
if (heap.size() <= 1) { return true; }
for(unsigned int i = 0; i < heap.size()/2; ++i){
if (2*i+1 < heap.size() && heap[i] > heap[2*i+1] ) { return false; }
if (2*i+2 < heap.size() && heap[i] > heap[2*i+2] ) { return false; }
}
return true;
}
// A utility to print the contents of the heap. Use it for debugging.
void print_heap( std::ostream & ostr )
{
for ( unsigned int i=0; i<m_heap.size(); ++i )
ostr << i << ": " << m_heap[i] << std::endl;
}
};
#endif | [
"59059975+thesammarks@users.noreply.github.com"
] | 59059975+thesammarks@users.noreply.github.com |
1f3d7f5c2babe1fe9ffce6d4fc993e15d149c98c | 85e098156370fdb3d513f20edfa8a514fe55175f | /higan/audio/stream.cpp | dc39be220111cfc34c237a84b0fbcc8a50dbb06b | [] | no_license | jeapostrophe/higan | 65efcbf70bd43ccb48cd3f8dddb7264bbef1b132 | c6fc15f8d26080b9d08e7bc029532c2f59a902ba | refs/heads/master | 2021-01-09T20:42:11.304359 | 2016-09-14T11:55:53 | 2016-09-14T11:55:53 | 62,882,832 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | auto Stream::reset(uint channels_, double inputFrequency, double outputFrequency) -> void {
channels.reset();
channels.resize(channels_);
for(auto& channel : channels) {
if(outputFrequency / inputFrequency <= 0.5) {
channel.iir.resize(order / 2);
for(auto phase : range(order / 2)) {
double q = DSP::IIR::Biquad::butterworth(order, phase);
channel.iir[phase].reset(DSP::IIR::Biquad::Type::LowPass, 20000.0 / inputFrequency, q);
}
}
channel.resampler.reset(inputFrequency, outputFrequency);
}
}
auto Stream::pending() const -> bool {
return channels && channels[0].resampler.pending();
}
auto Stream::read(double* samples) -> uint {
for(auto c : range(channels)) samples[c] = channels[c].resampler.read();
return channels.size();
}
auto Stream::write(const double* samples) -> void {
for(auto c : range(channels)) {
double sample = samples[c] + 1e-25; //constant offset used to suppress denormals
for(auto& iir : channels[c].iir) sample = iir.process(sample);
channels[c].resampler.write(sample);
}
audio.process();
}
| [
"screwtape@froup.com"
] | screwtape@froup.com |
826833005d2c7bd318b69386641630ea7f70dd39 | a3a8c5d5a600904d217d7db4e1f3994d785fbfd0 | /myknob.cpp | 6250e5202146687625fdfc01e9c363fcb55c01b1 | [] | no_license | lyhopq/test | d2b4bc2aa8f069b4dd1fd74e55232528f1dac987 | 16baa87db9b85920333d6b7848868eeb7f3973b1 | refs/heads/master | 2021-01-13T02:08:03.659300 | 2010-06-22T14:37:05 | 2010-06-22T14:37:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,562 | cpp | #include <QPainter>
#include <QFontMetrics>
#include <QRect>
#include <QMouseEvent>
#include "myknob.h"
MyKnob::MyKnob(QString _l1, QString _l2, QWidget *parent)
: QFrame(parent), l1(_l1), l2(_l2)
{
angle = 135.0;
//resize(100, 100);
isMouseOn = false;
setMinimumHeight(60);
setMouseTracking(true);
}
void MyKnob::paintEvent(QPaintEvent *)
{
QFontMetrics fm(font());
static const int w = fm.width(l1);
static const int h = fm.height();
const int p = qMax(width()/4-w/2, 10);
const int r = qMin(width(), height()-h)/2 - 3;
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawText(p, h, l1);
painter.drawText(width()-p-w, h, l2);
//painter.setWindow(QRect(0,0,100,100));
const QPointF center(QPoint(width()/2, (height()+h)/2));
painter.drawEllipse(center, r, r);
rect = QRect(-r+center.x(), -r+center.y(), r*2, r*2);
if(isMouseOn)
{
painter.setBrush(QColor(Qt::green).light(120));
painter.drawRect(rect);
}
//painter.save();
/***
QRadialGradient gradient(center, r);
gradient.setColorAt(0, QColor(Qt::gray));
gradient.setColorAt(1.0, QColor(Qt::lightGray));
QBrush brush(gradient);
painter.setBrush(brush);
***/
painter.setBrush(QColor(Qt::lightGray));
painter.setPen(Qt::NoPen);
painter.drawEllipse(center, r-6, r-6);
//painter.restore();
painter.translate(center);
qreal a;
if(angle)
a = 45;
else
a = 135;
painter.rotate(-a);
const int width = qMax(14, r/5);
const int length = qMax(15, r/6);
painter.setPen(QColor(Qt::white));
painter.setBrush(Qt::NoBrush);
painter.drawRect(QRect(-(r+5), -width/2, r*2+5, width));
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(Qt::gray));
painter.drawRect(QRect(r-length, -width/2, length, width));
painter.setBrush(QColor(Qt::lightGray));
painter.drawRect(QRect(-(r+3), -width/2, length-5, width));
painter.setBrush(QColor(Qt::red));
painter.drawRect(QRect(r-length/2-3, -width/4, 5, width/2));
//painter.drawPoint(QPoint(r-6, 0));
//painter.restore();
}
void MyKnob::mousePressEvent(QMouseEvent *e)
{
if(e->button() == Qt::LeftButton && rect.contains(e->pos()))
{
emit clicked();
isMouseOn = false;
update();
}
}
void MyKnob::mouseMoveEvent(QMouseEvent *e)
{
if(rect.contains(e->pos()))
{
isMouseOn = true;
}
else
isMouseOn = false;
update();
}
| [
"lyhopq@gmail.com"
] | lyhopq@gmail.com |
3b1512a1ec37591d2a24ea0ea47cce4d6a1875ad | 8c4a5cc8b283baa300bc7def50488dd9b82a692e | /item.cpp | 0a9273e80418d387b6be1c6682c3a05d92de1f7d | [] | no_license | tsubaki4242/Witch | 425e73b3efb3bc9ccd59f0dc883c937a8f65f6bf | 8895fefaa7ff82e37e104eef3a9d2f2dcf6a2abf | refs/heads/main | 2023-08-11T16:18:32.566174 | 2021-09-29T03:49:44 | 2021-09-29T03:49:44 | 411,521,181 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 10,351 | cpp | #include "stdafx.h"
#include "item.h"
HRESULT item::init(int itemMAX, float range)
{
_bulletMax = itemMAX;
_range = range;
return S_OK;
}
void item::release()
{
}
void item::update()
{
}
void item::render()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end(); ++_viitem)
{
_viitem->itemImage->frameRender(getMemDC(),
_viitem->rc.left,
_viitem->rc.top,
_viitem->itemImage->getFrameX(), 0);
_viitem->count++;
if (_viitem->count % 5 == 0)
{
_viitem->itemImage->setFrameX(_viitem->itemImage->getFrameX() + 1);
//최대 프레임보다 커지면
if (_viitem->itemImage->getFrameX() >= _viitem->itemImage->getMaxFrameX())
{
_viitem->itemImage->setFrameX(0);
}
_viitem->count = 0;
}
}
}
void item::setitem(float x, float y)
{
if (_bulletMax < _vitem.size()) return;
tagItem Item;
ZeroMemory(&Item, sizeof(tagItem));
Item.itemImage = new image;
Item.itemImage->init("item/100점.bmp", 0, 0, 144, 32, 4, 1, true, RGB(255, 0, 255));
Item.speed = 20.0f;
Item.x = Item.fireX = x;
Item.y = Item.fireY = y;
Item.rc = RectMakeCenter(Item.x, Item.y,
Item.itemImage->getFrameWidth(),
Item.itemImage->getFrameHeight());
_vitem.push_back(Item);
}
void item::move()
{
}
void item::removeitem(int arrNum)
{
_vitem[arrNum].itemImage->release();
_vitem.erase(_vitem.begin() + arrNum);
}
HRESULT item2::init(int itemMAX, float range)
{
_bulletMax = itemMAX;
_range = range;
return S_OK;
}
void item2::release()
{
}
void item2::update()
{
}
void item2::render()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end(); ++_viitem)
{
_viitem->itemImage->frameRender(getMemDC(),
_viitem->rc.left,
_viitem->rc.top,
_viitem->itemImage->getFrameX(), 0);
_viitem->count++;
if (_viitem->count % 5 == 0)
{
_viitem->itemImage->setFrameX(_viitem->itemImage->getFrameX() + 1);
//최대 프레임보다 커지면
if (_viitem->itemImage->getFrameX() >= _viitem->itemImage->getMaxFrameX())
{
_viitem->itemImage->setFrameX(0);
}
_viitem->count = 0;
}
}
}
void item2::setitem(float x, float y)
{
if (_bulletMax < _vitem.size()) return;
tagItem Item;
ZeroMemory(&Item, sizeof(tagItem));
Item.itemImage = new image;
Item.itemImage->init("item/200점.bmp", 0, 0, 144, 32, 4, 1, true, RGB(255, 0, 255));
Item.speed = 20.0f;
Item.x = Item.fireX = x;
Item.y = Item.fireY = y;
Item.rc = RectMakeCenter(Item.x, Item.y,
Item.itemImage->getFrameWidth(),
Item.itemImage->getFrameHeight());
_vitem.push_back(Item);
}
void item2::move()
{
}
void item2::removeitem(int arrNum)
{
_vitem[arrNum].itemImage->release();
_vitem.erase(_vitem.begin() + arrNum);
}
//============================================================
HRESULT SOUL::init(int itemMAX, float range)
{
_bulletMax = itemMAX;
_range = range;
Bswitch = false;
return S_OK;
}
void SOUL::release()
{
}
void SOUL::update()
{
if (Bswitch)
{
_timer++;
move2();
if (_timer > 20)
{
Bswitch = false;
_timer = 0;
}
}
else
{
move();
}
}
void SOUL::render()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end(); ++_viitem)
{
_viitem->itemImage->frameRender(getMemDC(),
_viitem->rc.left,
_viitem->rc.top,
_viitem->itemImage->getFrameX(), 0);
_viitem->count++;
if (_viitem->count % 5 == 0)
{
_viitem->itemImage->setFrameX(_viitem->itemImage->getFrameX() + 1);
//최대 프레임보다 커지면
if (_viitem->itemImage->getFrameX() >= _viitem->itemImage->getMaxFrameX())
{
_viitem->itemImage->setFrameX(0);
}
_viitem->count = 0;
}
}
}
void SOUL::setitem(float x, float y)
{
if (_bulletMax < _vitem.size()) return;
tagItem Item;
ZeroMemory(&Item, sizeof(tagItem));
Item.itemImage = new image;
Item.itemImage->init("item/bell.bmp", 0, 0, 468, 72, 8, 1, true, RGB(255, 0, 255));
Item.speed = 20.0f;
Item.x = Item.fireX = x;
Item.y = Item.fireY = y;
Item.rc = RectMakeCenter(Item.x, Item.y,
Item.itemImage->getFrameWidth(),
Item.itemImage->getFrameHeight());
_vitem.push_back(Item);
}
void SOUL::move()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end();)
{
_viitem->x --;
_viitem->rc = RectMakeCenter(_viitem->x, _viitem->y,
_viitem->itemImage->getFrameWidth(),
_viitem->itemImage->getFrameHeight());
//사거리보다 더 멀리 나가면(?)
if (_range < getDistance(_viitem->x, _viitem->y, _viitem->fireX, _viitem->fireY))
{
SAFE_RELEASE(_viitem->itemImage);
SAFE_DELETE(_viitem->itemImage);
_viitem = _vitem.erase(_viitem);
}
else ++_viitem;
}
}
void SOUL::move2()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end();)
{
_viitem->x += 5;
_viitem->rc = RectMakeCenter(_viitem->x, _viitem->y,
_viitem->itemImage->getFrameWidth(),
_viitem->itemImage->getFrameHeight());
//사거리보다 더 멀리 나가면(?)
if (_range < getDistance(_viitem->x, _viitem->y, _viitem->fireX, _viitem->fireY))
{
SAFE_RELEASE(_viitem->itemImage);
SAFE_DELETE(_viitem->itemImage);
_viitem = _vitem.erase(_viitem);
}
else ++_viitem;
}
}
void SOUL::moveateck()
{
Bswitch = true;
}
void SOUL::removeitem(int arrNum)
{
_vitem[arrNum].itemImage->release();
_vitem.erase(_vitem.begin() + arrNum);
}
//=================================================
HRESULT SOUL1::init(int itemMAX, float range)
{
_bulletMax = itemMAX;
_range = range;
Bswitch = false;
return S_OK;
}
void SOUL1::release()
{
}
void SOUL1::update()
{
if (Bswitch)
{
_timer++;
move2();
if (_timer > 20)
{
Bswitch = false;
_timer = 0;
}
}
else
{
move();
}
}
void SOUL1::render()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end(); ++_viitem)
{
_viitem->itemImage->frameRender(getMemDC(),
_viitem->rc.left,
_viitem->rc.top,
_viitem->itemImage->getFrameX(), 0);
_viitem->count++;
if (_viitem->count % 5 == 0)
{
_viitem->itemImage->setFrameX(_viitem->itemImage->getFrameX() + 1);
//최대 프레임보다 커지면
if (_viitem->itemImage->getFrameX() >= _viitem->itemImage->getMaxFrameX())
{
_viitem->itemImage->setFrameX(0);
}
_viitem->count = 0;
}
}
}
void SOUL1::setitem(float x, float y)
{
if (_bulletMax < _vitem.size()) return;
tagItem Item;
ZeroMemory(&Item, sizeof(tagItem));
Item.itemImage = new image;
Item.itemImage->init("item/bell1.bmp", 0, 0, 468, 72, 8, 1, true, RGB(255, 0, 255));
Item.speed = 20.0f;
Item.x = Item.fireX = x;
Item.y = Item.fireY = y;
Item.rc = RectMakeCenter(Item.x, Item.y,
Item.itemImage->getFrameWidth(),
Item.itemImage->getFrameHeight());
_vitem.push_back(Item);
}
void SOUL1::move()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end();)
{
_viitem->x--;
_viitem->rc = RectMakeCenter(_viitem->x, _viitem->y,
_viitem->itemImage->getFrameWidth(),
_viitem->itemImage->getFrameHeight());
//사거리보다 더 멀리 나가면(?)
if (_range < getDistance(_viitem->x, _viitem->y, _viitem->fireX, _viitem->fireY))
{
SAFE_RELEASE(_viitem->itemImage);
SAFE_DELETE(_viitem->itemImage);
_viitem = _vitem.erase(_viitem);
}
else ++_viitem;
}
}
void SOUL1::move2()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end();)
{
_viitem->x += 5;
_viitem->rc = RectMakeCenter(_viitem->x, _viitem->y,
_viitem->itemImage->getFrameWidth(),
_viitem->itemImage->getFrameHeight());
//사거리보다 더 멀리 나가면(?)
if (_range < getDistance(_viitem->x, _viitem->y, _viitem->fireX, _viitem->fireY))
{
SAFE_RELEASE(_viitem->itemImage);
SAFE_DELETE(_viitem->itemImage);
_viitem = _vitem.erase(_viitem);
}
else ++_viitem;
}
}
void SOUL1::moveateck()
{
Bswitch = true;
}
void SOUL1::removeitem(int arrNum)
{
_vitem[arrNum].itemImage->release();
_vitem.erase(_vitem.begin() + arrNum);
}
////======================================================
HRESULT SOUL2::init(int itemMAX, float range)
{
_bulletMax = itemMAX;
_range = range;
Bswitch = false;
return S_OK;
}
void SOUL2::release()
{
}
void SOUL2::update()
{
if (Bswitch)
{
_timer++;
move2();
if (_timer > 20)
{
Bswitch = false;
_timer = 0;
}
}
else
{
move();
}
}
void SOUL2::render()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end(); ++_viitem)
{
_viitem->itemImage->frameRender(getMemDC(),
_viitem->rc.left,
_viitem->rc.top,
_viitem->itemImage->getFrameX(), 0);
_viitem->count++;
if (_viitem->count % 5 == 0)
{
_viitem->itemImage->setFrameX(_viitem->itemImage->getFrameX() + 1);
//최대 프레임보다 커지면
if (_viitem->itemImage->getFrameX() >= _viitem->itemImage->getMaxFrameX())
{
_viitem->itemImage->setFrameX(0);
}
_viitem->count = 0;
}
}
}
void SOUL2::setitem(float x, float y)
{
if (_bulletMax < _vitem.size()) return;
tagItem Item;
ZeroMemory(&Item, sizeof(tagItem));
Item.itemImage = new image;
Item.itemImage->init("item/bell2.bmp", 0, 0, 468, 72, 8, 1, true, RGB(255, 0, 255));
Item.speed = 20.0f;
Item.x = Item.fireX = x;
Item.y = Item.fireY = y;
Item.rc = RectMakeCenter(Item.x, Item.y,
Item.itemImage->getFrameWidth(),
Item.itemImage->getFrameHeight());
_vitem.push_back(Item);
}
void SOUL2::move()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end();)
{
_viitem->x--;
_viitem->rc = RectMakeCenter(_viitem->x, _viitem->y,
_viitem->itemImage->getFrameWidth(),
_viitem->itemImage->getFrameHeight());
//사거리보다 더 멀리 나가면(?)
if (_range < getDistance(_viitem->x, _viitem->y, _viitem->fireX, _viitem->fireY))
{
SAFE_RELEASE(_viitem->itemImage);
SAFE_DELETE(_viitem->itemImage);
_viitem = _vitem.erase(_viitem);
}
else ++_viitem;
}
}
void SOUL2::move2()
{
for (_viitem = _vitem.begin(); _viitem != _vitem.end();)
{
_viitem->x += 5;
_viitem->rc = RectMakeCenter(_viitem->x, _viitem->y,
_viitem->itemImage->getFrameWidth(),
_viitem->itemImage->getFrameHeight());
//사거리보다 더 멀리 나가면(?)
if (_range < getDistance(_viitem->x, _viitem->y, _viitem->fireX, _viitem->fireY))
{
SAFE_RELEASE(_viitem->itemImage);
SAFE_DELETE(_viitem->itemImage);
_viitem = _vitem.erase(_viitem);
}
else ++_viitem;
}
}
void SOUL2::moveateck()
{
Bswitch = true;
}
void SOUL2::removeitem(int arrNum)
{
_vitem[arrNum].itemImage->release();
_vitem.erase(_vitem.begin() + arrNum);
} | [
"rlaals9509@daum.net"
] | rlaals9509@daum.net |
6b5b924c3e2d0f8f9a9c076daab8a6759962bb99 | 4e8a5ecca87b92545e95b761f8a8441987ee9997 | /src/qt/coincontroldialog.cpp | 64a249ae7683329c8aebd381c68a178cdfe2ac3d | [
"MIT"
] | permissive | bitbaba/stakecoin | a26dd59f1c7ce6e8072e6ae72d45e3da1b57756d | eba741d33373ba270ca83761fe4c6747122cff09 | refs/heads/master | 2021-05-12T00:19:32.215196 | 2018-04-17T04:03:44 | 2018-04-17T04:03:44 | 117,529,340 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 33,245 | cpp | #include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "init.h"
#include "bitcoinunits.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "optionsmodel.h"
#include "coincontrol.h"
#include <QApplication>
#include <QCheckBox>
#include <QClipboard>
#include <QColor>
#include <QCursor>
#include <QDateTime>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
using namespace std;
QList<std::pair<QString, qint64> > CoinControlDialog::payAddresses;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
CoinControlDialog::CoinControlDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0)
{
ui->setupUi(this);
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
//lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
//unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
//contextMenu->addSeparator();
//contextMenu->addAction(lockAction);
//contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
//connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
//connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 110);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
ui->treeWidget->setColumnWidth(COLUMN_COINAGE, 100);
ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but dont show it
ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
}
CoinControlDialog::~CoinControlDialog()
{
delete ui;
}
void CoinControlDialog::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel() && model->getAddressTableModel())
{
updateView();
//updateLabelLocked();
CoinControlDialog::updateLabels(model, this);
}
}
// helper function str_pad
QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
{
while (s.length() < nPadLength)
s = sPadding + s;
return s;
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
{
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
{
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
CoinControlDialog::updateLabels(model, this);
}
// context menu
void CoinControlDialog::showMenu(const QPoint &point)
{
QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
if(item)
{
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
//if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
//{
// lockAction->setEnabled(false);
// unlockAction->setEnabled(true);
//}
//else
//{
// lockAction->setEnabled(true);
// unlockAction->setEnabled(false);
//}
}
else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
//lockAction->setEnabled(false);
//unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_AMOUNT));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_LABEL));
else
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
/*void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
updateLabelLocked();
}*/
// context menu action: unlock coin
/*void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}*/
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
}
// copy label "Priority" to clipboard
void CoinControlDialog::clipboardPriority()
{
QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
}
// copy label "Low output" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder);
}
else
{
if (logicalIndex == COLUMN_AMOUNT) // sort by amount
logicalIndex = COLUMN_AMOUNT_INT64;
if (logicalIndex == COLUMN_PRIORITY) // sort by priority
logicalIndex = COLUMN_PRIORITY_INT64;
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else
{
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_AMOUNT_INT64 || sortColumn == COLUMN_PRIORITY_INT64 || sortColumn == COLUMN_DATE || sortColumn == COLUMN_CONFIRMATIONS) ? Qt::DescendingOrder : Qt::AscendingOrder); // if amount,date,conf,priority then default => desc, else default => asc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else
coinControl->Select(outpt);
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
}
// helper function, return human readable label for priority number
QString CoinControlDialog::getPriorityLabel(double dPriority)
{
if (dPriority > 576000ULL) // at least medium, this number is from AllowFree(), the other thresholds are kinda random
{
if (dPriority > 5760000000ULL) return tr("highest");
else if (dPriority > 576000000ULL) return tr("high");
else if (dPriority > 57600000ULL) return tr("medium-high");
else return tr("medium");
}
else
{
if (dPriority > 5760ULL) return tr("low-medium");
else if (dPriority > 58ULL) return tr("low");
else return tr("lowest");
}
}
// shows count of locked unspent outputs
/*void CoinControlDialog::updateLabelLocked()
{
vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
}
else ui->labelLocked->setVisible(false);
}*/
void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
qint64 nPayAmount = 0;
bool fLowOutput = false;
bool fDust = false;
CTransaction txDummy;
CBlockIndex *pindex;
{
LOCK(cs_main);
pindex = pindexBest;
}
BOOST_FOREACH(const PAIRTYPE(QString, qint64) &payee, CoinControlDialog::payAddresses)
{
qint64 amount = payee.second;
nPayAmount += amount;
if (amount > 0)
{
if (amount < CENT)
fLowOutput = true;
}
}
QString sPriorityLabel = "";
int64 nAmount = 0;
int64 nPayFee = 0;
int64 nAfterFee = 0;
int64 nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
double dPriority = 0;
double dPriorityInputs = 0;
unsigned int nQuantity = 0;
int nQuantityUncompressed = 0;
vector<COutPoint> vCoinControl;
vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
nPayFee = nTransactionFee;
loop
{
txDummy.vin.clear();
txDummy.vout.clear();
nQuantity = 0;
nAmount = 0;
dPriorityInputs = 0;
nBytesInputs = 0;
CScript scriptChange = (CScript)vector<unsigned char>(24, 0);
// Inputs
BOOST_FOREACH(const COutput& out, vOutputs)
{
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
// Priority
dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
// Bytes
CTxDestination address;
vector<valtype> vSolutions;
txnouttype whichType;
if (Solver(out.tx->vout[out.i].scriptPubKey, whichType, vSolutions) && whichType == TX_PUBKEY)
{
nBytesInputs += 114;
}
else if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey))
{
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
if (!pubkey.IsCompressed())
nQuantityUncompressed++;
}
else
nBytesInputs += 148; // in all error cases, simply assume 148 here
}
else nBytesInputs += 148;
// Default change script for avatar mode
scriptChange = out.tx->vout[out.i].scriptPubKey;
}
// Outputs
BOOST_FOREACH(const PAIRTYPE(QString, qint64) &payee, CoinControlDialog::payAddresses)
{
QString address = payee.first;
qint64 amount = payee.second;
CScript scriptPubKey;
scriptPubKey.SetDestination(CBitcoinAddress(address.toStdString()).Get());
CTxOut txout(amount, scriptPubKey);
txDummy.vout.push_back(txout);
}
// calculation
if (nQuantity > 0)
{
nChange = nAmount - nPayAmount - nPayFee;
// if sub-cent change is required, the fee must be raised to at least unit's min fee
// or until nChange becomes zero
// NOTE: this depends on the exact behaviour of GetMinFee
if (nPayFee < MIN_TX_FEE && nChange > 0 && nChange < CENT)
{
int64 nMoveToFee = min(nChange, MIN_TX_FEE - nPayFee);
nChange -= nMoveToFee;
nPayFee += nMoveToFee;
}
// stakecoin: sub-cent change is moved to fee
if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
{
nPayFee += nChange;
nChange = 0;
}
if (nChange > 0)
{
// Add a change address in the outputs
CTxOut txout(0, (CScript)vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
}
// Bytes
nBytes = nBytesInputs + GetSerializeSize(*(CTransaction*)&txDummy, SER_NETWORK, PROTOCOL_VERSION);
// Priority
dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority)
sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority);
// Fee
int64 nFee = nTransactionFee * (1 + (int64)nBytes / 1000);
// Min Fee
int64 nMinFee = txDummy.GetMinFee(nBytes);
if (nPayFee < max(nFee, nMinFee))
{
nPayFee = max(nFee, nMinFee);
continue;
}
// after fee
nAfterFee = nAmount - nPayFee;
if (nAfterFee < 0)
nAfterFee = 0;
}
break;
}
// actually update labels
int nDisplayUnit = BitcoinUnits::BTC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "low output" and "change"
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes
l6->setText(sPriorityLabel); // Priority
l7->setText((fLowOutput ? (fDust ? tr("DUST") : tr("yes")) : tr("no"))); // Low Output / Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
// turn labels "red"
l5->setStyleSheet((nBytes >= 10000) ? "color:red;" : ""); // Bytes >= 10000
l6->setStyleSheet((dPriority <= 576000) ? "color:red;" : ""); // Priority < "medium"
l7->setStyleSheet((fLowOutput) ? "color:red;" : ""); // Low Output = "yes"
l8->setStyleSheet((nChange > 0 && nChange < CENT) ? "color:red;" : ""); // Change < 0.01BTC
// tool tips
l5->setToolTip(tr("This label turns red, if the transaction size is bigger than 10000 bytes.\n\n Can vary +/- 1 Byte per input."));
l6->setToolTip(tr("Transactions with higher priority get more likely into a block.\n\nThis label turns red, if the priority is smaller than \"medium\"."));
l7->setToolTip(tr("This label turns red, if any recipient receives an amount smaller than %1.\n\n This means the transaction will be rejected.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
l8->setToolTip(tr("If the change is smaller than %1 it will be added to the fees.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)));
dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip());
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip());
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip());
// Insufficient funds
QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
map<QString, vector<COutput> > mapCoins;
model->listCoins(mapCoins);
BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins)
{
QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode)
{
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
for (int i = 0; i < ui->treeWidget->columnCount(); i++)
itemWalletAddress->setBackground(i, QColor(248, 247, 246));
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
}
int64 nSum = 0;
double dPrioritySum = 0;
int nChildren = 0;
int nInputSum = 0;
BOOST_FOREACH(const COutput& out, coins.second)
{
int nInputSize = 148; // 180 if uncompressed public key
nSum += out.tx->vout[out.i].nValue;
nChildren++;
QTreeWidgetItem *itemOutput;
if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress);
else itemOutput = new QTreeWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = CBitcoinAddress(outputAddress).ToString().c_str();
// if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
CPubKey pubkey;
CKeyID *keyid = boost::get< CKeyID >(&outputAddress);
if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
nInputSize = 180;
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
}
else if (!treeMode)
{
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setData(COLUMN_AMOUNT_INT64, Qt::DisplayRole, out.tx->vout[out.i].nValue);
// date
itemOutput->setText(COLUMN_DATE, QDateTime::fromTime_t(out.tx->GetTxTime()).toUTC().toString("yy-MM-dd hh:mm"));
// immature PoS reward
if (out.tx->IsCoinStake() && out.tx->GetBlocksToMaturity() > 0 && out.tx->GetDepthInMainChain() > 0)
{
itemOutput->setBackground(COLUMN_CONFIRMATIONS, Qt::red);
itemOutput->setDisabled(true);
}
// confirmations
itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::DisplayRole, out.nDepth);
// coin age
int nDayWeight = (min((GetAdjustedTime() - out.tx->GetTxTime()), (int64) STAKE_MAX_AGE) - nStakeMinAge) / 86400;
int64 coinAge = max(out.tx->vout[out.i].nValue * nDayWeight / COIN, (int64) 0);
itemOutput->setData(COLUMN_COINAGE, Qt::DisplayRole, coinAge);
// priority
double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority));
itemOutput->setData(COLUMN_PRIORITY_INT64, Qt::DisplayRole, (int64)dPriority);
dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
nInputSum += nInputSize;
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, txhash.GetHex().c_str());
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
/*if (model->isLockedCoin(txhash, out.i))
{
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed"));
}*/
// set checkbox
if (coinControl->IsSelected(txhash, out.i))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode)
{
dPrioritySum = dPrioritySum / (nInputSum + 78);
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setData(COLUMN_AMOUNT_INT64, Qt::DisplayRole, nSum);
itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum));
itemWalletAddress->setData(COLUMN_PRIORITY_INT64, Qt::DisplayRole, (int64)dPrioritySum);
}
}
// expand all partially selected
if (treeMode)
{
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
unselectSpent();
}
// Unselect coins that were spent (e.g. to mint a block)
void CoinControlDialog::unselectSpent()
{
map<QString, vector<COutput> > mapCoins;
vector<COutPoint> vCoinControl;
vector<COutPoint> vDelete;
int found;
model->listCoins(mapCoins);
coinControl->ListSelected(vCoinControl);
BOOST_FOREACH(const COutPoint outpt, vCoinControl)
{
found = 0;
BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins)
{
BOOST_FOREACH(const COutput& out, coins.second)
{
COutPoint outpt2(out.tx->GetHash(), out.i);
if(outpt2 == outpt)
{
found = 1;
break;
}
}
if(found)
break;
}
if(!found)
vDelete.push_back(outpt);
}
BOOST_FOREACH(COutPoint outpt, vDelete)
{
coinControl->UnSelect(outpt);
}
}
| [
"imzhhwu@gmail.com"
] | imzhhwu@gmail.com |
8fcd3fc99cb64ac968009ced5ceaede7298a0314 | 7249f67bfb1b1c7deb1a254e608494d9a970a4af | /CAR_01/motor_ctlr.ino | ed4ef4f76631a7866ab4125106a742e6fccf8eea | [] | no_license | twinsyiu/tst_clone_3 | 592916861e1fdc2e23e0496ba9025136a0232266 | 8215247043c18c72340172ecf0bdc40870ba1b3f | refs/heads/master | 2021-01-20T22:24:14.177755 | 2017-12-03T10:05:31 | 2017-12-03T10:05:31 | 101,819,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,303 | ino | #include "motor_ctlr.h"
// TY: This section of definition of motor is finely trimmed and projected
// please do not change any of the motor orientation, motor connection, and i/o ports for the L298 H-bridge in1..in4
// without discuss with me
#define MOTOR_L 1
#define MOTOR_R 0
#define DIR_FWD 0
#define DIR_REV 1
#define DIR_IO_IDX 0
#define PWM_IO_IDX 1
// connect motor controller pins to Arduino digital pins
// motor one
const byte in1dir = 7; // Dir grey
const byte in2spd = 6; // Speed white
// motor two
const byte in4spd = 5; // Speed blue
const byte in3dir = 4; // Dir red
unsigned int motor_io[2][2] = {
{in1dir, in2spd}, // motor_io[0] : motor A Left
{in3dir, in4spd} // motor_io[1] : motor B Right
};
void motor_drive_sp( unsigned int L_R, unsigned int Fwd_Rev, unsigned int PWM_Spd)
{
unsigned int act_PWM;
#ifdef DEBUG
Serial.print("Motor (L:0/R:1)= ");
Serial.print(L_R);Serial.print(" Dir (Fwd:0/Rev:1)= ");Serial.print(Fwd_Rev);Serial.print(" PWM=");
Serial.println(PWM_Spd);
#endif
// this function will run the motors in both directions at a fixed speed
digitalWrite(motor_io[L_R][DIR_IO_IDX], Fwd_Rev); // Dir
if ( Fwd_Rev )
{ // 1: REV -- needs to work out the complement of PWM as the logic within the L298 inversed by current design to save two IO pins
act_PWM = ( 100 - constrain(PWM_Spd, 0, 100) ) * 255 / 100;
}
else
{ // 0: FWD
act_PWM = PWM_Spd * 255 / 100;
}
analogWrite( motor_io[L_R][PWM_IO_IDX], act_PWM ); // speed
}
void motor_forward( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_forward PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_R, DIR_FWD, PWM );
motor_drive_sp( MOTOR_L, DIR_FWD, PWM );
}
void motor_stop( void )
{
#ifdef DEBUG
Serial.println("motor_stop IMMEDIATELY !!!");
#endif
motor_drive_sp( MOTOR_R, DIR_FWD, 0 );
motor_drive_sp( MOTOR_L, DIR_FWD, 0 );
}
void motor_reverse( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_reverse PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_R, DIR_REV, PWM );
motor_drive_sp( MOTOR_L, DIR_REV, PWM );
}
void motor_turn_left( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_turn_left PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_R, DIR_FWD, PWM );
motor_drive_sp( MOTOR_L, DIR_REV, PWM );
}
void motor_turn_right( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_turn_right PW = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_R, DIR_REV, PWM );
motor_drive_sp( MOTOR_L, DIR_FWD, PWM );
}
void motor_right_fwd( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_right_fwd PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_R, DIR_FWD, PWM );
}
void motor_right_rev( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_right_rev PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_R, DIR_REV, PWM );
}
void motor_left_fwd( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_left_fwd PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_L, DIR_FWD, PWM );
}
void motor_left_rev( unsigned int PWM )
{
#ifdef DEBUG
Serial.print("motor_left_rev PWM = ");Serial.println(PWM);
#endif
motor_drive_sp( MOTOR_L, DIR_REV, PWM );
}
| [
"kendotwins@gmail.com"
] | kendotwins@gmail.com |
7b1ddefc4e2ddf955f634c498df100268dbe418e | aac8ec3f561d156f3425064843e545cdd84f4b3f | /09-array-2.0/18-string-tokenizer-implementation.cpp | b917b08fc35f57d31d4faa9a91241205a731c8ce | [] | no_license | okmd/codingblocks | 5106f9c606140e24f3a7eb2c4e393b3e13f126f1 | 07c8805dbe5d455ed1ebb1984949690840342447 | refs/heads/master | 2022-03-04T03:10:19.102060 | 2022-02-05T10:02:00 | 2022-02-05T10:02:00 | 192,055,010 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | #include<iostream>
#include <cstring>
using namespace std;
char *mystrtok(char str[], char delim){
static char * input = NULL;
int i;
if(str!=NULL){
input = str; // point to str
}
if(input==NULL){
return input;
}
char *output = new char[strlen(input)+1]; // dynamic memory, will not destroy on its own
// return dynamically allocated array
// read from input and store to output
// and return word till deliminator
for(i=0; input[i]!='\0';i++){
if(input[i]!=delim){
//copy to char
output[i] = input[i];
}
else{
// it is deliminator
output[i] ='\0';
input += i+1; // pointer points to next word
return output;
}
}
// return the last word if delim is not there
output[i]='\0';
input=NULL;
return output;
}
int main(){
char para[]= "Hello my name is md!Who are you?:)";
char deliminator = ' ';
char *s = mystrtok(para, deliminator); // contanis static variable which store status in previous call.
while(s!=NULL){
cout<<s<<endl;
s = mystrtok(NULL, deliminator);
}
return 0;
}
/*
*/ | [
"md.softdeveloper@gmail.com"
] | md.softdeveloper@gmail.com |
4b807e13b379fa36c43278f103a2f8c0b0401c6a | 7be73f15f0ae1ce568b5cec160914e220673c8e0 | /Sorting_and_Searching/Distinct_Nums.cpp | 04fc861ccf87995bc798fe983dcc8d5975ab44ee | [] | no_license | ShrutiAggarwal99/CSES-Problems | aa22aba8885738fe15d40dbfed62a8a6fb6ebf8f | 33ba5587c2bfffb23bf0ca2138bb1372fbcf1a1a | refs/heads/master | 2022-08-07T09:11:10.091667 | 2020-05-25T18:52:12 | 2020-05-25T18:52:12 | 266,134,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 323 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,x;
cin>>n;
set<int> s; // not using unordered_set because that is giving TLE (maybe worst case scenario of O(n) reaching for some large input)
for(int i=0;i<n;i++){
cin>>x;
s.insert(x);
}
cout<<s.size();
return 0;
} | [
"aggshruti.99@gmail.com"
] | aggshruti.99@gmail.com |
a8e6630b193777f1397ff4f57e43fb6c5be6f385 | 1e715f84b7cba41444a624bf470579dce446255d | /BOJ/1107/1107.cpp | eb0f042dd7c1986397b6b931bd60d181adfd0606 | [] | no_license | KimYeonJun/ProblemSolving | bb82467db21fa4c5d83d0c971ed2b370ebcb934c | adeb46d8fe549f40375383862963f7cac6beae4a | refs/heads/master | 2020-11-28T08:42:29.290211 | 2020-11-18T07:08:29 | 2020-11-18T07:08:29 | 229,759,191 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,949 | cpp | /*
BOJ 1107 : 리모컨
Step1. 0~1000000 의 채널을 완전탐색한다.(N의 최대값이 500000이지만, 499999의 경우 9,8와 0이 고장났으면 477777에서 +버튼을 누르는 것(22222)보다 511111에서 -버튼을 누르는게(11111) 빠르기 때문
Step2. 각 채널에 대해서 해당 번호로 바로 이동 가능하다면 번호를 눌러서 이동한 횟수와, 100에서 +-를 눌러서 이동한 횟수를 비교하여 min값을 구한다.
Step3. 해당 채널에서 목표채널까지 차이를 Step2의 결과와 더한다.
Step4. 완전탐색을 하면서 최소값이 정답!
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N, M;
vector<int> broken;
vector<int>::iterator iter;
const int INF = 987654321;
int result = INF;
void Input() {
cin >> N >> M;
int num;
for (int i = 0; i < M; i++) {
cin >> num;
broken.push_back(num);
}
}
int IsPossiblePress(int num) {
if (num == 0) {
iter = find(broken.begin(), broken.end(), 0);
if (iter == broken.end()) {
return 1;
}
else {
return -1;
}
}
int cnt = 0;
while (num != 0) {
cnt++;
iter = find(broken.begin(), broken.end(), num%10);
if (iter != broken.end()) { //고장난 버튼이 이라면.
return -1;
}
num /= 10;
}
return cnt;
}
int getChannel(int num) {
int cnt = IsPossiblePress(num);
if (cnt == -1) { //고장난 버튼이 포함되어있으므로 무조건 +-로만 가야함.
return abs(num - 100);
}
else { //고장난 버튼이 포함되어있지않으므로 채널번호를 눌러서 가는것과 +-로 가는것을 비교.
return min(cnt, abs(num - 100));
}
}
void Solution() {
for (int i = 0; i <= 1000000; i++) {
int move = getChannel(i) + abs(i - N);
if (result > move)
result = move;
}
cout << result << endl;
}
void Solve() {
Input();
Solution();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
Solve();
return 0;
} | [
"duswns1783@naver.com"
] | duswns1783@naver.com |
b7500750b97ba6eedaaf0582d043378e64105c4e | 3daf1a9015332acf1217b944bc7f9c763a3c3ff8 | /src/application/dialogs/register/RegisterDialog.cpp | 69e9860e7584ae502e8985054245548b606b85c0 | [
"MIT"
] | permissive | dreamplayerzhang/capture3 | d0d558205e53e8622256b895b6bffdcbe17bacfa | e4fe57d0c14e4deecddf9f1a9d19824076a49a03 | refs/heads/master | 2023-01-24T07:49:59.151413 | 2020-11-01T10:20:04 | 2020-11-01T10:20:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include "RegisterDialog.h"
namespace Capture3
{
RegisterDialog::RegisterDialog() :
QWidget()
{
//
}
RegisterDialog::~RegisterDialog()
{
//
}
} | [
"info@madebyferdi.com"
] | info@madebyferdi.com |
cf325edcdb37a72bbea928b25f8cce5f7e9ca086 | dcf1003859d337aee88e6cc743a6f57b34338c3d | /src/main.cpp | 8171817278d7cf7076c1cb841b5206b1f223ffb9 | [] | no_license | dixx/nodemcu-rc | 5e3fc5f21d281275a81ccea140c16e24388cdec0 | f1bb829f059e4b69a4652cb4116addca9db0a56f | refs/heads/master | 2020-08-06T12:59:10.814914 | 2019-10-17T10:57:05 | 2019-10-17T10:57:05 | 212,984,436 | 0 | 0 | null | 2019-10-17T10:51:39 | 2019-10-05T10:56:50 | C++ | UTF-8 | C++ | false | false | 2,833 | cpp | #include <stdint.h>
#include "Arduino.h"
#include "Ticker.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "core.h"
#include "analog_input.h"
#include "digital_input.h"
#include "my_secrets.h" // <-- here goes RC_SSID and RC_WLAN_PASSWORD
DigitalInput BUTTON_1(D1);
DigitalInput BUTTON_2(D2);
AnalogInput SPEED(A0);
const uint32_t LED_1 = D5;
const uint32_t LED_2 = D6;
const uint32_t FLASH_DURATION = 200; // ms
const IPAddress IP(192, 168, 10, 101);
const IPAddress SUBNET(255, 255, 255, 0);
const String CLIENT_URL("http://192.168.10.73/");
Ticker blocker;
bool keepAlive = true; // TODO make class
bool inputChanged = false;
bool clientsConnected = false;
String data = "";
void allowSendingKeepAlive() {
keepAlive = true;
blocker.detach();
}
void denySendingKeepAlive() {
keepAlive = false;
blocker.attach(3.0, allowSendingKeepAlive);
}
void sendKeepAlive() {
if (!keepAlive) return;
WiFiClient client;
HTTPClient http;
http.begin(client, CLIENT_URL + "keep-alive");
Serial.print("keep alive: ");
Serial.print(http.GET());
Serial.print(", ");
Serial.println(http.getString());
http.end();
denySendingKeepAlive();
}
void processInput() {
BUTTON_1.update();
BUTTON_2.update();
SPEED.update();
inputChanged = BUTTON_1.hasChanged() || BUTTON_2.hasChanged();
}
void checkClients() {
clientsConnected = (WiFi.softAPgetStationNum() > 0);
digitalWrite(LED_2, clientsConnected ? HIGH : LOW);
}
void sendData() {
WiFiClient client;
client.setTimeout(200);
HTTPClient http;
http.begin(client, CLIENT_URL);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
data = "rc";
data += "?d1=";
data += BUTTON_1.state() ? '1' : '0';
data += "&d2=";
data += BUTTON_2.state() ? '1' : '0';
data += "&a=";
data += SPEED.value();
Serial.print("Send: ");
Serial.print(CLIENT_URL);
Serial.println(data);
Serial.print("HTTP status code: ");
Serial.println(http.POST(data));
Serial.print("HTTP returned: ");
Serial.println(http.getString());
http.end();
}
void setup() {
serial::init();
onboard_led::init();
BUTTON_1.init();
BUTTON_2.init();
SPEED.init();
pinMode(LED_1, OUTPUT);
pinMode(LED_2, OUTPUT);
WiFi.mode(WIFI_AP);
WiFi.setSleepMode(WIFI_NONE_SLEEP);
WiFi.softAPConfig(IP, IP, SUBNET);
if (WiFi.softAP(RC_SSID, RC_WLAN_PASSWORD, 8 /* channel */, true /* hidden SSID */, 2 /* max connections */)) {
Serial.print("WiFi on: ");
Serial.println(WiFi.softAPIP());
} else {
Serial.println("WiFi creation failed.");
}
}
void loop() {
checkClients();
processInput();
if (clientsConnected) {
sendKeepAlive();
if (inputChanged) sendData();
}
}
| [
"jenzdixx@googlemail.com"
] | jenzdixx@googlemail.com |
2422ab41672ae70a40f8ba495e6b3f14c838b34f | a9c12a1da0794eaf9a1d1f37ab5c404e3b95e4ec | /pricingengine/OptionParams.cpp | 1641b5362f3c80ddd81d7570d0de8223586517b1 | [] | no_license | shzdtech/FutureXPlatform | 37d395511d603a9e92191f55b8f8a6d60e4095d6 | 734cfc3c3d2026d60361874001fc20f00e8bb038 | refs/heads/master | 2021-03-30T17:49:22.010954 | 2018-06-19T13:21:53 | 2018-06-19T13:21:53 | 56,828,437 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | cpp | #include "OptionParams.h"
const std::string OptionParams::riskFreeRate_name("risk_free_rate");
const std::string OptionParams::dividend_name("dividend"); | [
"rainmilk@gmail.com"
] | rainmilk@gmail.com |
7d99e2faf9007961cc17d718929e51e426be588d | 81b9b8ae0e9cc6cf320a95cf373594599d81fe12 | /Tools/Delta/Common/Include/DeltaUnparsedCallsInStmt.h | 69c3cdcbb80165f8a091bccb30d21b18fdc62ed8 | [] | no_license | mouchtaris/delta-linux | 1041b9dcc549bda2858dcedbc61087bb73817415 | cca8bd3c1646957cb3203191bb03e80d52f30631 | HEAD | 2016-09-01T19:28:43.257785 | 2014-09-02T05:00:54 | 2014-09-02T05:00:54 | 23,297,561 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | h | // DeltaUnparsedCallsInStmt.h
// Part of program debug information.
// Information for all function calls of a sttmt in unparsed form.
// Defined mainly to support selective step-in.
// ScriptFighter Project.
// A. Savidis, September 2008.
//
#ifndef DELTAUNPARSEDCALLSINSTMT_H
#define DELTAUNPARSEDCALLSINSTMT_H
#include "DDebug.h"
#include "utypes.h"
#include "GenericReader.h"
#include "GenericWriter.h"
#include "DeltaStdDefs.h"
#include "DeltaUnparsedCall.h"
#include <list>
///////////////////////////////////////////////////////
class DBYTECODE_CLASS DeltaUnparsedCallsInStmt {
private:
std::list<DeltaUnparsedCall> calls;
util_ui32 line;
///////////////////////////////////////////////////////
public:
void WriteText (FILE* fp) const; // COMP
bool Read (GenericReader& reader); // DBG
void Write (GenericWriter& writer) const; // COMP
std::list<DeltaUnparsedCall>& GetAllCalls (void)
{ return calls; }
void GetCallsAfterInstruction (
DeltaCodeAddress addr,
std::list<DeltaUnparsedCall>& output
) const;
util_ui32 GetLine (void) const
{ return line; }
void SetLine (util_ui32 l)
{ line = l; }
util_ui16 GetTotal (void) const
{ return (util_ui16) calls.size(); }
void Add (const DeltaUnparsedCall& call)
{ calls.push_back(call); }
void Clear (void)
{ calls.clear(); line = 0; }
DeltaUnparsedCallsInStmt (util_ui32 _line = 0): line(_line) {}
DeltaUnparsedCallsInStmt (const DeltaUnparsedCallsInStmt& stmt);
~DeltaUnparsedCallsInStmt(){}
};
///////////////////////////////////////////////////////
#endif // Do not ad stuff beyond this point.
| [
"lilis@09f5c9fd-6ff0-f344-b9e4-4de1b5e69ea1"
] | lilis@09f5c9fd-6ff0-f344-b9e4-4de1b5e69ea1 |
cc1a272a828a302ada317245060e14843dfde520 | f50da5dfb1d27cf737825705ce5e286bde578820 | /Temp/il2cppOutput/il2cppOutput/System_Xml_System_Xml_XmlTextWriter_StringUtil420425683.h | 59e13a9abd80380521d2e17473dacca9da7894eb | [] | no_license | magonicolas/OXpecker | 03f0ea81d0dedd030d892bfa2afa4e787e855f70 | f08475118dc8f29fc9c89aafea5628ab20c173f7 | refs/heads/master | 2020-07-05T11:07:21.694986 | 2016-09-12T16:20:33 | 2016-09-12T16:20:33 | 67,150,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,780 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Globalization.CultureInfo
struct CultureInfo_t3603717042;
// System.Globalization.CompareInfo
struct CompareInfo_t4023832425;
#include "mscorlib_System_Object837106420.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Xml.XmlTextWriter/StringUtil
struct StringUtil_t420425683 : public Il2CppObject
{
public:
public:
};
struct StringUtil_t420425683_StaticFields
{
public:
// System.Globalization.CultureInfo System.Xml.XmlTextWriter/StringUtil::cul
CultureInfo_t3603717042 * ___cul_0;
// System.Globalization.CompareInfo System.Xml.XmlTextWriter/StringUtil::cmp
CompareInfo_t4023832425 * ___cmp_1;
public:
inline static int32_t get_offset_of_cul_0() { return static_cast<int32_t>(offsetof(StringUtil_t420425683_StaticFields, ___cul_0)); }
inline CultureInfo_t3603717042 * get_cul_0() const { return ___cul_0; }
inline CultureInfo_t3603717042 ** get_address_of_cul_0() { return &___cul_0; }
inline void set_cul_0(CultureInfo_t3603717042 * value)
{
___cul_0 = value;
Il2CppCodeGenWriteBarrier(&___cul_0, value);
}
inline static int32_t get_offset_of_cmp_1() { return static_cast<int32_t>(offsetof(StringUtil_t420425683_StaticFields, ___cmp_1)); }
inline CompareInfo_t4023832425 * get_cmp_1() const { return ___cmp_1; }
inline CompareInfo_t4023832425 ** get_address_of_cmp_1() { return &___cmp_1; }
inline void set_cmp_1(CompareInfo_t4023832425 * value)
{
___cmp_1 = value;
Il2CppCodeGenWriteBarrier(&___cmp_1, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"magonicolas@gmail.com"
] | magonicolas@gmail.com |
5f189039fe80a00bf295258053e7a20f100d2149 | 58f46a28fc1b58f9cd4904c591b415c29ab2842f | /chromium-courgette-redacted-29.0.1547.57/chrome/browser/chromeos/external_metrics.cc | 16b4963efc4664e98a34be23a18349947e2ae1fb | [
"BSD-3-Clause"
] | permissive | bbmjja8123/chromium-1 | e739ef69d176c636d461e44d54ec66d11ed48f96 | 2a46d8855c48acd51dafc475be7a56420a716477 | refs/heads/master | 2021-01-16T17:50:45.184775 | 2015-03-20T18:38:11 | 2015-03-20T18:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,176 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/external_metrics.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include <string>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/metrics/histogram.h"
#include "base/metrics/sparse_histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/perftimer.h"
#include "base/posix/eintr_wrapper.h"
#include "base/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
using content::BrowserThread;
using content::UserMetricsAction;
namespace chromeos {
namespace {
bool CheckValues(const std::string& name,
int minimum,
int maximum,
size_t bucket_count) {
if (!base::Histogram::InspectConstructionArguments(
name, &minimum, &maximum, &bucket_count))
return false;
base::HistogramBase* histogram =
base::StatisticsRecorder::FindHistogram(name);
if (!histogram)
return true;
return histogram->HasConstructionArguments(minimum, maximum, bucket_count);
}
bool CheckLinearValues(const std::string& name, int maximum) {
return CheckValues(name, 1, maximum, maximum + 1);
}
// Helper function for ChromeOS field trials whose group choice is left in a
// file by an external entity. The file needs to contain a single character
// (a trailing newline character is acceptable, as well) indicating the group.
char GetFieldTrialGroupFromFile(const std::string& name_of_experiment,
const std::string& path_to_group_file) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
// The dice for this experiment have been thrown at boot. The selected group
// number is stored in a file.
const base::FilePath kPathToGroupFile(
FILE_PATH_LITERAL(path_to_group_file.c_str()));
std::string file_content;
// If the file does not exist, the experiment has not started.
if (!file_util::ReadFileToString(kPathToGroupFile, &file_content)) {
LOG(INFO) << name_of_experiment << " field trial file "
<< path_to_group_file << " does not exist.";
return '\0';
}
// The file contains a single significant character followed by a newline.
if (file_content.empty()) {
LOG(WARNING) << name_of_experiment << " field trial: "
<< path_to_group_file << " is empty";
return '\0';
}
if (file_content.size() > 2) {
// File size includes newline character (since this is only useful under
// ChromeOS, we only need to deal with single-character newlines).
LOG(WARNING) << name_of_experiment << " field trial: "
<< path_to_group_file
<< " contains an unexpected number of characters"
<< "(" << file_content.size() << ") "
<< "'" << file_content << "'";
return '\0';
}
return file_content[0];
}
// Checks to see if the character, potentially describing the field trial,
// group actually corresponds to a group participating in the field trial.
// |name_of_experiment| and |path_to_group_file| (the file that contained the
// character in question) are only for logging. |group_char| is the character
// in question and |legal_group_chars| is the list of characters describing
// groups in the field trial. The character 'x', which is an implied legal
// character, describes the default/disabled group (i.e., it will not be
// taking part in the field trial).
bool IsGroupInFieldTrial(const std::string& name_of_experiment,
const std::string& path_to_group_file,
char group_char,
const std::string& legal_group_chars) {
if (group_char == 'x') {
LOG(INFO) << name_of_experiment << " in default/disabled group";
return false;
}
if (legal_group_chars.find_first_of(group_char) == std::string::npos) {
LOG(WARNING) << name_of_experiment << " field trial: "
<< path_to_group_file
<< " contains an illegal group (" << group_char << ").";
return false;
}
LOG(INFO) << name_of_experiment << " field trial: group " << group_char;
return true;
}
// Establishes field trial for zram (compressed swap) in chromeos.
// crbug.com/169925
void SetupZramFieldTrial() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
const char name_of_experiment[] = "ZRAM";
const char path_to_group_file[] = "/home/chronos/.swap_exp_enrolled";
char group_char = GetFieldTrialGroupFromFile(name_of_experiment,
path_to_group_file);
if (!IsGroupInFieldTrial(name_of_experiment, path_to_group_file, group_char,
"012345678")) {
return;
}
const base::FieldTrial::Probability kDivisor = 1; // on/off only.
scoped_refptr<base::FieldTrial> trial =
base::FieldTrialList::FactoryGetFieldTrial(name_of_experiment,
kDivisor,
"default",
2013, 12, 31, NULL);
// Assign probability of 1 to the group Chrome OS has picked. Assign 0 to
// all other choices.
trial->AppendGroup("2GB_RAM_no_swap", group_char == '0' ? kDivisor : 0);
trial->AppendGroup("2GB_RAM_2GB_swap", group_char == '1' ? kDivisor : 0);
trial->AppendGroup("2GB_RAM_3GB_swap", group_char == '2' ? kDivisor : 0);
trial->AppendGroup("4GB_RAM_no_swap", group_char == '3' ? kDivisor : 0);
trial->AppendGroup("4GB_RAM_4GB_swap", group_char == '4' ? kDivisor : 0);
trial->AppendGroup("4GB_RAM_6GB_swap", group_char == '5' ? kDivisor : 0);
trial->AppendGroup("snow_no_swap", group_char == '6' ? kDivisor : 0);
trial->AppendGroup("snow_1GB_swap", group_char == '7' ? kDivisor : 0);
trial->AppendGroup("snow_2GB_swap", group_char == '8' ? kDivisor : 0);
// Announce the experiment to any listeners (especially important is the UMA
// software, which will append the group names to UMA statistics).
trial->group();
LOG(INFO) << "Configured in group '" << trial->group_name() << "' for "
<< name_of_experiment << " field trial";
}
// Establishes field trial for wifi scanning in chromeos. crbug.com/242733.
void SetupProgressiveScanFieldTrial() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
const char name_of_experiment[] = "ProgressiveScan";
const char path_to_group_file[] = "/home/chronos/.progressive_scan_variation";
char group_char = GetFieldTrialGroupFromFile(name_of_experiment,
path_to_group_file);
if (!IsGroupInFieldTrial(name_of_experiment, path_to_group_file, group_char,
"c1234")) {
return;
}
const base::FieldTrial::Probability kDivisor = 1; // on/off only.
scoped_refptr<base::FieldTrial> trial =
base::FieldTrialList::FactoryGetFieldTrial(name_of_experiment,
kDivisor,
"default",
2013, 12, 31, NULL);
// Assign probability of 1 to the group Chrome OS has picked. Assign 0 to
// all other choices.
trial->AppendGroup("FullScan", group_char == 'c' ? kDivisor : 0);
trial->AppendGroup("33Percent_4MinMax", group_char == '1' ? kDivisor : 0);
trial->AppendGroup("50Percent_4MinMax", group_char == '2' ? kDivisor : 0);
trial->AppendGroup("50Percent_8MinMax", group_char == '3' ? kDivisor : 0);
trial->AppendGroup("100Percent_8MinMax", group_char == '4' ? kDivisor : 0);
// Announce the experiment to any listeners (especially important is the UMA
// software, which will append the group names to UMA statistics).
trial->group();
LOG(INFO) << "Configured in group '" << trial->group_name() << "' for "
<< name_of_experiment << " field trial";
}
} // namespace
// The interval between external metrics collections in seconds
static const int kExternalMetricsCollectionIntervalSeconds = 30;
ExternalMetrics::ExternalMetrics() : test_recorder_(NULL) {}
ExternalMetrics::~ExternalMetrics() {}
void ExternalMetrics::Start() {
// Register user actions external to the browser.
// chrome/tools/extract_actions.py won't understand these lines, so all of
// these are explicitly added in that script.
// TODO(derat): We shouldn't need to verify actions before reporting them;
// remove all of this once http://crosbug.com/11125 is fixed.
valid_user_actions_.insert("Cryptohome.PKCS11InitFail");
valid_user_actions_.insert("Updater.ServerCertificateChanged");
valid_user_actions_.insert("Updater.ServerCertificateFailed");
// Initialize any chromeos field trials that need to read from a file (e.g.,
// those that have an upstart script determine their experimental group for
// them) then schedule the data collection. All of this is done on the file
// thread.
bool task_posted = BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&chromeos::ExternalMetrics::SetupAllFieldTrials, this));
DCHECK(task_posted);
}
void ExternalMetrics::RecordActionUI(std::string action_string) {
if (valid_user_actions_.count(action_string)) {
content::RecordComputedAction(action_string);
} else {
DLOG(ERROR) << "undefined UMA action: " << action_string;
}
}
void ExternalMetrics::RecordAction(const char* action) {
std::string action_string(action);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&ExternalMetrics::RecordActionUI, this, action_string));
}
void ExternalMetrics::RecordCrashUI(const std::string& crash_kind) {
if (g_browser_process && g_browser_process->metrics_service()) {
g_browser_process->metrics_service()->LogChromeOSCrash(crash_kind);
}
}
void ExternalMetrics::RecordCrash(const std::string& crash_kind) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&ExternalMetrics::RecordCrashUI, this, crash_kind));
}
void ExternalMetrics::RecordHistogram(const char* histogram_data) {
int sample, min, max, nbuckets;
char name[128]; // length must be consistent with sscanf format below.
int n = sscanf(histogram_data, "%127s %d %d %d %d",
name, &sample, &min, &max, &nbuckets);
if (n != 5) {
DLOG(ERROR) << "bad histogram request: " << histogram_data;
return;
}
if (!CheckValues(name, min, max, nbuckets)) {
DLOG(ERROR) << "Invalid histogram " << name
<< ", min=" << min
<< ", max=" << max
<< ", nbuckets=" << nbuckets;
return;
}
// Do not use the UMA_HISTOGRAM_... macros here. They cache the Histogram
// instance and thus only work if |name| is constant.
base::HistogramBase* counter = base::Histogram::FactoryGet(
name, min, max, nbuckets, base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(sample);
}
void ExternalMetrics::RecordLinearHistogram(const char* histogram_data) {
int sample, max;
char name[128]; // length must be consistent with sscanf format below.
int n = sscanf(histogram_data, "%127s %d %d", name, &sample, &max);
if (n != 3) {
DLOG(ERROR) << "bad linear histogram request: " << histogram_data;
return;
}
if (!CheckLinearValues(name, max)) {
DLOG(ERROR) << "Invalid linear histogram " << name
<< ", max=" << max;
return;
}
// Do not use the UMA_HISTOGRAM_... macros here. They cache the Histogram
// instance and thus only work if |name| is constant.
base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
name, 1, max, max + 1, base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(sample);
}
void ExternalMetrics::RecordSparseHistogram(const char* histogram_data) {
int sample;
char name[128]; // length must be consistent with sscanf format below.
int n = sscanf(histogram_data, "%127s %d", name, &sample);
if (n != 2) {
DLOG(ERROR) << "bad sparse histogram request: " << histogram_data;
return;
}
// Do not use the UMA_HISTOGRAM_... macros here. They cache the Histogram
// instance and thus only work if |name| is constant.
base::HistogramBase* counter = base::SparseHistogram::FactoryGet(
name, base::HistogramBase::kUmaTargetedHistogramFlag);
counter->Add(sample);
}
void ExternalMetrics::CollectEvents() {
const char* event_file_path = "/var/log/metrics/uma-events";
struct stat stat_buf;
int result;
if (!test_path_.empty()) {
event_file_path = test_path_.value().c_str();
}
result = stat(event_file_path, &stat_buf);
if (result < 0) {
if (errno != ENOENT) {
DPLOG(ERROR) << event_file_path << ": bad metrics file stat";
}
// Nothing to collect---try later.
return;
}
if (stat_buf.st_size == 0) {
// Also nothing to collect.
return;
}
int fd = open(event_file_path, O_RDWR);
if (fd < 0) {
DPLOG(ERROR) << event_file_path << ": cannot open";
return;
}
result = flock(fd, LOCK_EX);
if (result < 0) {
DPLOG(ERROR) << event_file_path << ": cannot lock";
close(fd);
return;
}
// This processes all messages in the log. Each message starts with a 4-byte
// field containing the length of the entire message. The length is followed
// by a name-value pair of null-terminated strings. When all messages are
// read and processed, or an error occurs, truncate the file to zero size.
for (;;) {
int32 message_size;
result = HANDLE_EINTR(read(fd, &message_size, sizeof(message_size)));
if (result < 0) {
DPLOG(ERROR) << "reading metrics message header";
break;
}
if (result == 0) { // This indicates a normal EOF.
break;
}
if (result < static_cast<int>(sizeof(message_size))) {
DLOG(ERROR) << "bad read size " << result <<
", expecting " << sizeof(message_size);
break;
}
// kMetricsMessageMaxLength applies to the entire message: the 4-byte
// length field and the two null-terminated strings.
if (message_size < 2 + static_cast<int>(sizeof(message_size)) ||
message_size > static_cast<int>(kMetricsMessageMaxLength)) {
DLOG(ERROR) << "bad message size " << message_size;
break;
}
message_size -= sizeof(message_size); // The message size includes itself.
uint8 buffer[kMetricsMessageMaxLength];
result = HANDLE_EINTR(read(fd, buffer, message_size));
if (result < 0) {
DPLOG(ERROR) << "reading metrics message body";
break;
}
if (result < message_size) {
DLOG(ERROR) << "message too short: length " << result <<
", expected " << message_size;
break;
}
// The buffer should now contain a pair of null-terminated strings.
uint8* p = reinterpret_cast<uint8*>(memchr(buffer, '\0', message_size));
uint8* q = NULL;
if (p != NULL) {
q = reinterpret_cast<uint8*>(
memchr(p + 1, '\0', message_size - (p + 1 - buffer)));
}
if (q == NULL) {
DLOG(ERROR) << "bad name-value pair for metrics";
break;
}
char* name = reinterpret_cast<char*>(buffer);
char* value = reinterpret_cast<char*>(p + 1);
if (test_recorder_ != NULL) {
test_recorder_(name, value);
} else if (strcmp(name, "crash") == 0) {
RecordCrash(value);
} else if (strcmp(name, "histogram") == 0) {
RecordHistogram(value);
} else if (strcmp(name, "linearhistogram") == 0) {
RecordLinearHistogram(value);
} else if (strcmp(name, "sparsehistogram") == 0) {
RecordSparseHistogram(value);
} else if (strcmp(name, "useraction") == 0) {
RecordAction(value);
} else {
DLOG(ERROR) << "invalid event type: " << name;
}
}
result = ftruncate(fd, 0);
if (result < 0) {
DPLOG(ERROR) << "truncate metrics log";
}
result = flock(fd, LOCK_UN);
if (result < 0) {
DPLOG(ERROR) << "unlock metrics log";
}
result = close(fd);
if (result < 0) {
DPLOG(ERROR) << "close metrics log";
}
}
void ExternalMetrics::CollectEventsAndReschedule() {
PerfTimer timer;
CollectEvents();
UMA_HISTOGRAM_TIMES("UMA.CollectExternalEventsTime", timer.Elapsed());
ScheduleCollector();
}
void ExternalMetrics::ScheduleCollector() {
bool result;
result = BrowserThread::PostDelayedTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&chromeos::ExternalMetrics::CollectEventsAndReschedule, this),
base::TimeDelta::FromSeconds(kExternalMetricsCollectionIntervalSeconds));
DCHECK(result);
}
void ExternalMetrics::SetupAllFieldTrials() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
SetupZramFieldTrial();
SetupProgressiveScanFieldTrial();
ScheduleCollector();
}
} // namespace chromeos
| [
"Khilan.Gudka@cl.cam.ac.uk"
] | Khilan.Gudka@cl.cam.ac.uk |
77ddf0d4bd94d1f2745db56b129667a10b2513fd | 2fff83d018d0b022bab9797c7fb13711b1d9accf | /libtensor/expr/dag/node_scale.h | 359a0ed2ce1a9de80be05cbd0016215c0c12d571 | [
"BSL-1.0"
] | permissive | epifanovsky/libtensor | cd0ace467cf77ae8762df078d09116dd9ceaeb61 | 0e82b4f07adf0eb1d6a617d93e9deb6f43d24ede | refs/heads/master | 2023-05-31T14:33:24.385530 | 2021-02-24T20:12:47 | 2021-02-24T20:12:47 | 51,388,786 | 35 | 14 | BSL-1.0 | 2023-04-27T12:24:44 | 2016-02-09T18:30:03 | C | UTF-8 | C++ | false | false | 940 | h | #ifndef LIBTENSOR_EXPR_NODE_SCALE_H
#define LIBTENSOR_EXPR_NODE_SCALE_H
#include "node.h"
namespace libtensor {
namespace expr {
/** \brief Tensor expression node: scaling
Scaling multiplies the left-hand-side (first argument, node_ident)
by a constant factor (second argument, node_const_scalar).
\sa node, node_ident, node_const_scalar
\ingroup libtensor_expr_dag
**/
class node_scale : public node {
public:
static const char k_op_type[]; //!< Operation type
public:
/** \brief Creates a scaling node
\param n Tensor order
**/
node_scale(size_t n) :
node(k_op_type, n)
{ }
/** \brief Virtual destructor
**/
virtual ~node_scale() { }
/** \brief Creates a copy of the node via new
**/
virtual node *clone() const {
return new node_scale(*this);
}
};
} // namespace expr
} // namespace libtensor
#endif // LIBTENSOR_EXPR_NODE_SCALE_H
| [
"epif@q-chem.com"
] | epif@q-chem.com |
428be699e509005b799187fdd736b4b16f635102 | 895e2a73a0e7f9a4380cde464b1907654ae43b3c | /arquivos_exemplo/17-estrutuda_de_dados-listas_encadeadas/53-ListaEncadeada.cpp | 66e5b37d9380902de3ccabcfff055ca28e3f6c96 | [] | no_license | brcabral/curso_c_cpp | 94747f1a78d1a9be98bda2cca0e890f31382c970 | 6c7418b66a4f1859da9fe2b705fc3e074356857c | refs/heads/master | 2021-07-01T07:44:45.322449 | 2020-08-19T02:38:42 | 2020-08-19T02:38:42 | 133,731,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,630 | cpp | #include <stdlib.h>
#include <new>
#include <string>
#include <iostream>
using namespace std;
struct Pessoa {
int rg;
string nome;
struct Pessoa *proximo;
};
void limparTela() {
system("clear");
}
int retornaTamanhoLista(Pessoa *ponteiroEncadeado) {
int tamanho = 0;
Pessoa *p = ponteiroEncadeado;
if (p->nome != "") {
while (p != NULL) {
//O cursor recebe a posição de memória do próximo valor
p = p->proximo;
tamanho ++;
}
}
return tamanho;
}
void imprimirLista(Pessoa *ponteiroEncadeado) {
Pessoa *p = ponteiroEncadeado;
if (retornaTamanhoLista(p)) {
while (p != NULL) {
cout << "RG: " << p->rg << ", nome: " << p->nome << "\n";
//O cursor recebe a posição de memória do próximo valor
p = p->proximo;
}
} else {
cout << "Lista vazia!" << "\n";
}
cout << "\n";
}
void addElementoInicio(int rg, string nome, Pessoa *&ponteiroEncadeado) {
//Criar uma nova estrutura de Pessoa
Pessoa *novaListaEncadeada = new Pessoa;
novaListaEncadeada->rg = rg;
novaListaEncadeada->nome = nome;
//Verifica se a lista está vazia
if (ponteiroEncadeado-> nome == "") {
novaListaEncadeada->proximo = NULL;
} else {
novaListaEncadeada->proximo = ponteiroEncadeado;
}
//Atribuir o novo ponteiro para a lista encadeada
ponteiroEncadeado = novaListaEncadeada;
}
void addElementoFim(int rg, string nome, Pessoa *&ponteiroEncadeado) {
//Criar uma nova estrutura de Pessoa
Pessoa *novaListaEncadeada = new Pessoa;
novaListaEncadeada->rg = rg;
novaListaEncadeada->nome = nome;
novaListaEncadeada->proximo = NULL;
if (retornaTamanhoLista(ponteiroEncadeado) == 0) {
ponteiroEncadeado = novaListaEncadeada;
} else {
Pessoa *p = ponteiroEncadeado;
while (p != NULL) {
if (p->proximo == NULL) {
p->proximo = novaListaEncadeada;
return;
}
p = p->proximo;
}
}
}
void addElementoPosicaoIndicada(int rg, string nome, Pessoa *&ponteiroEncadeado, int posicao) {
//Criar uma nova estrutura de Pessoa
Pessoa *novaListaEncadeada = new Pessoa;
novaListaEncadeada->rg = rg;
novaListaEncadeada->nome = nome;
novaListaEncadeada->proximo = NULL;
int i = 0;
Pessoa *p = ponteiroEncadeado;
while (i <= posicao) {
if (i == (posicao - 1)) {
Pessoa *pessoaAux = new Pessoa;
//Armazena o próximo valor
pessoaAux->proximo = p->proximo;
//Atribui o novo valor como próximo elemento da lista
p->proximo = novaListaEncadeada;
//O novo valor recebe o próximo valor, que estava armazenado na variável pessoaAux.
novaListaEncadeada->proximo = pessoaAux->proximo;
free(pessoaAux);
}
p = p->proximo;
i++;
}
}
void delElementoInicio(Pessoa *&ponteiroEncadeado) {
if (ponteiroEncadeado->proximo == NULL) {
Pessoa *novaListaEncadeada = new Pessoa;
novaListaEncadeada->rg = 0;
novaListaEncadeada->nome = "";
novaListaEncadeada->proximo = NULL;
ponteiroEncadeado = novaListaEncadeada;
} else {
//O ponteiro principal irá apontar para o próximo valor
ponteiroEncadeado = ponteiroEncadeado->proximo;
}
}
// >>>> Melhorar o código do delElementoFim <<<<
void delElementoFim(Pessoa *&ponteiroEncadeado) {
Pessoa *p = ponteiroEncadeado;
Pessoa *pessoaAux = new Pessoa;
while (p->proximo != NULL) {
pessoaAux = p;
p = p->proximo;
}
//Faz com que o penúltimo elemento da lista passe a ser o último
pessoaAux->proximo = NULL;
}
void delElementoPosicaoIndicada(Pessoa *&ponteiroEncadeado, int posicao) {
int i = 0;
Pessoa *p = ponteiroEncadeado;
while (i <= posicao) {
if (i == (posicao - 1)) {
Pessoa *pessoaAux = new Pessoa;
//Armazena o próximo valor
pessoaAux = p->proximo;
//Atribui o novo valor como próximo elemento da lista
p->proximo = pessoaAux->proximo;
//O novo valor recebe o próximo valor, que estava armazenado na variável pessoaAux.
//novaListaEncadeada->proximo = pessoaAux->proximo;
free(pessoaAux);
}
p = p->proximo;
i++;
}
}
string pesquisaNomeByRg(Pessoa *&ponteiroEncadeado, int rg) {
Pessoa *p = ponteiroEncadeado;
string nome = "Não encontrado";
while (p != NULL) {
if (rg == p->rg) {
nome = p->nome;
break;
}
p = p->proximo;
}
return nome;
}
int main() {
int funcaoDesejada = 1;
//Criar uma nova lista encadeada
Pessoa *ponteiroEncadeado = new Pessoa;
ponteiroEncadeado->rg = 0;
ponteiroEncadeado->nome = "";
ponteiroEncadeado->proximo = NULL;
//Criar uma nova estrutura de Pessoa para a primeira posição
Pessoa *primeiraPessoa = new Pessoa;
primeiraPessoa->rg = 1002;
primeiraPessoa->nome = "Uni";
primeiraPessoa->proximo = NULL;
//Atribuir o ponteiro da primeiraPessoa para a lista encadeada (ponteiroEncadeado)
ponteiroEncadeado = primeiraPessoa;
//Criar uma nova estrutura de Pessoa para a segunda posição
Pessoa *segundaPessoa = new Pessoa;
segundaPessoa->rg = 110;
segundaPessoa->nome = "Gracinha";
segundaPessoa->proximo = NULL;
//Indicar que o elemento seguinte da primeiraPessoa é a segundaPessoa
primeiraPessoa->proximo = segundaPessoa;
Pessoa *terceiraPessoa = new Pessoa;
terceiraPessoa->rg = 406;
terceiraPessoa->nome = "Breno";
terceiraPessoa->proximo = NULL;
segundaPessoa->proximo = terceiraPessoa;
while (funcaoDesejada > 0 && funcaoDesejada < 9) {
cout << "OPERACOES" << "\n";
cout << "1 - Inserir uma pessoa no inicio da lista." << "\n";
cout << "2 - Inserir uma pessoa no fim da lista." << "\n";
cout << "3 - Inserir uma pessoa na posição indicada da lista." << "\n";
cout << "4 - Retirar uma pessoa do inicio da lista." << "\n";
cout << "5 - Retirar uma pessoa no fim da lista." << "\n";
cout << "6 - Retirar uma pessoa na posição indicada da lista." << "\n";
cout << "7 - Procurar o nome atraves do RG." << "\n";
cout << "8 - Imprimir a lista." << "\n";
cout << "9 - Sair do sistema." << "\n";
cout << "\n" << "Escolha um numero e pressione ENTER: ";
cin >> funcaoDesejada;
limparTela();
int rg, posicao;
string nome;
switch (funcaoDesejada) {
case 1:
cout << "Inserir uma pessoa no inicio da lista" << "\n";
cout << "Digite o RG: ";
cin >> rg;
cout << "Digite o nome: ";
cin >> nome;
cout << "\n";
addElementoInicio(rg, nome, ponteiroEncadeado);
break;
case 2:
cout << "Inserir uma pessoa no fim da lista" << "\n";
cout << "Digite o RG: ";
cin >> rg;
cout << "Digite o nome: ";
cin >> nome;
cout << "\n";
addElementoFim(rg, nome, ponteiroEncadeado);
break;
case 3:
cout << "Inserir uma pessoa na posição indicada da lista" << "\n";
cout << "Digite a posição onde a pessoa será adicionada: ";
cin >> posicao;
cout << "Digite o RG: ";
cin >> rg;
cout << "Digite o nome: ";
cin >> nome;
cout << "\n";
if (posicao == 0) {
addElementoInicio(rg, nome, ponteiroEncadeado);
} else if (posicao >= retornaTamanhoLista(ponteiroEncadeado)) {
addElementoFim(rg, nome, ponteiroEncadeado);
} else {
addElementoPosicaoIndicada(rg, nome, ponteiroEncadeado, posicao);
}
break;
case 4:
//cout << "Retirar uma pessoa do inicio da lista" << "\n";
delElementoInicio(ponteiroEncadeado);
break;
case 5:
//cout << "Retirar uma pessoa no fim da lista" << "\n";
if (retornaTamanhoLista(ponteiroEncadeado) == 1) {
delElementoInicio(ponteiroEncadeado);
} else {
// >>>> Melhorar o código do delElementoFim <<<<
delElementoFim(ponteiroEncadeado);
}
break;
case 6:
cout << "Retirar uma pessoa na posição indicada da lista" << "\n";
cout << "Digite a posição da pessoa que será removida da lista: ";
cin >> posicao;
if (posicao == 0) {
delElementoInicio(ponteiroEncadeado);
} else if (posicao >= retornaTamanhoLista(ponteiroEncadeado - 1)) {
delElementoFim(ponteiroEncadeado);
} else {
delElementoPosicaoIndicada(ponteiroEncadeado, posicao);
}
cout << "\n";
break;
case 7:
cout << "Procurar o nome atraves do RG" << "\n";
if (retornaTamanhoLista(ponteiroEncadeado) > 0) {
cout << "Digite o RG que deseja pesquisar: ";
cin >> rg;
cout << "\n";
string nome = pesquisaNomeByRg(ponteiroEncadeado, rg);
if (nome == "Não encontrado") {
cout << "Pessoa não encontrada." << "\n";
} else {
cout << "O RG " << rg << " pertence à: " << nome << "\n";
}
} else {
cout << "Lista vazia!" << "\n";
}
cout << "\n";
break;
case 8:
//cout << "Funcao escolhida: 8" << "\n";
cout << "Tamanho atual da lista: " << retornaTamanhoLista(ponteiroEncadeado) << "\n\n";
imprimirLista(ponteiroEncadeado);
break;
case 9:
cout << "Sair do sistema" << "\n";
break;
}
}
return 0;
}
| [
"brcabral@gmail.com"
] | brcabral@gmail.com |
dfbc01142871da1a4efddc5d64256c3b60375065 | b36f676c9cd93a431febf7ef6a8ceee9b453e565 | /subarraysumm.cpp | c5d515a36f2bdf5b20ef3a7330689064db7e1e0f | [] | no_license | HarshitShukla25/leetcode-solutions | 48c6b8b3deab5f51b3d932c2b17d5dc52113659e | 7c107c1c7b3358cd3d1f56445f624bf84714b33c | refs/heads/master | 2022-12-07T10:01:21.701966 | 2020-08-26T16:53:59 | 2020-08-26T16:53:59 | 268,213,509 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 679 | cpp |
Subset Sum (Not subarray)
1. Backtracking
isSS(set,n,sum) = isSS(set,n-1,sum) || isSS(set,n-1,sum-set[n-1])
2. DP
ek side no. of elements doosre side sum
int dp[n+1][sum+1];
for(int i=0;i<n;i++)
dp[i][0]=true // zero sum hai to always true hoga
dp[0][i]= false;
but dp[0][0] =true;
dp[i][j] = dp[i-1][j] || dp[i-1][j-set[i-1]];
//GFG solution
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < set[i - 1])
subset[i][j] = subset[i - 1][j];
if (j >= set[i - 1])
subset[i][j] = subset[i - 1][j]
|| subset[i - 1][j - set[i - 1]];
}
} | [
"harshitshukla.eee18@itbhu.ac.in"
] | harshitshukla.eee18@itbhu.ac.in |
6b248a671befe309aee7ba7e90633f8579d7af4d | a39b242d3a07b4611c8ca2b050f9ddd51496d2c8 | /My Carrots.cpp | 887ae4fcab14c3ade20951827bd4cc374e69ff7e | [] | no_license | abdullahalrifat/contest | 28b14c92894d5f388fe7182426980a5dc84795a8 | 063fda623cb9f5f020cc1ac7195e63344497e33f | refs/heads/master | 2020-12-20T16:41:16.049119 | 2019-06-26T11:51:12 | 2019-06-26T11:51:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
int ans;
if(x1==y1 && x2==y2){
ans=abs(x1-y2)-1;
}else if(x1==x2){
ans=abs(y1-y2)-1;
}else if(y1==y2){
ans=abs(x1-x2)-1;
}else{
ans=1;
}
cout << ans << endl;
return 0;
} | [
"mimtiaze@gmail.com"
] | mimtiaze@gmail.com |
75d0092970cd535111a8400a4e6220c3203bd680 | b0dd7779c225971e71ae12c1093dc75ed9889921 | /libs/thread/test/test_barrier.cpp | 0d4d9fe704ac1f3a720b1d4068c30dcb1c56a30e | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 1,970 | cpp | // Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/detail/config.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/test/unit_test.hpp>
#include <vector>
namespace {
// Shared variables for generation barrier test
const int N_THREADS=10;
boost::barrier gen_barrier(N_THREADS);
boost::mutex mutex;
long global_parameter;
void barrier_thread()
{
for (int i = 0; i < 5; ++i)
{
if (gen_barrier.wait())
{
boost::mutex::scoped_lock lock(mutex);
global_parameter++;
}
}
}
} // namespace
void test_barrier()
{
boost::thread_group g;
global_parameter = 0;
try
{
for (int i = 0; i < N_THREADS; ++i)
g.create_thread(&barrier_thread);
g.join_all();
}
catch(...)
{
g.interrupt_all();
g.join_all();
throw;
}
BOOST_CHECK_EQUAL(global_parameter,5);
}
boost::unit_test::test_suite* init_unit_test_suite(int, char*[])
{
boost::unit_test::test_suite* test =
BOOST_TEST_SUITE("Boost.Threads: barrier test suite");
test->add(BOOST_TEST_CASE(&test_barrier));
return test;
}
void remove_unused_warning()
{
//../../../boost/test/results_collector.hpp:40:13: warning: unused function 'first_failed_assertion' [-Wunused-function]
//(void)first_failed_assertion;
//../../../boost/test/tools/floating_point_comparison.hpp:304:25: warning: unused variable 'check_is_close' [-Wunused-variable]
//../../../boost/test/tools/floating_point_comparison.hpp:326:25: warning: unused variable 'check_is_small' [-Wunused-variable]
(void)boost::test_tools::check_is_close;
(void)boost::test_tools::check_is_small;
}
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
ce1ff1cb6e12111a109a90fe944748be96bb35cc | 7aa5b7134c72245d67654930f9f773c14d542bb2 | /luis/WaterRecognition/backup files/main-BETA-54.cpp | 27d088e5465cfccfbb429bfa15dab4af6272bfb3 | [
"BSD-3-Clause"
] | permissive | shantanu-vyas/crw-cmu | 2b226552e39db0906e231e85c8a086ebcb380255 | db2fe823665dbd53f25e78fa12bc49f57d4b63aa | refs/heads/master | 2021-01-19T18:07:29.549792 | 2013-08-12T19:26:16 | 2013-08-12T19:26:16 | 11,484,469 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 25,920 | cpp | /*
* File: main.cpp
* Author: pototo
*
* Created on June 3, 2011, 10:28 AM
*
* This program recognizes the water in front of the boat by using ground
* plane detection techniques already available. This will look for the pixels
* from the boat, and go up the image until it finds the vector plane the repre-
* sents the water
*/
#include <cstdlib>
#include <math.h>
#include <string.h>
#include <iostream>
#include "highgui.h"
#include "ml.h"
#include "cv.h"
#include "KNN.h"
using namespace std;
using namespace cv;
/*
*
*/
//access the elements of a picture
template<class T> class Image
{
private:
IplImage* imgp;
public:
Image(IplImage* img=0) {imgp=img;}
~Image(){imgp=0;}
void operator=(IplImage* img) {imgp=img;}
inline T* operator[](const int rowIndx)
{
return ((T *)(imgp->imageData + rowIndx*imgp->widthStep));
}
};
typedef struct
{
unsigned char h,s,v;
} HsvPixel;
typedef struct
{
float h,s,v;
} HsvPixelFloat;
typedef Image<HsvPixel> HsvImage;
typedef Image<HsvPixelFloat> HsvImageFloat;
typedef Image<unsigned char> BwImage;
typedef Image<float> BwImageFloat;
int main(int argc, char** argv)
{
/***********************************************************************/
//live image coming streamed straight from the boat's camera
IplImage* boatFront = cvLoadImage("bigObstacle.jpg");
//cout << boatFront->height << " " << boatFront->width << endl;
IplImage* backUpImage = cvLoadImage("bigObstacle.jpg");
boatFront->origin = IPL_ORIGIN_TL; //sets image origin to top left corner
//Crop the image to the ROI
cvSetImageROI(boatFront, cvRect(0,0,boatFront->height/0.5,boatFront->width/1.83));
cvSetImageROI(backUpImage, cvRect(0,0,backUpImage->height/0.5,backUpImage->width/1.83));
//cout << boatFront->height << " " << boatFront->width << endl;
int X = boatFront->height;
int Y = boatFront->width;
//cout << "height " << X << endl;
//cout << "width " << Y << endl;
/***********************************************************************/
//boat's edge distance from the camera. This is used for visual calibration
//to know the distance from the boat to the nearest obstacles.
//With respect to the mounted camera, distance is 21 inches (0.5334 m) side to side
//and 15 inches (0.381 m).
//float boatFrontDistance = 0.381; //distance in meters
//float boatSideDistance = 0.5334; //distance in meters
// These variables tell the distance from the center bottom of the image
// (the camera) to the square surrounding a the obstacle
float xObstacleDistance = 0.0;
float yObstacleDistance = 0.0;
float obstacleDistance = 0.0;
int pixelsNumber = 6; //number of pixels for an n x n matrix and # of neighbors
const int arraySize = pixelsNumber;
const int threeArraySize = pixelsNumber;
//if pixlesNumber gets changed, then the algorithm might have to be
//recalibrated. Try to keep it constant
//these variables are used for the k nearest neighbors
//int accuracy;
//reponses for each of the classifications
float responseWaterH, responseWaterS, responseWaterV;
//float responseGroundH, responseGroundS, responseGroundV;
//float responseSkyH, responseSkyS, responseSkyV;
float averageHue = 0.0;
float averageSat = 0.0;
float averageVal = 0.0;
CvMat* trainClasses = cvCreateMat( pixelsNumber, 1, CV_32FC1 );
CvMat* trainClasses2 = cvCreateMat( pixelsNumber, 1, CV_32FC1 );
for (int i = 0; i < pixelsNumber/2; i++)
{
cvmSet(trainClasses, i,0,1);
cvmSet(trainClasses2, i,0,1);
}
for (int i = pixelsNumber/2; i < pixelsNumber; i++)
{
cvmSet(trainClasses, i,0,2);
cvmSet(trainClasses2, i,0,2);
}
//CvMat sample = cvMat( 1, 2, CV_32FC1, _sample );
//used with the classifier
CvMat* nearestWaterH = cvCreateMat(1, pixelsNumber, CV_32FC1);
CvMat* nearestWaterS = cvCreateMat(1, pixelsNumber, CV_32FC1);
CvMat* nearestWaterV = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* nearestGroundH = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* nearestGroundS = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* nearestGroundV = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* nearestSkyH = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* nearestSkyS = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* nearestSkyV = cvCreateMat(1, pixelsNumber, CV_32FC1);
//Distance
//CvMat* distanceWaterH = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceWaterS = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceWaterV = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceGroundH = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceGroundS = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceGroundV = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceSkyH = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceSkyS = cvCreateMat(1, pixelsNumber, CV_32FC1);
//CvMat* distanceSkyV = cvCreateMat(1, pixelsNumber, CV_32FC1);
//these variables are use to traverse the picture by blocks of n x n pixels at
//a time.
//Index(0,0) does not exist, so make sure kj and ki start from 1 (in the
//right way, of course)
//x and y are the dimensions of the local patch of pixels
int x = (boatFront->height)/2.5 + pixelsNumber + 99;
int y = pixelsNumber-1;
//int ix = 0;
//int iy = 0;
int skyX = 0;
int skyY = 0;
//M controls the x axis (up and down); N controls the y axis (left and
//right)
int Mw = -550;
int Nw = 1300;
int Mg = -350;
int Ng = 700;
int row1 = 0;
int column1 = 0;
int row2 = 0;
int column2 = 0;
//ground sample
CvMat* groundTrainingHue = cvCreateMat(threeArraySize,arraySize,CV_32FC1);
CvMat* groundTrainingSat = cvCreateMat(threeArraySize,arraySize,CV_32FC1);
CvMat* groundTrainingVal = cvCreateMat(threeArraySize,arraySize,CV_32FC1);
//water sample
CvMat* waterTrainingHue = cvCreateMat(threeArraySize,arraySize,CV_32FC1);
CvMat* waterTrainingSat = cvCreateMat(threeArraySize,arraySize,CV_32FC1);
CvMat* waterTrainingVal = cvCreateMat(threeArraySize,arraySize,CV_32FC1);
//n x n sample patch taken from the picture
CvMat* sampleHue = cvCreateMat(1,arraySize,CV_32FC1);
CvMat* sampleSat = cvCreateMat(1,arraySize,CV_32FC1);
CvMat* sampleVal = cvCreateMat(1,arraySize,CV_32FC1);
CvMat* resampleHue = cvCreateMat(boatFront->height/20,boatFront->width/20,CV_32FC1);
CvMat* resampleSat = cvCreateMat(boatFront->height/20,boatFront->width/20,CV_32FC1);
CvMat* resampleVal = cvCreateMat(boatFront->height/20,boatFront->width/20,CV_32FC1);
//sky training sample
CvMat* skyTrainingHue = cvCreateMat(arraySize,arraySize,CV_32FC1);
CvMat* skyTrainingSat = cvCreateMat(arraySize,arraySize,CV_32FC1);
CvMat* skyTrainingVal = cvCreateMat(arraySize,arraySize,CV_32FC1);
//initialize each matrix element to zero for ease of use
cvZero(groundTrainingHue);
cvZero(groundTrainingSat);
cvZero(groundTrainingVal);
cvZero(waterTrainingHue);
cvZero(waterTrainingSat);
cvZero(waterTrainingVal);
cvZero(sampleHue);
cvZero(sampleSat);
cvZero(sampleVal);
cvZero(resampleHue);
cvZero(resampleSat);
cvZero(resampleVal);
cvZero(skyTrainingHue);
cvZero(skyTrainingSat);
cvZero(skyTrainingVal);
//Stores the votes for each channel (whether it belongs to water or not
//1 is part of water, 0 not part of water
//if sum of votes is bigger than 1/2 the number of elements, then it belongs to water
int votesSum = 0;
int comparator[3]; //used when only three votes are needed
//int comparatorTwo [3][3]; //used when six votes are needed
//initial sum of votes is zero
//Error if initialize both matrices inside a single for loop. Dont know why
for(int i = 0; i < 3; i++)
{
comparator[i] = 0;
}
/***********************************************************************/
//Convert from RGB to HSV to control the brightness of the objects.
//work with reflexion
/*Sky recognition. Might be useful for detecting reflexion on the water. If
the sky is detected, and the reflection has the same characteristics of
something below the horizon, that "something" might be water. Assume sky
wont go below the horizon
*/
//convert from RGB to HSV
cvCvtColor(boatFront, boatFront, CV_BGR2HSV);
cvCvtColor(backUpImage, backUpImage, CV_BGR2HSV);
HsvImage I(boatFront);
HsvImage IBackUp(backUpImage);
//Sky detection
for (int i=0; i<boatFront->height/3;i++)
{
for (int j=0; j<boatFront->width;j++)
{
//if something is bright enough, consider it sky and store the
//value. HSV values go from 0 to 180 ... RGB goes from 0 to 255
if (((I[i][j].v >= 180) && (I[i][j].s <= 16)))
// && ((I[i][j].h >=10)))) //&& (I[i][j].h <= 144))))
{
//The HSV values vary between 0 and 1
cvmSet(skyTrainingHue,skyX,skyY,I[i][j].h);
cvmSet(skyTrainingSat,skyX,skyY,I[i][j].s);
cvmSet(skyTrainingVal,skyX,skyY,I[i][j].v);
I[i][j].h = 0.3*180; //H (color)
I[i][j].s = 0.3*180; //S (color intensity)
I[i][j].v = 0.6*180; //V (brightness)
if (skyY == pixelsNumber-1)
{
if (skyX == pixelsNumber-1)
skyX = 1;
else
skyX = skyX + 1;
skyY = 1;
}
else
skyY = skyY + 1;
}
}
}
/***********************************************************************/
//offline input pictures. Samples of water properties are taken from these
//pictures to get a range of values for H, S, V that will be stored into a
//pre-defined classifier
IplImage* imageSample1 = cvLoadImage("bigObstacle.jpg");
cvSetImageROI(imageSample1, cvRect(0,0,imageSample1->height/0.5,imageSample1->width/1.83));
cvCvtColor(imageSample1, imageSample1, CV_BGR2HSV);
HsvImage I1(imageSample1);
IplImage* imageSample2 = cvLoadImage("bigObstacle2.jpg");
cvSetImageROI(imageSample2, cvRect(0,0,imageSample2->height/0.5,imageSample2->width/1.83));
cvCvtColor(imageSample2, imageSample2, CV_BGR2HSV);
HsvImage I2(imageSample2);
IplImage* imageSample3 = cvLoadImage("bigObstacle3.jpg");
cvSetImageROI(imageSample3, cvRect(0,0,imageSample3->height/0.5,imageSample3->width/1.83));
cvCvtColor(imageSample3, imageSample3, CV_BGR2HSV);
HsvImage I3(imageSample3);
IplImage* imageSample4 = cvLoadImage("river.jpg");
cvSetImageROI(imageSample4, cvRect(0,0,imageSample4->height/0.5,imageSample4->width/1.83));
cvCvtColor(imageSample4, imageSample4, CV_BGR2HSV);
HsvImage I4(imageSample4);
IplImage* imageSample5 = cvLoadImage("river2.jpg");
cvSetImageROI(imageSample5, cvRect(0,0,imageSample5->height/0.5,imageSample5->width/1.83));
cvCvtColor(imageSample5, imageSample5, CV_BGR2HSV);
HsvImage I5(imageSample5);
IplImage* imageSample6 = cvLoadImage("roundObstacle4.jpg");
cvSetImageROI(imageSample6, cvRect(0,0,imageSample6->height/0.5,imageSample6->width/1.83));
cvCvtColor(imageSample6, imageSample6, CV_BGR2HSV);
HsvImage I6(imageSample6);
IplImage* imageSample7 = cvLoadImage("farm.jpg");
cvSetImageROI(imageSample7, cvRect(0,0,imageSample7->height/0.5,imageSample7->width/1.83));
cvCvtColor(imageSample7, imageSample7, CV_BGR2HSV);
HsvImage I7(imageSample7);
IplImage* imageSample8 = cvLoadImage("bigObstacle4.jpg");
cvSetImageROI(imageSample8, cvRect(0,0,imageSample8->height/0.5,imageSample8->width/1.83));
cvCvtColor(imageSample8, imageSample8, CV_BGR2HSV);
HsvImage I8(imageSample8);
IplImage* imageSample9 = cvLoadImage("roundObstacle6.jpg");
cvSetImageROI(imageSample9, cvRect(0,0,imageSample9->height/0.5,imageSample9->width/1.83));
cvCvtColor(imageSample9, imageSample9, CV_BGR2HSV);
HsvImage I9(imageSample9);
IplImage* imageSample10 = cvLoadImage("roundObstacle.jpg");
cvSetImageROI(imageSample10, cvRect(0,0,imageSample10->height/0.5,imageSample10->width/1.83));
cvCvtColor(imageSample10, imageSample10, CV_BGR2HSV);
HsvImage I10(imageSample10);
for (int i=0; i < threeArraySize; i++)
{
for (int j=0; j < arraySize; j++)
{
row1 = ceil(X/1.2866)+ceil(X/5.237)+i+Mw;
column1 = ceil(Y/7.0755)+ceil(Y/21.01622)+j+Nw;
averageHue = (I1[row1][column1].h + I2[row1][column1].h + I3[row1][column1].h + I4[row1][column1].h +
I5[row1][column1].h + I6[row1][column1].h + I7[row1][column1].h + I8[row1][column1].h +
I9[row1][column1].h + I10[row1][column1].h) / 10;
averageSat = (I1[row1][column1].s + I2[row1][column1].s + I3[row1][column1].s + I4[row1][column1].s +
I5[row1][column1].s + I6[row1][column1].s + I7[row1][column1].s + I8[row1][column1].s +
I9[row1][column1].s + I10[row1][column1].s) / 10;
averageVal = (I1[row1][column1].v + I2[row1][column1].v + I3[row1][column1].v + I4[row1][column1].v +
I5[row1][column1].v + I6[row1][column1].v + I7[row1][column1].v + I8[row1][column1].v +
I9[row1][column1].v + I10[row1][column1].v) / 10;
//water patch sample (n X n matrix)
cvmSet(waterTrainingHue,i,j,averageHue);
cvmSet(waterTrainingSat,i,j,averageSat);
cvmSet(waterTrainingVal,i,j,averageVal);
//patch is red (this is for me to know where the ground patch sample is)
//I[row1][column1].h = 0;
//I[row1][column1].s = 255;
//I[row1][column1].v = 255;
}
}
//order the water samples in ascending order on order to know a range
cvSort(waterTrainingHue, waterTrainingHue, CV_SORT_ASCENDING);
cvSort(waterTrainingSat, waterTrainingSat, CV_SORT_ASCENDING);
cvSort(waterTrainingVal, waterTrainingVal, CV_SORT_ASCENDING);
// find the maximum and minimum values in the array to create a range
int maxH = cvmGet(waterTrainingHue,0,0);
int maxS = cvmGet(waterTrainingSat,0,0);
int maxV = cvmGet(waterTrainingVal,0,0);
int minH = cvmGet(waterTrainingHue,0,0);
int minS = cvmGet(waterTrainingSat,0,0);
int minV = cvmGet(waterTrainingVal,0,0);
for (int i=0; i < threeArraySize; i++)
{
for (int j=0; j < arraySize; j++)
{
if (cvmGet(waterTrainingHue,i,j) > maxH)
maxH = cvmGet(waterTrainingHue,i,j);
if (cvmGet(waterTrainingSat,i,j) > maxS)
maxS = cvmGet(waterTrainingHue,i,j);
if (cvmGet(waterTrainingVal,i,j) > maxV)
maxV = cvmGet(waterTrainingVal,i,j);
if (cvmGet(waterTrainingHue,i,j) < minH)
minH = cvmGet(waterTrainingHue,i,j);
if (cvmGet(waterTrainingSat,i,j) < minS)
minS = cvmGet(waterTrainingSat,i,j);
if (cvmGet(waterTrainingVal,i,j) < minV)
minV = cvmGet(waterTrainingVal,i,j);
}
}
/***********************************************************************/
//Grab a random patch of water below the horizon and compare every other
//pixel against it
//The results of the water detection depend on where in the picture the
//training samples are located. Maybe adding more training samples will
//help improve this?
/*
for (int i=0; i < threeArraySize; i++)
{
for (int j=0; j < arraySize; j++)
{
row2 = ceil(X/4.7291)+ceil(X/8.3176)+i+Mg;
column2 = ceil(Y/7.78378)+ceil(Y/16.54468)+j+Ng;
//ground patch sample (n X n matrix)
//Detecting the horizon in the picture might be an excellent visual aid to
//choose where (above the horizon) you can take a ground training(1:3*n,1:n)g sample
//from. The ground pixel sample can be at a constant distance from the
//horizon
cvmSet(groundTrainingHue,i,j,I[row2][column2].h);
cvmSet(groundTrainingSat,i,j,I[row2][column2].s);
cvmSet(groundTrainingVal,i,j,I[row2][column2].v);
//patch is red (this is for me to know where the ground patch sample is)
I[row2][column2].h = 60;
I[row2][column2].s = 180;
I[row2][column2].v = 90;
}
}
//order the water samples in ascending order on order to know a range
cvSort(groundTrainingHue, groundTrainingHue, CV_SORT_ASCENDING);
cvSort(groundTrainingSat, groundTrainingSat, CV_SORT_ASCENDING);
cvSort(groundTrainingVal, groundTrainingVal, CV_SORT_ASCENDING);
*/
// Main loop. It traverses through the picture
//skyX = 0;
//skyY = 0;
while (x < boatFront->height/1.33)
{
//get a random sample taken from the picture. Must be determined whether
//it is water or ground
for (int i = 0; i<pixelsNumber;i++)
{
cvmSet(sampleHue,0,i,I[x][y].h);
cvmSet(sampleSat,0,i,I[x][y].s);
cvmSet(sampleVal,0,i,I[x][y].v);
}
//Find the shortest distance between a pixel and the neighbors from each of
//the training samples (sort of inefficient, but might do the job...sometimes)
//HSV for water sample
// learn classifier
//CvKNearest knn(trainData, trainClasses, 0, false, itemsNumber);
//CvKNearest knnWaterHue(waterTrainingHue, trainClasses, 0, false, pixelsNumber);
//CvKNearest knnWaterSat(waterTrainingSat, trainClasses, 0, false, pixelsNumber);
//CvKNearest knnWaterVal(waterTrainingVal, trainClasses, 0, false, pixelsNumber);
//HSV for ground sample
//CvKNearest knnGroundHue(groundTrainingHue, trainClasses2, 0, false, pixelsNumber);
//CvKNearest knnGroundSat(groundTrainingSat, trainClasses2, 0, false, pixelsNumber);
//CvKNearest knnGroundVal(groundTrainingVal, trainClasses2, 0, false, pixelsNumber);
//HSV for sky sample
//if (cvmGet(skyTrainingHue,0,0)!=0.0 && cvmGet(skyTrainingSat,0,0)!=0.0 && cvmGet(skyTrainingVal,0,0)!=0.0)
//{
// CvKNearest knnSkyHue(skyTrainingHue, trainClasses, 0, false, pixelsNumber);
// CvKNearest knnSkySat(skyTrainingSat, trainClasses, 0, false, pixelsNumber);
//CvKNearest knnSkyVal(skyTrainingVal, trainClasses, 0, false, pixelsNumber);
//}
//scan nearest neighbors to each pixel
//responseWaterH = knnWaterHue.find_nearest(sampleHue,pixelsNumber,0,0,nearestWaterH,0);
//responseWaterS = knnWaterSat.find_nearest(sampleSat,pixelsNumber,0,0,nearestWaterS,0);
//responseWaterV = knnWaterVal.find_nearest(sampleVal,pixelsNumber,0,0,nearestWaterV,0);
//responseGroundH = knnGroundHue.find_nearest(sampleHue,pixelsNumber,0,0,nearestGroundH,0);
//responseGroundS = knnGroundSat.find_nearest(sampleSat,pixelsNumber,0,0,nearestGroundS,0);
//responseGroundV = knnGroundVal.find_nearest(sampleVal,pixelsNumber,0,0,nearestGroundV,0);
for (int i=0;i<pixelsNumber;i++)
{
for (int j=0;j<pixelsNumber;j++)
{
if ((minH <= cvmGet(sampleHue,0,j)) || (maxH >= cvmGet(sampleHue,0,j)))
//mark water samples as green
comparator[0] = 1;
else
comparator[0] = 0;
if (((minS <= cvmGet(sampleSat,0,j)) || (maxS <= cvmGet(sampleSat,0,j))))
//mark water samples as green
comparator[1] = 1;
else
comparator[1] = 0;
if ((minV <= cvmGet(sampleVal,0,j)) || (maxV <= cvmGet(sampleVal,0,j)))
//mark water samples as green
comparator[2] = 1;
else
comparator[2] = 0;
//count votes
for (int i3=0; i3 < 3; i3++)
votesSum = votesSum + comparator[i3];
//sky detection
if ((votesSum > 1))
//&& ((cvmGet(sampleSat,0,j)-cvmGet(sampleVal,0,j) <= 0.1) ||
//cvmGet(sampleVal,0,j)>=0.25 || cvmGet(sampleSat,0,j)<=0.6
//&& cvmGet(sampleVal,0,j)>=0.85 || cvmGet(sampleSat,0,j)!=1))
{
I[x-pixelsNumber+i][y-pixelsNumber+j].h = 0;
I[x-pixelsNumber+i][y-pixelsNumber+j].s = 255;
I[x-pixelsNumber+i][y-pixelsNumber+j].v = 255;
}
votesSum = 0;
}
}
if (y < Y-1)
y = y + pixelsNumber-1;
if (y > Y-1)
y = Y-1;
else if (y == Y-1)
{
x = x + pixelsNumber-1;
y = pixelsNumber-1;
}
//ix = 0;
}
//traverse through the image one more time, divide the image in grids of
// 500x500 pixels, and see how many pixels of water are in each grid. If
// most of the pixels are labeled water, then mark all the other pixels
// as water as well
for(int i = 0; i < 3; i++)
{
comparator[i] = 0;
}
//int counter = 0;
int xDivisor = 20;
int yDivisor = 20;
votesSum = 0;
column1 = 0;
row1 = 0;
x = ceil(boatFront->height/2.5);
obstacleDistance = x;
y = 0;
while (x < boatFront->height/1.33)
{
//get a random sample taken from the picture. Must be determined whether
//it is water or ground
for (int i = 0; i < ceil(boatFront->height/xDivisor); i++)
{
for(int j = 0; j < ceil(boatFront->width/yDivisor); j++)
{
cvmSet(resampleHue,i,j,I[x+i][y+j].h);
cvmSet(resampleSat,i,j,I[x+i][y+j].s);
cvmSet(resampleVal,i,j,I[x+i][y+j].v);
if(cvmGet(resampleHue,i,j)==0 && cvmGet(resampleSat,i,j)==255 && cvmGet(resampleVal,i,j)==255)
{
votesSum++;
}
}
}
if (votesSum > ((boatFront->height/xDivisor)*(boatFront->width/yDivisor)*(8.9/9)))
{
// if bigger than 4/5 the total number of pixels in a square, then consider the entire thing as water
// We might need to use other smaller quantities (like 5/6 maybe?)
for (int i = 0; i < ceil(boatFront->height/xDivisor);i++)
{
for (int j = 0; j < ceil(boatFront->width/yDivisor); j++)
{
row1 = x + i;
if (row1 > X-1)
row1 = X-1;
column1 = y+j;
I[row1][column1].h = 0;
I[row1][column1].s = 255;
I[row1][column1].v = 255;
}
}
}
else
{
// If not water, eliminate all red pixels and turn those pixels
// back to the original color. These pixels shall, then, be marked
// as obstacles
for (int i = 0; i < ceil(boatFront->height/xDivisor);i++)
{
for (int j = 0; j < ceil(boatFront->width/yDivisor); j++)
{
row1 = x + i;
if (row1 > X-1)
row1 = X-1;
column1 = y+j;
I[row1][column1].h = IBackUp[row1][column1].h;
I[row1][column1].s = IBackUp[row1][column1].s;
I[row1][column1].v = IBackUp[row1][column1].v;
}
}
// x,y coordinates of the obstacle
//The distance formula calculated by plotting points is given by:
/*********** distance = 0.0006994144*(1.011716711^pixels) *****************/
/*********** pixel = 610.04146*(distance^0.117053) *****************/
// Convert from pixel distance to normal distance in meters
xObstacleDistance = 0.0006994144*pow(1.011716711,((boatFront->height/xDivisor)+x)/2) ;
yObstacleDistance = 0.0006994144*pow(1.011716711,((boatFront->width/yDivisor)+y)/2);
if(obstacleDistance > sqrt(pow(xObstacleDistance,2) + pow(yObstacleDistance,2)))
obstacleDistance = sqrt(pow(xObstacleDistance,2) + pow(yObstacleDistance,2));
//cout << "Distance to Obstacle is: " << obstacleDistance << endl;
}
y = y + boatFront->width/xDivisor;
if (y > Y-1)
{
x = x + boatFront->height/yDivisor;
y = 0;
}
votesSum = 0;
}
//cout << "Distance to Obstacle is: " << obstacleDistance << endl;
//The distance formula calculated by plotting points is given by:
/*********** distance = 0.0006994144*(1.011716711^pixels) *****************/
/*********** pixel = 610.04146*(distance^0.117053) *****************/
//convert from HSV to RGB
cvCvtColor(boatFront, boatFront, CV_HSV2BGR);
cvCvtColor(backUpImage, backUpImage, CV_HSV2BGR);
cvNamedWindow( "Boat Front", 0); //0 to maintains sizes regardless of image size
cvResizeWindow("Boat Front",900,750); // new width/heigh in pixels
cvShowImage( "Boat Front", boatFront );
cvWaitKey(0);
cvResetImageROI(boatFront);
cvReleaseImage(&boatFront);
cvDestroyWindow("Boat Front");
cvReleaseMat(&trainClasses);
return 0;
} | [
"shantanusvyas@gmail.com"
] | shantanusvyas@gmail.com |
6a9442538583adbb7a86d4feaabae2b288e95dee | 409c250027c33b8c5fe755bb7e74b7acd441508a | /src/data_object.hpp | 633c39826a96d95869c0c5ad0b1dca4d16f921d5 | [
"MIT"
] | permissive | jshuffak/A-LITTLE-Compiler | 5327e514af1334be37b8b5eb5543bb95bb524550 | 409aaafc57fe0bb396a06ca89ea2ced2bf020d07 | refs/heads/master | 2021-06-08T23:22:01.374175 | 2016-12-09T23:42:31 | 2016-12-09T23:42:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,513 | hpp | #ifndef _DATA_OBJECT_H_
#define _DATA_OBJECT_H_
#include "symbol.hpp"
#include "operand.hpp"
#include "iri.hpp"
#define half_expr_t std::pair<int ,DataObject*>
#define half_expr_is_valid(half) \
((half).second !=0 )
class LittleParser;
// This class is a dataobject. It is meant to represent the type and name of the storage location
// of a literal, the results of an expression, the results of a function call, or a symbol
struct DataObject {
// Type definitions
enum DataType {INT, FLOAT, STRING};
enum RegisterType {TEMP, VAR};
// Static
//static int temp_num;
// The most awful thing you've seen all day
static LittleParser* parser;
// Members
DataType data_type;
RegisterType reg_type;
// Relevant only for VAR
std::string name;
Symbol* symbol; // A pointer to the symbol table entry
// Relevant only for TEMP
int number;
// Initialize var type
DataObject(Symbol* sym);
// Initialize temp type
DataObject(DataType type);
Operand get_operand();
// Null pointer indicates error
static IRI* get_IRI(DataObject* lhs, int op, DataObject* rhs, DataObject* result);
// Takes a half expression (op, lhs) and a data object (rhs) and:
// - generates a result DataObject
// - cleans up the inputs
// - sets IRI* iri to NULL or and iri if one needs to be generated
static DataObject* evaluate_expression(half_expr_t* half_expr, IRI** iri, DataObject* rhs);
};
// Arithmetic operations
enum ArithmeticOperation{
ADD, SUB, MUL, DIV
};
#endif
| [
"coltere@purdue.edu"
] | coltere@purdue.edu |
1aa9baa68278526eef81a6e6625adc3fd037882d | 297f48301c84586dd162ed31e3e4ce6ce0b5f47c | /adc_tlm_model/barrera@linda.rhrk.uni-kl.de/tb/offset_gain_tb.cpp | 12662f5a0a68272169baef25740d5c38bb91aee8 | [] | no_license | sebslee/virtual_prototyping | e85639d1482b89ba00d3afb5447cee0e8563c82e | d77cca0def1b51bd7f4979400f4a3481762a16ea | refs/heads/master | 2021-01-23T07:43:51.035792 | 2017-10-26T20:34:06 | 2017-10-26T20:34:06 | 102,514,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | //Created by Sebastian Lee
// Simple test bench for offset and gain modules..
#include "systemc-ams.h"
#include "../../exercise_2/src/wave_sine.cpp"
#include "../src/gain_stage.cpp"
#include "../src/offset.cpp"
class dummy : public sca_tdf::sca_module{
public :
sca_tdf::sca_out<double> offset_out;
sca_tdf::sca_out<double> gain;
dummy(sc_core::sc_module_name name){}
void set_attributes(){
gain.set_timestep(100, SC_NS);
}
void processing(){
gain.write(3);
offset_out.write(2);
}
};
int sc_main (int argc , char *argv[]){
sc_set_time_resolution (10.0 , SC_NS);
//signals..
sca_tdf::sca_signal<double> sine_source("sine_source");
sca_tdf::sca_signal<double> sine_gain("sine_amp");
sca_tdf::sca_signal<double> sine_offset("sine_offset");
sca_tdf::sca_signal<double> offset_s("offset");
sca_tdf::sca_signal<double> gain_s("gain");
wave_sine sine1("source" , 1000);
dummy dummy_i("dummy");
pga pga_i("pga");
offset offset_i("offset_i");
sine1.out(sine_source);
dummy_i.gain(gain_s);
dummy_i.offset_out(offset_s);
offset_i.input(sine_source);
offset_i.output(sine_offset);
offset_i.offset_in(offset_s);
pga_i.input(sine_source);
pga_i.output(sine_gain);
pga_i.gain(gain_s);
//wave dumping...
sca_trace_file* tfp = sca_create_tabular_trace_file("test");
sca_trace(tfp , sine_source , "sine_source");
sca_trace(tfp , sine_gain , "sine_pga");
sca_trace(tfp , sine_offset, "sine_offset");
sc_start(10 , SC_MS);
sca_close_tabular_trace_file(tfp);
return 0;
}
| [
"sbslee@gmail.com"
] | sbslee@gmail.com |
316b8fb19024cdf94eeb7ae2544b41445b16f801 | 53c90fcd687b7698617177b170287a73366f5153 | /irohad/ametsuchi/impl/postgres_specific_query_executor.cpp | 55ede6f044fd695163360eaf1515d2c88bc68860 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | schannamallu/iroha | dbe677a29c7ac639505318836c047bf4c0d02c92 | bd0dd42b817af3cd71f45bfb0fd47499f9170367 | refs/heads/master | 2020-06-30T01:05:48.916066 | 2019-08-05T11:34:06 | 2019-08-05T11:35:32 | 200,674,915 | 0 | 0 | null | 2019-08-05T14:47:52 | 2019-08-05T14:47:52 | null | UTF-8 | C++ | false | false | 56,323 | cpp | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "ametsuchi/impl/postgres_specific_query_executor.hpp"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/format.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/transform.hpp>
#include <boost/range/irange.hpp>
#include "ametsuchi/impl/soci_utils.hpp"
#include "ametsuchi/key_value_storage.hpp"
#include "backend/plain/peer.hpp"
#include "common/byteutils.hpp"
#include "interfaces/common_objects/amount.hpp"
#include "interfaces/iroha_internal/block.hpp"
#include "interfaces/iroha_internal/block_json_converter.hpp"
#include "interfaces/permission_to_string.hpp"
#include "interfaces/queries/asset_pagination_meta.hpp"
#include "interfaces/queries/get_account.hpp"
#include "interfaces/queries/get_account_asset_transactions.hpp"
#include "interfaces/queries/get_account_assets.hpp"
#include "interfaces/queries/get_account_detail.hpp"
#include "interfaces/queries/get_account_transactions.hpp"
#include "interfaces/queries/get_asset_info.hpp"
#include "interfaces/queries/get_block.hpp"
#include "interfaces/queries/get_peers.hpp"
#include "interfaces/queries/get_pending_transactions.hpp"
#include "interfaces/queries/get_role_permissions.hpp"
#include "interfaces/queries/get_roles.hpp"
#include "interfaces/queries/get_signatories.hpp"
#include "interfaces/queries/get_transactions.hpp"
#include "interfaces/queries/query.hpp"
#include "interfaces/queries/tx_pagination_meta.hpp"
#include "interfaces/transaction.hpp"
#include "logger/logger.hpp"
#include "pending_txs_storage/pending_txs_storage.hpp"
using namespace shared_model::interface::permissions;
namespace {
using namespace iroha;
shared_model::interface::types::DomainIdType getDomainFromName(
const shared_model::interface::types::AccountIdType &account_id) {
// TODO 03.10.18 andrei: IR-1728 Move getDomainFromName to shared_model
std::vector<std::string> res;
boost::split(res, account_id, boost::is_any_of("@"));
return res.at(1);
}
std::string getAccountRolePermissionCheckSql(
shared_model::interface::permissions::Role permission,
const std::string &account_alias = "role_account_id") {
const auto perm_str =
shared_model::interface::RolePermissionSet({permission}).toBitstring();
const auto bits = shared_model::interface::RolePermissionSet::size();
// TODO 14.09.18 andrei: IR-1708 Load SQL from separate files
std::string query = (boost::format(R"(
SELECT (COALESCE(bit_or(rp.permission), '0'::bit(%1%))
& '%2%') = '%2%' AS perm FROM role_has_permissions AS rp
JOIN account_has_roles AS ar on ar.role_id = rp.role_id
WHERE ar.account_id = :%3%)")
% bits % perm_str % account_alias)
.str();
return query;
}
/**
* Generate an SQL subquery which checks if creator has corresponding
* permissions for target account
* It verifies individual, domain, and global permissions, and returns true if
* any of listed permissions is present
*/
auto hasQueryPermission(
const shared_model::interface::types::AccountIdType &creator,
const shared_model::interface::types::AccountIdType &target_account,
Role indiv_permission_id,
Role all_permission_id,
Role domain_permission_id) {
const auto bits = shared_model::interface::RolePermissionSet::size();
const auto perm_str =
shared_model::interface::RolePermissionSet({indiv_permission_id})
.toBitstring();
const auto all_perm_str =
shared_model::interface::RolePermissionSet({all_permission_id})
.toBitstring();
const auto domain_perm_str =
shared_model::interface::RolePermissionSet({domain_permission_id})
.toBitstring();
boost::format cmd(R"(
WITH
has_indiv_perm AS (
SELECT (COALESCE(bit_or(rp.permission), '0'::bit(%1%))
& '%3%') = '%3%' FROM role_has_permissions AS rp
JOIN account_has_roles AS ar on ar.role_id = rp.role_id
WHERE ar.account_id = '%2%'
),
has_all_perm AS (
SELECT (COALESCE(bit_or(rp.permission), '0'::bit(%1%))
& '%4%') = '%4%' FROM role_has_permissions AS rp
JOIN account_has_roles AS ar on ar.role_id = rp.role_id
WHERE ar.account_id = '%2%'
),
has_domain_perm AS (
SELECT (COALESCE(bit_or(rp.permission), '0'::bit(%1%))
& '%5%') = '%5%' FROM role_has_permissions AS rp
JOIN account_has_roles AS ar on ar.role_id = rp.role_id
WHERE ar.account_id = '%2%'
)
SELECT ('%2%' = '%6%' AND (SELECT * FROM has_indiv_perm))
OR (SELECT * FROM has_all_perm)
OR ('%7%' = '%8%' AND (SELECT * FROM has_domain_perm)) AS perm
)");
return (cmd % bits % creator % perm_str % all_perm_str % domain_perm_str
% target_account % getDomainFromName(creator)
% getDomainFromName(target_account))
.str();
}
/// Query result is a tuple of optionals, since there could be no entry
template <typename... Value>
using QueryType = boost::tuple<boost::optional<Value>...>;
/**
* Create an error response in case user does not have permissions to perform
* a query
* @tparam Roles - type of roles
* @param roles, which user lacks
* @return lambda returning the error response itself
*/
template <typename... Roles>
auto notEnoughPermissionsResponse(
std::shared_ptr<shared_model::interface::PermissionToString>
perm_converter,
Roles... roles) {
return [perm_converter, roles...] {
std::string error = "user must have at least one of the permissions: ";
for (auto role : {roles...}) {
error += perm_converter->toString(role) + ", ";
}
return error;
};
}
static const std::string kEmptyDetailsResponse{"{}"};
template <typename T>
auto resultWithoutNulls(T range) {
return range | boost::adaptors::transformed([](auto &&t) {
return iroha::ametsuchi::rebind(t);
})
| boost::adaptors::filtered(
[](const auto &t) { return static_cast<bool>(t); })
| boost::adaptors::transformed([](auto t) { return *t; });
}
} // namespace
namespace iroha {
namespace ametsuchi {
PostgresSpecificQueryExecutor::PostgresSpecificQueryExecutor(
soci::session &sql,
KeyValueStorage &block_store,
std::shared_ptr<PendingTransactionStorage> pending_txs_storage,
std::shared_ptr<shared_model::interface::BlockJsonConverter> converter,
std::shared_ptr<shared_model::interface::QueryResponseFactory>
response_factory,
std::shared_ptr<shared_model::interface::PermissionToString>
perm_converter,
logger::LoggerPtr log)
: sql_(sql),
block_store_(block_store),
pending_txs_storage_(std::move(pending_txs_storage)),
converter_(std::move(converter)),
query_response_factory_{std::move(response_factory)},
perm_converter_(std::move(perm_converter)),
log_(std::move(log)) {}
QueryExecutorResult PostgresSpecificQueryExecutor::execute(
const shared_model::interface::Query &qry) {
return boost::apply_visitor(*this, qry.get());
}
template <typename RangeGen, typename Pred>
std::vector<std::unique_ptr<shared_model::interface::Transaction>>
PostgresSpecificQueryExecutor::getTransactionsFromBlock(
uint64_t block_id, RangeGen &&range_gen, Pred &&pred) {
std::vector<std::unique_ptr<shared_model::interface::Transaction>> result;
auto serialized_block = block_store_.get(block_id);
if (not serialized_block) {
log_->error("Failed to retrieve block with id {}", block_id);
return result;
}
auto deserialized_block =
converter_->deserialize(bytesToString(*serialized_block));
// boost::get of pointer returns pointer to requested type, or nullptr
if (auto e =
boost::get<expected::Error<std::string>>(&deserialized_block)) {
log_->error("{}", e->error);
return result;
}
auto &block =
boost::get<
expected::Value<std::unique_ptr<shared_model::interface::Block>>>(
deserialized_block)
.value;
boost::transform(range_gen(boost::size(block->transactions()))
| boost::adaptors::transformed(
[&block](auto i) -> decltype(auto) {
return block->transactions()[i];
})
| boost::adaptors::filtered(pred),
std::back_inserter(result),
[&](const auto &tx) { return clone(tx); });
return result;
}
template <typename QueryTuple,
typename PermissionTuple,
typename QueryExecutor,
typename ResponseCreator,
typename PermissionsErrResponse>
QueryExecutorResult PostgresSpecificQueryExecutor::executeQuery(
QueryExecutor &&query_executor,
ResponseCreator &&response_creator,
PermissionsErrResponse &&perms_err_response) {
using T = concat<QueryTuple, PermissionTuple>;
try {
soci::rowset<T> st = std::forward<QueryExecutor>(query_executor)();
auto range = boost::make_iterator_range(st.begin(), st.end());
return apply(
viewPermissions<PermissionTuple>(range.front()),
[this, range, &response_creator, &perms_err_response](
auto... perms) {
bool temp[] = {not perms...};
if (std::all_of(std::begin(temp), std::end(temp), [](auto b) {
return b;
})) {
// TODO [IR-1816] Akvinikym 03.12.18: replace magic number 2
// with a named constant
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed,
std::forward<PermissionsErrResponse>(perms_err_response)(),
2);
}
auto query_range =
range | boost::adaptors::transformed([](auto &t) {
return viewQuery<QueryTuple>(t);
});
return std::forward<ResponseCreator>(response_creator)(
query_range, perms...);
});
} catch (const std::exception &e) {
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, e.what(), 1);
}
}
bool PostgresSpecificQueryExecutor::hasAccountRolePermission(
shared_model::interface::permissions::Role permission,
const std::string &account_id) const {
using T = boost::tuple<int>;
boost::format cmd(R"(%s)");
try {
soci::rowset<T> st =
(sql_.prepare
<< (cmd % getAccountRolePermissionCheckSql(permission)).str(),
soci::use(account_id, "role_account_id"));
return st.begin()->get<0>();
} catch (const std::exception &e) {
log_->error("Failed to validate query: {}", e.what());
return false;
}
}
void PostgresSpecificQueryExecutor::setCreatorId(
const shared_model::interface::types::AccountIdType &creator_id) {
creator_id_ = creator_id;
}
void PostgresSpecificQueryExecutor::setQueryHash(
const shared_model::interface::types::HashType &query_hash) {
query_hash_ = query_hash;
}
std::unique_ptr<shared_model::interface::QueryResponse>
PostgresSpecificQueryExecutor::logAndReturnErrorResponse(
QueryErrorType error_type,
QueryErrorMessageType error_body,
QueryErrorCodeType error_code) const {
std::string error;
switch (error_type) {
case QueryErrorType::kNoAccount:
error = "could find account with such id: " + error_body;
break;
case QueryErrorType::kNoSignatories:
error = "no signatories found in account with such id: " + error_body;
break;
case QueryErrorType::kNoAccountDetail:
error = "no details in account with such id: " + error_body;
break;
case QueryErrorType::kNoRoles:
error =
"no role with such name in account with such id: " + error_body;
break;
case QueryErrorType::kNoAsset:
error =
"no asset with such name in account with such id: " + error_body;
break;
// other errors are either handled by generic response or do not
// appear yet
default:
error = "failed to execute query: " + error_body;
break;
}
log_->error("{}", error);
return query_response_factory_->createErrorQueryResponse(
error_type, error, error_code, query_hash_);
}
template <typename Query,
typename QueryChecker,
typename QueryApplier,
typename... Permissions>
QueryExecutorResult PostgresSpecificQueryExecutor::executeTransactionsQuery(
const Query &q,
QueryChecker &&qry_checker,
const std::string &related_txs,
QueryApplier applier,
Permissions... perms) {
using QueryTuple = QueryType<shared_model::interface::types::HeightType,
uint64_t,
uint64_t>;
using PermissionTuple = boost::tuple<int>;
const auto &pagination_info = q.paginationMeta();
auto first_hash = pagination_info.firstTxHash();
// retrieve one extra transaction to populate next_hash
auto query_size = pagination_info.pageSize() + 1u;
auto base = boost::format(R"(WITH has_perms AS (%s),
my_txs AS (%s),
first_hash AS (%s),
total_size AS (
SELECT COUNT(*) FROM my_txs
),
t AS (
SELECT my_txs.height, my_txs.index
FROM my_txs JOIN
first_hash ON my_txs.height > first_hash.height
OR (my_txs.height = first_hash.height AND
my_txs.index >= first_hash.index)
LIMIT :page_size
)
SELECT height, index, count, perm FROM t
RIGHT OUTER JOIN has_perms ON TRUE
JOIN total_size ON TRUE
)");
// select tx with specified hash
auto first_by_hash = R"(SELECT height, index FROM position_by_hash
WHERE hash = :hash LIMIT 1)";
// select first ever tx
auto first_tx = R"(SELECT height, index FROM position_by_hash
ORDER BY height, index ASC LIMIT 1)";
auto cmd = base % hasQueryPermission(creator_id_, q.accountId(), perms...)
% related_txs;
if (first_hash) {
cmd = base % first_by_hash;
} else {
cmd = base % first_tx;
}
auto query = cmd.str();
return executeQuery<QueryTuple, PermissionTuple>(
applier(query),
[&](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
uint64_t total_size = 0;
if (not boost::empty(range_without_nulls)) {
total_size = boost::get<2>(*range_without_nulls.begin());
}
std::map<uint64_t, std::vector<uint64_t>> index;
// unpack results to get map from block height to index of tx in
// a block
for (const auto &t : range_without_nulls) {
apply(t, [&index](auto &height, auto &idx, auto &) {
index[height].push_back(idx);
});
}
std::vector<std::unique_ptr<shared_model::interface::Transaction>>
response_txs;
// get transactions corresponding to indexes
for (auto &block : index) {
auto txs = this->getTransactionsFromBlock(
block.first,
[&block](auto) { return block.second; },
[](auto &) { return true; });
std::move(
txs.begin(), txs.end(), std::back_inserter(response_txs));
}
if (response_txs.empty()) {
if (first_hash) {
// if 0 transactions are returned, and there is a specified
// paging hash, we assume it's invalid, since query with valid
// hash is guaranteed to return at least one transaction
auto error = (boost::format("invalid pagination hash: %s")
% first_hash->hex())
.str();
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, error, 4);
}
// if paging hash is not specified, we should check, why 0
// transactions are returned - it can be because there are
// actually no transactions for this query or some of the
// parameters were wrong
if (auto query_incorrect =
std::forward<QueryChecker>(qry_checker)(q)) {
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed,
query_incorrect.error_message,
query_incorrect.error_code);
}
}
// if the number of returned transactions is equal to the
// page size + 1, it means that the last transaction is the
// first one in the next page and we need to return it as
// the next hash
if (response_txs.size() == query_size) {
auto next_hash = response_txs.back()->hash();
response_txs.pop_back();
return query_response_factory_->createTransactionsPageResponse(
std::move(response_txs), next_hash, total_size, query_hash_);
}
return query_response_factory_->createTransactionsPageResponse(
std::move(response_txs), boost::none, total_size, query_hash_);
},
notEnoughPermissionsResponse(perm_converter_, perms...));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetAccount &q) {
using QueryTuple =
QueryType<shared_model::interface::types::AccountIdType,
shared_model::interface::types::DomainIdType,
shared_model::interface::types::QuorumType,
shared_model::interface::types::DetailType,
std::string>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(R"(WITH has_perms AS (%s),
t AS (
SELECT a.account_id, a.domain_id, a.quorum, a.data, ARRAY_AGG(ar.role_id) AS roles
FROM account AS a, account_has_roles AS ar
WHERE a.account_id = :target_account_id
AND ar.account_id = a.account_id
GROUP BY a.account_id
)
SELECT account_id, domain_id, quorum, data, roles, perm
FROM t RIGHT OUTER JOIN has_perms AS p ON TRUE
)")
% hasQueryPermission(creator_id_,
q.accountId(),
Role::kGetMyAccount,
Role::kGetAllAccounts,
Role::kGetDomainAccounts))
.str();
auto query_apply = [this](auto &account_id,
auto &domain_id,
auto &quorum,
auto &data,
auto &roles_str) {
std::vector<shared_model::interface::types::RoleIdType> roles;
auto roles_str_no_brackets = roles_str.substr(1, roles_str.size() - 2);
boost::split(
roles, roles_str_no_brackets, [](char c) { return c == ','; });
return query_response_factory_->createAccountResponse(
account_id, domain_id, quorum, data, std::move(roles), query_hash_);
};
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(q.accountId(), "target_account_id"));
},
[this, &q, &query_apply](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
if (range_without_nulls.empty()) {
return this->logAndReturnErrorResponse(
QueryErrorType::kNoAccount, q.accountId(), 0);
}
return apply(range_without_nulls.front(), query_apply);
},
notEnoughPermissionsResponse(perm_converter_,
Role::kGetMyAccount,
Role::kGetAllAccounts,
Role::kGetDomainAccounts));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetBlock &q) {
if (not hasAccountRolePermission(Role::kGetBlocks, creator_id_)) {
// no permission
return query_response_factory_->createErrorQueryResponse(
shared_model::interface::QueryResponseFactory::ErrorQueryType::
kStatefulFailed,
notEnoughPermissionsResponse(perm_converter_, Role::kGetBlocks)(),
2,
query_hash_);
}
auto ledger_height = block_store_.last_id();
if (q.height() > ledger_height) {
// invalid height
return logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed,
"requested height (" + std::to_string(q.height())
+ ") is greater than the ledger's one ("
+ std::to_string(ledger_height) + ")",
3);
}
auto block_deserialization_msg = [height = q.height()] {
return "could not retrieve block with given height: "
+ std::to_string(height);
};
auto serialized_block = block_store_.get(q.height());
if (not serialized_block) {
// for some reason, block with such height was not retrieved
return logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, block_deserialization_msg(), 1);
}
return converter_->deserialize(bytesToString(*serialized_block))
.match(
[this](auto &&block) {
return this->query_response_factory_->createBlockResponse(
std::move(block.value), query_hash_);
},
[this, err_msg = block_deserialization_msg()](const auto &err) {
auto extended_error =
err_msg + ", because it was not deserialized: " + err.error;
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed,
std::move(extended_error),
1);
});
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetSignatories &q) {
using QueryTuple = QueryType<std::string>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(R"(WITH has_perms AS (%s),
t AS (
SELECT public_key FROM account_has_signatory
WHERE account_id = :account_id
)
SELECT public_key, perm FROM t
RIGHT OUTER JOIN has_perms ON TRUE
)")
% hasQueryPermission(creator_id_,
q.accountId(),
Role::kGetMySignatories,
Role::kGetAllSignatories,
Role::kGetDomainSignatories))
.str();
return executeQuery<QueryTuple, PermissionTuple>(
[&] { return (sql_.prepare << cmd, soci::use(q.accountId())); },
[this, &q](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
if (range_without_nulls.empty()) {
return this->logAndReturnErrorResponse(
QueryErrorType::kNoSignatories, q.accountId(), 0);
}
auto pubkeys = boost::copy_range<
std::vector<shared_model::interface::types::PubkeyType>>(
range_without_nulls | boost::adaptors::transformed([](auto t) {
return apply(t, [&](auto &public_key) {
return shared_model::interface::types::PubkeyType{
shared_model::crypto::Blob::fromHexString(public_key)};
});
}));
return query_response_factory_->createSignatoriesResponse(
pubkeys, query_hash_);
},
notEnoughPermissionsResponse(perm_converter_,
Role::kGetMySignatories,
Role::kGetAllSignatories,
Role::kGetDomainSignatories));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetAccountTransactions &q) {
std::string related_txs = R"(SELECT DISTINCT height, index
FROM tx_position_by_creator
WHERE creator_id = :account_id
ORDER BY height, index ASC)";
const auto &pagination_info = q.paginationMeta();
auto first_hash = pagination_info.firstTxHash();
// retrieve one extra transaction to populate next_hash
auto query_size = pagination_info.pageSize() + 1u;
auto apply_query = [&](const auto &query) {
return [&] {
if (first_hash) {
return (sql_.prepare << query,
soci::use(q.accountId()),
soci::use(first_hash->hex()),
soci::use(query_size));
} else {
return (sql_.prepare << query,
soci::use(q.accountId()),
soci::use(query_size));
}
};
};
auto check_query = [this](const auto &q) {
if (this->existsInDb<int>(
"account", "account_id", "quorum", q.accountId())) {
return QueryFallbackCheckResult{};
}
return QueryFallbackCheckResult{
5, "no account with such id found: " + q.accountId()};
};
return executeTransactionsQuery(q,
std::move(check_query),
related_txs,
apply_query,
Role::kGetMyAccTxs,
Role::kGetAllAccTxs,
Role::kGetDomainAccTxs);
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetTransactions &q) {
auto escape = [](auto &hash) { return "'" + hash.hex() + "'"; };
std::string hash_str = std::accumulate(
std::next(q.transactionHashes().begin()),
q.transactionHashes().end(),
escape(q.transactionHashes().front()),
[&escape](auto &acc, auto &val) { return acc + "," + escape(val); });
using QueryTuple =
QueryType<shared_model::interface::types::HeightType, std::string>;
using PermissionTuple = boost::tuple<int, int>;
auto cmd =
(boost::format(R"(WITH has_my_perm AS (%s),
has_all_perm AS (%s),
t AS (
SELECT height, hash FROM position_by_hash WHERE hash IN (%s)
)
SELECT height, hash, has_my_perm.perm, has_all_perm.perm FROM t
RIGHT OUTER JOIN has_my_perm ON TRUE
RIGHT OUTER JOIN has_all_perm ON TRUE
)") % getAccountRolePermissionCheckSql(Role::kGetMyTxs, "account_id")
% getAccountRolePermissionCheckSql(Role::kGetAllTxs, "account_id")
% hash_str)
.str();
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd, soci::use(creator_id_, "account_id"));
},
[&](auto range, auto &my_perm, auto &all_perm) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
if (boost::size(range_without_nulls)
!= q.transactionHashes().size()) {
// TODO [IR-1816] Akvinikym 03.12.18: replace magic number 4
// with a named constant
// at least one of the hashes in the query was invalid -
// nonexistent or permissions were missed
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed,
"At least one of the supplied hashes is incorrect",
4);
}
std::map<uint64_t, std::unordered_set<std::string>> index;
for (const auto &t : range_without_nulls) {
apply(t, [&index](auto &height, auto &hash) {
index[height].insert(hash);
});
}
std::vector<std::unique_ptr<shared_model::interface::Transaction>>
response_txs;
for (auto &block : index) {
auto txs = this->getTransactionsFromBlock(
block.first,
[](auto size) {
return boost::irange(static_cast<decltype(size)>(0), size);
},
[&](auto &tx) {
return block.second.count(tx.hash().hex()) > 0
and (all_perm
or (my_perm
and tx.creatorAccountId() == creator_id_));
});
std::move(
txs.begin(), txs.end(), std::back_inserter(response_txs));
}
return query_response_factory_->createTransactionsResponse(
std::move(response_txs), query_hash_);
},
notEnoughPermissionsResponse(
perm_converter_, Role::kGetMyTxs, Role::kGetAllTxs));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetAccountAssetTransactions &q) {
std::string related_txs = R"(SELECT DISTINCT height, index
FROM position_by_account_asset
WHERE account_id = :account_id
AND asset_id = :asset_id
ORDER BY height, index ASC)"; // consider index when changing this
const auto &pagination_info = q.paginationMeta();
auto first_hash = pagination_info.firstTxHash();
// retrieve one extra transaction to populate next_hash
auto query_size = pagination_info.pageSize() + 1u;
auto apply_query = [&](const auto &query) {
return [&] {
if (first_hash) {
return (sql_.prepare << query,
soci::use(q.accountId()),
soci::use(q.assetId()),
soci::use(first_hash->hex()),
soci::use(query_size));
} else {
return (sql_.prepare << query,
soci::use(q.accountId()),
soci::use(q.assetId()),
soci::use(query_size));
}
};
};
auto check_query = [this](const auto &q) {
if (not this->existsInDb<int>(
"account", "account_id", "quorum", q.accountId())) {
return QueryFallbackCheckResult{
5, "no account with such id found: " + q.accountId()};
}
if (not this->existsInDb<int>(
"asset", "asset_id", "precision", q.assetId())) {
return QueryFallbackCheckResult{
6, "no asset with such id found: " + q.assetId()};
}
return QueryFallbackCheckResult{};
};
return executeTransactionsQuery(q,
std::move(check_query),
related_txs,
apply_query,
Role::kGetMyAccAstTxs,
Role::kGetAllAccAstTxs,
Role::kGetDomainAccAstTxs);
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetAccountAssets &q) {
using QueryTuple =
QueryType<shared_model::interface::types::AccountIdType,
shared_model::interface::types::AssetIdType,
std::string,
size_t>;
using PermissionTuple = boost::tuple<int>;
// get the assets
auto cmd = (boost::format(R"(
with has_perms as (%s),
all_data as (
select row_number() over () rn, *
from (
select *
from account_has_asset
where account_id = :account_id
order by asset_id
) t
),
total_number as (
select rn total_number
from all_data
order by rn desc
limit 1
),
page_start as (
select rn
from all_data
where coalesce(asset_id = :first_asset_id, true)
limit 1
),
page_data as (
select * from all_data, page_start, total_number
where
all_data.rn >= page_start.rn and
coalesce( -- TODO remove after pagination is mandatory IR-516
all_data.rn < page_start.rn + :page_size,
true
)
)
select account_id, asset_id, amount, total_number, perm
from
page_data
right join has_perms on true
)")
% hasQueryPermission(creator_id_,
q.accountId(),
Role::kGetMyAccAst,
Role::kGetAllAccAst,
Role::kGetDomainAccAst))
.str();
// These must stay alive while soci query is being done.
const auto pagination_meta{q.paginationMeta()};
const auto req_first_asset_id =
pagination_meta | [](const auto &pagination_meta) {
return boost::optional<std::string>(pagination_meta.firstAssetId());
};
const auto req_page_size = // TODO 2019.05.31 mboldyrev make it
// non-optional after IR-516
pagination_meta | [](const auto &pagination_meta) {
return boost::optional<size_t>(pagination_meta.pageSize() + 1);
};
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(q.accountId(), "account_id"),
soci::use(req_first_asset_id, "first_asset_id"),
soci::use(req_page_size, "page_size"));
},
[&](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
std::vector<
std::tuple<shared_model::interface::types::AccountIdType,
shared_model::interface::types::AssetIdType,
shared_model::interface::Amount>>
assets;
size_t total_number = 0;
for (const auto &row : range_without_nulls) {
apply(row,
[&assets, &total_number](auto &account_id,
auto &asset_id,
auto &amount,
auto &total_number_col) {
total_number = total_number_col;
assets.push_back(std::make_tuple(
std::move(account_id),
std::move(asset_id),
shared_model::interface::Amount(amount)));
});
}
if (assets.empty() and req_first_asset_id) {
// nonexistent first_asset_id provided in query request
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, q.accountId(), 4);
}
assert(total_number >= assets.size());
const bool is_last_page = not q.paginationMeta()
or (assets.size() <= q.paginationMeta()->pageSize());
boost::optional<shared_model::interface::types::AssetIdType>
next_asset_id;
if (not is_last_page) {
next_asset_id = std::get<1>(assets.back());
assets.pop_back();
assert(assets.size() == q.paginationMeta()->pageSize());
}
return query_response_factory_->createAccountAssetResponse(
assets, total_number, next_asset_id, query_hash_);
},
notEnoughPermissionsResponse(perm_converter_,
Role::kGetMyAccAst,
Role::kGetAllAccAst,
Role::kGetDomainAccAst));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetAccountDetail &q) {
using QueryTuple =
QueryType<shared_model::interface::types::DetailType,
uint32_t,
shared_model::interface::types::AccountIdType,
shared_model::interface::types::AccountDetailKeyType,
uint32_t>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(R"(
with has_perms as (%s),
detail AS (
with filtered_plain_data as (
select row_number() over () rn, *
from (
select
data_by_writer.key writer,
plain_data.key as key,
plain_data.value as value
from
jsonb_each((
select data
from account
where account_id = :account_id
)) data_by_writer,
jsonb_each(data_by_writer.value) plain_data
where
coalesce(data_by_writer.key = :writer, true) and
coalesce(plain_data.key = :key, true)
order by data_by_writer.key asc, plain_data.key asc
) t
),
page_limits as (
select start.rn as start, start.rn + :page_size as end
from (
select rn
from filtered_plain_data
where
coalesce(writer = :first_record_writer, true) and
coalesce(key = :first_record_key, true)
limit 1
) start
),
total_number as (select count(1) total_number from filtered_plain_data),
next_record as (
select writer, key
from
filtered_plain_data,
page_limits
where rn = page_limits.end
),
page as (
select json_object_agg(writer, data_by_writer) json
from (
select writer, json_object_agg(key, value) data_by_writer
from
filtered_plain_data,
page_limits
where
rn >= page_limits.start and
coalesce(rn < page_limits.end, true)
group by writer
) t
),
target_account_exists as (
select count(1) val
from account
where account_id = :account_id
)
select
page.json json,
total_number,
next_record.writer next_writer,
next_record.key next_key,
target_account_exists.val target_account_exists
from
page
left join total_number on true
left join next_record on true
right join target_account_exists on true
)
select detail.*, perm from detail
right join has_perms on true
)")
% hasQueryPermission(creator_id_,
q.accountId(),
Role::kGetMyAccDetail,
Role::kGetAllAccDetail,
Role::kGetDomainAccDetail))
.str();
const auto writer = q.writer();
const auto key = q.key();
boost::optional<std::string> first_record_writer;
boost::optional<std::string> first_record_key;
boost::optional<size_t> page_size;
// TODO 2019.05.29 mboldyrev IR-516 remove when pagination is made
// mandatory
q.paginationMeta() | [&](const auto &pagination_meta) {
page_size = pagination_meta.pageSize();
pagination_meta.firstRecordId() | [&](const auto &first_record_id) {
first_record_writer = first_record_id.writer();
first_record_key = first_record_id.key();
};
};
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(q.accountId(), "account_id"),
soci::use(writer, "writer"),
soci::use(key, "key"),
soci::use(first_record_writer, "first_record_writer"),
soci::use(first_record_key, "first_record_key"),
soci::use(page_size, "page_size"));
},
[&, this](auto range, auto &) {
if (range.empty()) {
assert(not range.empty());
log_->error("Empty response range in {}.", q);
return this->logAndReturnErrorResponse(
QueryErrorType::kNoAccountDetail, q.accountId(), 0);
}
return apply(
range.front(),
[&, this](auto &json,
auto &total_number,
auto &next_writer,
auto &next_key,
auto &target_account_exists) {
if (target_account_exists.value_or(0) == 0) {
// TODO 2019.06.11 mboldyrev IR-558 redesign missing data
// handling
return this->logAndReturnErrorResponse(
QueryErrorType::kNoAccountDetail, q.accountId(), 0);
}
assert(target_account_exists.value() == 1);
if (json) {
BOOST_ASSERT_MSG(total_number, "Mandatory value missing!");
if (not total_number) {
this->log_->error(
"Mandatory total_number value is missing in "
"getAccountDetail query result {}.",
q);
}
boost::optional<
shared_model::interface::types::AccountDetailRecordId>
next_record_id{[this, &next_writer, &next_key]()
-> decltype(next_record_id) {
if (next_key or next_writer) {
if (not next_writer) {
log_->error(
"next_writer not set for next_record_id!");
assert(next_writer);
return boost::none;
}
if (not next_key) {
log_->error(
"next_key not set for next_record_id!");
assert(next_key);
return boost::none;
}
return shared_model::interface::types::
AccountDetailRecordId{next_writer.value(),
next_key.value()};
}
return boost::none;
}()};
return query_response_factory_->createAccountDetailResponse(
json.value(),
total_number.value_or(0),
next_record_id,
query_hash_);
}
if (total_number.value_or(0) > 0) {
// the only reason for it is nonexistent first record
assert(first_record_writer or first_record_key);
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, q.accountId(), 4);
} else {
// no account details matching query
// TODO 2019.06.11 mboldyrev IR-558 redesign missing data
// handling
return query_response_factory_->createAccountDetailResponse(
kEmptyDetailsResponse, 0, boost::none, query_hash_);
}
});
},
notEnoughPermissionsResponse(perm_converter_,
Role::kGetMyAccDetail,
Role::kGetAllAccDetail,
Role::kGetDomainAccDetail));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetRoles &q) {
using QueryTuple = QueryType<shared_model::interface::types::RoleIdType>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(
R"(WITH has_perms AS (%s)
SELECT role_id, perm FROM role
RIGHT OUTER JOIN has_perms ON TRUE
)") % getAccountRolePermissionCheckSql(Role::kGetRoles))
.str();
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(creator_id_, "role_account_id"));
},
[&](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
auto roles = boost::copy_range<
std::vector<shared_model::interface::types::RoleIdType>>(
range_without_nulls | boost::adaptors::transformed([](auto t) {
return apply(t, [](auto &role_id) { return role_id; });
}));
return query_response_factory_->createRolesResponse(roles,
query_hash_);
},
notEnoughPermissionsResponse(perm_converter_, Role::kGetRoles));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetRolePermissions &q) {
using QueryTuple = QueryType<std::string>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(
R"(WITH has_perms AS (%s),
perms AS (SELECT permission FROM role_has_permissions
WHERE role_id = :role_name)
SELECT permission, perm FROM perms
RIGHT OUTER JOIN has_perms ON TRUE
)") % getAccountRolePermissionCheckSql(Role::kGetRoles))
.str();
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(creator_id_, "role_account_id"),
soci::use(q.roleId(), "role_name"));
},
[this, &q](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
if (range_without_nulls.empty()) {
return this->logAndReturnErrorResponse(
QueryErrorType::kNoRoles,
"{" + q.roleId() + ", " + creator_id_ + "}",
0);
}
return apply(range_without_nulls.front(), [this](auto &permission) {
return query_response_factory_->createRolePermissionsResponse(
shared_model::interface::RolePermissionSet(permission),
query_hash_);
});
},
notEnoughPermissionsResponse(perm_converter_, Role::kGetRoles));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetAssetInfo &q) {
using QueryTuple =
QueryType<shared_model::interface::types::DomainIdType, uint32_t>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(
R"(WITH has_perms AS (%s),
perms AS (SELECT domain_id, precision FROM asset
WHERE asset_id = :asset_id)
SELECT domain_id, precision, perm FROM perms
RIGHT OUTER JOIN has_perms ON TRUE
)") % getAccountRolePermissionCheckSql(Role::kReadAssets))
.str();
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(creator_id_, "role_account_id"),
soci::use(q.assetId(), "asset_id"));
},
[this, &q](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
if (range_without_nulls.empty()) {
return this->logAndReturnErrorResponse(
QueryErrorType::kNoAsset,
"{" + q.assetId() + ", " + creator_id_ + "}",
0);
}
return apply(range_without_nulls.front(),
[this, &q](auto &domain_id, auto &precision) {
return query_response_factory_->createAssetResponse(
q.assetId(), domain_id, precision, query_hash_);
});
},
notEnoughPermissionsResponse(perm_converter_, Role::kReadAssets));
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetPendingTransactions &q) {
std::vector<std::unique_ptr<shared_model::interface::Transaction>>
response_txs;
if (q.paginationMeta()) {
return pending_txs_storage_
->getPendingTransactions(creator_id_,
q.paginationMeta()->pageSize(),
q.paginationMeta()->firstTxHash())
.match(
[this, &response_txs](auto &&response) {
auto &interface_txs = response.value.transactions;
response_txs.reserve(interface_txs.size());
// TODO igor-egorov 2019-06-06 IR-555 avoid use of clone()
std::transform(interface_txs.begin(),
interface_txs.end(),
std::back_inserter(response_txs),
[](auto &tx) { return clone(*tx); });
return query_response_factory_
->createPendingTransactionsPageResponse(
std::move(response_txs),
response.value.all_transactions_size,
std::move(response.value.next_batch_info),
query_hash_);
},
[this, &q](auto &&error) {
switch (error.error) {
case iroha::PendingTransactionStorage::ErrorCode::kNotFound:
return query_response_factory_->createErrorQueryResponse(
shared_model::interface::QueryResponseFactory::
ErrorQueryType::kStatefulFailed,
std::string("The batch with specified first "
"transaction hash not found, the hash: ")
+ q.paginationMeta()->firstTxHash()->toString(),
4, // missing first tx hash error
query_hash_);
default:
BOOST_ASSERT_MSG(false,
"Unknown and unhandled type of error "
"happend in pending txs storage");
return query_response_factory_->createErrorQueryResponse(
shared_model::interface::QueryResponseFactory::
ErrorQueryType::kStatefulFailed,
std::string("Unknown type of error happened: ")
+ std::to_string(error.error),
1, // unknown internal error
query_hash_);
}
});
} else { // TODO 2019-06-06 igor-egorov IR-516 remove deprecated
// interface
auto interface_txs =
pending_txs_storage_->getPendingTransactions(creator_id_);
response_txs.reserve(interface_txs.size());
std::transform(interface_txs.begin(),
interface_txs.end(),
std::back_inserter(response_txs),
[](auto &tx) { return clone(*tx); });
return query_response_factory_->createTransactionsResponse(
std::move(response_txs), query_hash_);
}
}
QueryExecutorResult PostgresSpecificQueryExecutor::operator()(
const shared_model::interface::GetPeers &q) {
using QueryTuple =
QueryType<std::string, shared_model::interface::types::AddressType>;
using PermissionTuple = boost::tuple<int>;
auto cmd = (boost::format(
R"(WITH has_perms AS (%s)
SELECT public_key, address, perm FROM peer
RIGHT OUTER JOIN has_perms ON TRUE
)") % getAccountRolePermissionCheckSql(Role::kGetPeers))
.str();
return executeQuery<QueryTuple, PermissionTuple>(
[&] {
return (sql_.prepare << cmd,
soci::use(creator_id_, "role_account_id"));
},
[&](auto range, auto &) {
auto range_without_nulls = resultWithoutNulls(std::move(range));
shared_model::interface::types::PeerList peers;
for (const auto &row : range_without_nulls) {
apply(row, [&peers](auto &peer_key, auto &address) {
peers.push_back(std::make_shared<shared_model::plain::Peer>(
address,
shared_model::interface::types::PubkeyType{
shared_model::crypto::Blob::fromHexString(peer_key)}));
});
}
return query_response_factory_->createPeersResponse(peers,
query_hash_);
},
notEnoughPermissionsResponse(perm_converter_, Role::kGetPeers));
}
template <typename ReturnValueType>
bool PostgresSpecificQueryExecutor::existsInDb(
const std::string &table_name,
const std::string &key_name,
const std::string &value_name,
const std::string &value) const {
auto cmd = (boost::format(R"(SELECT %s
FROM %s
WHERE %s = '%s'
LIMIT 1)")
% value_name % table_name % key_name % value)
.str();
soci::rowset<ReturnValueType> result = this->sql_.prepare << cmd;
return result.begin() != result.end();
}
} // namespace ametsuchi
} // namespace iroha
| [
"lebdron@gmail.com"
] | lebdron@gmail.com |
48b921f27a019f4c142213b12d785d7edde4c350 | 97790b82f556c639173a54ad6aab498f5db62017 | /list_h.h | f1df38732fa9a09e25189053df717281e350aa7a | [] | no_license | Fedya1998/libs | 5274a2cdfa42de403e7fdc243e9ac99369c08ade | 55ee038eb09fe2a9a45bc5d2616a6fd2b55f2f53 | refs/heads/master | 2021-01-01T17:30:46.160651 | 2017-08-30T10:40:52 | 2017-08-30T10:40:52 | 98,092,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | h | //
// Created by fedya on 23.07.17.
//
#ifndef GAME_LIST_H_H
#define GAME_LIST_H_H
#endif //GAME_LIST_H_H
template<typename T>
class List_Elem;
template<typename T>
class List; | [
"fedor.chuprakov@mail.ru"
] | fedor.chuprakov@mail.ru |
8060c19534e2867057159c2c0c48b539ceac1ede | 3a7adfdcf7a5048045c8e95a93369a1796cfd532 | /nixio/test/xcompat/readblocks.cpp | 4890fefe104c4e285de801b4e91b7e299183ae41 | [
"BSD-3-Clause"
] | permissive | theGreenJedi/nixpy | e06025077d5d224a7d051532ebfbd48845339c58 | 40b5ecdaa9b074c7bf73137d1a94cb84fcbae5be | refs/heads/master | 2022-02-01T15:14:22.133157 | 2019-06-03T09:10:57 | 2019-06-03T09:10:57 | 197,896,640 | 1 | 0 | null | 2019-07-20T07:37:03 | 2019-07-20T07:37:02 | null | UTF-8 | C++ | false | false | 736 | cpp | #include "testutil.hpp"
#include <nix.hpp>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Please specify a nix file (and nothing else)" << std::endl;
return 1;
}
std::string fname = argv[1];
nix::File nf = nix::File::open(fname, nix::FileMode::ReadOnly);
int idx = 0, errcount = 0;
std::string expname, expdef;
for (const auto &block : nf.blocks()) {
expname = "test_block" + nix::util::numToStr(idx);
expdef = "definition block " + nix::util::numToStr(idx++);
errcount += compare(expname, block.name());
errcount += compare("blocktype", block.type());
errcount += compare(expdef, block.definition());
}
return errcount;
}
| [
"achilleas.k@gmail.com"
] | achilleas.k@gmail.com |
ef84978204f34c7bd3ac7bcc847efdc05a4813fa | 944079085751d03a9013d75060515c04aed9fff9 | /src/BlockList.h | 56ab8d4e3512e52313801976b6ac8aec511c3a26 | [] | no_license | EnterCheery/RCCT-1 | fee4485c26f8415aee22a94307909a05230cec06 | 147cc05ba3ba4454c86f9b429f09df6c3bde5c0c | refs/heads/main | 2023-02-25T22:53:35.016194 | 2021-01-29T05:10:50 | 2021-01-29T05:10:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | h | #pragma once
#include <vector>
#include "Block.h"
using namespace std;
class BlockList
{
public:
vector<Block> FuncBlockList; //store all the blocks in one function model;
public:
void insert(Block block); //insert one block to the list
int find(string block_name); //return the block according to its name
Block findById(int id);
void erase(int id);
void cleanList(); //clean the content of the blocklist
int getListSize();
void setBodyBlock(); // find the loop body block in the decompiled IR
BlockList();
~BlockList();
};
| [
"leibo@hust.edu.cn"
] | leibo@hust.edu.cn |
30a9b1433660094ad5d3f095186f359832b2cb95 | 0379dd91363f38d8637ff242c1ce5d3595c9b549 | /windows_10_shared_source_kit/windows_10_shared_source_kit/10_1_14354_1000/Source/Tests/Graphics/Graphics/DirectX/d3d/conf/Viewports/ScissorPosition.cpp | 1d4b21d5e2ab5a41fedd764307398ef935babf50 | [] | no_license | zhanglGitHub/windows_10_shared_source_kit | 14f25e6fff898733892d0b5cc23b2b88b04458d9 | 6784379b0023185027894efe6b97afee24ca77e0 | refs/heads/master | 2023-03-21T05:04:08.653859 | 2020-09-28T16:44:54 | 2020-09-28T16:44:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,225 | cpp | #include "ScissorPosition.h"
BEGIN_NAMED_VALUES( ScissorPositions )
NAMED_VALUE( _T( "LARGER_THAN_TARGET" ), LARGER_THAN_TARGET )
NAMED_VALUE( _T( "OFF_TARGET" ), OFF_TARGET )
END_NAMED_VALUES( ScissorPositions )
void ScissorPosition::InitTestParameters()
{
m_bUseIndex = true;
testfactor::RFactor rFact;
CTestCaseParameter< UINT > *pNumViewportsParam = AddParameter< UINT >( _T("NumViewports"), &m_NumViewports );
CTestCaseParameter< ScissorPositions > *pScissorPosition = AddParameter< ScissorPositions >( _T("ScissorPosition"), &m_position );
//larger than render target
rFact = AddParameterValue< UINT >( pNumViewportsParam, 1 )*AddParameterValue< ScissorPositions >( pScissorPosition, LARGER_THAN_TARGET);
//off target
rFact = rFact + (AddParameterValueSet< UINT >( pNumViewportsParam, new CRangeValueSet< UINT >( 1, 16, 1 ) )*
AddParameterValue< ScissorPositions >( pScissorPosition, OFF_TARGET));
SetRootTestFactor( GetOutputTypeBaseRFactor() * rFact );
}
TEST_RESULT ScissorPosition::SetupTestCase()
{
TEST_RESULT result = ViewportsTest::SetupTestCase();
if( result != RESULT_PASS )
{
return result;
}
GetEffectiveContext()->RSSetState( m_pRSScissor );
UINT numHorizontal, numVertical, width, height, index;
BOOL bExtra = FALSE;
if (m_position == LARGER_THAN_TARGET)
m_scissorSize = m_RTWidth + 2; //one pixel bigger on each edge
else
m_scissorSize = m_RTWidth / 3;
//set up viewports
for (UINT index = 0; index < m_NumViewports; ++index)
{
m_Viewports[index].Height = (float) m_RTHeight;
m_Viewports[index].Width = (float) m_RTWidth;
m_Viewports[index].TopLeftX = 0.0f;
m_Viewports[index].TopLeftY = 0.0f;
m_Viewports[index].MinDepth = 0.0f;
m_Viewports[index].MaxDepth = 1.0f;
}
//set up scissors
if (m_position == LARGER_THAN_TARGET)
{
m_Scissors[0].left = -1;
m_Scissors[0].top = -1;
m_Scissors[0].right = m_Scissors[0].left + m_scissorSize;
m_Scissors[0].bottom = m_Scissors[0].top + m_scissorSize;
}
else //in a ring around the render target
{
for (UINT i = 0; i < m_NumViewports; ++i)
{
int xpos = -((int) m_RTWidth / 3) - 1;
int ypos = -((int) m_RTWidth / 3) - 1;
switch ( i )
{
case 4:
ypos += m_scissorSize;
case 3:
ypos += m_scissorSize;
case 2:
ypos += m_scissorSize;
case 1:
ypos += m_scissorSize + 1;
case 0:
break;
case 5:
ypos += (3*m_scissorSize) + (m_scissorSize + 1);
case 6:
xpos = 0;
break;
case 7:
ypos += (3*m_scissorSize) + (m_scissorSize + 1);
case 8:
xpos = (m_scissorSize);
break;
case 9:
ypos += (3*m_scissorSize) + (m_scissorSize + 1);
case 10:
xpos = 2*(m_scissorSize);
break;
case 11:
ypos += m_scissorSize;
case 12:
ypos += m_scissorSize;
case 13:
ypos += m_scissorSize;
case 14:
ypos += (m_scissorSize + 1);
case 15:
xpos = m_RTWidth;
break;
default:
xpos = m_RTWidth;
ypos = m_RTHeight;
};
m_Scissors[i].left = xpos;
m_Scissors[i].top = ypos;
m_Scissors[i].right = m_Scissors[i].left + m_scissorSize;
m_Scissors[i].bottom = m_Scissors[i].top + m_scissorSize;
}
}
GetEffectiveContext()->RSSetViewports( m_NumViewports, m_Viewports );
GetEffectiveContext()->RSSetScissorRects( m_NumViewports, m_Scissors ); //same number of viewports and scissors
VERTS *pDestVerts;
D3D11_MAPPED_SUBRESOURCE mappedRes;
if ( FAILED(GetEffectiveContext()->Map( m_pVBuffer, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mappedRes ) ) )
{
WriteToLog("Map on vertex buffer failed.");
return RESULT_FAIL;
}
pDestVerts = (VERTS*) mappedRes.pData;
UINT *pDestViewportIndices;
D3D11_MAPPED_SUBRESOURCE mappedResDest;
if ( FAILED( GetEffectiveContext()->Map( m_pVIBuffer, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mappedResDest ) ) )
{
WriteToLog("Map on vertex buffer failed.");
return RESULT_FAIL;
}
pDestViewportIndices = (UINT*) mappedResDest.pData;
for ( UINT i = 0; i < m_NumViewports; ++i )
{
UINT offset = i*4;
pDestViewportIndices[offset] = i;
pDestVerts[offset].Color = MultiColors[i];
pDestViewportIndices[1+offset] = i;
pDestVerts[1+offset].Color = MultiColors[i];
pDestViewportIndices[2+offset] = i;
pDestVerts[2+offset].Color = MultiColors[i];
pDestViewportIndices[3+offset] = i;
pDestVerts[3+offset].Color = MultiColors[i];
pDestVerts[offset].Pos = pos(0.0f, 0.0f);
pDestVerts[1+offset].Pos = pos(1.0f, 0.0f);
pDestVerts[2+offset].Pos = pos(0.0f, 1.0f);
pDestVerts[3+offset].Pos = pos(1.0f, 1.0f);
}
GetEffectiveContext()->Unmap(m_pVBuffer,0);
GetEffectiveContext()->Unmap(m_pVIBuffer,0);
return RESULT_PASS;
}
TEST_RESULT ScissorPosition::ExecuteTestCase()
{
TEST_RESULT tRes = RESULT_PASS;
FLOAT RelativeEpsilon = 0.0005f;
FLOAT RelativeDiff[3];
D3D11_MAPPED_SUBRESOURCE texMap;
D3D11_MAPPED_SUBRESOURCE overdrawTexMap;
for( UINT vp = 0; vp < m_NumViewports; vp++ )
{
GetEffectiveContext()->Draw( 4, vp*4 );
}
if ( MapRT( &texMap, &overdrawTexMap ) ) // Executes the effective context
{
UINT16 *pData = NULL; //On the assumption that we're looking at 16-bit floats.
UINT32 *pOverdrawData = NULL;
UINT FailedPix = 0, PassedPix = 0;
bool bViewportFailed = false;
pData = (UINT16*)texMap.pData;
if( m_OutputType == OUTPUT_TYPE_UAV )
{
pOverdrawData = (UINT32*)overdrawTexMap.pData;
}
for ( UINT y = 0; y < m_RTHeight; ++y )
{
for ( UINT x = 0; x < m_RTWidth; ++x )
{
bool CurPixelColorPassed = false;
color Colors = color(
CDXGIFloat16(pData[x*4]),
CDXGIFloat16(pData[x*4+1]),
CDXGIFloat16(pData[x*4+2])
);
color TargetColor;
UINT32 OverdrawCount = 0;
if( m_OutputType == OUTPUT_TYPE_UAV )
{
OverdrawCount = pOverdrawData[x];
}
UINT32 ExpectedOverdrawCount = 0;
if (m_position == LARGER_THAN_TARGET)
{
TargetColor = MultiColors[0];
ExpectedOverdrawCount = 1;
}
else
{
TargetColor = BLACK;
ExpectedOverdrawCount = 0;
}
CalcRelativeDiff( TargetColor, Colors, RelativeDiff );
//Check to see if it matches any of the viewport colors set
if (RelativeDiff[0] > RelativeEpsilon ||
RelativeDiff[1] > RelativeEpsilon ||
RelativeDiff[2] > RelativeEpsilon )
{
CurPixelColorPassed = false;
++FailedPix;
bViewportFailed = true;
tRes = RESULT_FAIL;
}
else
{
CurPixelColorPassed = true;
++PassedPix;
}
// If outputting to UAVs, check for proper OverdrawCount
if( m_OutputType == OUTPUT_TYPE_UAV && CurPixelColorPassed )
{
if( OverdrawCount != ExpectedOverdrawCount )
{
bViewportFailed = true;
tRes = RESULT_FAIL;
// We executed the color comparison logic already, so subtract 1 from passing pixel count
--PassedPix;
// Increment the unexpected pixel count
++FailedPix;
}
}
}
pData += texMap.RowPitch / sizeof(UINT16);
pOverdrawData += overdrawTexMap.RowPitch / sizeof(UINT32);
}
if ( bViewportFailed )
{
//Output info for log
WriteToLog( "\n" );
WriteToLog( "Passing pixels: %d ", PassedPix );
if ( 0 < FailedPix )
{
WriteToLog( "Unrecognized pixel colors inside scissor for viewport: %d", FailedPix );
}
}
UnMapRT(true);
}
else
{
WriteToLog( "Failed to map render target." );
tRes = RESULT_FAIL;
}
g_App.Present();
return tRes;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
9956e3ec2fb81d7ef26e5f9c35b1f6f021e64b7c | 484e5e138dcd7d362cd045a73fee8bedd69d5cb1 | /ElectronTCPandOTATest.cpp | 147ce66d3077980655e18e0ee5f54e60896b6e69 | [
"MIT"
] | permissive | rickkas7/ElectronTCPandOTATest | 55a841ada4ace74e07403288ac6ec2ed2f023430 | efe9757b8c8140ea1a445d34c93c78c3c8b11cd6 | refs/heads/master | 2020-03-07T01:53:17.135016 | 2018-03-29T10:29:33 | 2018-03-29T10:29:33 | 127,195,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp | #include "Particle.h"
#include "TCPTester.h"
// ALL_LEVEL, DEBUG_LEVEL
SerialDebugOutput debugOutput(9600, ALL_LEVEL);
SYSTEM_THREAD(ENABLED);
TCPTester tcpTester(IPAddress(65, 19, 178, 42), 7123);
const unsigned long CHECK_PERIOD_MS = 1000;
unsigned long lastCheck = 0;
void setup() {
Serial.begin(9600);
tcpTester.setup();
}
void loop() {
tcpTester.loop();
if (millis() - lastCheck >= CHECK_PERIOD_MS) {
lastCheck = millis();
Log.info("updatesPending=%d", System.updatesPending());
}
}
| [
"rickk@rickk.com"
] | rickk@rickk.com |
1ef6b0155affadf40fe2ee80ca1204131e797260 | 18a784a631b0a54676e9d1d82af6aeb9622ac573 | /test/test_c_timer_framework.cpp | 47aa0aa9476ee146108650b6936cef867dd22b8c | [
"MIT"
] | permissive | apmorton/etl | 792d472d577a419daaf01f3d66ca9ff7d76761b2 | 08a52159f41f6295f4375b2a56152e4fa32690a1 | refs/heads/master | 2021-09-23T07:20:55.143370 | 2018-04-14T12:27:48 | 2018-04-14T12:27:48 | 116,849,571 | 0 | 0 | null | 2018-01-09T17:42:19 | 2018-01-09T17:42:19 | null | UTF-8 | C++ | false | false | 20,313 | cpp | /******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2017 jwellbelove
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 "UnitTest++.h"
#include "ExtraCheckMacros.h"
#include "platform.h"
extern "C"
{
uint32_t timer_semaphore;
#include "../include/etl/c/ecl_timer.h"
}
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#if defined(ETL_COMPILER_MICROSOFT)
#include <Windows.h>
#endif
#define REALTIME_TEST 0
namespace
{
uint64_t ticks = 0;
std::vector<uint64_t> callback_list1;
std::vector<uint64_t> callback_list2;
std::vector<uint64_t> callback_list3;
void callback1()
{
callback_list1.push_back(ticks);
}
void callback2()
{
callback_list2.push_back(ticks);
}
void callback3()
{
callback_list3.push_back(ticks);
}
void callback3b()
{
callback_list3.push_back(ticks);
ecl_timer_start(2, ECL_TIMER_START_DELAYED);
ecl_timer_start(1, ECL_TIMER_START_DELAYED);
}
const int NTIMERS = 3;
struct ecl_timer_config timers[NTIMERS];
SUITE(test_ecl_timer)
{
//=========================================================================
TEST(ecl_timer_too_many_timers)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id4 = ecl_timer_register(callback3, 11, ECL_TIMER_SINGLE_SHOT);
CHECK(id1 != ECL_TIMER_NO_TIMER);
CHECK(id2 != ECL_TIMER_NO_TIMER);
CHECK(id3 != ECL_TIMER_NO_TIMER);
CHECK(id4 == ECL_TIMER_NO_TIMER);
ecl_timer_clear();
id3 = ecl_timer_register(callback3, 11, ECL_TIMER_SINGLE_SHOT);
CHECK(id3 != ECL_TIMER_NO_TIMER);
}
//=========================================================================
TEST(ecl_timer_one_shot)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_SINGLE_SHOT);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_enable(ECL_TIMER_ENABLED);
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 1;
while (ticks <= 100U)
{
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 37 };
std::vector<uint64_t> compare2 = { 23 };
std::vector<uint64_t> compare3 = { 11 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_repeating)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_REPEATING);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_enable(ECL_TIMER_ENABLED);
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 1;
while (ticks <= 100U)
{
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 37, 74 };
std::vector<uint64_t> compare2 = { 23, 46, 69, 92 };
std::vector<uint64_t> compare3 = { 11, 22, 33, 44, 55, 66, 77, 88, 99 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_repeating_bigger_step)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_REPEATING);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_enable(ECL_TIMER_ENABLED);
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 5;
while (ticks <= 100U)
{
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 40, 75 };
std::vector<uint64_t> compare2 = { 25, 50, 70, 95 };
std::vector<uint64_t> compare3 = { 15, 25, 35, 45, 55, 70, 80, 90, 100 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_repeating_stop_start)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_REPEATING);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_enable(ECL_TIMER_ENABLED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 1;
while (ticks <= 100U)
{
if (ticks == 40)
{
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_stop(id2);
}
if (ticks == 80)
{
ecl_timer_stop(id1);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
}
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 77 };
std::vector<uint64_t> compare2 = { 23 };
std::vector<uint64_t> compare3 = { 11, 22, 33, 44, 55, 66, 77, 88, 99 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_timer_starts_timer_small_step)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback3b, 100, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id2 = ecl_timer_register(callback3, 10, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 22, ECL_TIMER_SINGLE_SHOT);
(void)id2;
(void)id3;
callback_list3.clear();
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 1;
while (ticks <= 200U)
{
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare3 = { 100, 110, 122 };
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_timer_starts_timer_big_step)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback3b, 100, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id2 = ecl_timer_register(callback3, 10, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 22, ECL_TIMER_SINGLE_SHOT);
(void)id2;
(void)id3;
callback_list3.clear();
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 3;
while (ticks <= 200U)
{
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare3 = { 102, 111, 123 };
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_repeating_register_unregister)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1;
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 1;
while (ticks <= 100U)
{
if (ticks == 40)
{
ecl_timer_unregister(id2);
id1 = ecl_timer_register(callback1, 37, ECL_TIMER_REPEATING);
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
}
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 77 };
std::vector<uint64_t> compare2 = { 23 };
std::vector<uint64_t> compare3 = { 11, 22, 33, 44, 55, 66, 77, 88, 99 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_repeating_clear)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_REPEATING);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_enable(ECL_TIMER_ENABLED);
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 1;
while (ticks <= 100U)
{
ticks += step;
if (ticks == 40)
{
ecl_timer_clear();
}
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 37 };
std::vector<uint64_t> compare2 = { 23 };
std::vector<uint64_t> compare3 = { 11, 22, 33, 44, 55, 66, 77, 88, 99 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_delayed_immediate)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 37, ECL_TIMER_REPEATING);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 23, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 11, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 5;
ecl_timer_tick(uint32_t(ticks));
ecl_timer_start(id1, ECL_TIMER_START_IMMEDIATE);
ecl_timer_start(id2, ECL_TIMER_START_IMMEDIATE);
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
const uint32_t step = 1;
while (ticks <= 100U)
{
ticks += step;
ecl_timer_tick(step);
}
std::vector<uint64_t> compare1 = { 6, 42, 79 };
std::vector<uint64_t> compare2 = { 6, 28, 51, 74, 97 };
std::vector<uint64_t> compare3 = { 16, 27, 38, 49, 60, 71, 82, 93 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
CHECK_ARRAY_EQUAL(compare3.data(), callback_list3.data(), compare3.size());
}
//=========================================================================
TEST(ecl_timer_one_shot_big_step_short_delay_insert)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 15, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 5, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 11;
ticks += step;
ecl_timer_tick(step);
ticks += step;
ecl_timer_tick(step);
std::vector<uint64_t> compare1 = { 22 };
std::vector<uint64_t> compare2 = { 11, 11, 22, 22 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), compare2.size());
}
//=========================================================================
TEST(ecl_timer_one_shot_empty_list_huge_tick_before_insert)
{
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 5, ECL_TIMER_SINGLE_SHOT);
callback_list1.clear();
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
ticks = 0;
const uint32_t step = 5;
for (uint32_t i = 0; i < step; ++i)
{
++ticks;
ecl_timer_tick(1);
}
// Huge tick count.
ecl_timer_tick(UINT32_MAX - step + 1);
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
for (uint32_t i = 0; i < step; ++i)
{
++ticks;
ecl_timer_tick(1);
}
std::vector<uint64_t> compare1 = { 5, 10 };
CHECK(callback_list1.size() != 0);
CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), compare1.size());
}
//=========================================================================
#if REALTIME_TEST
#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported
#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)
#define FIX_PROCESSOR_AFFINITY SetThreadAffinityMask(GetCurrentThread(), 1);
#else
#error No thread priority modifier defined
#endif
void timer_event()
{
const uint32_t TICK = 1;
uint32_t tick = TICK;
ticks = 1;
RAISE_THREAD_PRIORITY;
FIX_PROCESSOR_AFFINITY;
while (ticks <= 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (ecl_timer_tick(tick))
{
tick = TICK;
}
else
{
tick += TICK;
}
++ticks;
}
}
TEST(ecl_timer_threads)
{
FIX_PROCESSOR_AFFINITY;
ecl_timer_init(timers, NTIMERS);
ecl_timer_id_t id1 = ecl_timer_register(callback1, 400, ECL_TIMER_SINGLE_SHOT);
ecl_timer_id_t id2 = ecl_timer_register(callback2, 100, ECL_TIMER_REPEATING);
ecl_timer_id_t id3 = ecl_timer_register(callback3, 10, ECL_TIMER_REPEATING);
callback_list1.clear();
callback_list2.clear();
callback_list3.clear();
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
ecl_timer_start(id2, ECL_TIMER_START_DELAYED);
ecl_timer_enable(ECL_TIMER_ENABLED);
std::thread t1(timer_event);
bool restart_1 = true;
while (ticks <= 1000U)
{
if ((ticks > 200U) && (ticks < 500U))
{
ecl_timer_stop(id3);
}
if ((ticks > 600U) && (ticks < 800U))
{
ecl_timer_start(id3, ECL_TIMER_START_DELAYED);
}
if ((ticks > 500U) && restart_1)
{
ecl_timer_start(id1, ECL_TIMER_START_DELAYED);
restart_1 = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
//Join the thread with the main thread
t1.join();
CHECK_EQUAL(2U, callback_list1.size());
CHECK_EQUAL(10U, callback_list2.size());
CHECK(callback_list3.size() < 65U);
std::vector<uint64_t> compare1 = { 400, 900 };
std::vector<uint64_t> compare2 = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
CHECK(callback_list1.size() != 0);
CHECK(callback_list2.size() != 0);
CHECK(callback_list3.size() != 0);
//CHECK_ARRAY_EQUAL(compare1.data(), callback_list1.data(), min(compare1.size(), callback_list1.size()));
//CHECK_ARRAY_EQUAL(compare2.data(), callback_list2.data(), min(compare2.size(), callback_list2.size()));
}
#endif
};
}
| [
"github@wellbelove.co.uk"
] | github@wellbelove.co.uk |
0c6c300f319e1b08282a34c73de67284af64ca15 | 0453c761e303ebecdcde78ddf8903982f75b4c8f | /Fibers/FiberScheduler.cpp | 2c756ed972d9c0911ef99ab5069c253661f4da6f | [] | no_license | tumbris/Fibers | b46cb86bd26ef132bc291182af1d4e4a0b95f3b1 | 67e70267dd2900e874c3c8025a9d7a3a5c9c62b8 | refs/heads/master | 2020-11-24T16:40:13.533393 | 2019-12-15T21:47:58 | 2019-12-15T21:47:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | cpp | #include "FiberScheduler.h"
#include "Fiber.h"
#include <algorithm>
#include <cassert>
namespace fibers
{
FiberScheduler::FiberScheduler()
: m_fiberToDelete(nullptr)
{
}
Fiber* FiberScheduler::getNext()
{
Fiber* thisFiber = this_fiber::getThisFiber();
auto it = std::find_if(m_fibers.begin(), m_fibers.end(), [=](Fiber* f)
{
return f != m_fiberToDelete && f != thisFiber;
});
if (it == m_fibers.end())
{
return thisFiber;
}
return *it;
}
void FiberScheduler::markForDelete(Fiber* fiber)
{
assert(std::find(m_fibers.begin(), m_fibers.end(), fiber) != m_fibers.end());
m_fiberToDelete = fiber;
}
} | [
"sergsy.gerashenko@gmail.com"
] | sergsy.gerashenko@gmail.com |
e3aa7934181b1577aa3c11298cd458a0b3b56b86 | 5baf591dfd275e396684e03e90be27bd8955752d | /C++/SquareOfAstrisks.cpp | d976ae17704026bb7fe86e96d1858df208e4f271 | [] | no_license | sydturn/UniversityAssignments | f6ed56ec44230ce91736836643588a2e89b109b8 | 247417f11fab701ea81b8a8b48949a97a92244df | refs/heads/master | 2021-01-09T20:22:47.533687 | 2017-02-08T03:15:52 | 2017-02-08T03:15:52 | 81,281,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | /*
Sydney Turnbull
Assignment 1 Question 4.26
*/
#include <iostream>
using namespace std;
int main() {
int size{0};
cout << "Enter the size of the sides of the square: ";
cin >> size;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i > 0 && i < size - 1 && j !=0 && j != size-1) {
cout << " ";
continue;
}
cout << "*";
}
cout << "\n";
}
} | [
"turnbull.sydney@gmail.com"
] | turnbull.sydney@gmail.com |
80a279b4d323055dccafe9866826f7dfbc89d109 | fac52aacf1a7145d46f420bb2991528676e3be3f | /SDK/Cal_50BMG_5pcs_classes.h | 056b8d53468027f2da236d2c53dc85adcb593579 | [] | no_license | zH4x-SDK/zSCUM-SDK | 2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed | 711376eb272b220521fec36d84ca78fc11d4802a | refs/heads/main | 2023-07-15T16:02:22.649492 | 2021-08-27T13:44:21 | 2021-08-27T13:44:21 | 400,522,163 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 626 | h | #pragma once
// Name: SCUM, Version: 4.20.3
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Cal_50BMG_5pcs.Cal_50BMG_5pcs_C
// 0x0000 (0x0880 - 0x0880)
class ACal_50BMG_5pcs_C : public AAmmunitionItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Cal_50BMG_5pcs.Cal_50BMG_5pcs_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
d7f621a4d19c7fe83dd36e33742fc0371639ee27 | ba5a03c4b1a47203f2e3fd339a7deaeb21a28877 | /integration/RKC/actual_integrator.H | 9ac7a05db62b80372f0cc863191c541d1d3484ac | [
"BSD-3-Clause"
] | permissive | maxpkatz/Microphysics | f65ec154e4e846046273dd779c7887fd65b9e4da | bcf06921ae6144e0f1d24ceb8181af43357e9f84 | refs/heads/master | 2023-08-30T13:51:38.678408 | 2023-06-01T12:00:11 | 2023-06-01T12:00:11 | 160,952,852 | 1 | 0 | NOASSERTION | 2022-03-12T16:24:44 | 2018-12-08T15:36:24 | Jupyter Notebook | UTF-8 | C++ | false | false | 4,417 | h | #ifndef actual_integrator_H
#define actual_integrator_H
#include <iomanip>
#include <network.H>
#include <burn_type.H>
#include <eos_type.H>
#include <eos.H>
#include <extern_parameters.H>
#include <rkc_type.H>
#include <rkc.H>
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE
void actual_integrator (burn_t& state, Real dt)
{
rkc_t rkc_state{};
// Set the tolerances.
rkc_state.atol_spec = atol_spec; // mass fractions
rkc_state.atol_enuc = atol_enuc; // energy generated
rkc_state.rtol_spec = rtol_spec; // mass fractions
rkc_state.rtol_enuc = rtol_enuc; // energy generated
// Start off by assuming a successful burn.
state.success = true;
// Initialize the integration time.
rkc_state.t = 0.0_rt;
rkc_state.tend = dt;
// We assume that (rho, T) coming in are valid, do an EOS call
// to fill the rest of the thermodynamic variables.
eos(eos_input_rt, state);
// Fill in the initial integration state.
burn_to_integrator(state, rkc_state);
// Save the initial composition, temperature, and energy for our later diagnostics.
#ifndef AMREX_USE_GPU
Real xn_in[NumSpec];
for (int n = 0; n < NumSpec; ++n) {
xn_in[n] = state.xn[n];
}
Real T_in = state.T;
#endif
Real e_in = state.e;
// Call the integration routine.
int ierr = rkc(state, rkc_state);
// Copy the integration data back to the burn state.
integrator_to_burn(rkc_state, state);
// Subtract off the initial energy (the application codes expect
// to get back only the generated energy during the burn).
// Don't subtract it for primordial chem
if (subtract_internal_energy) {
state.e -= e_in;
}
// Normalize the final abundances.
// Don't normalize for primordial chem
if (!use_number_densities) {
normalize_abundances_burn(state);
}
// Get the number of RHS and Jacobian evaluations.
state.n_rhs = rkc_state.nfe;
state.n_jac = 0;
state.n_step = rkc_state.nsteps;
if (ierr > 2) {
state.success = false;
}
// VODE does not always fail even though it can lead to unphysical states.
// Add some checks that indicate a burn fail even if VODE thinks the
// integration was successful.
for (int n = 1; n <= NumSpec; ++n) {
if (rkc_state.y(n) < -rkc_failure_tolerance) {
state.success = false;
}
// Don't enforce the condition below
// for primordial chem
if (!use_number_densities) {
if (rkc_state.y(n) > 1.0_rt + rkc_failure_tolerance) {
state.success = false;
}
}
}
#ifndef AMREX_USE_GPU
if (burner_verbose) {
// Print out some integration statistics, if desired.
std::cout << "integration summary: " << std::endl;
std::cout << "dens: " << state.rho << " temp: " << state.T << std::endl;
std::cout << " energy released: " << state.e << std::endl;
std::cout << "number of steps taken: " << rkc_state.nsteps << std::endl;
std::cout << "number of f evaluations: " << rkc_state.nfe << std::endl;
}
#endif
// If we failed, print out the current state of the integration.
if (!state.success) {
#ifndef AMREX_USE_GPU
std::cout << Font::Bold << FGColor::Red << "[ERROR] integration failed in net" << ResetDisplay << std::endl;
std::cout << "ierr = " << ierr << std::endl;
std::cout << "zone = (" << state.i << ", " << state.j << ", " << state.k << ")" << std::endl;
std::cout << "time = " << rkc_state.t << std::endl;
std::cout << "dt = " << std::setprecision(16) << dt << std::endl;
std::cout << "temp start = " << std::setprecision(16) << T_in << std::endl;
std::cout << "xn start = ";
for (int n = 0; n < NumSpec; ++n) {
std::cout << std::setprecision(16) << xn_in[n] << " ";
}
std::cout << std::endl;
std::cout << "dens current = " << std::setprecision(16) << state.rho << std::endl;
std::cout << "temp current = " << std::setprecision(16) << state.T << std::endl;
std::cout << "xn current = ";
for (int n = 0; n < NumSpec; ++n) {
std::cout << std::setprecision(16) << state.xn[n] << " ";
}
std::cout << std::endl;
std::cout << "energy generated = " << state.e << std::endl;
#endif
}
}
#endif
| [
"noreply@github.com"
] | maxpkatz.noreply@github.com |
5b8d273eb7cb278c9f73aa7cc532b09d3fbb2662 | 5df66b7c0cf0241831ea7d8345aa4102f77eba03 | /Carberp Botnet/source - absource/pro/all source/Locker/src/privileges.h | 8025949b43b0082153a8ecef7d7fad4a2979eb4b | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | bengalm/fireroothacker | e8f20ae69f4246fc4fe8c48bbb107318f7a79265 | ceb71ba972caca198524fe91a45d1e53b80401f6 | refs/heads/main | 2023-04-02T03:00:41.437494 | 2021-04-06T00:26:28 | 2021-04-06T00:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | h | #ifndef UUID_67CC7598B46343D4B3E09E57633401CB
#define UUID_67CC7598B46343D4B3E09E57633401CB
struct ScopedDebugPrivilege
{
ScopedDebugPrivilege();
~ScopedDebugPrivilege();
bool Enabled();
private:
bool m_enabled;
};
#endif | [
"ludi@ps.ac.cn"
] | ludi@ps.ac.cn |
a22f3d0162a2e9833274b51a44288b1216e41b4a | 3c167ba443a26340be24560ff55a01ab14408103 | /Source/ALSV4_CPP/Public/Character/Animation/BMCharacterAnimInstance.h | 911fd41ea76594183d6337437de7b8d5b8dea54b | [
"MIT"
] | permissive | razor950/ALSV4_CPP | 97613ad652eb84bc646adbeef3cdef75a1f68b81 | a7372d4d821ed5c4d71b927ebe6ab8cf50c04bae | refs/heads/master | 2022-07-02T07:59:19.745089 | 2020-05-07T19:50:04 | 2020-05-07T19:50:04 | 263,211,445 | 2 | 0 | NOASSERTION | 2020-05-12T02:26:43 | 2020-05-12T02:26:43 | null | UTF-8 | C++ | false | false | 24,042 | h | // Copyright (C) 2020, Doga Can Yanikoglu
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimInstance.h"
#include "Library/BMCharacterEnumLibrary.h"
#include "BMCharacterAnimInstance.generated.h"
class ABMBaseCharacter;
class UCurveFloat;
class UAnimSequence;
class UCurveVector;
USTRUCT(BlueprintType)
struct FBMDynamicMontageParams
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UAnimSequenceBase* Animation = nullptr;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float BlendInTime = 0.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float BlendOutTime = 0.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float PlayRate = 0.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float StartTime = 0.0f;
};
USTRUCT(BlueprintType)
struct FBMLeanAmount
{
GENERATED_USTRUCT_BODY()
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
float LR = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
float FB = 0.0f;
};
USTRUCT(BlueprintType)
struct FBMVelocityBlend
{
GENERATED_USTRUCT_BODY()
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
float F = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
float B = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
float L = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly)
float R = 0.0f;
};
USTRUCT(BlueprintType)
struct FBMTurnInPlaceAsset
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere, BlueprintReadOnly)
UAnimSequenceBase* Animation = nullptr;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
float AnimatedAngle = 0.0f;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
FName SlotName;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
float PlayRate = 1.0f;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
bool ScaleTurnAngle = true;
};
/**
* Main anim instance class for character
*/
UCLASS(Blueprintable, BlueprintType)
class ALSV4_CPP_API UBMCharacterAnimInstance : public UAnimInstance
{
GENERATED_BODY()
void NativeInitializeAnimation() override;
void NativeUpdateAnimation(float DeltaSeconds) override;
UFUNCTION(BlueprintCallable)
void PlayTransition(const FBMDynamicMontageParams& Parameters);
UFUNCTION(BlueprintCallable)
void PlayTransitionChecked(const FBMDynamicMontageParams& Parameters);
UFUNCTION(BlueprintCallable)
void PlayDynamicTransition(float ReTriggerDelay, FBMDynamicMontageParams Parameters);
public:
UFUNCTION(BlueprintCallable)
void OnJumped();
UFUNCTION(BlueprintCallable)
void OnPivot();
/** Enable Movement Animations if IsMoving and HasMovementInput, or if the Speed is greater than 150. */
UFUNCTION(BlueprintCallable, Category = "Grounded")
bool ShouldMoveCheck();
/** Only perform a Rotate In Place Check if the character is Aiming or in First Person. */
UFUNCTION(BlueprintCallable, Category = "Grounded")
bool CanRotateInPlace();
/**
* Only perform a Turn In Place check if the character is looking toward the camera in Third Person,
* and if the "Enable Transition" curve is fully weighted. The Enable_Transition curve is modified within certain
* states of the AnimBP so that the character can only turn while in those states..
*/
UFUNCTION(BlueprintCallable, Category = "Grounded")
bool CanTurnInPlace();
/**
* Only perform a Dynamic Transition check if the "Enable Transition" curve is fully weighted.
* The Enable_Transition curve is modified within certain states of the AnimBP so
* that the character can only transition while in those states.
*/
UFUNCTION(BlueprintCallable, Category = "Grounded")
bool CanDynamicTransition();
private:
void PlayDynamicTransitionDelay();
void OnJumpedDelay();
void OnPivotDelay();
/** Update Values */
void UpdateAimingValues(float DeltaSeconds);
void UpdateLayerValues();
void UpdateFootIK(float DeltaSeconds);
void UpdateMovementValues(float DeltaSeconds);
void UpdateRotationValues();
void UpdateInAirValues(float DeltaSeconds);
void UpdateRagdollValues();
/** Foot IK */
void SetFootLocking(float DeltaSeconds, FName EnableFootIKCurve, FName FootLockCurve, FName IKFootBone,
float& CurFootLockAlpha, FVector& CurFootLockLoc, FRotator& CurFootLockRot);
void SetFootLockOffsets(float DeltaSeconds, FVector& LocalLoc, FRotator& LocalRot);
void SetPelvisIKOffset(float DeltaSeconds, FVector FootOffsetLTarget, FVector FootOffsetRTarget);
void ResetIKOffsets(float DeltaSeconds);
void SetFootOffsets(float DeltaSeconds, FName EnableFootIKCurve, FName IKFootBone, FName RootBone,
FVector& CurLocationTarget, FVector& CurLocationOffset, FRotator& CurRotationOffset);
/** Grounded */
void RotateInPlaceCheck();
void TurnInPlaceCheck(float DeltaSeconds);
void DynamicTransitionCheck();
FBMVelocityBlend CalculateVelocityBlend();
void TurnInPlace(FRotator TargetRotation, float PlayRateScale, float StartTime, bool OverrideCurrent);
/** Movement */
FVector CalculateRelativeAccelerationAmount();
float CalculateStrideBlend();
float CalculateWalkRunBlend();
float CalculateStandingPlayRate();
float CalculateDiagonalScaleAmount();
float CalculateCrouchingPlayRate();
float CalculateLandPrediction();
FBMLeanAmount CalculateAirLeanAmount();
EBMMovementDirection CalculateMovementDirection();
EBMMovementDirection CalculateQuadrant(EBMMovementDirection Current, float FRThreshold, float FLThreshold, float BRThreshold,
float BLThreshold, float Buffer, float Angle);
/** Util */
float GetAnimCurveClamped(const FName& Name, float Bias, float ClampMin, float ClampMax);
public:
/** References */
UPROPERTY(BlueprintReadWrite)
ABMBaseCharacter* Character = nullptr;
/** Character Information */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
FRotator AimingRotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
FRotator CharacterActorRotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
FVector Velocity;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
FVector RelativeVelocityDirection;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
FVector Acceleration;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
FVector MovementInput;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
bool bIsMoving = false;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
bool bHasMovementInput = false;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
float Speed = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
float MovementInputAmount = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
float AimYawRate = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
float ZoomAmount = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMMovementState MovementState = EBMMovementState::None;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMMovementState PrevMovementState = EBMMovementState::None;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMMovementAction MovementAction = EBMMovementAction::None;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMRotationMode RotationMode = EBMRotationMode::LookingDirection;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMGait Gait = EBMGait::Walking;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMStance Stance = EBMStance::Standing;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMViewMode ViewMode = EBMViewMode::ThirdPerson;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Character Information")
EBMOverlayState OverlayState = EBMOverlayState::Default;
/** Anim Graph - Grounded */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite, Category = "Read Only Data|Anim Graph - Grounded")
EBMGroundedEntryState GroundedEntryState = EBMGroundedEntryState::None;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
EBMMovementDirection MovementDirection = EBMMovementDirection::Forward;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite, Category = "Read Only Data|Anim Graph - Grounded")
EBMHipsDirection TrackedHipsDirection = EBMHipsDirection::F;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
FVector RelativeAccelerationAmount;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
bool bShouldMove = false; // Should be false initially
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
bool bRotateL = false;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
bool bRotateR = false;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite, Category = "Read Only Data|Anim Graph - Grounded")
bool bPivot = false;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float RotateRate = 1.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float RotationScale = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float DiagonalScaleAmount = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float WalkRunBlend = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float StandingPlayRate = 1.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float CrouchingPlayRate = 1.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float StrideBlend = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
FBMVelocityBlend VelocityBlend;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
FBMLeanAmount LeanAmount;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float FYaw = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float BYaw = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float LYaw = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Grounded")
float RYaw = 0.0f;
/** Anim Graph - In Air */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - In Air")
bool bJumped = false;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - In Air")
float JumpPlayRate = 1.2f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - In Air")
float FallSpeed = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - In Air")
float LandPrediction = 1.0f;
/** Anim Graph - Aiming Values */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
FRotator SmoothedAimingRotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
FRotator SpineRotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
FVector2D AimingAngle;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
FVector2D SmoothedAimingAngle;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
float AimSweepTime = 0.5f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
float InputYawOffsetTime = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
float ForwardYawTime = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
float LeftYawTime = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Aiming Values")
float RightYawTime = 0.0f;
/** Anim Graph - Ragdoll */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite, Category = "Read Only Data|Anim Graph - Ragdoll")
float FlailRate = 0.0f;
/** Anim Graph - Layer Blending */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite, Category = "Read Only Data|Anim Graph - Layer Blending")
int32 OverlayOverrideState = 0;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float EnableAimOffset = 1.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float BasePose_N = 1.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float BasePose_CLF = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_L = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_L_Add = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_L_LS = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_L_MS = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_R = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_R_Add = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_R_LS = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Arm_R_MS = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Hand_L = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Hand_R = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Legs = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Legs_Add = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Pelvis = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Pelvis_Add = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Spine = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Spine_Add = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Head = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float Head_Add = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float EnableHandIK_L = 1.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Layer Blending")
float EnableHandIK_R = 1.0f;
/** Anim Graph - Foot IK */
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
float FootLock_L_Alpha = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
float FootLock_R_Alpha = 0.0f;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FVector FootLock_L_Location;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FVector FootLock_R_Location;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FRotator FootLock_L_Rotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FRotator FootLock_R_Rotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FVector FootOffset_L_Location;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FVector FootOffset_R_Location;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FRotator FootOffset_L_Rotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FRotator FootOffset_R_Rotation;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
FVector PelvisOffset;
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Read Only Data|Anim Graph - Foot IK")
float PelvisAlpha = 0.0f;
/** Turn In Place */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
float TurnCheckMinAngle = 45.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
float Turn180Threshold = 130.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
float AimYawRateLimit = 50.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
float ElapsedDelayTime = 0.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
float MinAngleDelay = 0.75f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
float MaxAngleDelay = 0.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset N_TurnIP_L90;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset N_TurnIP_R90;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset N_TurnIP_L180;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset N_TurnIP_R180;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset CLF_TurnIP_L90;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset CLF_TurnIP_R90;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset CLF_TurnIP_L180;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Turn In Place")
FBMTurnInPlaceAsset CLF_TurnIP_R180;
/** Rotate In Place */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Rotate In Place")
float RotateMinThreshold = -50.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Rotate In Place")
float RotateMaxThreshold = 50.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Rotate In Place")
float AimYawRateMinRange = 90.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Rotate In Place")
float AimYawRateMaxRange = 270.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Rotate In Place")
float MinPlayRate = 1.15f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Rotate In Place")
float MaxPlayRate = 3.0f;
/** Configuration */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float AnimatedWalkSpeed = 150.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float AnimatedRunSpeed = 350.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float AnimatedSprintSpeed = 600.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float AnimatedCrouchSpeed = 150.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float VelocityBlendInterpSpeed = 12.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float GroundedLeanInterpSpeed = 4.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float InAirLeanInterpSpeed = 4.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float SmoothedAimingRotationInterpSpeed = 10.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float InputYawOffsetInterpSpeed = 8.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float TriggerPivotSpeedLimit = 200.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float FootHeight = 13.5f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float IK_TraceDistanceAboveFoot = 50.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Configuration|Main Configuration")
float IK_TraceDistanceBelowFoot = 45.0f;
/** Blend Curves */
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveFloat* DiagonalScaleAmountCurve;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveFloat* StrideBlend_N_Walk;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveFloat* StrideBlend_N_Run;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveFloat* StrideBlend_C_Walk;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveFloat* LandPredictionCurve;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveFloat* LeanInAirCurve;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveVector* YawOffset_FB;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Blend Curves")
UCurveVector* YawOffset_LR;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Dynamic Transition")
UAnimSequenceBase* TransitionAnim_R;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Configuration|Dynamic Transition")
UAnimSequenceBase* TransitionAnim_L;
private:
FTimerHandle OnPivotTimer;
FTimerHandle PlayDynamicTransitionTimer;
FTimerHandle OnJumpedTimer;
bool bCanPlayDynamicTransition = true;
};
| [
"dcyanikoglu@gmail.com"
] | dcyanikoglu@gmail.com |
7c2752332a776af1f72ac22a8df152c28da18ae0 | 774ceaeaaf31df44b3a0429c815d63c7aba015ae | /MiniGolfProject/Project1/src/ResourceManager.h | 96b0180e7f47431e984aeefa09204bcfc720f80d | [] | no_license | hamencheez/CMPS164_Engine | 11bf12e2335058067ea5a5236f5e049461d4e817 | f837117a814ecc8472cf1bd9460ee42d9656f4fa | refs/heads/master | 2021-01-01T19:42:49.996529 | 2013-06-10T23:59:51 | 2013-06-10T23:59:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | h | //ResourceManger.h
#pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include "Tee.h"
#include "Cup.h"
#include "Ball.h"
#include "Physics.h"
#include "Vector3.h"
using namespace std;
class ResourceManager {
private:
vector<Tile> tiles;
vector<vector<Tile>> levels;
vector<Cup> cups;
vector<Tee> tees;
map<string, vector<float>> objData;
map<string, vector<float>> vertData;
vector<int> levelPar;
vector<string> levelNames;
void addTile(Tile &newTile, int levelInd);
void addCup(Cup &newCup);
void addTee(Tee &newTee);
void clearVecs();
public:
ResourceManager();
~ResourceManager();
void readTileFile(char* inputFile);
void readCourseFile(char* inputFile);
void readObjFile(char* inputFile);
map<string, vector<float>>* getObjData(){return &objData;};
vector<float> getObjVector(string ID);
vector<vector<Tile>> getLevels();
vector<Tile> tileList();
vector<Cup> getCups(){return cups;};
vector<Tee> getTees(){return tees;};
vector<int> getLevelPars(){return levelPar;};
vector<string> getLevelNames(){return levelNames;};
Tile getTile(Vector3* pos, Tile last, Physics* physics, int level);
}; | [
"jbarrica@ucsc.edu"
] | jbarrica@ucsc.edu |
9994b1363d4c8e0664d3b3b88ba30b8a1b3b1658 | 41a0fa3b6fa55f2c278e06718a04ad38e645dfa0 | /codechef/PROBDIFF.cpp | e968d38d8ffab09ca0978e9bd8c102a787468dda | [] | no_license | sharmarajdaksh/cp | d3a42bca8349fd958f2a3f19a173980d4aa94e44 | c0f900e14a4f502c647b0f40c2b00871e2fd43de | refs/heads/master | 2023-07-28T22:04:02.357209 | 2021-09-13T14:59:50 | 2021-09-13T14:59:50 | 277,243,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
unordered_set<int> questions;
int tmp;
vector<int> freq(10, 0);
int max_freq = 0;
for (int i = 0; i < 4; i++) {
cin >> tmp;
freq[tmp - 1]++;
max_freq = max(max_freq, freq[tmp - 1]);
}
int ans;
if (max_freq == 1) {
ans = 2;
} else if (max_freq == 2) {
ans = 2;
} else if (max_freq == 3) {
ans = 1;
} else if (max_freq == 4) {
ans = 0;
}
cout << ans << endl;
}
} | [
"sharmarajdaksh@gmail.com"
] | sharmarajdaksh@gmail.com |
a1e9d6fa7ed3d736c269108a29a1d806f259b4b7 | 20fdb0563cc5401b9608966b8b0bd695710c053b | /SignalsPs/SignalsPs.h | fe42ed735fb79bf4aced63b1ec53a286759afd14 | [] | no_license | Kuznetsov-Mikhail/Information_Technology | df1b025cf6558b3fd1936fc07c76d6cea5ccab3a | 481fdbb39b40c49b7ea64cd85bf1db85e802ebf1 | refs/heads/master | 2023-02-01T23:46:56.326072 | 2020-12-22T22:58:56 | 2020-12-22T22:58:56 | 298,621,410 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 622 | h |
// SignalsPs.h: главный файл заголовка для приложения PROJECT_NAME
//
#pragma once
#ifndef __AFXWIN_H__
#error "включить pch.h до включения этого файла в PCH"
#endif
#include "resource.h" // основные символы
// CSignalsPsApp:
// Сведения о реализации этого класса: SignalsPs.cpp
//
class CSignalsPsApp : public CWinApp
{
public:
CSignalsPsApp();
// Переопределение
public:
virtual BOOL InitInstance();
// Реализация
DECLARE_MESSAGE_MAP()
};
extern CSignalsPsApp theApp;
| [
"Freddy152@ya.ru"
] | Freddy152@ya.ru |
585cdde1daa2bc2f24f80cf906b5bf696ce59056 | 735a3a4b486b6f925471006ea00a75c40a24bbb5 | /src/detection.cc | 77237cbb73edd7e19dfad893cc697076d5504394 | [
"MIT"
] | permissive | juandez87/ELMA-Rasp-detection | 3c7e7d3d53817a825c47d6073455e3798b220a1b | 8789d2e762e9e53955ebcc9a2393d13560f9f4ab | refs/heads/master | 2020-04-28T01:57:22.105345 | 2019-03-26T13:34:46 | 2019-03-26T13:34:46 | 174,879,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,340 | cc | #include <chrono>
#include <vector>
#include "detection.h"
#include <wiringPi.h>
#include <softPwm.h>
// Pins definition
#define TRIG 7
#define ECHO 0
#define RED 1
#define BLUE 3
#define GREEN 2
#define PWM 4
//#include "user_interface.h"
using namespace std::chrono;
using namespace elma;
using namespace stopwatch;
StopWatch::StopWatch() : StateMachine("stopwatch") {
// Define state machine initial states and transitions here
set_initial(off);
set_propagate(false);
add_transition("start/stop", off, on);
add_transition("reset", off, off);
add_transition("start/stop", on, off);
// Make sure we start in the right condition
// OUTPUT
setup();
reset();
}
high_resolution_clock::duration StopWatch::value() {
if ( current().name() == "on" ) {
return high_resolution_clock::now() - _start_time + _elapsed;
} else {
return _elapsed;
}
}
void StopWatch::begin() {
_start_time = high_resolution_clock::now();
digitalWrite (GREEN, HIGH);
digitalWrite (RED, LOW);
}
void StopWatch::reset() {
_elapsed = high_resolution_clock::duration::zero();
_laps.clear();
digitalWrite (GREEN, LOW);
digitalWrite (RED, LOW);
}
void StopWatch::stop() {
_elapsed += high_resolution_clock::now() - _start_time;
digitalWrite (GREEN, LOW);
digitalWrite (RED, HIGH);
}
void StopWatch::setup() {
wiringPiSetup();
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode (BLUE, OUTPUT) ;
pinMode (GREEN, OUTPUT) ;
pinMode (RED, OUTPUT) ;
pinMode(PWM, PWM_OUTPUT);
digitalWrite(PWM, 0);
softPwmCreate(PWM, 0, 200);
softPwmWrite (PWM, 9);
//TRIG pin must start LOW
digitalWrite(TRIG, LOW);
delay(30);
}
int StopWatch::getCM() {
//delay(500);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int i=0;
//Wait for echo start
while(digitalRead(ECHO) == LOW);
//Wait for echo end
long startTime = micros();
while(digitalRead(ECHO) == HIGH);
long travelTime = micros() - startTime;
//Get distance in cm
int distance = travelTime / 58;
delay(500);
return distance;
}
void StopWatch::searching(double x) {
softPwmWrite (PWM, x);
}
| [
"juandez87@gmail.com"
] | juandez87@gmail.com |
3abc71f9c695b732ea34f70fe1d11b2183438fc5 | fd931b240b10e9753d9eee9a699dcab5226e8061 | /build/build.cpp | 8ee82807d367955e24e44219876729fcbadcc501 | [] | no_license | CGCL-codes/DGraph | 1418808c57f867649503b32be526f9a7c8150fef | 685f8ae1811127db7f8b2a7a93252dd3cbb6c250 | refs/heads/master | 2021-01-22T07:22:26.539454 | 2017-02-13T00:54:19 | 2017-02-13T00:54:19 | 81,809,539 | 11 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 17,573 | cpp | #include "build.h"
#include "pathgraph.h"
using namespace std;
ID N = 0; // maxid
/*
* Build scc
*/
//build scc output
vector<Vtx*> vtxs;
vector<SCC_Vtx*> scc_vtxs;
vector<SCC_Vtx*> vtx_to_scc;
//tarjan global parameter
stack<Vtx*> scc_stk, scc_buff;
//QuickStack<Vtx*> scc_stk, scc_buff;
vector<ID> dfn, low;
vector<bool> in_stack;
ID scc_index = 0, scc_cnt = 0; //to generate dfn
void build_scc(VtxsFile<ID> &fvtxs)
{
//Initralize
vtxs.resize(N + 1);
//#pragma omp parallel for schedule(static)
for(ID i = 0; i <= N; i++)
{
vtxs[i] = new Vtx();
vtx_init(vtxs[i], fvtxs[i]);
}
dfn.resize(N + 1, 0);
low.resize(N + 1, INT_MAX);
vtx_to_scc.resize(N + 1);
in_stack.resize(N + 1, false);
//Tarjan algorithm
cout << "Tarjan" << endl;
for(ID i = 0; i <= N; i++)
{
if(dfn[vtxs[i]->id] == 0)
tarjan(i);
}
//free space
dfn.clear();
low.clear();
in_stack.clear();
/* cnt_t scc_size = scc_vtxs.size();
cout << "scc num: " << scc_size << endl;
for(ID i = 0; i < scc_size; i++)
{
SCC_Vtx *scc = scc_vtxs[i];
cout << "scc-" << scc->id << " : ";
for(ID j = 0; j < scc->scc_group.size(); j++)
cout << scc->scc_group[j]->id << " " ;
cout << endl;
}
*/
//Make scc graph
cout << "scc num: " << scc_vtxs.size() << endl;
}
void build_scc_graph(VtxsFile<ID> &fscc_vtxs)
{
typedef set<SCC_Vtx*>::iterator sit;
cnt_t scc_num = scc_vtxs.size();
//combine scc vtx border
//#pragma omp parallel for schedule(dynamic, 100)
for(ID i = 0; i < scc_num; i++)
{
set<SCC_Vtx*> tmp_outbr;
SCC_Vtx *scc_u = scc_vtxs[i];
for(ID j = 0; j < scc_u->scc_group.size(); j++)
{
Vtx *u = scc_u->scc_group[j];
for(ID k = 0; k < u->out_cnt; k ++)
{
SCC_Vtx *scc_v = vtx_to_scc[u->bor[k]];
if(scc_u != scc_v)
tmp_outbr.insert(scc_v);
}
}
//Convert set to vector to reduce memory space.
fscc_vtxs.add_vtx_start(scc_u->id);
for(sit iter = tmp_outbr.begin(); iter != tmp_outbr.end(); iter++)
{
fscc_vtxs.add_bor((*iter)->id);
}
fscc_vtxs.add_vtx_end();
scc_u->outcnt = tmp_outbr.size();
}
//Add file base addr to scc_u
for(ID i = 0; i < scc_num; i++)
{
SCC_Vtx *scc_u = scc_vtxs[i];
addr_t scc_base = fscc_vtxs.get_vtx_base_addr(scc_u->id);
scc_u->outbr = VtxUnitData<ID>::bor(scc_base);
}
}
void tarjan(ID vi)
{
Vtx *u = new Vtx();
vtx_init(u, vi);
do
{
while(u->outi >= 0)
{
Vtx *v = vtxs[u->bor[u->outi]];
if(dfn[v->id] == 0)
{
dfn[v->id] = low[v->id] = ++scc_index;
scc_stk.push(v);
in_stack[v->id] = true;
scc_buff.push(u);
u = v;
}
else
{
if(in_stack[v->id])
low[u->id] = min(low[u->id], dfn[v->id]);
u->outi--;
}
}
if(dfn[u->id] == low[u->id])
{
SCC_Vtx *scc_u = new SCC_Vtx(scc_cnt++);
scc_vtxs.push_back(scc_u);
Vtx *v;
do
{
v = scc_stk.top();
scc_stk.pop();
in_stack[v->id] = false;
scc_u->scc_group.push_back(v);
vtx_to_scc[v->id] = scc_u; //record to toposort
}while(v != u);
}
u = scc_buff.top();
scc_buff.pop();
low[u->id] = min(low[u->id], low[vtxs[u->bor[u->outi]]->id]);
u->outi--;
}while(!scc_buff.empty() || u->outi >= 0 );
}
/*
* Topo sort
*/
//Topo sort global output
vector<SCC_Vtx*> topo_scc_vtxs;
vector<ID> scc_vtxs_map; // old to new
//Toposort que
queue<SCC_Vtx*> scc_que;
vector<SCC_Vtx*> scc_topo_buff[2];
queue<SCC_Vtx*> big_scc;
void add_scc_to_vec(SCC_Vtx *u, vector<SCC_Vtx*> &scc_topo_buff)
{
if(u->scc_group.size() > BIG_SCC_SIZE)
big_scc.push(u);
else scc_topo_buff.push_back(u);
}
void visit_scc_bor(SCC_Vtx *u, vector<SCC_Vtx*> &scc_topo_buff)
{
for(ID i = 0; i < u->outcnt; i++)
{
SCC_Vtx *v = scc_vtxs[u->outbr[i]];
v->incnt--;
if(v->incnt == 0)
add_scc_to_vec(v, scc_topo_buff);
}
}
void copy_scc_topo_buff(vector<SCC_Vtx*> &scc_topo_buff, RawFile<ID> &scc_topo_level, cnt_t level)
{
RawUnit<ID> &ru = scc_topo_level[level];
ru.first = topo_scc_vtxs.size();
for(cnt_t i = 0; i < scc_topo_buff.size(); i++)
{
topo_scc_vtxs.push_back(scc_topo_buff[i]);
scc_vtxs_map[scc_topo_buff[i]->id] = topo_scc_vtxs.size() - 1;
}
ru.second = topo_scc_vtxs.size();
//[from, to)
cout << "scc level: " << ru.first << "-" << ru.second << endl;
}
/*
* RawFile<ID> scc_topo_level: for para calc small scc
* [from, to) = [from_scc_num, to_scc_num + 1);
*/
void build_toposort(RawFile<ID> &scc_topo_level)
{
init_topo_incnt();
init_topo_sort();
cnt_t level = 0;
for (ID i = 0; i < scc_vtxs.size(); i++)
{
SCC_Vtx* u = scc_vtxs[i];
if (u->incnt == 0)
add_scc_to_vec(u, scc_topo_buff[0]);
}
cnt_t itr = 0;
while (!scc_topo_buff[0].empty() || !scc_topo_buff[1].empty() || !big_scc.empty())
{
//Calculate small scc.
for(ID i = 0; i < scc_topo_buff[itr % 2].size(); i++)
{
SCC_Vtx *u = scc_topo_buff[itr % 2][i];
visit_scc_bor(u, scc_topo_buff[(itr + 1) % 2]);
}
copy_scc_topo_buff(scc_topo_buff[itr % 2], scc_topo_level, level++);
scc_topo_buff[itr % 2].clear();
//Calculate big scc. Check if there are big scc
while(!big_scc.empty())
{
SCC_Vtx *u = big_scc.front();
big_scc.pop();
visit_scc_bor(u, scc_topo_buff[(itr + 1) % 2]);
topo_scc_vtxs.push_back(u);
scc_vtxs_map[u->id] = topo_scc_vtxs.size() - 1;
//[from, to)
scc_topo_level[level].first = topo_scc_vtxs.size() - 1;
scc_topo_level[level].second = topo_scc_vtxs.size();
level++;
cout << "big level: " << topo_scc_vtxs.size() -1 << endl;
}
itr++;
}
scc_topo_level.set_raw_num(level);
cout << "topo scc num:" << topo_scc_vtxs.size() << endl;
/*
for(ID i = 0; i < topo_scc_vtxs.size(); i++)
{
SCC_Vtx* u = topo_scc_vtxs[i];
if(u->scc_group.size() < 1)
continue;
cout << "scc-" << i;
for(ID j = 0; j < u->scc_group.size(); j++)
cout << " " << u->scc_group[j]->id;
cout << endl;
}
*/
}
void init_topo_incnt()
{
for(ID i = 0; i < scc_vtxs.size(); i++)
{
SCC_Vtx* u = scc_vtxs[i];
for(ID j = 0; j < u->outcnt; j++)
scc_vtxs[u->outbr[j]]->const_incnt++;
}
}
void init_topo_sort()
{
for(ID i = 0; i < scc_vtxs.size(); i++)
scc_vtxs[i]->incnt = scc_vtxs[i]->const_incnt;
scc_vtxs_map.resize(scc_vtxs.size());
}
/*
* File operaton
*/
void read_dataset_adj_no_size(char *fname, RawFile<ID> &rfile)
{
FILE *f = fopen(fname, "r");
//Start read dataset
cout << "Start read dataset "; get_time(false); cout << endl;
ID from;
long long maxlen = 10000000;
char *s = (char*)malloc(maxlen);
char delims[] = " \t\n";
long long brcnt = 0;
while (fgets(s, maxlen, f) != NULL)
{
if (s[0] == '#' || s[0] == '%' || s[0] == '\n')
continue; //Comment
char *t = strtok(s, delims);
from = atoi(t);
N = max(N, from);
ID to;
while ((t = strtok(NULL, delims)) != NULL)
{
to = atoi(t);
N = max(N, to);
RawUnit<ID> &ru = rfile[brcnt];
ru.first = from;
ru.second = to;
brcnt++;
}
///*
if (from % 100000 == 0)
cout << from << endl;
//*/
/*
if (++brcnt % 1000000 == 0)
cout << brcnt << endl;
//*/
}
rfile.set_raw_num(brcnt);
fclose(f);
free(s);
cout << "End read dataset max id: " << N << " "; get_time(); cout << endl;
}
void read_dataset_hlist(char *fname, RawFile<ID> &rfile)
{
read_dataset_adj_no_size(fname, rfile);
}
void convert_raw_to_adj(RawFile<ID> &raw_file, VtxsFile<ID> &adj_file, bool is_in_not_out = false,
ID* mapping = NULL)
{
cnt_t raw_size = raw_file.size();
ID last_from = (0 - 1); //define a non-exist id to last_from
bool first_set = true;
for(cnt_t i = 0; i < raw_size; i++)
{
RawUnit<ID> &ru = raw_file[i];
ID from, to;
//set from to
if(!is_in_not_out)
{
from = ru.first;
to = ru.second;
}
else
{
from = ru.second;
to = ru.first;
}
if(mapping != NULL)
{
from = mapping[from];
to = mapping[to];
}
if(last_from != from)
{
if(!first_set)
adj_file.add_vtx_end();
else first_set = false;
last_from = from;
adj_file.add_vtx_start(from);
}
adj_file.add_bor(to);
}
if(!first_set)
adj_file.add_vtx_end();
}
void build_topo_scc_file(VtxsFile<ID> &topo_fscc_vtxs)
{
typedef set<SCC_Vtx*>::iterator sit;
for(ID i = 0; i < topo_scc_vtxs.size(); i++)
{
SCC_Vtx *u = topo_scc_vtxs[i];
topo_fscc_vtxs.add_vtx_start(i);
for(int i = 0; i < u->outcnt; i++)
{
topo_fscc_vtxs.add_bor(scc_vtxs_map[u->outbr[i]]);
}
topo_fscc_vtxs.add_vtx_end();
}
}
void build_vtxs_map(VtxIndexFile<ID> &vtxs_map_otn, VtxIndexFile<ID> &vtxs_map_nto) // vtxs_map[old] = new
{
ID new_id = 0;
for(ID i = 0; i < topo_scc_vtxs.size(); i++)
{
SCC_Vtx *u = topo_scc_vtxs[i];
u->from_id = new_id;
for(long long j = u->scc_group.size() - 1; j >= 0; j--) // according to tarjan's dfs order for faster convergence
{
ID old_id = u->scc_group[j]->id;
vtxs_map_otn[old_id] = new_id;
vtxs_map_nto[new_id++] = old_id;
}
u->to_id = new_id - 1;
}
/*
cout << "otn map size: " << vtxs_map_otn.size() << endl;
for(ID i = 0; i < vtxs_map_otn.size(); i++)
cout << i << " -> " << vtxs_map_otn[i] << endl;
//*/
}
//build_order_vtxs_out compare function
int id_greater(const void *a, const void *b){return *(int*)a - *(int*)b;};
int id_less(const void *a, const void *b){return *(int*)b - *(int*)a;};
void sort_bor(VtxsFile<ID> &fvtxs, bool is_in_not_out)
{
for(ID i = 0; i < fvtxs.size(); i++)
{
VtxUnit<ID> *vu = fvtxs[i];
if(is_in_not_out) qsort((void*)vu->bor, *(vu->cnt_p), sizeof(ID), id_greater); //in is upper sort
else qsort((void*)vu->bor, *(vu->cnt_p), sizeof(ID), id_less); //out is lower sort
delete vu;
}
}
void build_order_vtxs_out(VtxsFile<ID> &vtxs_io, VtxIndexFile<ID> &vtxs_map_nto, VtxIndexFile<ID> &vtxs_map_otn)//, bool is_in_not_out)
{
ID new_id = 0;
for(new_id = 0; new_id < vtxs_map_nto.size(); new_id ++)
{
Vtx *v = vtxs[vtxs_map_nto[new_id]];
vtxs_io.add_vtx_start(new_id);
cnt_t bor_cnt = v->out_cnt;
for(ID k = 0; k < bor_cnt; k++)
{
vtxs_io.add_bor(vtxs_map_otn[v->bor[k]]);
}
vtxs_io.add_vtx_end();
//sort bor according to tarjan's dfs order for faster convergence
/* VtxUnit<ID> *vu = vtxs_io[new_id];
if(is_in_not_out) qsort((void*)vu->bor, bor_cnt, sizeof(ID), id_greater); //in is upper sort
else qsort((void*)vu->bor, bor_cnt, sizeof(ID), id_less); //out is lower sort
cout << "v-" << *(vu->id_p);
for(ID k = 0; k < bor_cnt; k++)
cout << " " << vu->bor[k];
cout << endl;
delete vu;
*/
}
sort_bor(vtxs_io, false);
}
void build_scc_group_file(RawFile<ID> &fscc_group)
{
for(ID i = 0; i < topo_scc_vtxs.size(); i++)
{
RawUnit<ID> &ru = fscc_group[i];
SCC_Vtx *v = topo_scc_vtxs[i];
ru.first = v->from_id;
ru.second = v->to_id;
}
fscc_group.set_raw_num(topo_scc_vtxs.size());
/*
for(ID i = 0; i < fscc_group.size(); i++)
{
RawUnit<ID> &ru = fscc_group[i];
cout << "scc-" << i << " " << ru.first << "-" << ru.second << endl;
}
*/
}
void convert_raw_file(RawFile<ID> &rfile, ID* mapping)
{
#pragma omp parallel for schedule(static)
for(cnt_t i = 0; i < rfile.size(); i++)
{
RawUnit<ID> &ru = rfile[i];
ru.first = mapping[ru.first];
ru.second = mapping[ru.second];
}
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
cout << "Usage ./build <dataset.txt> <to dir>" << endl;
return 0;
}
string dir(argv[2]);
//Remove old files.
cout << "Remove old files"; get_time(false);
string cmd = string("rm -f ") + dir + string("/*.bin");
system(cmd.c_str());
get_time(); cout << endl;
//Record start time
time_t start_time = get_time(false);
cout << "\n------------------Read Dataset---------------------" << endl;
//Create unsorted raw file from dataset
cout << "Dataset --> Normal RawFile " << endl; get_time(false);
RawFile<ID> us_rfile("unsorted_raw_file.bin", dir);
us_rfile.open();
read_dataset_adj_no_size(argv[1], us_rfile);
cout << "Max id: " << N << endl;
//Sort it
cout << "Sort Normal RawFile --> Sorted RawFile(first unit order) " << endl; get_time(false);
RawFile<ID> s_rfile("sorted_raw_file.bin", dir);
s_rfile.open();
Sorter::sort_raw(us_rfile, s_rfile, true);
get_time(); cout << endl;
//Generate normal adj file
cout << "Sorted RawFile(first unit order) --> Normal AdjFile "; get_time(false);
VtxsFile<ID> fvtxs_out("normal_vtxs_out.bin", "normal_vindex_out.bin", dir);
fvtxs_out.open();
convert_raw_to_adj(s_rfile, fvtxs_out, false);
get_time(); cout << endl;
cout << "\n----------------Build SCC & Topo Sort--------------" << endl;
//Build scc
cout << "Build SCC " << endl; get_time(false);
build_scc(fvtxs_out);
get_time(); cout << endl;
//Generate scc vtxs adj file
cout << "Generate SCC --> SCC AdjFile "; get_time(false);
VtxsFile<ID> fscc_vtxs("scc_vtx.bin", "scc_vindex.bin", dir);
fscc_vtxs.open();
build_scc_graph(fscc_vtxs);
get_time(); cout << endl;
//Build topo sort
cout << "Topo Sort --> SCC Topo Level File" << endl; get_time(false);
RawFile<ID> scc_topo_level("scc_topo_level.bin", dir);
scc_topo_level.open();
build_toposort(scc_topo_level);
scc_topo_level.close();
get_time(); cout << endl;
/*
//Generate scc vtxs adj file
cout << "Generate Topo SCC --> Topo SCC AdjFile "; get_time(false);
VtxsFile<ID> topo_fscc_vtxs("topo_scc_vtx.bin", "topo_scc_vindex.bin", dir);
topo_fscc_vtxs.open();
build_topo_scc_file(topo_fscc_vtxs);
topo_fscc_vtxs.close();
get_time(); cout << endl;
//*/
//Generate vtx map file
cout << "Convert Vertex ID --> Vertex MapFile "; get_time(false);
VtxIndexFile<ID> vtxs_map_otn("vtxs_map_old_to_new.bin", dir), vtxs_map_nto("vtxs_map_new_to_old.bin", dir);
vtxs_map_otn.open();
vtxs_map_nto.open();
build_vtxs_map(vtxs_map_otn, vtxs_map_nto);
get_time(); cout << endl;
cout << "\n---------------Generate Out AdjFile----------------" << endl;
//Generate order vtx outbor file
cout << "Generate Vertex Out AdjFile "; get_time(false);
VtxsFile<ID> vtxs_out("order_vtxs_out.bin", "order_vindex_out.bin", dir);
vtxs_out.open();
build_order_vtxs_out(vtxs_out, vtxs_map_nto, vtxs_map_otn);//, false); //out
//vtxs_map_nto.close();
//vtxs_out.close();
get_time(); cout << endl;
cout << "\n---------------Generate In AdjFile-----------------" << endl;
//Generate order vtx inbor file
cout << "Convert Normal RawFile ID --> New ID RawFile "; get_time(false);
convert_raw_file(us_rfile, vtxs_map_otn.get_start());
get_time(); cout << endl;
cout << "Sort New ID RawFile --> Sorted RawFile(second unit order) " << endl; get_time(false);
Sorter::sort_raw(us_rfile, s_rfile, false);
get_time(); cout << endl;
cout << "Sorted RawFile(second unit order) --> Vertex In AdjFile "; get_time(false);
VtxsFile<ID> vtxs_in("order_vtxs_in.bin", "order_vindex_in.bin", dir);
vtxs_in.open();
convert_raw_to_adj(s_rfile, vtxs_in, true);
sort_bor(vtxs_in, true);
//vtxs_in.close();
get_time(); cout << endl;
//vtxs_map_otn.close();
us_rfile.close();
s_rfile.close();
cout << "\n--------------Generate SCC Group File--------------" << endl;
//Generate scc group file
cout << "Generate SCC Group File "; get_time(false);
RawFile<ID> fscc_group("scc_group.bin", dir);
fscc_group.open();
build_scc_group_file(fscc_group);
fscc_group.close();
//fvtxs_out.close();
get_time(); cout << endl;
cout << "\n--------------Generate PathGraph File--------------" << endl;
//Generate PathGraph File in SCC DAg order
cout << "Generate SCC Group PathGraph File "; get_time(false);
//Matrixso map
cout << endl << "Building Matrixso Map" << endl;
VtxIndexFile<ID> pg_map_so_otn("pg_map_matrixso_otn.bin", dir), pg_map_so_nto("pg_map_matrixso_nto.bin", dir);
pg_map_so_otn.open();
pg_map_so_nto.open();
PathGraph::generate_map(topo_scc_vtxs, vtxs_out, vtxs_map_otn, pg_map_so_otn, pg_map_so_nto, false, vtxs_map_nto.get_start());
pg_map_so_otn.close();
pg_map_so_nto.close();
get_time(); cout << endl;
//Matrixos map
cout << "Building Matrixos Map" << endl;
VtxIndexFile<ID> pg_map_os_otn("pg_map_matrixos_otn.bin", dir), pg_map_os_nto("pg_map_matrixos_nto.bin", dir);
pg_map_os_otn.open();
pg_map_os_nto.open();
//PathGraph::generate_map(topo_scc_vtxs, vtxs_in, vtxs_map_otn, pg_map_os_otn, pg_map_os_nto, true, vtxs_map_nto.get_start());
PathGraph::generate_map_os(topo_scc_vtxs, vtxs_in, vtxs_map_otn, pg_map_os_otn, pg_map_os_nto, N, vtxs_map_nto.get_start());
pg_map_os_nto.close();
get_time(); cout << endl;
//Close scc vtxs data
fscc_vtxs.close();
//Convert adj to Matrixos adj file
cout << "Convert adj file to Matrixos adj File" << endl;
/*
* To close PathGraph: add comment "//" to 2 lines below and modify api.h map_nto & map_otn
* Re-make the project and re-build the dataset.
* */
PathGraph::convert_adj_file(vtxs_out, pg_map_os_otn, vtxs_map_nto.get_start());
PathGraph::convert_adj_file(vtxs_in, pg_map_os_otn, vtxs_map_nto.get_start());
pg_map_os_otn.close();
vtxs_map_nto.close();
cout << "Generate compress PathGraph vtxs file" << endl;
PGVtxsFile<ID> pg_vtxs_out("pg_vtxs_out.bin", "pg_vindex_out.bin", dir);
pg_vtxs_out.open();
pg_vtxs_out.generate(vtxs_out);
pg_vtxs_out.close();
vtxs_out.close();
PGVtxsFile<ID> pg_vtxs_in("pg_vtxs_in.bin", "pg_vindex_in.bin", dir);
pg_vtxs_in.open();
pg_vtxs_in.generate(vtxs_in);
pg_vtxs_in.close();
vtxs_in.close();
vtxs_map_otn.close();
fvtxs_out.close();
get_time(); cout << endl;
cout << "---------------------------------------------------" << endl;
cout << "Build end." << " cost: " << get_time(false) - start_time << " ms" << endl;
return 0;
}
| [
"jimmyshi@tencent.com"
] | jimmyshi@tencent.com |
d40a27b7bf882301cfff28533b60a88a4b54f534 | 0b203dfcb7e1328756b13f2aad1dd229b3d5f91c | /cameraview.h | 48fc26f5c558ea95dbe904dae2759b4d64a11327 | [] | no_license | milan-vahala/MyQtOpenGL | 334c67e122c5e7a3f642cd815399e277aa43789e | b0b7b4b9bf230871f59087692d194158d6f9d275 | refs/heads/master | 2020-05-07T19:13:49.862133 | 2019-04-15T10:55:29 | 2019-04-15T10:55:29 | 180,803,740 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | h | #ifndef CAMERAVIEW_H
#define CAMERAVIEW_H
#include <QVector2D>
#include "position.h"
class CameraView
{
public:
CameraView(QVector<Triangle>* aFloor);
float getVerticalAngle() const;
void turnVerticaly(float turnAngle);
bool step(float stepSize);
void turnHorizontaly(float turnAngle);
float getX() const;
float getY() const;
float getZ() const;
float getAngle() const;
bool gravityOn() const;
void startGravity(const QVector3D& velocity);
void applyGravity();
private:
Position position;
float verticalAngle;
float viewZ; //z-coordinate of eyes
};
#endif // CAMERAVIEW_H
| [
"milan.vahala@gmail.com"
] | milan.vahala@gmail.com |
3356da6856764440e3cb81f506547171f8d2dd23 | 90a72f0f05ff5b2ec722a29660e64b6469de4852 | /tensorflow/core/kernels/mkl_identity_op.cc | e138cc2e959550cc3aaf4092e48f7289c670a32f | [
"Apache-2.0"
] | permissive | wodesuck/tensorflow | 179a28103f15a7cfc2ef9a6f0f09034bda1f4713 | a610b34f806ee0e0f33e4f94ee512d7affd44de6 | refs/heads/master | 2021-01-20T15:17:50.576377 | 2017-05-09T12:11:19 | 2017-05-09T12:11:19 | 90,740,794 | 1 | 0 | null | 2017-05-09T12:11:20 | 2017-05-09T12:01:01 | C++ | UTF-8 | C++ | false | false | 2,409 | cc | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#ifdef INTEL_MKL
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/mkl_util.h"
#include "third_party/mkl/include/mkl_dnn.h"
#include "third_party/mkl/include/mkl_dnn_types.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
template <typename Device, typename T>
class MklIdentityOp : public OpKernel {
public:
explicit MklIdentityOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
MklShape mkl_shape_input;
GetMklShape(context, 0, &mkl_shape_input);
bool input_in_mkl_format = mkl_shape_input.IsMklTensor();
if (input_in_mkl_format) {
ForwarMklTensorInToOut(context, 0, 0);
} else {
FowardTfTensorInToOut(context, 0, 0);
}
}
bool IsExpensive() override { return false; }
};
#define REGISTER_MKL_CPU(T) \
REGISTER_KERNEL_BUILDER(Name("_MklIdentity") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.Label(mkl_op_registry::kMklOpLabel), \
MklIdentityOp<CPUDevice, T>); \
TF_CALL_float(REGISTER_MKL_CPU);
#undef REGISTER_MKL_CPU
} // namespace tensorflow
#endif // INTEL_MKL
| [
"vrv@google.com"
] | vrv@google.com |
92a121544859ad8f2f80d77f3f7f665af826fc03 | 7b21fed18a6d518aab1ca380fd9ba30a93c1b6aa | /Projects/Reflectpp/include/details/custom/sequence_container_vector.h | 908259bc37e238aff7aff47c0372b7c677f38c72 | [
"BSD-3-Clause"
] | permissive | Nohzmi/Reflectpp | a16b00e15e30df7fdc84c3f5559d92a9458bb06a | 35a340f277ef374c9f9aeef89849918fdf7c2848 | refs/heads/master | 2023-03-05T09:16:08.481317 | 2021-02-16T22:43:02 | 2021-02-16T22:57:44 | 270,348,458 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | h | // Copyright (c) 2020, Nohzmi. All rights reserved.
/**
* @file sequence_container_vector.h
* @author Nohzmi
* @version 1.0
*/
#pragma once
#include <vector>
#include "details/custom/sequence_container.h"
namespace reflectpp
{
namespace details
{
template<typename T>
struct sequence_container<std::vector<T>> final
{
REFLECTPP_INLINE static auto get_data() REFLECTPP_NOEXCEPT;
};
template<typename T>
struct is_sequence_container<std::vector<T>> final : std::true_type {};
}
}
#include "details/custom/impl/sequence_container_vector.inl"
| [
"parant.maxime.contact@gmail.com"
] | parant.maxime.contact@gmail.com |
63af5507595f7ef0887f4e49be19132e6029d6c4 | c0c7460629dfcba09f1bebf0bb919d3371a97f7f | /3/31.cpp | fa074eb4dca9db96ff6558dee0641844187e62ed | [] | no_license | Warasar/c01begin | fa9c57213b587d73b61a6dbad45462c5559f8af6 | a3bcde8d758ee0862ba5ab2503c2165b58f93603 | refs/heads/master | 2022-09-09T12:50:24.637860 | 2020-05-19T07:45:11 | 2020-05-19T07:45:11 | 262,260,565 | 0 | 0 | null | 2020-05-08T07:50:07 | 2020-05-08T07:50:06 | null | UTF-8 | C++ | false | false | 355 | cpp | #define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double s, s1, s2, s3, r;
cin >> r;
s = (r + r) * (r + r); //площадь квадрата
s1 = M_PI * r * r; //площадь круга
s2 = (s - s1) / 4; //верхний угол
s3 = r * r; //нижний угол
cout << s2 + s3 << endl;
} | [
"noreply@github.com"
] | Warasar.noreply@github.com |
8d418f286fe665b28953280a2d778c99ab8dfaab | f81b774e5306ac01d2c6c1289d9e01b5264aae70 | /ash/home_screen/drag_window_from_shelf_controller_unittest.cc | 0c9e56179fbe5c85818b4f3487c8ff2b48f1816d | [
"BSD-3-Clause"
] | permissive | waaberi/chromium | a4015160d8460233b33fe1304e8fd9960a3650a9 | 6549065bd785179608f7b8828da403f3ca5f7aab | refs/heads/master | 2022-12-13T03:09:16.887475 | 2020-09-05T20:29:36 | 2020-09-05T20:29:36 | 293,153,821 | 1 | 1 | BSD-3-Clause | 2020-09-05T21:02:50 | 2020-09-05T21:02:49 | null | UTF-8 | C++ | false | false | 55,796 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/home_screen/drag_window_from_shelf_controller.h"
#include "ash/app_list/test/app_list_test_helper.h"
#include "ash/app_list/views/app_list_view.h"
#include "ash/home_screen/drag_window_from_shelf_controller_test_api.h"
#include "ash/home_screen/home_screen_controller.h"
#include "ash/home_screen/home_screen_delegate.h"
#include "ash/public/cpp/overview_test_api.h"
#include "ash/public/cpp/test/shell_test_api.h"
#include "ash/public/cpp/window_backdrop.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_metrics.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "ash/wallpaper/wallpaper_view.h"
#include "ash/wallpaper/wallpaper_widget_controller.h"
#include "ash/wm/mru_window_tracker.h"
#include "ash/wm/overview/overview_constants.h"
#include "ash/wm/overview/overview_controller.h"
#include "ash/wm/overview/overview_grid.h"
#include "ash/wm/overview/overview_item.h"
#include "ash/wm/overview/overview_test_util.h"
#include "ash/wm/splitview/split_view_constants.h"
#include "ash/wm/splitview/split_view_controller.h"
#include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h"
#include "ash/wm/window_properties.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/window_util.h"
namespace ash {
namespace {
// Helper function to get the index of |child|, given its parent window
// |parent|.
int IndexOf(aura::Window* child, aura::Window* parent) {
aura::Window::Windows children = parent->children();
auto it = std::find(children.begin(), children.end(), child);
DCHECK(it != children.end());
return static_cast<int>(std::distance(children.begin(), it));
}
} // namespace
class DragWindowFromShelfControllerTest : public AshTestBase {
public:
DragWindowFromShelfControllerTest() = default;
~DragWindowFromShelfControllerTest() override = default;
// AshTestBase:
void SetUp() override {
AshTestBase::SetUp();
TabletModeControllerTestApi().EnterTabletMode();
base::RunLoop().RunUntilIdle();
}
void TearDown() override {
// Destroy |window_drag_controller_| so that its scheduled task won't get
// run after the test environment is gone.
window_drag_controller_.reset();
AshTestBase::TearDown();
}
void StartDrag(aura::Window* window,
const gfx::Point& location_in_screen,
HotseatState hotseat_state) {
window_drag_controller_ = std::make_unique<DragWindowFromShelfController>(
window, gfx::PointF(location_in_screen), hotseat_state);
}
void Drag(const gfx::Point& location_in_screen,
float scroll_x,
float scroll_y) {
window_drag_controller_->Drag(gfx::PointF(location_in_screen), scroll_x,
scroll_y);
}
void EndDrag(const gfx::Point& location_in_screen,
base::Optional<float> velocity_y) {
window_drag_controller_->EndDrag(gfx::PointF(location_in_screen),
velocity_y);
window_drag_controller_->FinalizeDraggedWindow();
}
void CancelDrag() { window_drag_controller_->CancelDrag(); }
void WaitForHomeLauncherAnimationToFinish() {
// Wait until home launcher animation finishes.
while (GetAppListTestHelper()
->GetAppListView()
->GetWidget()
->GetLayer()
->GetAnimator()
->is_animating()) {
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(),
base::TimeDelta::FromMilliseconds(200));
run_loop.Run();
}
}
SplitViewController* split_view_controller() {
return SplitViewController::Get(Shell::GetPrimaryRootWindow());
}
DragWindowFromShelfController* window_drag_controller() {
return window_drag_controller_.get();
}
private:
std::unique_ptr<DragWindowFromShelfController> window_drag_controller_;
DISALLOW_COPY_AND_ASSIGN(DragWindowFromShelfControllerTest);
};
// Tests that we may hide different sets of windows with a special flag
// kHideDuringWindowDragging.
TEST_F(DragWindowFromShelfControllerTest,
HideWindowDuringWindowDraggingWithFlag) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window3 = CreateTestWindow();
auto window2 = CreateTestWindow();
auto window1 = CreateTestWindow();
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
EXPECT_FALSE(window1->GetProperty(kHideDuringWindowDragging));
EXPECT_FALSE(window2->GetProperty(kHideDuringWindowDragging));
EXPECT_FALSE(window3->GetProperty(kHideDuringWindowDragging));
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 1.f, 1.f);
EXPECT_TRUE(window1->IsVisible());
EXPECT_FALSE(window2->IsVisible());
EXPECT_FALSE(window3->IsVisible());
EXPECT_FALSE(window1->GetProperty(kHideDuringWindowDragging));
EXPECT_TRUE(window2->GetProperty(kHideDuringWindowDragging));
EXPECT_TRUE(window3->GetProperty(kHideDuringWindowDragging));
EndDrag(shelf_bounds.CenterPoint(), /*velocity_y=*/base::nullopt);
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
EXPECT_FALSE(window1->GetProperty(kHideDuringWindowDragging));
EXPECT_FALSE(window2->GetProperty(kHideDuringWindowDragging));
EXPECT_FALSE(window3->GetProperty(kHideDuringWindowDragging));
}
// Tests that we may hide different sets of windows in splitview and restores
// windows correctly after dragging.
TEST_F(DragWindowFromShelfControllerTest,
HideWindowDuringWindowDraggingInSplitView) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window3 = CreateTestWindow();
auto window2 = CreateTestWindow();
auto window1 = CreateTestWindow();
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
// In splitview mode, the snapped windows will stay visible during dragging.
split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT);
split_view_controller()->SnapWindow(window2.get(),
SplitViewController::RIGHT);
// Try to drag a left snapped window
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 1.f, 1.f);
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_FALSE(window3->IsVisible());
EndDrag(shelf_bounds.bottom_left(), /*velocity_y=*/base::nullopt);
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
// Ensure that all windows are restored correctly without triggering auto
// snapping.
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_EQ(split_view_controller()->GetPositionOfSnappedWindow(window1.get()),
SplitViewController::LEFT);
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window2.get()));
EXPECT_EQ(split_view_controller()->GetPositionOfSnappedWindow(window2.get()),
SplitViewController::RIGHT);
EXPECT_FALSE(split_view_controller()->IsWindowInSplitView(window3.get()));
// Try to drag a right snapped window
StartDrag(window2.get(), shelf_bounds.right_center(),
HotseatState::kExtended);
Drag(gfx::Point(400, 200), 1.f, 1.f);
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_FALSE(window3->IsVisible());
EndDrag(shelf_bounds.bottom_right(), /*velocity_y=*/base::nullopt);
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
// Ensure that all windows are restored correctly without triggering auto
// snapping.
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_EQ(split_view_controller()->GetPositionOfSnappedWindow(window1.get()),
SplitViewController::LEFT);
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window2.get()));
EXPECT_EQ(split_view_controller()->GetPositionOfSnappedWindow(window2.get()),
SplitViewController::RIGHT);
EXPECT_FALSE(split_view_controller()->IsWindowInSplitView(window3.get()));
}
// Test home launcher is hidden during dragging.
TEST_F(DragWindowFromShelfControllerTest, HideHomeLauncherDuringDraggingTest) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 0.f, 1.f);
aura::Window* home_screen_window =
Shell::Get()->home_screen_controller()->delegate()->GetHomeScreenWindow();
EXPECT_TRUE(home_screen_window);
EXPECT_FALSE(home_screen_window->IsVisible());
EndDrag(shelf_bounds.CenterPoint(),
/*velocity_y=*/base::nullopt);
EXPECT_TRUE(home_screen_window->IsVisible());
}
// Test the windows that were hidden before drag started may or may not reshow,
// depending on different scenarios.
TEST_F(DragWindowFromShelfControllerTest, MayOrMayNotReShowHiddenWindows) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window2 = CreateTestWindow();
auto window1 = CreateTestWindow();
// If the dragged window restores to its original position, reshow the hidden
// windows.
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
EXPECT_FALSE(window2->IsVisible());
EndDrag(shelf_bounds.CenterPoint(), base::nullopt);
EXPECT_TRUE(window2->IsVisible());
// If fling to homescreen, do not reshow the hidden windows.
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
EXPECT_FALSE(window2->IsVisible());
EndDrag(gfx::Point(200, 200),
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold);
EXPECT_FALSE(window1->IsVisible());
EXPECT_FALSE(window2->IsVisible());
// If the dragged window is added to overview, do not reshow the hidden
// windows.
window2->Show();
window1->Show();
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
EXPECT_FALSE(window2->IsVisible());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(gfx::Point(200, 200), base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window1.get()));
EXPECT_FALSE(window2->IsVisible());
overview_controller->EndOverview();
// If the dragged window is snapped in splitview, while the other windows are
// showing in overview, do not reshow the hidden windows.
window2->Show();
window1->Show();
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 0.f, 1.f);
EXPECT_FALSE(window2->IsVisible());
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(0, 200), base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_FALSE(window2->IsVisible());
}
// Test during window dragging, if overview is open, the minimized windows can
// show correctly in overview.
TEST_F(DragWindowFromShelfControllerTest, MinimizedWindowsShowInOverview) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window3 = CreateTestWindow();
auto window2 = CreateTestWindow();
auto window1 = CreateTestWindow();
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
// Drag it far enough so overview should be open behind the dragged window.
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(window1->IsVisible());
EXPECT_FALSE(window2->IsVisible());
EXPECT_TRUE(WindowState::Get(window2.get())->IsMinimized());
EXPECT_FALSE(window3->IsVisible());
EXPECT_TRUE(WindowState::Get(window3.get())->IsMinimized());
EXPECT_FALSE(overview_controller->overview_session()->IsWindowInOverview(
window1.get()));
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window2.get()));
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window3.get()));
// Release the drag, the window should be added to overview.
EndDrag(gfx::Point(200, 200), base::nullopt);
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window1.get()));
}
// Test when swiping up from the shelf, we only open overview when the y scroll
// delta (velocity) decrease to kOpenOverviewThreshold or less.
TEST_F(DragWindowFromShelfControllerTest, OpenOverviewWhenHold) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f,
DragWindowFromShelfController::kOpenOverviewThreshold + 1);
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_FALSE(overview_controller->InOverviewSession());
Drag(gfx::Point(200, 200), 0.f,
DragWindowFromShelfController::kOpenOverviewThreshold);
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(200, 200), base::nullopt);
}
// Test if the dragged window is not dragged far enough than
// kReturnToMaximizedThreshold, it will restore back to its original position.
TEST_F(DragWindowFromShelfControllerTest, RestoreWindowToOriginalBounds) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
const gfx::Rect display_bounds = display::Screen::GetScreen()
->GetDisplayNearestWindow(window.get())
.bounds();
// Drag it for a small distance and then release.
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f,
DragWindowFromShelfController::kShowOverviewThreshold + 1);
EXPECT_FALSE(window->layer()->GetTargetTransform().IsIdentity());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_FALSE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(200, 400), base::nullopt);
EXPECT_TRUE(window->layer()->GetTargetTransform().IsIdentity());
EXPECT_TRUE(WindowState::Get(window.get())->IsMaximized());
// Drag it for a large distance and then drag back to release.
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
EXPECT_FALSE(window->layer()->GetTargetTransform().IsIdentity());
EXPECT_TRUE(overview_controller->InOverviewSession());
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(
gfx::Point(
200,
display_bounds.bottom() -
DragWindowFromShelfController::GetReturnToMaximizedThreshold() +
1),
base::nullopt);
EXPECT_TRUE(window->layer()->GetTargetTransform().IsIdentity());
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_TRUE(WindowState::Get(window.get())->IsMaximized());
// The same thing should happen if splitview mode is active.
auto window2 = CreateTestWindow();
split_view_controller()->SnapWindow(window.get(), SplitViewController::LEFT);
split_view_controller()->SnapWindow(window2.get(),
SplitViewController::RIGHT);
StartDrag(window.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 0.f, 1.f);
EXPECT_FALSE(window->layer()->GetTargetTransform().IsIdentity());
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(0, 400), base::nullopt);
EXPECT_TRUE(window->layer()->GetTargetTransform().IsIdentity());
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_EQ(split_view_controller()->left_window(), window.get());
}
// Test if overview is active and splitview is not active, fling in overview may
// or may not head to the home screen.
TEST_F(DragWindowFromShelfControllerTest, FlingInOverview) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
// If fling velocity is smaller than kVelocityToHomeScreenThreshold, decide
// where the window should go based on the release position.
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(
gfx::Point(0, 350),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold + 10));
// The window should restore back to its original position.
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_TRUE(WindowState::Get(window.get())->IsMaximized());
// If fling velocity is equal or larger than kVelocityToHomeScreenThreshold
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(0, 350),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold));
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_TRUE(WindowState::Get(window.get())->IsMinimized());
}
// Verify that metrics of home launcher animation are recorded correctly when
// swiping up from shelf with sufficient velocity.
TEST_F(DragWindowFromShelfControllerTest, VerifyHomeLauncherAnimationMetrics) {
// Set non-zero animation duration to report animation metrics.
ui::ScopedAnimationDurationScaleMode non_zero_duration_mode(
ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
base::HistogramTester histogram_tester;
// Ensure that fling velocity is sufficient to show homelauncher without
// triggering overview mode.
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f,
DragWindowFromShelfController::kOpenOverviewThreshold + 1);
EndDrag(gfx::Point(0, 350),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold));
WaitForHomeLauncherAnimationToFinish();
// Verify that animation to show the home launcher is recorded.
histogram_tester.ExpectTotalCount(
"Apps.HomeLauncherTransition.AnimationSmoothness.FadeOutOverview", 1);
}
// Test if splitview is active when fling happens, the window will be put in
// overview.
TEST_F(DragWindowFromShelfControllerTest, DragOrFlingInSplitView) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window1 = CreateTestWindow();
auto window2 = CreateTestWindow();
OverviewController* overview_controller = Shell::Get()->overview_controller();
split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT);
split_view_controller()->SnapWindow(window2.get(),
SplitViewController::RIGHT);
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
// If the window is only dragged for a small distance:
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(100, 200), 0.f, 1.f);
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(100, 350), base::nullopt);
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window2.get()));
// If the window is dragged for a long distance:
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(100, 200), 0.f, 1.f);
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(100, 200), base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window1.get()));
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_FALSE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window2.get()));
overview_controller->EndOverview();
// If the window is flung with a small velocity:
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(100, 200), 0.f, 1.f);
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(
gfx::Point(100, 350),
base::make_optional(
-DragWindowFromShelfController::kVelocityToOverviewThreshold + 10));
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window2.get()));
// If the window is flung with a large velocity:
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(100, 200), 0.f, 1.f);
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(overview_controller->InOverviewSession());
EndDrag(gfx::Point(100, 150),
base::make_optional(
-DragWindowFromShelfController::kVelocityToOverviewThreshold));
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window1.get()));
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_FALSE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window2.get()));
overview_controller->EndOverview();
}
// Test wallpaper should be blurred as in overview, even though overview might
// not open during dragging.
TEST_F(DragWindowFromShelfControllerTest, WallpaperBlurDuringDragging) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 0.f,
DragWindowFromShelfController::kShowOverviewThreshold + 1);
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_FALSE(overview_controller->InOverviewSession());
auto* wallpaper_view =
RootWindowController::ForWindow(window->GetRootWindow())
->wallpaper_widget_controller()
->wallpaper_view();
EXPECT_EQ(wallpaper_view->property().blur_sigma,
overview_constants::kBlurSigma);
EndDrag(shelf_bounds.CenterPoint(),
/*velocity_y=*/base::nullopt);
EXPECT_EQ(wallpaper_view->property().blur_sigma,
wallpaper_constants::kClear.blur_sigma);
}
// Test overview is hidden during dragging and shown when drag slows down or
// stops.
TEST_F(DragWindowFromShelfControllerTest, HideOverviewDuringDragging) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window2 = CreateTestWindow();
auto window1 = CreateTestWindow();
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
// We test the visibility of overview by testing the drop target widget's
// visibility in the overview.
OverviewGrid* current_grid =
overview_controller->overview_session()->GetGridWithRootWindow(
window1->GetRootWindow());
OverviewItem* drop_target_item = current_grid->GetDropTarget();
EXPECT_TRUE(drop_target_item);
EXPECT_EQ(drop_target_item->GetWindow()->layer()->GetTargetOpacity(), 1.f);
Drag(gfx::Point(200, 200), 0.5f,
DragWindowFromShelfController::kShowOverviewThreshold + 1);
// Test overview should be invisble.
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_EQ(drop_target_item->GetWindow()->layer()->GetTargetOpacity(), 0.f);
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(gfx::Point(200, 200),
/*velocity_y=*/base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
// |window1| should have added to overview. Test its visibility.
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window1.get()));
EXPECT_EQ(window1->layer()->GetTargetOpacity(), 1.f);
}
// Check the split view drag indicators window dragging states.
TEST_F(DragWindowFromShelfControllerTest,
SplitViewDragIndicatorsWindowDraggingStates) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
OverviewSession* overview_session = overview_controller->overview_session();
ASSERT_EQ(1u, overview_session->grid_list().size());
SplitViewDragIndicators* drag_indicators =
overview_session->grid_list()[0]->split_view_drag_indicators();
EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kFromShelf,
drag_indicators->current_window_dragging_state());
Drag(gfx::Point(0, 200), 0.5f, 0.5f);
EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kToSnapLeft,
drag_indicators->current_window_dragging_state());
Drag(gfx::Point(0, 300), 0.5f, 0.5f);
EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kFromShelf,
drag_indicators->current_window_dragging_state());
Drag(gfx::Point(0, 200), 0.5f, 0.5f);
EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kToSnapLeft,
drag_indicators->current_window_dragging_state());
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kFromShelf,
drag_indicators->current_window_dragging_state());
EndDrag(shelf_bounds.CenterPoint(),
/*velocity_y=*/base::nullopt);
}
// Test there is no black backdrop behind the dragged window if we're doing the
// scale down animation for the dragged window.
TEST_F(DragWindowFromShelfControllerTest, NoBackdropDuringWindowScaleDown) {
ui::ScopedAnimationDurationScaleMode test_duration_mode(
ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
EXPECT_TRUE(window->layer()->GetTargetTransform().IsIdentity());
WindowBackdrop* window_backdrop = WindowBackdrop::Get(window.get());
EXPECT_NE(window_backdrop->mode(), WindowBackdrop::BackdropMode::kDisabled);
StartDrag(window.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 0.f, 10.f);
EndDrag(gfx::Point(0, 200),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold));
EXPECT_FALSE(window->layer()->GetTargetTransform().IsIdentity());
EXPECT_NE(window_backdrop->mode(), WindowBackdrop::BackdropMode::kDisabled);
EXPECT_TRUE(window_backdrop->temporarily_disabled());
}
// Test that if drag is cancelled, overview should be dismissed and other
// hidden windows should restore to its previous visibility state.
TEST_F(DragWindowFromShelfControllerTest, CancelDragDismissOverview) {
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window3 = CreateTestWindow();
auto window2 = CreateTestWindow();
auto window1 = CreateTestWindow();
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
StartDrag(window1.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(window1->IsVisible());
EXPECT_FALSE(window2->IsVisible());
EXPECT_FALSE(window3->IsVisible());
CancelDrag();
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_TRUE(window1->IsVisible());
EXPECT_TRUE(window2->IsVisible());
EXPECT_TRUE(window3->IsVisible());
}
TEST_F(DragWindowFromShelfControllerTest, CancelDragIfWindowDestroyed) {
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EXPECT_EQ(window_drag_controller()->dragged_window(), window.get());
EXPECT_TRUE(window_drag_controller()->drag_started());
base::HistogramTester histogram_tester;
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kDragCanceled, 0);
window.reset();
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kDragCanceled, 1);
EXPECT_EQ(window_drag_controller()->dragged_window(), nullptr);
EXPECT_FALSE(window_drag_controller()->drag_started());
// No crash should happen if Drag() call still comes in.
Drag(gfx::Point(200, 200), 0.5f, 0.5f);
CancelDrag();
}
TEST_F(DragWindowFromShelfControllerTest, FlingWithHiddenHotseat) {
base::HistogramTester histogram_tester;
histogram_tester.ExpectBucketCount(
kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kRestoreToOriginalBounds, 0);
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
gfx::Point start = shelf_bounds.CenterPoint();
StartDrag(window.get(), start, HotseatState::kHidden);
// Only drag for a small distance and then fling.
Drag(gfx::Point(start.x(), start.y() - 10), 0.5f, 0.5f);
EndDrag(gfx::Point(start.x(), start.y() - 10),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold));
// The window should restore back to its original position.
EXPECT_TRUE(WindowState::Get(window.get())->IsMaximized());
histogram_tester.ExpectBucketCount(
kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kRestoreToOriginalBounds, 1);
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToHomeScreen, 0);
// Now a bigger distance to fling.
StartDrag(window.get(), start, HotseatState::kHidden);
Drag(gfx::Point(start.x(), start.y() - 200), 0.5f, 0.5f);
EndDrag(gfx::Point(start.x(), start.y() - 200),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold));
// The window should be minimized.
EXPECT_TRUE(WindowState::Get(window.get())->IsMinimized());
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToHomeScreen, 1);
}
TEST_F(DragWindowFromShelfControllerTest, DragToSnapMinDistance) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window1 = CreateTestWindow();
auto window2 = CreateTestWindow();
const gfx::Rect display_bounds = display::Screen::GetScreen()
->GetDisplayNearestWindow(window1.get())
.bounds();
const int snap_edge_inset =
DragWindowFromShelfController::kScreenEdgeInsetForSnap;
base::HistogramTester histogram_tester;
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToOverviewMode,
0);
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToSplitviewMode,
0);
// If the drag starts outside of the snap region and then into snap region,
// but the drag distance is not long enough.
gfx::Point start = gfx::Point(display_bounds.x() + snap_edge_inset + 50,
shelf_bounds.CenterPoint().y());
StartDrag(window1.get(), start, HotseatState::kExtended);
Drag(start + gfx::Vector2d(0, 100), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
// Drag into the snap region and release.
gfx::Point end = gfx::Point(
start.x() - DragWindowFromShelfController::kMinDragDistance + 10, 200);
EndDrag(end, base::nullopt);
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_FALSE(split_view_controller()->InSplitViewMode());
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToOverviewMode,
1);
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToSplitviewMode,
0);
wm::ActivateWindow(window1.get());
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_FALSE(split_view_controller()->InSplitViewMode());
// If the drag starts outside of the snap region and then into snap region
// (kScreenEdgeInsetForSnap), and the drag distance is long enough.
StartDrag(window1.get(), start, HotseatState::kExtended);
Drag(start + gfx::Vector2d(0, 100), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
// Drag into the snap region and release.
end.set_x(start.x() - 10 - DragWindowFromShelfController::kMinDragDistance);
EndDrag(end, base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToOverviewMode,
1);
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToSplitviewMode,
1);
WindowState::Get(window1.get())->Maximize();
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_FALSE(split_view_controller()->InSplitViewMode());
// If the drag starts inside of the snap region (kScreenEdgeInsetForSnap), but
// the drag distance is not long enough.
start = gfx::Point(display_bounds.x() + snap_edge_inset - 5,
shelf_bounds.CenterPoint().y());
StartDrag(window1.get(), start, HotseatState::kExtended);
Drag(start + gfx::Vector2d(0, 100), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
// Drag for a small distance and release.
end.set_x(start.x() - 10);
EndDrag(end, base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_FALSE(split_view_controller()->InSplitViewMode());
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToOverviewMode,
2);
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToSplitviewMode,
1);
wm::ActivateWindow(window1.get());
EXPECT_FALSE(overview_controller->InOverviewSession());
EXPECT_FALSE(split_view_controller()->InSplitViewMode());
// If the drag starts near the screen edge (kDistanceFromEdge), the window
// should snap directly.
start = gfx::Point(
display_bounds.x() + DragWindowFromShelfController::kDistanceFromEdge - 5,
shelf_bounds.CenterPoint().y());
StartDrag(window1.get(), start, HotseatState::kExtended);
Drag(start + gfx::Vector2d(0, 100), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
end.set_x(start.x() - 5);
EndDrag(end, base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToOverviewMode,
2);
histogram_tester.ExpectBucketCount(kHandleDragWindowFromShelfHistogramName,
ShelfWindowDragResult::kGoToSplitviewMode,
2);
}
// Test that if overview is invisible when drag ends, the window will be taken
// to the home screen.
TEST_F(DragWindowFromShelfControllerTest, GoHomeIfOverviewInvisible) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
StartDrag(window.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 10.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
// End drag without any fling, the window should be added to overview.
EndDrag(gfx::Point(200, 200), base::nullopt);
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window.get()));
wm::ActivateWindow(window.get());
StartDrag(window.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 10.f);
// At this moment overview should be invisible. End the drag without any
// fling, the window should be taken to home screen.
EndDrag(gfx::Point(200, 200), base::nullopt);
EXPECT_TRUE(WindowState::Get(window.get())->IsMinimized());
}
// Test that if overview is invisible when drag ends, the window will be taken
// to the home screen, even if drag satisfied min snap distance.
TEST_F(DragWindowFromShelfControllerTest,
GoHomeIfOverviewInvisibleWithMinSnapDistance) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
const gfx::Rect display_bounds = display::Screen::GetScreen()
->GetDisplayNearestWindow(window.get())
.bounds();
int snap_edge_inset =
display_bounds.width() * kHighlightScreenPrimaryAxisRatio +
kHighlightScreenEdgePaddingDp;
// Start the drag outside snap region.
gfx::Point start = gfx::Point(display_bounds.x() + snap_edge_inset + 50,
shelf_bounds.CenterPoint().y());
StartDrag(window.get(), start, HotseatState::kExtended);
// Drag into the snap region and release without a fling.
// At this moment overview should be invisible, so the window should be taken
// to the home screen.
gfx::Point end =
start -
gfx::Vector2d(10 + DragWindowFromShelfController::kMinDragDistance, 200);
EndDrag(end, base::nullopt);
EXPECT_FALSE(Shell::Get()->overview_controller()->InOverviewSession());
EXPECT_FALSE(split_view_controller()->InSplitViewMode());
EXPECT_TRUE(WindowState::Get(window.get())->IsMinimized());
}
// Test that the original backdrop is restored in the drag window after drag
// ends, no matter where the window ends.
TEST_F(DragWindowFromShelfControllerTest, RestoreBackdropAfterDragEnds) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
WindowBackdrop* window_backdrop = WindowBackdrop::Get(window.get());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
// For window that ends in overview:
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
EXPECT_TRUE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(gfx::Point(200, 200), base::nullopt);
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(overview_controller->overview_session()->IsWindowInOverview(
window.get()));
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
EXPECT_FALSE(window_backdrop->temporarily_disabled());
// For window that ends in homescreen:
wm::ActivateWindow(window.get());
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
EXPECT_TRUE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(gfx::Point(200, 200),
base::make_optional(
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold));
EXPECT_TRUE(WindowState::Get(window.get())->IsMinimized());
EXPECT_FALSE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
// For window that restores to its original bounds:
wm::ActivateWindow(window.get());
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
EXPECT_TRUE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
Drag(gfx::Point(200, 200), 0.f, 1.f);
EndDrag(shelf_bounds.CenterPoint(), base::nullopt);
EXPECT_FALSE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
// For window that ends in homescreen because overview did not start during
// the gesture:
wm::ActivateWindow(window.get());
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
EXPECT_TRUE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
EndDrag(gfx::Point(0, 200), base::nullopt);
EXPECT_TRUE(WindowState::Get(window.get())->IsMinimized());
EXPECT_FALSE(window_backdrop->temporarily_disabled());
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
// For window that ends in splitscreen:
wm::ActivateWindow(window.get());
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
EXPECT_TRUE(window_backdrop->temporarily_disabled());
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(gfx::Point(0, 200), base::nullopt);
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window.get()));
EXPECT_EQ(window_backdrop->mode(), WindowBackdrop::BackdropMode::kAuto);
EXPECT_FALSE(window_backdrop->temporarily_disabled());
}
TEST_F(DragWindowFromShelfControllerTest,
DoNotChangeActiveWindowDuringDragging) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
wm::ActivateWindow(window.get());
EXPECT_EQ(window.get(), window_util::GetActiveWindow());
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
EXPECT_TRUE(overview_controller->InOverviewSession());
// During dragging, the active window should not change.
EXPECT_EQ(window.get(), window_util::GetActiveWindow());
EndDrag(gfx::Point(200, 200), base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
OverviewSession* overview_session = overview_controller->overview_session();
EXPECT_TRUE(overview_session->IsWindowInOverview(window.get()));
// After window is added to overview, the active window should change to the
// overview focus widget.
EXPECT_EQ(overview_session->GetOverviewFocusWindow(),
window_util::GetActiveWindow());
}
// Test that if the window are dropped in overview before the overview start
// animation is completed, there is no crash.
TEST_F(DragWindowFromShelfControllerTest,
NoCrashIfDropWindowInOverviewBeforeStartAnimationComplete) {
ui::ScopedAnimationDurationScaleMode test_duration_mode(
ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);
OverviewController* overview_controller = Shell::Get()->overview_controller();
overview_controller->set_delayed_animation_task_delay_for_test(
base::TimeDelta::FromMilliseconds(100));
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window = CreateTestWindow();
wm::ActivateWindow(window.get());
EXPECT_EQ(window.get(), window_util::GetActiveWindow());
StartDrag(window.get(), shelf_bounds.CenterPoint(), HotseatState::kExtended);
Drag(gfx::Point(200, 200), 0.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EXPECT_TRUE(overview_controller->InOverviewSession());
// During dragging, the active window should not change.
EXPECT_EQ(window.get(), window_util::GetActiveWindow());
OverviewSession* overview_session = overview_controller->overview_session();
EndDrag(gfx::Point(200, 200), base::nullopt);
EXPECT_TRUE(overview_controller->InOverviewSession());
EXPECT_TRUE(overview_session->IsWindowInOverview(window.get()));
// After window is added to overview, the active window should change to the
// overview focus widget.
EXPECT_EQ(overview_session->GetOverviewFocusWindow(),
window_util::GetActiveWindow());
ShellTestApi().WaitForOverviewAnimationState(
OverviewAnimationState::kEnterAnimationComplete);
// After start animation is done, active window should remain the same.
EXPECT_EQ(overview_session->GetOverviewFocusWindow(),
window_util::GetActiveWindow());
}
// Test that when the dragged window is dropped into overview, it is positioned
// and stacked correctly.
TEST_F(DragWindowFromShelfControllerTest, DropsIntoOverviewAtCorrectPosition) {
std::unique_ptr<aura::Window> window1 = CreateTestWindow();
std::unique_ptr<aura::Window> window2 = CreateTestWindow();
std::unique_ptr<aura::Window> window3 = CreateTestWindow();
ToggleOverview();
ui::test::EventGenerator* generator = GetEventGenerator();
generator->MoveMouseTo(gfx::ToRoundedPoint(
GetOverviewItemForWindow(window1.get())->target_bounds().CenterPoint()));
generator->DragMouseTo(0, 400);
generator->MoveMouseTo(gfx::ToRoundedPoint(
GetOverviewItemForWindow(window2.get())->target_bounds().CenterPoint()));
generator->DragMouseTo(799, 400);
EXPECT_EQ(window1.get(), split_view_controller()->left_window());
EXPECT_EQ(window2.get(), split_view_controller()->right_window());
ToggleOverview();
StartDrag(window1.get(),
Shelf::ForWindow(Shell::GetPrimaryRootWindow())
->GetIdealBounds()
.left_center(),
HotseatState::kExtended);
Drag(gfx::Point(200, 200), 1.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
EndDrag(gfx::Point(200, 200), base::nullopt);
// Verify the grid arrangement.
OverviewController* overview_controller = Shell::Get()->overview_controller();
ASSERT_TRUE(overview_controller->InOverviewSession());
const std::vector<aura::Window*> expected_mru_list = {
window2.get(), window1.get(), window3.get()};
const std::vector<aura::Window*> expected_overview_list = {
window2.get(), window1.get(), window3.get()};
EXPECT_EQ(
expected_mru_list,
Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk));
EXPECT_EQ(expected_overview_list,
overview_controller->GetWindowsListInOverviewGridsForTest());
// Verify the stacking order.
aura::Window* parent = window1->parent();
ASSERT_EQ(parent, window2->parent());
ASSERT_EQ(parent, window3->parent());
EXPECT_GT(IndexOf(GetOverviewItemForWindow(window2.get())
->item_widget()
->GetNativeWindow(),
parent),
IndexOf(GetOverviewItemForWindow(window1.get())
->item_widget()
->GetNativeWindow(),
parent));
EXPECT_GT(IndexOf(GetOverviewItemForWindow(window1.get())
->item_widget()
->GetNativeWindow(),
parent),
IndexOf(GetOverviewItemForWindow(window3.get())
->item_widget()
->GetNativeWindow(),
parent));
}
// Tests that when dragging a snapped window is cancelled, the window
// still keep at the original snap position.
TEST_F(DragWindowFromShelfControllerTest,
KeepSplitWindowSnappedAfterRestoreToOriginalBounds) {
UpdateDisplay("400x400");
const gfx::Rect shelf_bounds =
Shelf::ForWindow(Shell::GetPrimaryRootWindow())->GetIdealBounds();
auto window1 = CreateTestWindow();
auto window2 = CreateTestWindow();
// In splitview mode, the snapped windows will stay visible during dragging.
split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT);
split_view_controller()->SnapWindow(window2.get(),
SplitViewController::RIGHT);
// Try to drag a left snapped window from shelf, but finally restore to
// original bounds.
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 1.f, 1.f);
EndDrag(shelf_bounds.bottom_left(), /*velocity_y=*/base::nullopt);
// Ensure that the window still keep its initial snap position.
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_EQ(split_view_controller()->GetPositionOfSnappedWindow(window1.get()),
SplitViewController::LEFT);
// Try to drag a right snapped window from shelf, and finally drop to
// overview.
StartDrag(window2.get(), shelf_bounds.right_center(),
HotseatState::kExtended);
Drag(gfx::Point(400, 200), 1.f, 1.f);
DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown(
window_drag_controller());
OverviewController* overview_controller = Shell::Get()->overview_controller();
OverviewSession* overview_session = overview_controller->overview_session();
EndDrag(gfx::Point(200, 200), /*velocity_y=*/base::nullopt);
// Ensure that the window is not in splitview but in overview.
EXPECT_FALSE(split_view_controller()->IsWindowInSplitView(window2.get()));
EXPECT_TRUE(overview_session->IsWindowInOverview(window2.get()));
// Try to drag the left window again within the restore distance.
StartDrag(window1.get(), shelf_bounds.left_center(), HotseatState::kExtended);
Drag(gfx::Point(0, 200), 1.f, 1.f);
EndDrag(shelf_bounds.bottom_left(), /*velocity_y=*/base::nullopt);
// Ensure that the left window still keep snapped.
EXPECT_TRUE(split_view_controller()->IsWindowInSplitView(window1.get()));
EXPECT_EQ(split_view_controller()->GetPositionOfSnappedWindow(window1.get()),
SplitViewController::LEFT);
// Ensure that the right window is still in the overview.
EXPECT_FALSE(split_view_controller()->IsWindowInSplitView(window2.get()));
EXPECT_TRUE(overview_session->IsWindowInOverview(window2.get()));
}
} // namespace ash
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
26b716953b0255b0a7863a9e3d6d3088c69509c0 | 45274690d003df4477bc88d77355276d9b8bb9b0 | /geeks_for_geeks/strings/brackets.cpp | 5b82209a79a7daf0b800ee10916862df9ee753e5 | [] | no_license | Sunil2120/Coding_questions | cecd589d829fb7483ad62b01c06251cb8978227d | 6a42c66154b0936a579345b70ddd32d500197a74 | refs/heads/master | 2023-06-23T14:47:40.045264 | 2021-07-23T03:18:10 | 2021-07-23T03:18:10 | 388,649,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include<bits/stdc++.h>
using namespace std;
bool solve(string input)
{
int n = input.size();
vector<char> stack;
for(int i=0;i<n;i++)
{
if(input[i]=='(' || input[i]=='[' || input[i]=='{')
{
stack.push_back(input[i]);
}
else
{
if(stack.size()==0)
{
return false;
}
char cur = stack.back();
if(input[i]==')'&& cur!='(')
{
return false;
}
if(input[i]==']' && cur!='[')
{
return false;
}
if(input[i]=='}' && cur!='{')
{
return false;
}
stack.pop_back();
}
}
if(stack.size()>0)
{
return false;
}
return true;
}
int main()
{
int t;
cin >> t;
while(t--)
{
string input;
cin >> input;
cout << solve(input) << endl;
}
} | [
"sunilms2120@gmail.com"
] | sunilms2120@gmail.com |
eb8ac08e0796669c0fb2b5611d9b18793a9476d8 | 134fca5b62ca6bac59ba1af5a5ebd271d9b53281 | /build/stx/libdb/nosql/mongoDB/tests/libInit.cc | dca6715a52f58b3d99267c73d5410487eb77b885 | [
"MIT"
] | permissive | GunterMueller/ST_STX_Fork | 3ba5fb5482d9827f32526e3c32a8791c7434bb6b | d891b139f3c016b81feeb5bf749e60585575bff7 | refs/heads/master | 2020-03-28T03:03:46.770962 | 2018-09-06T04:19:31 | 2018-09-06T04:19:31 | 147,616,821 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | cc | /*
* $Header: /cvs/stx/stx/libdb/nosql/mongoDB/tests/libInit.cc,v 1.4 2013-04-25 09:36:00 mb Exp $
*
* DO NOT EDIT
* automagically generated from the projectDefinition: stx_libdb_nosql_mongoDB_tests.
*/
#define __INDIRECTVMINITCALLS__
#include <stc.h>
#ifdef WIN32
# pragma codeseg INITCODE "INITCODE"
#endif
#if defined(INIT_TEXT_SECTION) || defined(DLL_EXPORT)
DLL_EXPORT void _libstx_libdb_nosql_mongoDB_tests_Init() INIT_TEXT_SECTION;
DLL_EXPORT void _libstx_libdb_nosql_mongoDB_tests_InitDefinition() INIT_TEXT_SECTION;
#endif
void _libstx_libdb_nosql_mongoDB_tests_InitDefinition(pass, __pRT__, snd)
OBJ snd; struct __vmData__ *__pRT__; {
__BEGIN_PACKAGE2__("libstx_libdb_nosql_mongoDB_tests__DFN", _libstx_libdb_nosql_mongoDB_tests_InitDefinition, "stx:libdb/nosql/mongoDB/tests");
_stx_137libdb_137nosql_137mongoDB_137tests_Init(pass,__pRT__,snd);
__END_PACKAGE__();
}
void _libstx_libdb_nosql_mongoDB_tests_Init(pass, __pRT__, snd)
OBJ snd; struct __vmData__ *__pRT__; {
__BEGIN_PACKAGE2__("libstx_libdb_nosql_mongoDB_tests", _libstx_libdb_nosql_mongoDB_tests_Init, "stx:libdb/nosql/mongoDB/tests");
_MongoTestCase_Init(pass,__pRT__,snd);
_stx_137libdb_137nosql_137mongoDB_137tests_Init(pass,__pRT__,snd);
_BSONTest_Init(pass,__pRT__,snd);
__END_PACKAGE__();
}
| [
"gunter.mueller@gmail.com"
] | gunter.mueller@gmail.com |
7b299b652916380e0bbf740bab3b20fdf1f93472 | 88ae8695987ada722184307301e221e1ba3cc2fa | /chrome/updater/test/http_request.cc | ede63c37d101f3c90c35ebe10caa9669c8679ab5 | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 2,498 | cc | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/updater/test/http_request.h"
#include <algorithm>
#include <cctype>
#include <iterator>
#include <string>
#include "base/logging.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "net/test/embedded_test_server/http_request.h"
#include "third_party/zlib/google/compression_utils.h"
namespace updater::test {
namespace {
std::string GetDecodedContent(const net::test_server::HttpRequest& request) {
net::test_server::HttpRequest::HeaderMap::const_iterator it =
request.headers.find("Content-Encoding");
if (it == request.headers.end() ||
base::CompareCaseInsensitiveASCII(it->second, "gzip") != 0) {
return request.content;
}
std::string content;
if (!compression::GzipUncompress(request.content, &content)) {
VLOG(0) << "Cannot inflate gzip content.";
return request.content;
}
return content;
}
} // namespace
HttpRequest::HttpRequest(const net::test_server::HttpRequest& request)
: net::test_server::HttpRequest(request),
decoded_content(GetDecodedContent(request)) {}
HttpRequest::HttpRequest() = default;
HttpRequest::HttpRequest(const HttpRequest&) = default;
HttpRequest& HttpRequest::operator=(const HttpRequest&) = default;
HttpRequest::~HttpRequest() = default;
std::string GetPrintableContent(const HttpRequest& request) {
if (!request.has_content) {
return "<no content>";
}
const size_t dump_limit =
std::min(request.decoded_content.size(), size_t{2048});
std::string printable_content;
printable_content.reserve(dump_limit);
base::ranges::transform(request.decoded_content.begin(),
request.decoded_content.begin() + dump_limit,
std::back_inserter(printable_content),
[](unsigned char c) {
return std::isprint(c) || std::isspace(c) ? c : '.';
});
if (request.decoded_content.size() <= dump_limit) {
return printable_content;
}
return base::StringPrintf("%s\n<Total size: %zu, skipped printing %zu bytes>",
printable_content.c_str(),
request.decoded_content.size(),
request.decoded_content.size() - dump_limit);
}
} // namespace updater::test
| [
"jengelh@inai.de"
] | jengelh@inai.de |
82ea8ab9185916178f0762e341859ab4a6974b79 | 6a615cbb5ec1ade197e0c8a0699446b46d80cecf | /src/main.cpp | d3b3d75ab5ea12a621ce7aec353c5c4ec4934603 | [] | no_license | pajamity/gstreamer-rs-qt-player | ede69c847ab97da42470aef9e3dd94be365a0d50 | 484726e220799325eb1fe1b2af8e2fb08c71f847 | refs/heads/master | 2022-09-17T11:12:46.763361 | 2020-06-03T08:27:34 | 2020-06-03T08:27:34 | 269,026,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,759 | cpp | #include "Bindings.h"
#include <QtCore/QFile>
#include <QtGui/QGuiApplication>
#include <QtQml/QQmlApplicationEngine>
#include <QtQuick/QQuickItem>
#include <QtQuick/QQuickWindow>
#include <QtQml/qqml.h>
#include <iostream>
#include <glib-object.h>
// #include <gst/gst.h>
// exported functions
extern "C" {
// functions C++ source exports (and Rust source calls them)
int main_cpp(const char* app);
void set_widget_to_sink(void *sink, QQuickItem *videoItem);
// functions Rust source exports (so C++ source calls it)
void set_video_item_pointer(QQuickItem *videoItem);
}
// QQuickItem *videoItem;
int main_cpp(const char* appPath) {
int argc = 1;
char* argv[1] = { (char*)appPath };
QGuiApplication app(argc, argv);
qmlRegisterType<Player>("RustCode", 1, 0, "Player");
QQmlApplicationEngine engine;
if (QFile("main.qml").exists()) {
engine.load(QUrl(QStringLiteral("main.qml")));
} else {
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
}
if (engine.rootObjects().isEmpty())
return -1;
QQuickWindow *rootObject = static_cast<QQuickWindow *>(engine.rootObjects().first());
QQuickItem *videoItem = rootObject->findChild<QQuickItem *>("videoItem");
set_video_item_pointer(videoItem);
std::cout << "Passed the address of videoItem to Rust: " << videoItem << std::endl;
return app.exec(); // This starts an event loop so we won't return till that loop ends.
}
void set_widget_to_sink(void *sink, QQuickItem *videoItem) {
std::cout << "Address of sink C++ was given by Rust: " << sink << std::endl;
std::cout << "Address of videoItem C++ was given by Rust: " << videoItem << std::endl;
g_object_set(sink, "widget", videoItem, NULL);
} | [
"pajamity@tutanota.com"
] | pajamity@tutanota.com |
b7eabfca23d9bfe158a784f668217f24020a3cb5 | 3342fca48f194851a2c9050a19ebc1d546c9d864 | /mareklib/core/mareklib.cpp | d5332233ce40e6648ce6632ba1555ecf977b8e11 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | iVideo/ofxmarek | 12a279d0d3ecedac4aeb802a0fe12856594a6eb1 | e8d299c147e131595b3f964e60436f4f39f2b7bd | refs/heads/master | 2021-01-16T21:02:46.652724 | 2012-02-09T12:34:43 | 2012-02-09T12:34:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | cpp | #include "ofMain.h"
#include "mareklib.h"
void mareklib::drawFramerate(int color) {
ofSetHexColor(color);
ofDrawBitmapString(ofToString(ofGetFrameRate()), 10, ofGetHeight()-20);
}
void mareklib::setDataPathRootToAppContents() {
char path[512];
getcwd(path, 512);
string dataRoot = path;
dataRoot += "/../data/";
ofSetDataPathRoot(dataRoot);
}
string padZeros(int t) {
if(t<10) return ofToString(t);
else return "0"+ofToString(t);
}
string mareklib::dateTimeString() {
return padZeros(ofGetDay())
+ "." + padZeros(ofGetMonth()) + "." + padZeros(ofGetYear()) + " "
+ padZeros(ofGetHours()) +"-"+padZeros(ofGetMinutes()) +"-"+
padZeros(ofGetSeconds());
}
string mareklib::getHomeDirectory() {
FILE *fp = popen("who am I", "r");
if(fp!=NULL) {
printf("popen made it\n");
char name[512];
string username;
ofSleepMillis(100);
if(fgets(name, 512, fp)) {
printf("fgets\n");
username = name;
if(username.find(' ')!=-1) {
username = username.substr(0, username.find(' '));
string home = "/Users/"+username;
return home;
}
}
pclose(fp);
} else {
printf("Couldn't find user's name, going with default\n");
}
return "";
}
string mareklib::getDesktopPath() {
return getHomeDirectory() + "/Desktop";
}
string mareklib::getPreferencesDirectory(string appName) {
string prefsDir = getHomeDirectory() + "/Library/Preferences/"+appName;
struct stat stFileInfo;
// Attempt to get the file attributes
if(stat(prefsDir.c_str(),&stFileInfo)!=0) {
if(mkdir(prefsDir.c_str(), 0777)==0) {
return prefsDir;
} else {
printf("Failed to create preferences directory: %s\n", prefsDir.c_str());
return "";
}
}
} | [
"bereza@gmail.com"
] | bereza@gmail.com |
ef98d61df856e61ce5aef1fa952c227caad9c8a3 | 54c67306d63bb69a5cf381d12108d3dc98ae0f5d | /third-party/xdelta3/xdelta3/cpp-btree/btree_test.cc | 6b1837d33465ca8c212e346a1a1b7e45836c31e1 | [
"Apache-2.0",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | permissive | open-goal/jak-project | adf30a3459c24afda5b180e3abe1583c93458a37 | d96dce27149fbf58586160cfecb634614f055943 | refs/heads/master | 2023-09-01T21:51:16.736237 | 2023-09-01T16:10:59 | 2023-09-01T16:10:59 | 289,585,720 | 1,826 | 131 | ISC | 2023-09-14T13:27:47 | 2020-08-22T23:55:21 | Common Lisp | UTF-8 | C++ | false | false | 10,140 | cc | // Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gtest/gtest.h"
#include "btree_map.h"
#include "btree_set.h"
#include "btree_test.h"
namespace btree {
namespace {
template <typename K, int N>
void SetTest() {
typedef TestAllocator<K> TestAlloc;
ASSERT_EQ(sizeof(btree_set<K>), sizeof(void*));
BtreeTest<btree_set<K, std::less<K>, std::allocator<K>, N>, std::set<K> >();
BtreeAllocatorTest<btree_set<K, std::less<K>, TestAlloc, N> >();
}
template <typename K, int N>
void MapTest() {
typedef TestAllocator<K> TestAlloc;
ASSERT_EQ(sizeof(btree_map<K, K>), sizeof(void*));
BtreeTest<btree_map<K, K, std::less<K>, std::allocator<K>, N>, std::map<K, K> >();
BtreeAllocatorTest<btree_map<K, K, std::less<K>, TestAlloc, N> >();
BtreeMapTest<btree_map<K, K, std::less<K>, std::allocator<K>, N> >();
}
TEST(Btree, set_int32_32) { SetTest<int32_t, 32>(); }
TEST(Btree, set_int32_64) { SetTest<int32_t, 64>(); }
TEST(Btree, set_int32_128) { SetTest<int32_t, 128>(); }
TEST(Btree, set_int32_256) { SetTest<int32_t, 256>(); }
TEST(Btree, set_int64_256) { SetTest<int64_t, 256>(); }
TEST(Btree, set_string_256) { SetTest<std::string, 256>(); }
TEST(Btree, set_pair_256) { SetTest<std::pair<int, int>, 256>(); }
TEST(Btree, map_int32_256) { MapTest<int32_t, 256>(); }
TEST(Btree, map_int64_256) { MapTest<int64_t, 256>(); }
TEST(Btree, map_string_256) { MapTest<std::string, 256>(); }
TEST(Btree, map_pair_256) { MapTest<std::pair<int, int>, 256>(); }
// Large-node tests
TEST(Btree, map_int32_1024) { MapTest<int32_t, 1024>(); }
TEST(Btree, map_int32_1032) { MapTest<int32_t, 1032>(); }
TEST(Btree, map_int32_1040) { MapTest<int32_t, 1040>(); }
TEST(Btree, map_int32_1048) { MapTest<int32_t, 1048>(); }
TEST(Btree, map_int32_1056) { MapTest<int32_t, 1056>(); }
TEST(Btree, map_int32_2048) { MapTest<int32_t, 2048>(); }
TEST(Btree, map_int32_4096) { MapTest<int32_t, 4096>(); }
TEST(Btree, set_int32_1024) { SetTest<int32_t, 1024>(); }
TEST(Btree, set_int32_2048) { SetTest<int32_t, 2048>(); }
TEST(Btree, set_int32_4096) { SetTest<int32_t, 4096>(); }
TEST(Btree, map_string_1024) { MapTest<std::string, 1024>(); }
TEST(Btree, map_string_2048) { MapTest<std::string, 2048>(); }
TEST(Btree, map_string_4096) { MapTest<std::string, 4096>(); }
TEST(Btree, set_string_1024) { SetTest<std::string, 1024>(); }
TEST(Btree, set_string_2048) { SetTest<std::string, 2048>(); }
TEST(Btree, set_string_4096) { SetTest<std::string, 4096>(); }
template <typename K, int N>
void MultiSetTest() {
typedef TestAllocator<K> TestAlloc;
ASSERT_EQ(sizeof(btree_multiset<K>), sizeof(void*));
BtreeMultiTest<btree_multiset<K, std::less<K>, std::allocator<K>, N>,
std::multiset<K> >();
BtreeAllocatorTest<btree_multiset<K, std::less<K>, TestAlloc, N> >();
}
template <typename K, int N>
void MultiMapTest() {
typedef TestAllocator<K> TestAlloc;
ASSERT_EQ(sizeof(btree_multimap<K, K>), sizeof(void*));
BtreeMultiTest<btree_multimap<K, K, std::less<K>, std::allocator<K>, N>,
std::multimap<K, K> >();
BtreeMultiMapTest<btree_multimap<K, K, std::less<K>, std::allocator<K>, N> >();
BtreeAllocatorTest<btree_multimap<K, K, std::less<K>, TestAlloc, N> >();
}
TEST(Btree, multiset_int32_256) { MultiSetTest<int32_t, 256>(); }
TEST(Btree, multiset_int64_256) { MultiSetTest<int64_t, 256>(); }
TEST(Btree, multiset_string_256) { MultiSetTest<std::string, 256>(); }
TEST(Btree, multiset_pair_256) { MultiSetTest<std::pair<int, int>, 256>(); }
TEST(Btree, multimap_int32_256) { MultiMapTest<int32_t, 256>(); }
TEST(Btree, multimap_int64_256) { MultiMapTest<int64_t, 256>(); }
TEST(Btree, multimap_string_256) { MultiMapTest<std::string, 256>(); }
TEST(Btree, multimap_pair_256) { MultiMapTest<std::pair<int, int>, 256>(); }
// Large-node tests
TEST(Btree, multimap_int32_1024) { MultiMapTest<int32_t, 1024>(); }
TEST(Btree, multimap_int32_2048) { MultiMapTest<int32_t, 2048>(); }
TEST(Btree, multimap_int32_4096) { MultiMapTest<int32_t, 4096>(); }
TEST(Btree, multiset_int32_1024) { MultiSetTest<int32_t, 1024>(); }
TEST(Btree, multiset_int32_2048) { MultiSetTest<int32_t, 2048>(); }
TEST(Btree, multiset_int32_4096) { MultiSetTest<int32_t, 4096>(); }
TEST(Btree, multimap_string_1024) { MultiMapTest<std::string, 1024>(); }
TEST(Btree, multimap_string_2048) { MultiMapTest<std::string, 2048>(); }
TEST(Btree, multimap_string_4096) { MultiMapTest<std::string, 4096>(); }
TEST(Btree, multiset_string_1024) { MultiSetTest<std::string, 1024>(); }
TEST(Btree, multiset_string_2048) { MultiSetTest<std::string, 2048>(); }
TEST(Btree, multiset_string_4096) { MultiSetTest<std::string, 4096>(); }
// Verify that swapping btrees swaps the key comparision functors.
struct SubstringLess {
SubstringLess() : n(2) {}
SubstringLess(size_t length)
: n(length) {
}
bool operator()(const std::string &a, const std::string &b) const {
std::string as(a.data(), std::min(n, a.size()));
std::string bs(b.data(), std::min(n, b.size()));
return as < bs;
}
size_t n;
};
TEST(Btree, SwapKeyCompare) {
typedef btree_set<std::string, SubstringLess> SubstringSet;
SubstringSet s1(SubstringLess(1), SubstringSet::allocator_type());
SubstringSet s2(SubstringLess(2), SubstringSet::allocator_type());
ASSERT_TRUE(s1.insert("a").second);
ASSERT_FALSE(s1.insert("aa").second);
ASSERT_TRUE(s2.insert("a").second);
ASSERT_TRUE(s2.insert("aa").second);
ASSERT_FALSE(s2.insert("aaa").second);
swap(s1, s2);
ASSERT_TRUE(s1.insert("b").second);
ASSERT_TRUE(s1.insert("bb").second);
ASSERT_FALSE(s1.insert("bbb").second);
ASSERT_TRUE(s2.insert("b").second);
ASSERT_FALSE(s2.insert("bb").second);
}
TEST(Btree, UpperBoundRegression) {
// Regress a bug where upper_bound would default-construct a new key_compare
// instead of copying the existing one.
typedef btree_set<std::string, SubstringLess> SubstringSet;
SubstringSet my_set(SubstringLess(3));
my_set.insert("aab");
my_set.insert("abb");
// We call upper_bound("aaa"). If this correctly uses the length 3
// comparator, aaa < aab < abb, so we should get aab as the result.
// If it instead uses the default-constructed length 2 comparator,
// aa == aa < ab, so we'll get abb as our result.
SubstringSet::iterator it = my_set.upper_bound("aaa");
ASSERT_TRUE(it != my_set.end());
EXPECT_EQ("aab", *it);
}
TEST(Btree, IteratorIncrementBy) {
// Test that increment_by returns the same position as increment.
const int kSetSize = 2341;
btree_set<int32_t> my_set;
for (int i = 0; i < kSetSize; ++i) {
my_set.insert(i);
}
{
// Simple increment vs. increment by.
btree_set<int32_t>::iterator a = my_set.begin();
btree_set<int32_t>::iterator b = my_set.begin();
a.increment();
b.increment_by(1);
EXPECT_EQ(*a, *b);
}
btree_set<int32_t>::iterator a = my_set.begin();
for (int i = 1; i < kSetSize; ++i) {
++a;
// increment_by
btree_set<int32_t>::iterator b = my_set.begin();
b.increment_by(i);
EXPECT_EQ(*a, *b) << ": i=" << i;
}
}
TEST(Btree, Comparison) {
const int kSetSize = 1201;
btree_set<int64_t> my_set;
for (int i = 0; i < kSetSize; ++i) {
my_set.insert(i);
}
btree_set<int64_t> my_set_copy(my_set);
EXPECT_TRUE(my_set_copy == my_set);
EXPECT_TRUE(my_set == my_set_copy);
EXPECT_FALSE(my_set_copy != my_set);
EXPECT_FALSE(my_set != my_set_copy);
my_set.insert(kSetSize);
EXPECT_FALSE(my_set_copy == my_set);
EXPECT_FALSE(my_set == my_set_copy);
EXPECT_TRUE(my_set_copy != my_set);
EXPECT_TRUE(my_set != my_set_copy);
my_set.erase(kSetSize - 1);
EXPECT_FALSE(my_set_copy == my_set);
EXPECT_FALSE(my_set == my_set_copy);
EXPECT_TRUE(my_set_copy != my_set);
EXPECT_TRUE(my_set != my_set_copy);
btree_map<std::string, int64_t> my_map;
for (int i = 0; i < kSetSize; ++i) {
my_map[std::string(i, 'a')] = i;
}
btree_map<std::string, int64_t> my_map_copy(my_map);
EXPECT_TRUE(my_map_copy == my_map);
EXPECT_TRUE(my_map == my_map_copy);
EXPECT_FALSE(my_map_copy != my_map);
EXPECT_FALSE(my_map != my_map_copy);
++my_map_copy[std::string(7, 'a')];
EXPECT_FALSE(my_map_copy == my_map);
EXPECT_FALSE(my_map == my_map_copy);
EXPECT_TRUE(my_map_copy != my_map);
EXPECT_TRUE(my_map != my_map_copy);
my_map_copy = my_map;
my_map["hello"] = kSetSize;
EXPECT_FALSE(my_map_copy == my_map);
EXPECT_FALSE(my_map == my_map_copy);
EXPECT_TRUE(my_map_copy != my_map);
EXPECT_TRUE(my_map != my_map_copy);
my_map.erase(std::string(kSetSize - 1, 'a'));
EXPECT_FALSE(my_map_copy == my_map);
EXPECT_FALSE(my_map == my_map_copy);
EXPECT_TRUE(my_map_copy != my_map);
EXPECT_TRUE(my_map != my_map_copy);
}
TEST(Btree, RangeCtorSanity) {
typedef btree_set<int, std::less<int>, std::allocator<int>, 256> test_set;
typedef btree_map<int, int, std::less<int>, std::allocator<int>, 256>
test_map;
typedef btree_multiset<int, std::less<int>, std::allocator<int>, 256>
test_mset;
typedef btree_multimap<int, int, std::less<int>, std::allocator<int>, 256>
test_mmap;
std::vector<int> ivec;
ivec.push_back(1);
std::map<int, int> imap;
imap.insert(std::make_pair(1, 2));
test_mset tmset(ivec.begin(), ivec.end());
test_mmap tmmap(imap.begin(), imap.end());
test_set tset(ivec.begin(), ivec.end());
test_map tmap(imap.begin(), imap.end());
EXPECT_EQ(1, tmset.size());
EXPECT_EQ(1, tmmap.size());
EXPECT_EQ(1, tset.size());
EXPECT_EQ(1, tmap.size());
}
} // namespace
} // namespace btree
| [
"noreply@github.com"
] | open-goal.noreply@github.com |
b4b30f72ce339ff45881e7616a69737f0d41bd81 | 87b61b564f285858fcda8b50b892c2183bd23d51 | /client/third_party/google_gadgets_for_linux/ggadget/mac/quartz_graphics.h | 438b9b49653030ae4ff182d3064ff895cc0de16c | [
"Apache-2.0",
"FSFUL"
] | permissive | randyli/google-input-tools | e1da92fed47c23cf7b8e2ff63aee90c89e1f0347 | daa9806724dc6dc3915dbd9d6e3daad4e579bf72 | refs/heads/master | 2021-05-18T13:00:21.892514 | 2020-04-11T13:26:33 | 2020-04-11T13:26:33 | 251,252,155 | 0 | 0 | Apache-2.0 | 2020-03-30T08:58:26 | 2020-03-30T08:58:26 | null | UTF-8 | C++ | false | false | 2,050 | h | /*
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef GGADGET_MAC_QUARTZ_GRAPHICS_H_
#define GGADGET_MAC_QUARTZ_GRAPHICS_H_
#include <string>
#include "ggadget/common.h"
#include "ggadget/graphics_interface.h"
#include "ggadget/scoped_ptr.h"
#include "ggadget/slot.h"
namespace ggadget {
class TextFormat;
} // namespace ggadget
namespace ggadget {
namespace mac {
class CtFont;
// This class realizes the GraphicsInterface using the Quartz graphics library.
class QuartzGraphics : public GraphicsInterface {
public:
explicit QuartzGraphics(double zoom);
virtual ~QuartzGraphics();
virtual CanvasInterface* NewCanvas(double w, double h) const;
virtual ImageInterface* NewImage(const std::string& tag,
const std::string& data,
bool is_mask) const;
virtual FontInterface* NewFont(const std::string &family,
double pt_size,
FontInterface::Style style,
FontInterface::Weight weight) const;
virtual TextRendererInterface* NewTextRenderer() const;
virtual void SetZoom(double zoom);
virtual double GetZoom() const;
virtual Connection* ConnectOnZoom(Slot1<void, double>* slot) const;
FontInterface* NewFont(const TextFormat &format) const;
private:
class Impl;
scoped_ptr<Impl> impl_;
DISALLOW_EVIL_CONSTRUCTORS(QuartzGraphics);
};
} // namespace mac
} // namespace ggadget
#endif // GGADGET_MAC_QUARTZ_GRAPHICS_H_
| [
"synch@google.com"
] | synch@google.com |
bdba9ba80098a88af8cf17c33d3e4897e634eeb2 | b5e157fc30e0fc770632c3879a5e416a872a59e1 | /OpenGL/translate.h | bc3d8c3094a933a2198f1236fe7ec0150fbc6f03 | [] | no_license | lcbasu/Xcode | 53df7ae402ef4678ebd77a8747ec293a3dcda0af | a46983ba4faaa18f62c22d43bc930871d5171dd3 | refs/heads/master | 2021-05-28T13:30:50.301714 | 2015-02-17T03:59:35 | 2015-02-17T03:59:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,844 | h | //
// translate.h
// OpenGL
//
// Created by Lokesh Basu on 16/08/14.
// Copyright (c) 2014 Samsung. All rights reserved.
//
#ifndef OpenGL_translate_h
#define OpenGL_translate_h
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void handleKeyPress(unsigned char key, int x, int y)
{
switch (key)
{
case 27:
exit(0);
}
}
void initRendering()
{
glEnable(GL_DEPTH_TEST);
}
// called when window is resized
void handleResize(int w, int h)
{
// tells opengl how to convert form coordinates to pixel values
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); //switch to setting the camera perspective
// setting the camera perspective
glLoadIdentity(); // reset the camera
gluPerspective(45.0 // the camera angle
, (double)w/(double)h // the width to height ratio
, 1 // the near z clipping co-ordinate
, 200); // the far z clipping co-ordinate
}
// drwas the 3D scene
void drawScene()
{
// clear information from the last draw
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW); // switch to the drawing perspectve
glLoadIdentity();
glBegin(GL_QUADS); // begin quadrilateral co-ordinates
// trapezoid
glVertex3f(-0.7f, -1.5f, -5.0f);
glVertex3f(0.7f, -1.5f, -5.0f);
glVertex3f(0.4f, -0.5f, -5.0f);
glVertex3f(-0.4f, -0.5f, -5.0f);
glEnd(); // end quadrilateral co-ordinates
glBegin(GL_TRIANGLES); // begin triangle co-ordinates
// pentagon
glVertex3f(0.5f, 0.5f, -5.0f);
glVertex3f(1.5f, 0.5f, -5.0f);
glVertex3f(0.5f, 1.0f, -5.0f);
glVertex3f(0.5f, 1.0f, -5.0f);
glVertex3f(1.5f, 0.5f, -5.0f);
glVertex3f(1.5f, 1.0f, -5.0f);
glVertex3f(0.5f, 1.0f, -5.0f);
glVertex3f(1.5f, 1.0f, -5.0f);
glVertex3f(1.0f, 1.5f, -5.0f);
// triangle
glVertex3f(-0.5f, 0.5f, -5.0f);
glVertex3f(-1.0f, 1.5f, -5.0f);
glVertex3f(-1.5f, 0.5f, -5.0f);
glEnd(); // end trianle co-ordinates
glutSwapBuffers(); // send the 3d scene to the screen
}
void test()
{
// initialize glut
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400); // set the window size
// create the window
glutCreateWindow("Shapes");
initRendering(); // initialize rendering
// set handler function for drawing, keypress and window resizes
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeyPress);
glutReshapeFunc(handleResize);
glutMainLoop(); // start the main loop. glutMainLoop doesn't return.
}
#endif
| [
"lokesh.basu@gmail.com"
] | lokesh.basu@gmail.com |
656ae4dca290619db49b4a2c8e3d02230a960860 | cfcde6061bfd4fd957dd667309579b3035fe0984 | /include/kinect_common/memory.h | c0eac65dd58a0c6296f2f046b3f001cfd82ee9d8 | [] | no_license | sdebnathusc/kinect_bridge_ubuntu | dddf4dff841f255e84ed4277a6b1bc01f84036d1 | f5d1650f9250d703fa99b2f9ea74aeb30a7b9148 | refs/heads/master | 2021-01-17T17:08:26.598637 | 2017-03-07T01:11:41 | 2017-03-07T01:11:41 | 84,127,788 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,373 | h | #ifndef _KINECTCOMMON_MEMORY_H_
#define _KINECTCOMMON_MEMORY_H_
#include <memory>
#include <iostream>
// Safe release for interfaces
template<class __Interface>
inline void SafeRelease( __Interface *& pInterfaceToRelease )
{
if( pInterfaceToRelease != NULL )
{
pInterfaceToRelease->Release();
pInterfaceToRelease = NULL;
}
}
// ####################################################################################################
template<class __Wrapped>
class ReleasableWrapper
{
public:
typedef __Wrapped _Wrapped;
typedef __Wrapped * _WrappedPtr;
typedef __Wrapped const * _WrappedConstPtr;
typedef uint8_t _TrackerData;
typedef std::shared_ptr<_TrackerData> _Tracker;
_Tracker tracker_;
_WrappedPtr wrapped_ptr_;
// ====================================================================================================
ReleasableWrapper( _WrappedPtr wrapped_ptr = NULL )
:
wrapped_ptr_( wrapped_ptr ),
tracker_( std::make_shared<_TrackerData>() )
{
//
}
// ====================================================================================================
~ReleasableWrapper()
{
release();
}
// ====================================================================================================
void release()
{
if( wrapped_ptr_ && tracker_.unique() )
{
wrapped_ptr_->Release();
wrapped_ptr_ = NULL;
}
}
// ====================================================================================================
_WrappedPtr operator->()
{
return wrapped_ptr_;
}
// ====================================================================================================
_WrappedConstPtr operator->() const
{
return const_cast<_WrappedConstPtr>( wrapped_ptr_ );
}
// ====================================================================================================
_WrappedPtr & get()
{
return wrapped_ptr_;
}
// ====================================================================================================
_WrappedConstPtr get() const
{
return wrapped_ptr_;
}
__Wrapped ** getAddr()
{
return &wrapped_ptr_;
}
};
#endif // _KINECTCOMMON_MEMORY_H_
| [
"sdebnath@usc.edu"
] | sdebnath@usc.edu |
d5305592e93548b390b05f655e9a50c1f240ff9e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_old_hunk_1917.cpp | 0333d10bff135297491a54178d2075e103176a1d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | */
if (!file_req) {
if ((access_status = ap_location_walk(r))) {
return access_status;
}
if ((access_status = ap_run_translate_name(r))) {
return decl_die(access_status, "translate", r);
}
}
/* Reset to the server default config prior to running map_to_storage
| [
"993273596@qq.com"
] | 993273596@qq.com |
5298ae0c5abbada3ddcc46d9294c5538ab0b58c7 | 1b8d6ac932cfefe9405051db9632b65f54db3af9 | /src/refl/Meta.cpp | 0e5186c6aacac8ebe75c11bdd893cec40b16b85c | [
"Zlib"
] | permissive | rjpearsoniv/mud | c66235d489c600e9f6474b4f37f1f4c9340231de | 182ba242565c479406eca5cd0f08cabb66c9e86a | refs/heads/master | 2020-03-25T16:41:07.334332 | 2018-08-07T20:28:30 | 2018-08-07T20:28:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,685 | cpp | // Copyright (c) 2018 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#include <infra/Cpp20.h>
#ifdef MUD_MODULES
module mud.refl;
#else
#include <refl/Meta.h>
#include <refl/MetaDecl.h>
#include <refl/Class.h>
#include <refl/Enum.h>
#include <refl/Convert.h>
#include <obj/Types.h>
#include <obj/Any.h>
#include <infra/StringConvert.h>
#include <refl/Injector.h>
//#include <proto/Proto.h>
//#include <proto/Complex.h>
#include <infra/Vector.h>
//#include <srlz/Serial.h>
#endif
namespace mud
{
std::vector<Meta*> g_meta = std::vector<Meta*>(c_max_types);
std::vector<Class*> g_class = std::vector<Class*>(c_max_types);
std::vector<Enum*> g_enu = std::vector<Enum*>(c_max_types);
std::vector<Convert*> g_convert = std::vector<Convert*>(c_max_types);
template <>
void init_string<void>() {}
template <>
void init_string<cstring>() {}
template <>
void init_assign<cstring>() {}
bool is_string(Type& type)
{
return type.is<string>() || type.is<cstring>() || type.is<string>();
}
string get_string(Member& member, Ref value)
{
if(member.m_type->is<cstring>())
return val<cstring>(member.get(value));
else if(member.m_type->is<string>())
return val<string>(member.get(value)).c_str();
else
return val<string>(member.get(value));
}
Meta::Meta(Type& type, Namespace* location, cstring name, size_t size, TypeClass type_class)
: m_type(&type)
, m_namespace(location)
, m_name(name)
, m_size(size)
, m_type_class(type_class)
{
type.m_name = m_name;
g_meta[type.m_id] = this;
}
Enum::Enum(Type& type, bool scoped, const std::vector<cstring>& names, const std::vector<size_t>& indices, const std::vector<Var>& values)
: m_type(type)
, m_scoped(scoped)
, m_names(names)
, m_indices(indices)
, m_values(values)
{
g_enu[type.m_id] = this;
for(size_t i = 0; i < m_names.size(); ++i)
{
size_t index = m_indices[i];
m_map.resize(index + 1);
m_map[index] = m_names[i];
}
}
uint32_t Enum::value(cstring name)
{
for(size_t i = 0; i < m_names.size(); ++i)
if(strcmp(name, m_names[i]) == 0)
return m_indices[i];
printf("WARNING: fetching unknown Enum %s value : %s\n", m_type.m_name, name);
return m_indices[0];
}
size_t Enum::index(cstring name)
{
for(size_t i = 0; i < m_names.size(); ++i)
if(strcmp(name, m_names[i]) == 0)
return i;
printf("WARNING: fetching unknown Enum %s index : %s\n", m_type.m_name, name);
return 0;
}
Class::Class(Type& type)
: m_type(&type)
, m_meta(&meta(type))
, m_root(&type)
{
g_class[type.m_id] = this;
}
Class::Class(Type& type, std::vector<Type*> bases, std::vector<size_t> bases_offsets, std::vector<Constructor> constructors, std::vector<CopyConstructor> copy_constructors,
std::vector<Member> members, std::vector<Method> methods, std::vector<Static> static_members)
: m_type(&type)
, m_meta(&meta(type))
, m_root(&type)
, m_bases(bases)
, m_bases_offsets(bases_offsets)
, m_constructors(constructors)
, m_copy_constructors(copy_constructors)
, m_members(members)
, m_methods(methods)
, m_static_members(static_members)
{
g_class[type.m_id] = this;
}
Class::~Class()
{}
void Class::inherit(std::vector<Type*> types)
{
for(Type* type : types)
if(g_class[type->m_id])
{
vector_prepend(m_members, cls(*type).m_members);
vector_prepend(m_methods, cls(*type).m_methods);
}
}
void Class::setup_class()
{
this->inherit(m_bases);
for(size_t i = 0; i < m_members.size(); ++i)
m_members[i].m_index = i;
for(size_t i = 0; i < m_constructors.size(); ++i)
m_constructors[i].m_index = i;
for(Member& member : m_members)
{
if(member.is_structure() && strcmp(member.m_name, "contents") == 0) // @kludge name check is a kludge until we separate structure and nested member
m_nested = true;
if(strcmp(member.m_name, "id") == 0 || strcmp(member.m_name, "index") == 0)
m_id_member = &member;
if(strcmp(member.m_name, "name") == 0 && is_string(*member.m_type))
m_name_member = &member;
if(strcmp(member.m_name, "type") == 0 && member.m_type->is<Type>())
m_type_member = &member;
if(member.is_component())
m_components.push_back(&member);
m_field_names.push_back(member.m_name);
m_field_values.push_back(member.m_default_value);
}
for(Member* component : m_components)
if(g_class[component->m_type->m_id])
{
Class& c = cls(*component->m_type);
for(Member& member : c.m_members)
m_deep_members.push_back(&member);
for(Method& method : c.m_methods)
m_deep_methods.push_back(&method);
}
}
Ref Class::upcast(Ref object, Type& base)
{
if(!object) return object;
for(size_t i = 0; i < m_bases.size(); ++i)
if(m_bases[i] == &base)
{
return { static_cast<char*>(object.m_value) + m_bases_offsets[i], base };
}
return object;
}
Ref Class::downcast(Ref object, Type& base)
{
if(!object) return object;
for(size_t i = 0; i < m_bases.size(); ++i)
if(m_bases[i] == &base)
{
return { static_cast<char*>(object.m_value) - m_bases_offsets[i], *m_type };
}
return object;
}
Member& Class::member(cstring name)
{
for(Member& member : m_members)
if(strcmp(member.m_name, name) == 0)
return member;
return m_members[0];
}
Method& Class::method(cstring name)
{
for(Method& method : m_methods)
if(strcmp(method.m_name, name) == 0)
return method;
return m_methods[0];
}
Static& Class::static_member(cstring name)
{
for(Static& member : m_static_members)
if(strcmp(member.m_name, name) == 0)
return member;
return m_static_members[0];
}
Operator& Class::op(cstring name)
{
for(Operator& op : m_operators)
if(strcmp(op.m_function->m_name, name) == 0)
return op;
return m_operators[0];
}
bool Class::has_member(cstring name)
{
return vector_has_pred(m_members, [&](const Member& member) { return strcmp(member.m_name, name) == 0; });
}
bool Class::has_method(cstring name)
{
return vector_has_pred(m_methods, [&](const Method& method) { return strcmp(method.m_name, name) == 0; });
}
Member& Class::member(Address address)
{
for(Member& look : m_members)
if(look.m_address == address)
return look;
printf("ERROR: retrieving member\n");
return m_members[0];
}
Method& Class::method(Address address)
{
for(Method& look : m_methods)
if(look.m_address == address)
return look;
printf("ERROR: retrieving method\n");
return m_methods[0];
}
bool Class::has_member(Address address)
{
return vector_has_pred(m_members, [&](const Member& look) { return look.m_address == address; });
}
bool Class::has_method(Address address)
{
return vector_has_pred(m_methods, [&](const Method& look) { return look.m_address == address; });
}
const Constructor* Class::constructor(ConstructorIndex index) const
{
const Constructor* constructor = nullptr;
if(index == ConstructorIndex::Default)
constructor = this->constructor(m_members.size());
if(!constructor && !m_constructors.empty())
return &m_constructors[0];
return constructor;
}
const Constructor* Class::constructor(size_t arguments) const
{
for(const Constructor& constructor : m_constructors)
{
size_t min_args = constructor.m_arguments.size() - 1 - constructor.m_num_defaults;
size_t max_args = constructor.m_arguments.size() - 1;
if(arguments >= min_args && arguments <= max_args)
return &constructor;
}
return nullptr;
}
bool Class::is(Type& component)
{
return vector_find(m_components, [&](Member* member) { return member->m_type->is(component); }) != nullptr;
}
Ref Class::as(Ref object, Type& component)
{
Member* member = *vector_find(m_components, [&](Member* member) { return member->m_type->is(component); });
return cls(*member->m_type).upcast(member->get(object), component);
}
bool compare(Ref first, Ref second)
{
UNUSED(first); UNUSED(second);
return false;
}
void copy_construct(Ref dest, Ref source)
{
if(is_basic(*dest.m_type))
memcpy(dest.m_value, source.m_value, meta(dest).m_size);
else if(cls(dest).m_copy_constructors.size() > 0)
cls(dest).m_copy_constructors[0].m_call(dest, source);
}
void assign(Ref first, Ref second)
{
if(second.m_type->is(*first.m_type))
meta(first).m_copy_assign(first, second);
else
printf("WARNING: can't assign values of unrelated types\n");
}
void assign_pointer(Ref first, Ref second)
{
UNUSED(first); UNUSED(second);
}
string to_name(Type& type, Ref value)
{
string name;
if(is_basic(type))
name = to_string(value);
else if(!value)
name = "null";
else if(cls(type).m_name_member)
name = get_string(*cls(type).m_name_member, value);
else if(cls(type).m_id_member)
name = string(type.m_name) + " : " + to_string(cls(type).m_id_member->get(value));
else
name = string(type.m_name); // + " : " + to_string(value.m_value); // @todo void* to string fails with vs2017 + modules
return name;
}
TypeConverter::TypeConverter()
: DoubleDispatch()
{
this->default_converter<float, double>();
this->default_converter<float, int>();
this->default_converter<float, uint16_t>();
this->default_converter<float, uint32_t>();
this->default_converter<float, size_t>();
this->default_converter<double, int>();
this->default_converter<double, uint16_t>();
this->default_converter<double, uint32_t>();
this->default_converter<double, size_t>();
this->default_converter<int, uint16_t>();
this->default_converter<int, uint32_t>();
this->default_converter<int, size_t>();
this->default_converter<uint16_t, size_t>();
this->default_converter<uint16_t, uint32_t>();
this->default_converter<uint32_t, size_t>();
}
bool TypeConverter::check(Type& input, Type& output)
{
return DoubleDispatch::check(input, output);
}
bool TypeConverter::check(Ref input, Type& output)
{
return DoubleDispatch::check(*input.m_type, output);
}
Var TypeConverter::convert(Ref input, Type& output)
{
Var result = meta(output).m_empty_var;
DoubleDispatch::dispatch(input, result);
return result;
}
void TypeConverter::convert(Ref input, Type& output, Var& result)
{
if(result.none() || !type(result).is(output))
result = meta(output).m_empty_var;
DoubleDispatch::dispatch(input, result);
}
bool is_related(Type& input, Type& output)
{
UNUSED(input); UNUSED(output);
return false;
}
inline void assign(Var& source, Var& dest, bool ref)
{
if(ref)
dest = source;
else
dest = source.m_ref;
}
bool convert(Var& source, Type& output, Var& dest, bool ref)
{
Ref value = source;
if(output.is(type<Ref>()))
dest = source;
else if(type(value).is(output))
assign(source, dest, ref);
else if(g_class[type(source).m_id] && cls(source).is(output))
dest = cls(source).as(source.m_ref, output);
else if(TypeConverter::me().check(value, output))
TypeConverter::me().convert(value, output, dest);
else
{
dest.clear();
return false;
}
return true;
}
bool convert(Ref input, Type& output, Var& result)
{
Var inputvar = input;
return convert(inputvar, output, result);
}
Var convert(Ref input, Type& output)
{
Var result;
convert(input, output, result);
return result;
}
bool can_convert(Type& input, Type& output)
{
return input.is(output) || is_related(input, output) || TypeConverter::me().check(input, output);
}
bool can_convert(Ref input, Type& output)
{
return type(input).is(output) || is_related(type(input), output) || TypeConverter::me().check(input, output);
}
}
| [
"hugo.amiard@laposte.net"
] | hugo.amiard@laposte.net |
f379ad59e9ec578bd8a7b46e8a7cf1a2d533bd6a | 9be0baa3d53e460fb9088280b2f38d6352a4097e | /doc/nml_ex1_n_codegen_protos.hh | 73f980b222bce3f722487268a89266f5492605bf | [
"LicenseRef-scancode-public-domain"
] | permissive | usnistgov/rcslib | 480cd9f97b9abe83c23dcddc1dd4db253084ff13 | f26d07fd14e068a1a5bfb97b0dc6ba5afefea0a1 | refs/heads/master | 2023-04-06T13:35:53.884499 | 2023-04-03T20:01:08 | 2023-04-03T20:01:08 | 32,079,125 | 35 | 22 | NOASSERTION | 2020-10-12T22:03:48 | 2015-03-12T13:43:52 | Java | UTF-8 | C++ | false | false | 1,295 | hh | /*
* New C++ Header File starts here.
* This file should be named nml_ex1_n_codegen_protos.hh
* Automatically generated by NML CodeGen Java Applet.
* with command line arguments : HHFile=nml_ex1.hh -o /tmp/nml_ex1.cc
* RCS_VERSION=@(#) RCS_LIBRARY_VERSION: 2009.06.05_1506:1507 Compiled on Mon Jun 8 09:24:56 EDT 2009 for the java platform.
* $Id: CodeGenCommon.java 1512 2009-06-10 13:23:49Z shackle $
*
* .gen script :
* 0:load nml_ex1.hh
* 1:clear
* 2:select_from_file nml_ex1.hh
* 3:generate C++ protos>nml_ex1_n_codegen_protos.hh
*
*/
#ifndef nml_ex1_n_codegen_protos_hh_included
#define nml_ex1_n_codegen_protos_hh_included
// Include all NML, CMS, and RCS classes and functions
#include "rcs.hh"
// Include command and status message definitions
#include "nml_ex1.hh"
// Forward Function Prototypes
#ifndef MAX_EX_NAME_LENGTH
#define MAX_EX_NAME_LENGTH 12
#endif
#ifndef EX_NAME_LIST_LENGTH
#define EX_NAME_LIST_LENGTH 2
#endif
/* This list must be in alphabetical order and the three lists must correspond. */
extern const NMLTYPE ex_id_list[EX_NAME_LIST_LENGTH];
extern const size_t ex_size_list[EX_NAME_LIST_LENGTH];
// Enumerated Type Constants
extern int ex_format(NMLTYPE type, void *buffer, CMS *cms);
#endif
/* # endif nml_ex1_n_codegen_protos_hh_included */
| [
"william.shackleford@nist.gov"
] | william.shackleford@nist.gov |
dd862dcb6723921f96ee086298074f402a2a8de1 | c1c70168fe5ed0c9c81e08915a647961200d1766 | /TOJ/已註解,整碼/toj249.cpp | c73c79a1e79178f4208cab39b1afa3de96642f6a | [] | no_license | cies96035/CPP_programs | 046fa81e1d7d6e5594daee671772dbfdbdfb2870 | 9877fb44c0cd6927c7bfe591bd595886b1531501 | refs/heads/master | 2023-08-30T15:53:57.064865 | 2023-08-27T10:01:12 | 2023-08-27T10:01:12 | 250,568,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | #include<iostream>
using namespace std;
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
int n,num;
cin>>n>>num;
n--;
long long sum=num,ans=num;
//預設ans及sum為第一個數而非0
//避免全負數而答案為0的狀況(題目至少要取一個)
while(n--)
{
cin>>num;
sum+=num;
if(sum>ans)ans=sum;
//紀錄連續總和最大值
if(sum<0)sum=0;
//如果連續總和<0,則前面就不取了
//因為 -sum + num < num 必成立
}
cout<<ans<<'\n';
//輸出答案
}
| [
"cies9001005@gmail.com"
] | cies9001005@gmail.com |
6aa329dcce79aa52410b448c551458e17b9446ca | 830934ba65b11c21aa9051546eac0aa03893b210 | /libs/libfbxsdk_2020.3.1/include/fbxsdk/scene/geometry/fbxcamera.h | 42d0db19460ed8adcbe5214a07a2b7a24ec8d8e6 | [
"MIT"
] | permissive | NickHardeman/ofxFBX | e9cca47c232a10ef4b89c12672fc2df68d9ecbc4 | f032fd43a78a740e7ab4b4f497a61a1654ef9a59 | refs/heads/master | 2023-09-03T19:21:22.013743 | 2023-08-30T14:51:34 | 2023-08-30T14:51:34 | 32,026,580 | 117 | 43 | MIT | 2022-11-22T15:13:13 | 2015-03-11T15:53:23 | C++ | UTF-8 | C++ | false | false | 79,521 | h | /****************************************************************************************
Copyright (C) 2015 Autodesk, Inc.
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
//! \file fbxcamera.h
#ifndef _FBXSDK_SCENE_GEOMETRY_CAMERA_H_
#define _FBXSDK_SCENE_GEOMETRY_CAMERA_H_
#include <fbxsdk/fbxsdk_def.h>
#include <fbxsdk/core/base/fbxstring.h>
#include <fbxsdk/core/math/fbxvector4.h>
#include <fbxsdk/scene/geometry/fbxnodeattribute.h>
#include <fbxsdk/fbxsdk_nsbegin.h>
class FbxTexture;
/** This node attribute contains methods for accessing the properties of a camera.
* \nosubgrouping
* A camera can be set to automatically point at and follow
* another node in the hierarchy. To do this, the focus source
* must be set to EFocusDistanceSource::eFocusSrcCameraInterest and the
* followed node associated with function FbxNode::SetTarget().
* \see FbxCameraStereo and FbxCameraSwitcher.
*/
class FBXSDK_DLL FbxCamera : public FbxNodeAttribute
{
FBXSDK_OBJECT_DECLARE(FbxCamera,FbxNodeAttribute);
public:
//! Return the type of node attribute which is EType::eCamera.
FbxNodeAttribute::EType GetAttributeType() const override;
//! Reset the camera to default values.
void Reset();
/** Camera projection types.
* \remarks By default, the camera projection type is set to ePerspective.
* If the camera projection type is set to eOrthogonal, the following options
* are not relevant:
* - aperture format
* - aperture mode
* - aperture width and height
* - angle of view/focal length
* - squeeze ratio
*/
enum EProjectionType
{
ePerspective, //!< Perspective projection.
eOrthogonal //!< Orthogonal projection.
};
/**
* \name Functions to handle the viewing area.
*/
//@{
/** Camera formats identifiers.
* \remarks This is designed as the same as in MotionBuilder.
* \see SetFormat, GetFormat and CameraFormat.
*/
enum EFormat
{
eCustomFormat, //!< The format's width, height, or pixel ratio has been user-specified, and matches none of the other picture formats.
eD1NTSC, //!< Standard format for D1 NTSC (720 by 486).
eNTSC, //!< NTSC standard for North American television broadcast (640 by 480).
ePAL, //!< PAL standard for European television broadcast (570 by 486).
eD1PAL, //!< Standard format for D1 PAL (720 by 576).
eHD, //!< HD format(1920 by 1080).
e640x480, //!< Recommended computer screen format (640 by 480).
e320x200, //!< Recommended format for World Wide Web production(320 by 200).
e320x240, //!< Alternate World Wide Web format(320 by 240).
e128x128, //!< Format(128 by 128)
eFullscreen //!< Full computer screen format (1280 by 1024 pixels).
};
/** Set the camera format.
* \param pFormat The camera format identifier.
* \remarks Changing the camera format sets the camera aspect
* ratio mode to eFixedResolution and modifies the aspect width
* size, height size, and pixel ratio accordingly.
*/
void SetFormat(EFormat pFormat);
/** Get the camera format.
* \return The current camera format identifier.
*/
EFormat GetFormat() const;
/** Camera's aspect ratio modes.
* \see SetAspect, GetAspectRatioMode, AspectWidth, AspectHeight and AspectRatioMode.
*/
enum EAspectRatioMode
{
eWindowSize, //!< Both width and height values aren't relevant.
eFixedRatio, //!< The height value is set to 1.0 and the width value is relative to the height value.
eFixedResolution, //!< Both width and height values are in pixels.
eFixedWidth, //!< The width value is in pixels and the height value is relative to the width value.
eFixedHeight //!< The height value is in pixels and the width value is relative to the height value.
};
/** Set the camera's aspect ratio mode.
* \param pRatioMode Camera's aspect ratio mode.
* \param pWidth Camera's aspect width, must be a positive value.
* \param pHeight Camera's aspect height, must be a positive value.
* \remarks Changing the camera aspect sets the camera format to eCustomFormat.
* \see EAspectRatioMode.
*/
void SetAspect(EAspectRatioMode pRatioMode, double pWidth, double pHeight);
/** Get the camera aspect ratio mode.
* \return The current aspect ratio mode.
*/
EAspectRatioMode GetAspectRatioMode() const;
/** Set the pixel ratio.
* \param pRatio The pixel ratio value.
* \remarks The value must be a positive number. Comprised between 0.05 and 20.0. Values
* outside these limits will be clamped. Changing the pixel ratio sets the camera format to eCustomFormat.
*/
void SetPixelRatio(double pRatio);
/** Get the pixel ratio.
* \return The current camera's pixel ratio value.
*/
double GetPixelRatio() const;
/** Set the near plane distance from the camera.
* The near plane is the minimum distance to render a scene on the camera display.
* A synonym for the near plane is "front clipping plane".
* \param pDistance The near plane distance value.
* \remarks The near plane value is limited to the range [0.001, 600000.0] and
* must be inferior to the far plane value.
*/
void SetNearPlane(double pDistance);
/** Get the near plane distance from the camera.
* The near plane is the minimum distance to render a scene on the camera display.
* A synonym for the near plane is "front clipping plane".
* \return The near plane value.
*/
double GetNearPlane() const;
/** Set the far plane distance from camera.
* The far plane is the maximum distance to render a scene on the camera display.
* A synonym for the far plane is "back clipping plane".
* \param pDistance The far plane distance value.
* \remarks The far plane value is limited to the range [0.001, 600000.0] and
* must be superior to the near plane value.
*/
void SetFarPlane(double pDistance);
/** Get the far plane distance from camera.
* The far plane is the maximum distance to render a scene on the camera display.
* A synonym for the far plane is "back clipping plane".
* \return The far plane value.
*/
double GetFarPlane() const;
//@}
/**
* \name Aperture and Film Functions.
* In photography, the aperture is the size of hole allowing light from the lens to get through to the film.
* The aperture mode determines which values drive the camera aperture. When the aperture mode is \e eHorizAndVert,
* \e eHorizontal or \e eVertical, the field of view is used. When the aperture mode is \e eFocalLength, the focal length is used.
*
* It is possible to convert the aperture mode into field of view or vice versa using functions ComputeFieldOfView and
* ComputeFocalLength. These functions use the camera aperture width and height for their computation.
*/
//@{
/** Camera's aperture formats.
* \remarks This is designed as the same as in MotionBuilder.
* \see SetApertureFormat, GetApertureFormat, FilmFormat, FilmWidth, FilmHeight, FilmSqueezeRatio and FilmAspectRatio.
*/
enum EApertureFormat
{
eCustomAperture, //!< The film size, squeeze ratio and aspect ratio has been user-specified, and matches none of the other aperture formats.
e16mmTheatrical, //!< Film Size: 0.404, 0.295 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.369.
eSuper16mm, //!< Film Size: 0.493, 0.292 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.688.
e35mmAcademy, //!< Film Size: 0.864, 0.630 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.371.
e35mmTVProjection, //!< Film Size: 0.816, 0.612 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.333.
e35mmFullAperture, //!< Film Size: 0.980, 0.735 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.333.
e35mm185Projection, //!< Film Size: 0.825, 0.446 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.850.
e35mmAnamorphic, //!< Film Size: 0.864, 0.732 inches. Film Squeeze Ratio: 2.0. Film Aspect Ratio:1.180.
e70mmProjection, //!< Film Size: 2.066, 0.906 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 2.280.
eVistaVision, //!< Film Size: 1.485, 0.991 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.498.
eDynaVision, //!< Film Size: 2.080, 1.480 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.405.
eIMAX //!< Film Size: 2.772, 2.072 inches. Film Squeeze Ratio: 1.0. Film Aspect Ratio: 1.338.
};
/** Set the camera aperture format.
* \param pFormat The camera aperture format identifier.
* \remarks Changing the aperture format modifies the aperture width, height, and squeeze ratio accordingly.
*/
void SetApertureFormat(EApertureFormat pFormat);
/** Get the camera aperture format.
* \return The camera's current aperture format identifier.
*/
EApertureFormat GetApertureFormat() const;
/** Camera aperture modes.
* The aperture mode determines which values drive the camera aperture.
* If the aperture mode is \e eHorizAndVert, \e eHorizontal, or \e eVertical, then the field of view is used.
* If the aperture mode is \e eFocalLength, then the focal length is used.
*/
enum EApertureMode
{
eHorizAndVert, //!< Set the angle values for both the horizontal and vertical settings.
eHorizontal, //!< Set only the horizontal angle.
eVertical, //!< Set only the vertical angle.
eFocalLength //!< Use focal length directly.
};
/** Set the camera aperture mode.
* \param pMode The camera aperture mode identifier.
*/
void SetApertureMode(EApertureMode pMode);
/** Get the camera aperture mode.
* \return The camera's current aperture mode identifier.
*/
EApertureMode GetApertureMode() const;
/** Set the camera aperture width in inches.
* \param pWidth The aperture width value.
* \remarks Must be a positive value. The minimum accepted value is 0.0001.
* Changing the aperture width sets the camera aperture format to eCustomFormat.
*/
void SetApertureWidth(double pWidth);
/** Get the camera aperture width in inches.
* \return The camera's current aperture width value in inches.
*/
double GetApertureWidth() const;
/** Set the camera aperture height in inches.
* \param pHeight The aperture height value.
* \remarks Must be a positive value. The minimum accepted value is 0.0001.
* Changing the aperture height sets the camera aperture format to eCustomFormat.
*/
void SetApertureHeight(double pHeight);
/** Get the camera aperture height in inches.
* \return The camera's current aperture height value in inches.
*/
double GetApertureHeight() const;
/** Set the squeeze ratio.
* \param pRatio The squeeze ratio value.
* \remarks Must be a positive value. The minimum accepted value is 0.0001.
* Changing the squeeze ratio sets the camera aperture format to eCustomFormat.
*/
void SetSqueezeRatio(double pRatio);
/** Get the camera squeeze ratio.
* \return The camera's current squeeze ratio value.
*/
double GetSqueezeRatio() const;
/** Camera's gate fit modes.
* There are two gates for a camera, film gate and resolution gate.
* Film gate is a border indicating the area of the camera's view as a real-world camera records on film.
* The dimensions of the film gate represent the dimensions of the camera aperture.
* But the film gate does not represent the render region.
* It is the resolution gate that represents the rendering resolution.
* The gate fit mode controls the size of the resolution gate relative to the film gate.
*/
enum EGateFit
{
eFitNone, //!< No resolution gate fit.
eFitVertical, //!< Fit the resolution gate vertically within the film gate.
eFitHorizontal, //!< Fit the resolution gate horizontally within the film gate.
eFitFill, //!< Fit the resolution gate within the film gate.
eFitOverscan, //!< Fit the film gate within the resolution gate.
eFitStretch //!< Fit the resolution gate to the film gate.
};
/** Compute the angle of view based on the given focal length, the aperture width, and aperture height.
* \param pFocalLength The focal length in millimeters.
* \return The computed angle of view in degrees.
* \remark If aperture mode is not vertical, horizontal is assumed.
*/
double ComputeFieldOfView(double pFocalLength) const;
/** Compute the focal length based on the given angle of view, the aperture width, and aperture height.
* \param pAngleOfView The angle of view in degrees.
* \return The computed focal length in millimeters.
* \remark If aperture mode is not vertical, horizontal is assumed.
*/
double ComputeFocalLength(double pAngleOfView) const;
/** Specifies how the roll is applied with respect to the pivot value.
*/
enum EFilmRollOrder
{
eRotateFirst, //!< The film back is first rotated then translated by the pivot point value.
eTranslateFirst //!< The film back is first translated then rotated by the film roll value.
};
//@}
/**
* \name Functions to handle BackPlane/FrontPlane and Plate.
*
* In the FbxSdk terminology, the Back/Front plane is the support of the plate. And the plate is
* the support of the texture used for backgrounds/foregrounds. Functions and properties
* identified by the "Plate" name are affecting the display of the texture on the plate.
* The functions and properties identified with the "Back/FrontPlane" are affecting the plate.
*
* Typically a client application would place the BackPlate a small distance in front of the
* FarPlane and the FrontPlate just behind the NearPlane to avoid them to be hidden by the clipping.
* Unless otherwise noted, there are no restrictions on the values stored by the camera object
* therefore it is the responsibility of the client application to process the information in a
* meaningful way and to maintain consistency between the different properties relationships.
*/
//@{
/** Set the associated background image file.
* \param pFileName The path of the background image file.
* \remarks The background image file name must be valid.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
void SetBackgroundFileName(const char* pFileName);
/** Get the background image file name.
* \return Pointer to the background filename string or \c NULL if not set.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
const char* GetBackgroundFileName() const;
/** Set the media name associated to the background image file.
* \param pFileName The media name of the background image file.
* \remarks The media name is a unique name used to identify the background image file.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
void SetBackgroundMediaName(const char* pFileName);
/** Get the media name associated to the background image file.
* \return Pointer to the media name string or \c NULL if not set.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
const char* GetBackgroundMediaName() const;
/** Set the associated foreground image file.
* \param pFileName The path of the foreground image file.
* \remarks The foreground image file name must be valid.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
void SetForegroundFileName(const char* pFileName);
/** Get the foreground image file name.
* \return Pointer to the foreground filename string or \c NULL if not set.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
const char* GetForegroundFileName() const;
/** Set the media name associated to the foreground image file.
* \param pFileName The media name of the foreground image file.
* \remarks The media name is a unique name used to identify the foreground image file.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
void SetForegroundMediaName(const char* pFileName);
/** Get the media name associated to the foreground image file.
* \return Pointer to the media name string or \c NULL if not set.
* \remarks This method is still provided just for legacy files (Fbx version 5.0 and earlier)
* and must not be used in any other cases.
*/
const char* GetForegroundMediaName() const;
/** Image plate drawing modes.
*/
enum EPlateDrawingMode
{
ePlateBackground, //!< Image is drawn behind models.
ePlateForeground, //!< Image is drawn in front of models based on alpha channel.
ePlateBackAndFront //!< Image is drawn behind and in front of models depending on alpha channel.
};
/** Set front plate matte threshold.
* \param pThreshold Threshold value on a range from 0.0 to 1.0.
* \remarks This option is only relevant if the image plate drawing mode is set to ePlateForeground or ePlateBackAndFront.
*/
void SetBackgroundAlphaTreshold(double pThreshold);
/** Get front plate matte threshold.
* \return Threshold value on a range from 0.0 to 1.0.
* \remarks This option is only relevant if the image plate drawing mode is set to ePlateForeground or ePlateBackAndFront.
*/
double GetBackgroundAlphaTreshold() const;
/** Change the back plate fit image flag.
* If this flag is on, scale the back plate image to fit on the back plane.
* \param pFitImage New value for the BackPlateFitImage property.
*/
void SetBackPlateFitImage(bool pFitImage);
/** Get the current back plate image flag.
* If this flag is on, scale the back plate image to fit on the back plane.
* \return The value of the BackPlateFitImage property.
*/
bool GetBackPlateFitImage() const;
/** Change the back plate crop flag.
* If this flag is on, crop the back plate image to fit on the back plane.
* If the image is smaller than the plane, this flag has no effect.
* \param pCrop New value for the BackPlateCrop property.
*/
void SetBackPlateCrop(bool pCrop);
/** Get the current back plate crop flag.
* If this flag is on, crop the back plate image to fit on the back plane.
* If the image is smaller than the plane, this flag has no effect.
* \return The value of the BackPlateCrop property.
*/
bool GetBackPlateCrop() const;
/** Change the back plate center flag.
* If this flag is on, center the back plate image on the back plane.
* \param pCenter New value for the BackPlateCenter property.
*/
void SetBackPlateCenter(bool pCenter);
/** Get the current back plate center flag.
* If this flag is on, center the back plate image on the back plane.
* \return The value of the BackPlateCenter property.
*/
bool GetBackPlateCenter() const;
/** Change the back plate keep ratio flag.
* If this flag is on, keep the aspect ratio of the back plate image.
* Turn on both the keep ration flag and the fit image flag to scale the back plate image proportionately.
* \param pKeepRatio New value for the BackPlateKeepRatio property.
*/
void SetBackPlateKeepRatio(bool pKeepRatio);
/** Get the current back plate keep ratio flag.
* If this flag is on, keep the aspect ratio of the back plate image.
* Turn on both the keep ration flag and the fit image flag to scale the back plate image proportionately.
* \return The value of the BackPlateKeepRatio property.
*/
bool GetBackPlateKeepRatio() const;
/** Enable or disable the display of the texture without the need to disconnect it from its plate.
* \param pEnable If \c true the texture is displayed, \c false otherwise.
* \remarks It is the responsibility of the client application to perform the required tasks according to the state
* of this flag.
*/
void SetShowFrontPlate(bool pEnable);
/** Get the current state of the flag to display the front plate or not.
* \return \c true if show front plate is enabled, otherwise \c false.
* \remarks It is the responsibility of the client application to perform the required tasks according to the state
* of this flag.
*/
bool GetShowFrontPlate() const;
/** Change the front plate fit image flag.
* If this flag is on, scale the front plate image to fit on the front plane.
* \param pFrontPlateFitImage New value for the FrontPlateFitImage property.
*/
void SetFrontPlateFitImage(bool pFrontPlateFitImage);
/** Get the current front plate fit image flag.
* If this flag is on, scale the front plate image to fit on the front plane.
* \return The value of the BackPlateFitImage property.
*/
bool GetFrontPlateFitImage() const;
/** Change the front plate crop flag.
* If this flag is on, crop the front plate image to fit on the front plane.
* If the image is smaller than the plane, this flag has no effect.
* \param pFrontPlateCrop New value for the FrontPlateCrop property.
*/
void SetFrontPlateCrop(bool pFrontPlateCrop);
/** Get the current front plate crop flag.
* If this flag is on, crop the front plate image to fit on the front plane.
* If the image is smaller than the plane, this flag has no effect.
* \return The value of the FrontPlateCrop property.
*/
bool GetFrontPlateCrop() const;
/** Change the front plate center flag.
* If this flag is on, center the front plate image on the front plane.
* \param pFrontPlateCenter New value for the FrontPlateCenter property.
*/
void SetFrontPlateCenter(bool pFrontPlateCenter);
/** Get the current front plate center flag.
* If this flag is on, center the front plate image on the front plane.
* \return The value of the FrontPlateCenter property.
*/
bool GetFrontPlateCenter() const;
/** Change the front plate keep ratio flag.
* If this flag is on, keep the aspect ratio of the front plate image.
* Turn on both the keep ration flag and the fit image flag to scale the front plate image proportionately.
* \param pFrontPlateKeepRatio New value for the FrontPlateKeepRatio property.
*/
void SetFrontPlateKeepRatio(bool pFrontPlateKeepRatio);
/** Get the current front plate keep ratio flag.
* If this flag is on, keep the aspect ratio of the front plate image.
* Turn on both the keep ration flag and the fit image flag to scale the front plate image proportionately.
* \return The value of the FrontPlateKeepRatio property.
*/
bool GetFrontPlateKeepRatio() const;
/** Set the front plate opacity value.
* \param pOpacity New value for the ForegroundOpacity property.
*/
void SetForegroundOpacity(double pOpacity);
/** Get the front plate opacity value.
* \return The value of the ForegroundOpacity property.
*/
double GetForegroundOpacity() const;
/** Attach the texture to the front plate.
* \param pTexture The pointer to the texture to attach.
*/
void SetForegroundTexture(FbxTexture* pTexture);
/** Get the texture connected to the front plate.
* \return A pointer to the texture attached to front plate.
*/
FbxTexture* GetForegroundTexture() const;
/** Front and BackPlane distance modes.
* \see SetBackPlaneDistanceMode and GetBackPlaneDistanceMode.
*/
enum EFrontBackPlaneDistanceMode
{
eRelativeToInterest, //!< The back plane distance is measured in relation to the camera interest.
eRelativeToCamera //!< The back plane distance is measured in relation to the camera.
};
/** Set the back plane distance mode.
* \param pMode The back plane distance mode to set.
*/
void SetBackPlaneDistanceMode(EFrontBackPlaneDistanceMode pMode);
/** Get the back plane distance mode.
* \return Return the back plane distance mode.
*/
EFrontBackPlaneDistanceMode GetBackPlaneDistanceMode() const;
/** Set the front plane distance from the camera. The the absolute position of the plane must be calculated
* by taking into consideration of the FrontPlaneDistanceMode.
* \param pDistance The front plane distance value.
* \remarks It is the responsibility of the client application to ensure that this plane position is
* within the frustum boundaries.
*/
void SetFrontPlaneDistance(double pDistance);
/** Get the front plane distance value.
* \return double The front plane distance value.
*/
double GetFrontPlaneDistance() const;
/** Set the front plane distance mode.
* \param pMode The front plane distance mode to set.
*/
void SetFrontPlaneDistanceMode(EFrontBackPlaneDistanceMode pMode);
/** Get the front plane distance mode flag.
* \return The front plane distance mode.
*/
EFrontBackPlaneDistanceMode GetFrontPlaneDistanceMode() const;
/** Front/back plane display modes.
*/
enum EFrontBackPlaneDisplayMode
{
ePlanesDisabled, //!< Disables the front/back plane whether a texture is being projected or not.
ePlanesAlways, //!< Always shows the front/back plane, even if no texture has been added.
ePlanesWhenMedia //!< Shows the front/back plane only if a texture has been added.
};
/** Set the front plane display mode. This mode can be used by the client application to
* decide under which circumstance the front plane should be drawn in the viewport.
* \param pMode The front/back plane display mode.
*/
void SetViewFrustumFrontPlaneMode(EFrontBackPlaneDisplayMode pMode);
/** Get the front plane display mode.
* \return The front/back plane display mode.
*/
EFrontBackPlaneDisplayMode GetViewFrustumFrontPlaneMode() const;
/** Set the back plane display mode. This mode can be used by the client application to
* decide under which circumstance the back plane should be drawn in the viewport.
* \param pMode The front/back plane display mode.
*/
void SetViewFrustumBackPlaneMode(EFrontBackPlaneDisplayMode pMode);
/** Get the back plane display mode.
* \return The front/back plane display mode.
*/
EFrontBackPlaneDisplayMode GetViewFrustumBackPlaneMode() const;
//@}
/**
* \name Camera View Functions
* It is the responsibility of the client application to perform the required tasks according to the state
* of the options that are either set or returned by these methods.
*/
//@{
/** Change the camera interest visibility flag.
* \param pEnable Set to \c true if the camera interest is shown, \c false otherwise.
*/
void SetViewCameraInterest(bool pEnable);
/** Get current visibility state of the camera interest.
* \return \c true if the camera interest is shown, or \c false if hidden.
*/
bool GetViewCameraInterest() const;
/** Change the camera near and far planes visibility flag.
* \param pEnable Set to \c true if the near and far planes are shown, \c false otherwise.
*/
void SetViewNearFarPlanes(bool pEnable);
/** Get current visibility state of the camera near and far planes.
* \return \c true if the near and far planes are shown, \c false otherwise.
*/
bool GetViewNearFarPlanes() const;
/** Camera safe area display styles.
*/
enum ESafeAreaStyle
{
eSafeAreaRound, //!< Rounded safe area.
eSafeAreaSquare //!< Square safe area.
};
//@}
/**
* \name Render Functions
* It is the responsibility of the client application to perform the required tasks according to the state
* of the options that are either set or returned by these methods.
*/
//@{
/** Render options usage time.
*/
enum ERenderOptionsUsageTime
{
eInteractive, //!< To render in real time.
eOnDemand //!< Only render when it is asked.
};
/** Anti-aliasing methods.
*/
enum EAntialiasingMethod
{
eAAOversampling, //!< To do anti-aliasing by oversampling.
eAAHardware //!< To do anti-aliasing by hardware.
};
/** Oversampling types for anti-aliasing.
*/
enum ESamplingType
{
eSamplingUniform, /*!< The Uniform method samples each pixel at the same location.
The pixel is divided into equal parts, and each part is sampled.
The number of samples determines the number of times the pixel is divided. */
eSamplingStochastic /*!< The Stochastic method randomly samples each pixel.
This produces an accurate color using a small number of samples. */
};
/** Camera focus sources, that is the focal point for the depth of field.
* \see FocusDistance.
*/
enum EFocusDistanceSource
{
eFocusSrcCameraInterest, /*!< Base the depth of field on the camera interest. Models at the camera interest are in focus.
As you move toward or away from the camera interest, models become increasingly blurred. */
eFocusSpecificDistance //!< Base the depth of field on a point defined by a specific distance from the camera interest.
};
//@}
//! \name Utility Functions.
//@{
/** Evaluate the camera position (eye).
* \param pTime The time at which the camera should be evaluated.
* \return The camera position evaluated from property value and animation. */
FbxVector4 EvaluatePosition(const FbxTime& pTime=FBXSDK_TIME_ZERO) const;
/** Evaluate the camera target position (look at).
* \param pTime The time at which the camera should be evaluated.
* \return The camera target position evaluated from property value and animation. */
FbxVector4 EvaluateLookAtPosition(const FbxTime& pTime=FBXSDK_TIME_ZERO) const;
/** Evaluate the camera up direction, taking target up objects into consideration.
* \param pCameraPosition The camera current position. You can retrieve this with FbxCamera::EvaluatePosition().
* \param pLookAtPosition The camera target position. you can retrieve this with FbxCamera::EvaluateLookAtPosition().
* \param pTime The time at which the camera should be evaluated.
* \return The camera up direction vector based on provided information. */
FbxVector4 EvaluateUpDirection(const FbxVector4& pCameraPosition, const FbxVector4& pLookAtPosition, const FbxTime& pTime=FBXSDK_TIME_ZERO) const;
/** Compute the camera projection matrix.
* \param pWidth The width of the output frame.
* \param pHeight The height of the output frame.
* \param pVerticalFOV Calculate FOV vertically (based on height) if true or horizontally (based on width) if false (Note: Only applicable in perspective proj).
* \return The camera projection matrix, or the default identity matrix in case of wrong camera parameters. */
FbxMatrix ComputeProjectionMatrix(const int pWidth, const int pHeight, const bool pVerticalFOV = true) const;
/** Determine if the given bounding box is in the camera's view. The input points do not need to be ordered in any particular way.
* \param pWorldToScreen The world to screen transformation. Please refer to FbxCamera::ComputeWorldToScreen.
* \param pWorldToCamera The world to camera transformation. Inverse of the matrix returned from FbxAnimEvaluator::GetNodeGlobalTransform is suitable.
* Please refer to FbxScene::GetEvaluator and FbxAnimEvaluator::GetNodeGlobalTransform.
* \param pPoints 8 corners of the bounding box.
* \return \c true if any of the given points are in the camera's view, \c false otherwise. */
bool IsBoundingBoxInView(const FbxMatrix& pWorldToScreen, const FbxMatrix& pWorldToCamera, const FbxVector4 pPoints[8]) const;
/** Determine if the given 3d point is in the camera's view.
* \param pWorldToScreen The world to screen transformation. Please refer to FbxCamera::ComputeWorldToScreen.
* \param pWorldToCamera The world to camera transformation. Inverse of the matrix returned from FbxAnimEvaluator::GetNodeGlobalTransform is suitable.
* Please refer to FbxScene::GetEvaluator and FbxAnimEvaluator::GetNodeGlobalTransform.
* \param pPoint World-space point to test.
* \return \c true if the given point is in the camera's view, \c false otherwise. */
bool IsPointInView(const FbxMatrix& pWorldToScreen, const FbxMatrix& pWorldToCamera, const FbxVector4& pPoint) const;
/** Compute world space to screen space transformation matrix.
* \param pPixelHeight The pixel height of the output image.
* \param pPixelWidth The pixel height of the output image.
* \param pWorldToCamera The world to camera affine transformation matrix.
* \return The world to screen space matrix, or the identity matrix on error. */
FbxMatrix ComputeWorldToScreen(int pPixelWidth, int pPixelHeight, const FbxAMatrix& pWorldToCamera) const;
/** Compute screen space to world space ray direction.
* \param pX The horizontal screen coordinate.
* \param pY The vertical screen coordinate.
* \param pWidth The width of the viewport in pixels.
* \param pHeight The height of the viewport in pixels.
* \param pTime The time to use to evaluate the camera's view matrix.
* \return a normalized vector corresponding to the ray direction. */
FbxVector4 ComputeScreenToWorld(float pX, float pY, float pWidth, float pHeight, const FbxTime& pTime=FBXSDK_TIME_INFINITE) const;
//@}
//////////////////////////////////////////////////////////////////////////
//
// Properties
//
//////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------
// Geometrical
// -----------------------------------------------------------------------
/** This property handles the camera's position (XYZ coordinates).
*
* To access this property do: Position.Get().
* To set this property do: Position.Set(FbxDouble3).
*
* \remarks Default Value is (0.0, 0.0, 0.0).
*/
FbxPropertyT<FbxDouble3> Position;
/** This property handles the camera's Up Vector (XYZ coordinates).
*
* To access this property do: UpVector.Get().
* To set this property do: UpVector.Set(FbxDouble3).
*
* \remarks Default Value is (0.0, 1.0, 0.0).
*/
FbxPropertyT<FbxDouble3> UpVector;
/** This property handles the default point (XYZ coordinates) the camera is looking at.
*
* To access this property do: InterestPosition.Get().
* To set this property do: InterestPosition.Set(FbxDouble3).
*
* \remarks During the computations of the camera position
* and orientation, this property is overridden by the
* position of a valid target in the parent node.
*
* \remarks Default Value is (0.0, 0.0, 0.0).
*/
FbxPropertyT<FbxDouble3> InterestPosition;
/** This property handles the camera roll angle in degrees.
*
* To access this property do: Roll.Get().
* To set this property do: Roll.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> Roll;
/** This property handles the camera optical center X, in pixels.
* It sets horizontal offset of the optical center.
* When the camera's aperture mode is set to \e eVertical, this property has no effect.
*
* To access this property do: OpticalCenterX.Get().
* To set this property do: OpticalCenterX.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> OpticalCenterX;
/** This property handles the camera optical center Y, in pixels.
* It sets the vertical offset of the optical center.
* When the camera's aperture mode is set to \e eHorizontal, this property has no effect.
*
* To access this property do: OpticalCenterY.Get().
* To set this property do: OpticalCenterY.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> OpticalCenterY;
/** This property handles the RGB values of the camera's background color.
*
* To access this property do: BackgroundColor.Get().
* To set this property do: BackgroundColor.Set(FbxDouble3).
*
* Default value is black (0, 0, 0)
*/
FbxPropertyT<FbxDouble3> BackgroundColor;
/** When modeling 3D objects, you often need to review or evaluate your models during the creation process.
* You may create a camera with turn table animation to view your models in 360 or certain degrees.
* This property handles the camera's turn table angle in degrees.
*
* To access this property do: TurnTable.Get().
* To set this property do: TurnTable.Set(FbxDouble).
*
* Default value is 0.
*/
FbxPropertyT<FbxDouble> TurnTable;
/** This property handles a flag that indicates if the camera displays the
* Turn Table icon or not.
*
* To access this property do: DisplayTurnTableIcon.Get().
* To set this property do: DisplayTurnTableIcon.Set(FbxBool).
*
* Default value is false (no display).
*/
FbxPropertyT<FbxBool> DisplayTurnTableIcon;
// -----------------------------------------------------------------------
// Motion Blur
// -----------------------------------------------------------------------
/** This property handles a flag that indicates if the camera uses
* motion blur or not.
*
* To access this property do: UseMotionBlur.Get().
* To set this property do: UseMotionBlur.Set(FbxBool).
*
* Default value is false (do not use motion blur).
*/
FbxPropertyT<FbxBool> UseMotionBlur;
/** This property handles a flag that indicates if the camera uses
* real time motion blur or not.
*
* To access this property do: UseRealTimeMotionBlur.Get().
* To set this property do: UseRealTimeMotionBlur.Set(FbxBool).
*
* Default value is false (use real time motion blur).
*/
FbxPropertyT<FbxBool> UseRealTimeMotionBlur;
/** This property handles the camera's motion blur intensity (in pixels).
*
* To access this property do: MotionBlurIntensity.Get().
* To set this property do: MotionBlurIntensity.Set(FbxDouble).
*
* Default value is 1.0.
*/
FbxPropertyT<FbxDouble> MotionBlurIntensity;
// -----------------------------------------------------------------------
// Optical
// -----------------------------------------------------------------------
/** This property handles the camera's aspect ratio mode.
*
* \remarks This property is read-only.
* \remarks Please use function SetAspect() if you want to change its value.
*
* Default value is eWindowSize.
*
*/
FbxPropertyT<EAspectRatioMode> AspectRatioMode;
/** This property handles the camera's aspect width.
*
* \remarks This property is read-only.
* \remarks Please use function SetAspect() if you want to change its value.
*
* Default value is 320.
*/
FbxPropertyT<FbxDouble> AspectWidth;
/** This property handles the camera's aspect height.
*
* \remarks This property is read-only.
* \remarks Please use function SetAspect() if you want to change its value.
*
* Default value is 200.
*/
FbxPropertyT<FbxDouble> AspectHeight;
/** This property handles the pixel aspect ratio.
*
* \remarks This property is read-only.
* \remarks Please use function SetPixelRatio() if you want to change its value.
*
* Default value is 1.
* \remarks Value range is [0.050, 20.0].
*/
FbxPropertyT<FbxDouble> PixelAspectRatio;
/** This property handles the aperture mode.
*
* To access this property do: ApertureMode.Get().
* To set this property do: ApertureMode.Set(EApertureMode).
*
* Default value is eVertical.
*/
FbxPropertyT<EApertureMode> ApertureMode;
/** This property handles the gate fit mode.
* To control the size of the resolution gate relative to the film gate.
* If the resolution gate and the film gate have the same aspect ratio, then the property has no effect.
*
* To access this property do: GateFit.Get().
* To set this property do: GateFit.Set(EGateFit).
*
* Default value is eFitNone.
*/
FbxPropertyT<EGateFit> GateFit;
/** This property handles the field of view in degrees.
*
* To access this property do: FieldOfView.Get().
* To set this property do: FieldOfView.Set(FbxDouble).
*
* \remarks This property has meaning only when
* property ApertureMode equals eHorizontal or eVertical.
*
* \remarks Default value is 40.
* \remarks Value range is [1.0, 179.0].
*/
FbxPropertyT<FbxDouble> FieldOfView;
/** This property handles the X (horizontal) field of view in degrees.
*
* To access this property do: FieldOfViewX.Get().
* To set this property do: FieldOfViewX.Set(FbxDouble).
*
* \remarks This property has meaning only when
* property ApertureMode equals eHorizAndVert.
*
* Default value is 1.
* \remarks Value range is [1.0, 179.0].
*/
FbxPropertyT<FbxDouble> FieldOfViewX;
/** This property handles the Y (vertical) field of view in degrees.
*
* To access this property do: FieldOfViewY.Get().
* To set this property do: FieldOfViewY.Set(FbxDouble).
*
* \remarks This property has meaning only when
* property ApertureMode equals eHorizAndVert.
*
* \remarks Default value is 1.
* \remarks Value range is [1.0, 179.0].
*/
FbxPropertyT<FbxDouble> FieldOfViewY;
/** This property handles the focal length (in millimeters).
*
* To access this property do: FocalLength.Get().
* To set this property do: FocalLength.Set(FbxDouble).
*
* Default value is the result of ComputeFocalLength(40.0).
*/
FbxPropertyT<FbxDouble> FocalLength;
/** This property handles the camera's format.
*
* To access this property do: CameraFormat.Get().
* To set this property do: CameraFormat.Set(EFormat).
*
* \remarks This property is read-only.
* \remarks Please use function SetFormat() if you want to change its value.
*
* Default value is eCustomFormat.
*/
FbxPropertyT<EFormat> CameraFormat;
// -----------------------------------------------------------------------
// Frame
// -----------------------------------------------------------------------
/** This property stores a flag that indicates to draw a border with color around the camera's viewable area or not.
* To access this property do: UseFrameColor.Get().
* To set this property do: UseFrameColor.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> UseFrameColor;
/** This property is used to define the color of the border around the camera view.
*
* To access this property do: FrameColor.Get().
* To set this property do: FrameColor.Set(FbxDouble3).
*
* Default value is (0.3, 0.3, 0.3).
*/
FbxPropertyT<FbxDouble3> FrameColor;
// -----------------------------------------------------------------------
// On Screen Display
// -----------------------------------------------------------------------
/** This property handles the flag to show the camera's name or not.
*
* To access this property do: ShowName.Get().
* To set this property do: ShowName.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> ShowName;
/** This property handles the flag to show info on moving or not.
*
* To access this property do: ShowInfoOnMoving.Get().
* To set this property do: ShowInfoOnMoving.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> ShowInfoOnMoving;
/** This property handles the flag to draw floor grid or not.
*
* To access this property do: ShowGrid.Get().
* To set this property do: ShowGrid.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> ShowGrid;
/** This property handles the flag to show optical center or not.
*
* To access this property do: ShowOpticalCenter.Get().
* To set this property do: ShowOpticalCenter.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> ShowOpticalCenter;
/** This property handles the flag to show the camera's sight line or not.
* When the camera is revolved about the center of interest in the perspective view,
* the angle of a camera's sight line relative to a plane perpendicular to the ground plane is referred to as its azimuth;
* and the angle of a camera's sight line relative to the ground plane is referred to as its elevation;
*
* To access this property do: ShowAzimut.Get().
* To set this property do: ShowAzimut.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> ShowAzimut;
/** This property handles the flag to show time code or not.
*
* To access this property do: ShowTimeCode.Get().
* To set this property do: ShowTimeCode.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> ShowTimeCode;
/** This property handles the flag to show audio or not.
*
* To access this property do: ShowAudio.Get().
* To set this property do: ShowAudio.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> ShowAudio;
/** This property handles audio color.
*
* To access this property do: AudioColor.Get().
* To set this property do: AudioColor.Set(FbxDouble3).
*
* Default value is (0.0, 1.0, 0.0).
*/
FbxPropertyT<FbxDouble3> AudioColor;
// -----------------------------------------------------------------------
// Clipping Planes
// -----------------------------------------------------------------------
/** This property handles the near plane distance.
*
* \remarks This property is read-only.
* \remarks Please use function SetNearPlane() if you want to change its value.
*
* Default value is 10.
* \remarks Value range is [0.001, 600000.0].
*/
FbxPropertyT<FbxDouble> NearPlane;
/** This property handles the far plane distance.
*
* \remarks This property is read-only.
* \remarks Please use function SetFarPlane() if you want to change its value.
*
* Default value is 4000.
* \remarks Value range is [0.001, 600000.0].
*/
FbxPropertyT<FbxDouble> FarPlane;
/** This property indicates that the clip planes should be automatically computed or not.
*
* To access this property do: AutoComputeClipPlanes.Get().
* To set this property do: AutoComputeClipPlanes.Set(FbxBool).
*
* When this property is set to true, the NearPlane and FarPlane values are
* ignored. Note that not all applications support this flag.
*/
FbxPropertyT<FbxBool> AutoComputeClipPlanes;
// -----------------------------------------------------------------------
// Camera Film Setting
// -----------------------------------------------------------------------
/** This property handles the film aperture width (in inches).
*
* \remarks This property is read-only.
* \remarks Please use function SetApertureWidth()
* or SetApertureFormat() if you want to change its value.
*
* Default value is 0.8160.
* \remarks Value range is [0.0001, +inf).
*/
FbxPropertyT<FbxDouble> FilmWidth;
/** This property handles the film aperture height (in inches).
*
* \remarks This property is read-only.
* \remarks Please use function SetApertureHeight()
* or SetApertureFormat() if you want to change its value.
*
* Default value is 0.6120.
* \remarks Value range is [0.0001, +inf).
*/
FbxPropertyT<FbxDouble> FilmHeight;
/** This property handles the film aperture aspect ratio.
*
* \remarks This property is read-only.
* \remarks Please use function SetApertureFormat() if you want to change its value.
*
* Default value is (FilmWidth / FilmHeight).
* \remarks Value range is [0.0001, +inf).
*/
FbxPropertyT<FbxDouble> FilmAspectRatio;
/** This property handles the film aperture squeeze ratio.
*
* \remarks This property is read-only.
* \remarks Please use function SetSqueezeRatio()
* or SetApertureFormat() if you want to change its value.
*
* Default value is 1.0.
* \remarks Value range is [0.0001, +inf).
*/
FbxPropertyT<FbxDouble> FilmSqueezeRatio;
/** This property handles the film aperture format.
*
* \remarks This property is read-only.
* \remarks Please use function SetApertureFormat()
* if you want to change its value.
*
* Default value is eCustomAperture.
*/
FbxPropertyT<EApertureFormat> FilmFormat;
/** This property handles the horizontal offset from the center of the film aperture,
* defined by the film height and film width. The offset is measured in inches.
*
* To access this property do: FilmOffsetX.Get().
* To set this property do: FilmOffsetX.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> FilmOffsetX;
/** This property handles the vertical offset from the center of the film aperture,
* defined by the film height and film width. The offset is measured
* in inches.
*
* To access this property do: FilmOffsetY.Get().
* To set this property do: FilmOffsetY.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> FilmOffsetY;
/** This property handles the pre-scale value.
* The value is multiplied against the computed projection matrix.
* It is applied before the film roll.
*
* To access this property do: PreScale.Get().
* To set this property do: PreScale.Set(FbxDouble).
*
* Default value is 1.0.
*/
FbxPropertyT<FbxDouble> PreScale;
/** This property handles the horizontal film horizontal translation.
* To access this property do: FilmTranslateX.Get().
* To set this property do: FilmTranslateX.Set(FbxDouble).
* Default value is 0.0
*/
FbxPropertyT<FbxDouble> FilmTranslateX;
/** This property handles the vertical film translation.
*
* To access this property do: FilmTranslateY.Get().
* To set this property do: FilmTranslateY.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> FilmTranslateY;
/** This property handles the horizontal pivot point used for rotating the film back.
*
* To access this property do: FilmRollPivotX.Get().
* To set this property do: FilmRollPivotX.Set(FbxDouble).
*
* Default value is 0.0.
* \remarks FilmRollPivot value is used to compute the film roll matrix, which is a component of the post projection matrix.
*/
FbxPropertyT<FbxDouble> FilmRollPivotX;
/** This property handles the vertical pivot point used for rotating the film back.
*
* To access this property do: FilmRollPivotY.Get().
* To set this property do: FilmRollPivotY.Set(FbxDouble).
*
* Default value is 0.0.
* \remarks FilmRollPivot value is used to compute the film roll matrix, which is a component of the post projection matrix.
*/
FbxPropertyT<FbxDouble> FilmRollPivotY;
/** This property handles the amount of rotation around the film back.
* The roll value is specified in degrees.
*
* To access this property do: FilmRollValue.Get().
* To set this property do: FilmRollValue.Set(FbxDouble).
*
* Default value is 0.0.
* \remarks The rotation occurs around the specified pivot point,
* this value is used to compute a film roll matrix, which is a component of the post-projection matrix.
*/
FbxPropertyT<FbxDouble> FilmRollValue;
/** This property handles how the roll is applied with respect to the pivot value.
* eRotateFirst The film back is first rotated then translated by the pivot point value.
* eTranslateFirst The film back is first translated then rotated by the film roll value.
*
* To access this property do: FilmRollOrder.Get().
* To set this property do: FilmRollOrder.Set(EFilmRollOrder).
*
* Default value is eRotateFirst.
*/
FbxPropertyT<EFilmRollOrder> FilmRollOrder ;
// -----------------------------------------------------------------------
// Camera View Widget Option
// -----------------------------------------------------------------------
/** This property handles the camera's look-at flag.
* If this flag is on, the camera will look at the camera interest.
*
* To access this property do: ViewCameraToLookAt.Get().
* To set this property do: ViewCameraToLookAt.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> ViewCameraToLookAt;
/** This property handles to display the near and far plane or not.
*
* To access this property do: ViewFrustumNearFarPlane.Get().
* To set this property do: ViewFrustumNearFarPlane.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> ViewFrustumNearFarPlane;
/** This property handles the back plane display mode.
*
* To access this property do: ViewFrustumBackPlaneMode.Get().
* To set this property do: ViewFrustumBackPlaneMode.Set(EFrontBackPlaneDisplayMode).
*
* Default value is ePlanesWhenMedia.
*/
FbxPropertyT<EFrontBackPlaneDisplayMode> ViewFrustumBackPlaneMode;
/** This property handles the back plane distance.
*
* To access this property do: BackPlaneDistance.Get().
* To set this property do: BackPlaneDistance.Set(FbxDouble).
*
* Default value is 100.0.
*/
FbxPropertyT<FbxDouble> BackPlaneDistance;
/** This property handles the back plane distance mode.
*
* To access this property do: BackPlaneDistanceMode.Get().
* To set this property do: BackPlaneDistanceMode.Set(EFrontBackPlaneDistanceMode).
*
* Default value is eRelativeToInterest.
*/
FbxPropertyT<EFrontBackPlaneDistanceMode> BackPlaneDistanceMode;
/** This property handles the front plane mode.
*
* To access this property do: ViewFrustumFrontPlaneMode.Get().
* To set this property do: ViewFrustumFrontPlaneMode.Set(EFrontBackPlaneDisplayMode).
*
* Default value is ePlanesWhenMedia.
*/
FbxPropertyT<EFrontBackPlaneDisplayMode> ViewFrustumFrontPlaneMode;
/** This property handles the front plane distance.
*
* To access this property do: FrontPlaneDistance.Get().
* To set this property do: FrontPlaneDistance.Set(FbxDouble).
*
* Default value is 100.0.
*/
FbxPropertyT<FbxDouble> FrontPlaneDistance;
/** This property handles the front plane distance mode.
*
* To access this property do: FrontPlaneDistanceMode.Get().
* To set this property do: FrontPlaneDistanceMode.Set(EFrontBackPlaneDistanceMode).
*
* Default value is eRelativeToInterest.
*/
FbxPropertyT<EFrontBackPlaneDistanceMode> FrontPlaneDistanceMode;
// -----------------------------------------------------------------------
// Camera Lock Mode
// -----------------------------------------------------------------------
/** This property handles the flag to lock the camera's navigation.
* When this flag is on, the camera's view can not be changed anymore.
* To access this property do: LockMode.Get().
* To set this property do: LockMode.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> LockMode;
/** This property handles the flag to lock the camera interest's navigation.
* When this flag is one, the position of the camera interest is locked.
* To access this property do: LockInterestNavigation.Get().
* To set this property do: LockInterestNavigation.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> LockInterestNavigation;
// -----------------------------------------------------------------------
// Background Image Display Options
// -----------------------------------------------------------------------
/** This property handles the fit image flag of back plane.
*
* To access this property do: BackPlateFitImage.Get().
* To set this property do: BackPlateFitImage.Set(FbxBool).
*
* Default value is false.
* \see SetFitImage and GetFitImage.
*/
FbxPropertyT<FbxBool> BackPlateFitImage;
/** This property handles the crop flag of back plane.
*
* To access this property do: BackPlateCrop.Get().
* To set this property do: BackPlateCrop.Set(FbxBool).
*
* Default value is false.
* \see SetCrop and GetCrop.
*/
FbxPropertyT<FbxBool> BackPlateCrop;
/** This property handles the center flag of back plane.
*
* To access this property do: BackPlateCenter.Get().
* To set this property do: BackPlateCenter.Set(FbxBool).
*
* Default value is true.
* see SetCenter and GetCenter.
*/
FbxPropertyT<FbxBool> BackPlateCenter;
/** This property handles the keep ratio flag of back plane.
*
* To access this property do: BackPlateKeepRatio.Get().
* To set this property do: BackPlateKeepRatio.Set(FbxBool).
*
* Default value is true.
* \see SetKeepRatio and GetKeepRatio.
*/
FbxPropertyT<FbxBool> BackPlateKeepRatio;
/** This property handles the background alpha threshold value.
*
* To access this property do: BackgroundAlphaTreshold.Get().
* To set this property do: BackgroundAlphaTreshold.Set(FbxDouble).
*
* Default value is 0.5.
*/
FbxPropertyT<FbxDouble> BackgroundAlphaTreshold;
/** This property handles the back plane offset X.
*
* To access this property do: BackPlaneOffsetX.Get().
* To set this property do: BackPlaneOffsetX.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> BackPlaneOffsetX;
/** This property handles the back plane offset Y.
*
* To access this property do: BackPlaneOffsetY.Get().
* To set this property do: BackPlaneOffsetY.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> BackPlaneOffsetY;
/** This property handles the back plane rotation.
*
* To access this property do: BackPlaneRotation.Get().
* To set this property do: BackPlaneRotation.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> BackPlaneRotation;
/** This property handles the back plane scaling X.
*
* To access this property do: BackPlaneScaleX.Get().
* To set this property do: BackPlaneScaleX.Set(FbxDouble).
*
* Default value is 1.0.
* \remarks The application manipulating the camera has to take into consideration of
* the BackPlateKeepRatio value too.
*/
FbxPropertyT<FbxDouble> BackPlaneScaleX;
/** This property handles the back plane scaling Y.
*
* To access this property do: BackPlaneScaleY.Get().
* To set this property do: BackPlaneScaleY.Set(FbxDouble).
*
* Default value is 1.0.
* \remarks The application manipulating the camera has to take into consideration of
* the BackPlateKeepRatio value too.
*/
FbxPropertyT<FbxDouble> BackPlaneScaleY;
/** This property handles the flag to show back plane or not.
*
* To access this property do: ShowBackPlate.Get().
* To set this property do: ShowBackPlate.Set(FbxBool).
*
* Default value is false.
* \remarks This replaces ForegroundTransparent.
*/
FbxPropertyT<FbxBool> ShowBackplate;
/** This property has the background texture connected to it.
*
* To access this property do: BackgroundTexture.Get().
* To set this property do: BackgroundTexture.Set().
*
* \remarks The background texture is connected as source object.
*/
FbxPropertyT<FbxReference> BackgroundTexture;
// -----------------------------------------------------------------------
// Foreground Image Display Options
// -----------------------------------------------------------------------
/** This property handles the fit image flag of front plate.
*
* To access this property do: FrontPlateFitImage.Get().
* To set this property do: FrontPlateFitImage.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> FrontPlateFitImage;
/** This property handles the crop flag of front plane.
*
* To access this property do: FrontPlateCrop.Get().
* To set this property do: FrontPlateCrop.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> FrontPlateCrop;
/** This property handles the center flag of front plane.
*
* To access this property do: FrontPlateCenter.Get().
* To set this property do: FrontPlateCenter.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> FrontPlateCenter;
/** This property handles the keep ratio flag of front plane.
*
* To access this property do: FrontPlateKeepRatio.Get().
* To set this property do: FrontPlateKeepRatio.Set(FbxBool).
*
* Default value is true.
*/
FbxPropertyT<FbxBool> FrontPlateKeepRatio;
/** This property handles the flag to show front plane or not.
*
* To access this property do: ShowFrontplate.Get().
* To set this property do: ShowFrontplate.Set(FbxBool).
*
* Default value is false.
* \remarks This replaces ForegroundTransparent.
*/
FbxPropertyT<FbxBool> ShowFrontplate;
/** This property handles the front plane offset X.
*
* To access this property do: FrontPlaneOffsetX.Get().
* To set this property do: FrontPlaneOffsetX.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> FrontPlaneOffsetX;
/** This property handles the front plane offset Y.
*
* To access this property do: FrontPlaneOffsetY.Get().
* To set this property do: FrontPlaneOffsetY.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> FrontPlaneOffsetY;
/** This property handles the front plane rotation.
*
* To access this property do: FrontPlaneRotation.Get().
* To set this property do: FrontPlaneRotation.Set(FbxDouble).
*
* Default value is 0.0.
*/
FbxPropertyT<FbxDouble> FrontPlaneRotation;
/** This property handles the front plane scaling X.
*
* To access this property do: FrontPlaneScaleX.Get().
* To set this property do: FrontPlaneScaleX.Set(FbxDouble).
*
* Default value is 1.0.
*/
FbxPropertyT<FbxDouble> FrontPlaneScaleX;
/** This property handles the front plane scaling Y.
*
* To access this property do: FrontPlaneScaleY.Get().
* To set this property do: FrontPlaneScaleY.Set(FbxDouble).
*
* Default value is 1.0.
*/
FbxPropertyT<FbxDouble> FrontPlaneScaleY;
/** This property has the foreground texture connected to it.
*
* To access this property do: ForegroundTexture.Get().
* To set this property do: ForegroundTexture.Set().
*
* \remarks The foreground texture is connected as source object.
*/
FbxPropertyT<FbxReference> ForegroundTexture;
/** This property handles the foreground image opacity value.
*
* To access this property do: ForegroundOpacity.Get().
* To set this property do: ForegroundOpacity.Set(FbxDouble).
*
* Default value is 1.0.
*/
FbxPropertyT<FbxDouble> ForegroundOpacity;
// -----------------------------------------------------------------------
// Safe Area
// -----------------------------------------------------------------------
/** This property handles the flag to display safe area or not.
*
* To access this property do: DisplaySafeArea.Get().
* To set this property do: DisplaySafeArea.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> DisplaySafeArea;
/** This property handles the flag display safe area on render or not.
*
* To access this property do: DisplaySafeAreaOnRender.Get().
* To set this property do: DisplaySafeAreaOnRender.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> DisplaySafeAreaOnRender;
/** This property handles the style to display safe area.
*
* To access this property do: SafeAreaDisplayStyle.Get().
* To set this property do: SafeAreaDisplayStyle.Set(ESafeAreaStyle).
*
* Default value is eSafeAreaSquare.
*/
FbxPropertyT<ESafeAreaStyle> SafeAreaDisplayStyle;
/** This property handles the display aspect ratio of safe area.
*
* To access this property do: SafeAreaDisplayStyle.Get().
* To set this property do: SafeAreaAspectRatio.Set(FbxDouble).
*
* Default value is 1.33333333333333.
*/
FbxPropertyT<FbxDouble> SafeAreaAspectRatio;
// -----------------------------------------------------------------------
// 2D Magnifier
// -----------------------------------------------------------------------
/** This property handles the flag to use 2d magnifier zoom or not.
* The 2D Magnifier lets you perform a 2D enlargement of the scene using the
* current camera without changing any camera settings.
*
* To access this property do: Use2DMagnifierZoom.Get().
* To set this property do: Use2DMagnifierZoom.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> Use2DMagnifierZoom;
/** This property handles the 2d magnifier zoom value.
*
* To access this property do: _2DMagnifierZoom.Get().
* To set this property do: _2DMagnifierZoom.Set(FbxDouble).
*
* Default value is 100.0.
*/
FbxPropertyT<FbxDouble> _2DMagnifierZoom;
/** This property handles the 2d magnifier X value.
*
* To access this property do: _2DMagnifierX.Get().
* To set this property do: _2DMagnifierX.Set(FbxDouble).
*
* Default value is 50.0.
*/
FbxPropertyT<FbxDouble> _2DMagnifierX;
/** This property handles the 2d magnifier Y value.
*
* To access this property do: _2DMagnifierY.Get().
* To set this property do: _2DMagnifierY.Set(FbxDouble).
*
* Default value is 50.0.
*/
FbxPropertyT<FbxDouble> _2DMagnifierY;
// -----------------------------------------------------------------------
// Projection Type: Ortho, Perspective
// -----------------------------------------------------------------------
/** This property handles the projection type.
*
* To access this property do: ProjectionType.Get().
* To set this property do: ProjectionType.Set(EProjectionType).
*
* Default value is ePerspective.
*/
FbxPropertyT<EProjectionType> ProjectionType;
/** This property handles the orthographic zoom value.
*
* To access this property do: OrthoZoom.Get().
* To set this property do: OrthoZoom.Set(FbxDouble).
*
* Default value is 1.0.
*/
FbxPropertyT<FbxDouble> OrthoZoom;
// -----------------------------------------------------------------------
// Depth Of Field & Anti Aliasing
// -----------------------------------------------------------------------
/** This property handles the flag to use real time Depth of Field and Anti-Aliasing or not.
*
* To access this property do: UseRealTimeDOFAndAA.Get().
* To set this property do: UseRealTimeDOFAndAA.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> UseRealTimeDOFAndAA;
/** This property handles the flag to use depth of field or not.
*
* To access this property do: UseDepthOfField.Get().
* To set this property do: UseDepthOfField.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> UseDepthOfField;
/** This property handles the focus source.
*
* To access this property do: FocusSource.Get().
* To set this property do: FocusSource.Set(EFocusDistanceSource).
*
* Default value is eFocusSrcCameraInterest.
* \see FocusDistance.
*/
FbxPropertyT<EFocusDistanceSource> FocusSource;
/** This property handles the focus angle (in degrees).
*
* To access this property do: FocusAngle.Get().
* To set this property do: FocusAngle.Set(FbxDouble).
*
* Default value is 3.5.
*/
FbxPropertyT<FbxDouble> FocusAngle;
/** This property handles the focus distance.
* Focus distance is the distance between the camera and the object on which the camera is focused.
* There are two possible sources for this distance.
* \see EFocusDistanceSource
*
* To access this property do: FocusDistance.Get().
* To set this property do: FocusDistance.Set(FbxDouble).
*
* Default value is 200.0.
*/
FbxPropertyT<FbxDouble> FocusDistance;
/** This property handles the flag to use anti aliasing or not.
*
* To access this property do: UseAntialiasing.Get().
* To set this property do: UseAntialiasing.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> UseAntialiasing;
/** This property handles the anti aliasing intensity.
*
* To access this property do: AntialiasingIntensity.Get().
* To set this property do: AntialiasingIntensity.Set(FbxDouble).
*
* Default value is 0.77777.
*/
FbxPropertyT<FbxDouble> AntialiasingIntensity;
/** This property handles the anti aliasing method.
*
* To access this property do: AntialiasingMethod.Get().
* To set this property do: AntialiasingMethod.Set(EAntialiasingMethod).
*
* Default value is eAAOversampling.
*/
FbxPropertyT<EAntialiasingMethod> AntialiasingMethod;
// -----------------------------------------------------------------------
// Accumulation Buffer
// -----------------------------------------------------------------------
/** This property handles the flag to use accumulation buffer or not.
*
* To access this property do: UseAccumulationBuffer.Get().
* To set this property do: UseAccumulationBuffer.Set(FbxBool).
*
* Default value is false.
*/
FbxPropertyT<FbxBool> UseAccumulationBuffer;
/** This property handles the frame sampling count.
*
* To access this property do: FrameSamplingCount.Get().
* To set this property do: FrameSamplingCount.Set(FbxInt).
*
* Default value is 7.
*/
FbxPropertyT<FbxInt> FrameSamplingCount;
/** This property handles the frame sampling type.
*
* To access this property do: FrameSamplingType.Get().
* To set this property do: FrameSamplingType.Set(ESamplingType).
*
* Default value is eSamplingStochastic.
*/
FbxPropertyT<ESamplingType> FrameSamplingType;
/*****************************************************************************************************************************
** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **
*****************************************************************************************************************************/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
FbxObject& Copy(const FbxObject& pObject) override;
protected:
void ConstructProperties(bool pForceSet) override;
FbxStringList GetTypeFlags() const override;
private:
double ComputePixelRatio(FbxUInt pWidth, FbxUInt pHeight, double pScreenRatio = 1.3333333333);
// Background Properties
FbxString mBackgroundMediaName;
FbxString mBackgroundFileName;
// Foreground Properties
FbxString mForegroundMediaName;
FbxString mForegroundFileName;
FbxVector4 mLastUp;
#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/
};
inline EFbxType FbxTypeOf(const FbxCamera::EAntialiasingMethod&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EApertureFormat&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EApertureMode&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EAspectRatioMode&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EFrontBackPlaneDisplayMode&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EFrontBackPlaneDistanceMode&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EPlateDrawingMode&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EFocusDistanceSource&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EFormat&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EGateFit&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EProjectionType&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::ERenderOptionsUsageTime&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::ESafeAreaStyle&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::ESamplingType&){ return eFbxEnum; }
inline EFbxType FbxTypeOf(const FbxCamera::EFilmRollOrder&){ return eFbxEnum; }
#include <fbxsdk/fbxsdk_nsend.h>
#endif /* _FBXSDK_SCENE_GEOMETRY_CAMERA_H_ */
| [
"nickhardeman@gmail.com"
] | nickhardeman@gmail.com |
f4841f6812e48e8ba6c036ef33a0da68ccf3aba8 | 8352635a95c36f77f6abbcb101caa26ce8f5507d | /bdsg/include/bdsg/graph_proxy.hpp | 0691e729ee5896f821d101f85b9511ae6dd029be | [
"MIT"
] | permissive | vgteam/libbdsg | 868524ed7d8a2f31a3a32a6daf68082ad31813c6 | 8e47864fbf6513d54810b1d16df38b1b4cffcdfe | refs/heads/master | 2023-08-14T01:37:27.676687 | 2023-06-15T22:35:17 | 2023-06-15T22:35:17 | 186,671,820 | 25 | 7 | MIT | 2023-06-15T22:35:18 | 2019-05-14T17:44:56 | C++ | UTF-8 | C++ | false | false | 3,628 | hpp | #ifndef BDSG_GRAPH_PROXY_HPP_INCLUDED
#define BDSG_GRAPH_PROXY_HPP_INCLUDED
/**
* \file graph_proxy.hpp
* Defines a mechanism for implementing a handle graph by using a contained
* object that actually does the work.
*/
#include <handlegraph/mutable_path_deletable_handle_graph.hpp>
#include <handlegraph/serializable_handle_graph.hpp>
namespace bdsg {
using namespace std;
using namespace handlegraph;
// !!!!!!!!!!!!!!!!!!!!!! MASSIVE HACK ALERT !!!!!!!!!!!!!!!!!!!!!!
// Binder can't properly bind any of these types if they define methods
// inherited from virtual base classes, for some reason. See
// <https://github.com/RosettaCommons/binder/issues/169>.
// So we code gen the types we need by including unguarded, fragmentary
// class-contents headers into several types of proxy.
// This is so we can achieve code sharing between different proxies with different feature sets, without using inheritance.
// Macros would be nicer, but thay can't easily be multi-line.
// The fragments are protected with an #ifdef BDSG_INSIDE_CLASS / #endif,
// because Binder will pick up on our using includes and put the same includes
// at the tops of its files, even if that's syntactically inadvisable. But they
// lack conventional include guards since we will include them multiple times.
// We also BINDER_IGNORE them to keep them out of the all-headers list, because
// it still tries to parse everything there.
/**
* Defines a proxy you can inherit to implement PathHandleGraph by referencing a
* different backing implementation, which implements the concept if not the
* interface.
*
* Can be multiple-inherited alongsize other proxies and will use the same
* backing implementation.
*/
template<typename BackingGraph>
struct PathHandleGraphProxy : public PathHandleGraph {
#define BDSG_INSIDE_CLASS
#include "bdsg/internal/graph_proxy_fragment.classfragment" // BINDER_IGNORE
#include "bdsg/internal/graph_proxy_handle_graph_fragment.classfragment" // BINDER_IGNORE
#include "bdsg/internal/graph_proxy_path_handle_graph_fragment.classfragment" // BINDER_IGNORE
#undef BDSG_INSIDE_CLASS
};
/**
* Defines a fully-featured GraphProxy that you can inherit from to implement
* MutablePathDeletableHandleGraph and SerializableHandleGraph from one backing
* object that need not implement either, as long as it satisfies the concept.
*/
template<typename BackingGraph>
struct GraphProxy : public MutablePathDeletableHandleGraph, public SerializableHandleGraph {
#define BDSG_INSIDE_CLASS
#include "bdsg/internal/graph_proxy_fragment.classfragment" // BINDER_IGNORE
#include "bdsg/internal/graph_proxy_handle_graph_fragment.classfragment" // BINDER_IGNORE
#include "bdsg/internal/graph_proxy_path_handle_graph_fragment.classfragment" // BINDER_IGNORE
#include "bdsg/internal/graph_proxy_mutable_path_deletable_handle_graph_fragment.classfragment" // BINDER_IGNORE
#include "bdsg/internal/graph_proxy_serializable_handle_graph_fragment.classfragment" // BINDER_IGNORE
#undef BDSG_INSIDE_CLASS
};
/**
* A GraphProxy over an object at a specific address. Must not outlive the
* backing object, and does not own it.
*/
template<typename BackingGraph>
class NonOwningGraphProxy : public GraphProxy<BackingGraph> {
public:
NonOwningGraphProxy(BackingGraph* implementation) : implementation(implementation) {
// Nothing to do!
}
BackingGraph* get() {
return implementation;
}
const BackingGraph* get() const {
return implementation;
}
protected:
BackingGraph* implementation;
};
}
#endif
| [
"anovak@soe.ucsc.edu"
] | anovak@soe.ucsc.edu |
b800e6fecc5bd90f79aedbb3aee6c1eb6eab45df | f9c231a866ef7138c033f301becbf24c8bdca633 | /Test8/LamLai/6c2.cpp | 20bbbabcab91419cadd005c38cc53e1b6bb14286 | [] | no_license | cuongnh28/DSAFall2019 | 3eef8f5e0e1cbe008bd304c847dd9abaa4ad144f | 2729d834b3c4a3560bf63aa6d1dcfc7457385246 | refs/heads/main | 2023-02-02T14:41:39.353309 | 2020-12-23T16:20:02 | 2020-12-23T16:20:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include<bits/stdc++.h>
using namespace std;
void Solve(){
int n; cin>>n;
long long tmp;
queue<long long> q;
q.push(9);
do{
tmp=q.front(); q.pop();
q.push(tmp*10);
q.push(tmp*10+9);
}while(tmp%n!=0);
cout<<tmp<<endl;
}
int main()
{
int t; cin>>t;
while(t--)
{
Solve();
}
}
| [
"hongcuongcl98@gmail.com"
] | hongcuongcl98@gmail.com |
3be3f1cb936babb200dffe46bf701a27260cda6c | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Database/APR/StorageSvc/StorageSvc/DbObjectSet.h | 4f2127b9afb24348ff094cb90f80d9cb4c5dd0b6 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,508 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// $Id: DbObjectSet.h 458019 2011-09-09 10:11:57Z mnowak $
//====================================================================
// DbDomainObj object definition
//--------------------------------------------------------------------
//
// Package : StorageSvc (The POOL project)
//
// @author M.Frank
//====================================================================
#ifndef POOL_DBDOMAINOBJ_H
#define POOL_DBDOMAINOBJ_H 1
#include "StorageSvc/pool.h"
#include <set>
/*
* POOL namespace declaration
*/
namespace pool {
// POOL forward declarations
class DbTypeInfo;
class DbObjectSetBase;
class DbObjectSetBase {
protected:
typedef void (*dtor_t)(void*);
/// Object destructor
dtor_t m_destructor;
/// Object type
const std::type_info& m_type;
/// Set of objects
std::set<void*> m_objects;
public:
/// Constructor
DbObjectSetBase(dtor_t dtor, const std::type_info& type);
/// Standard destructor
virtual ~DbObjectSetBase();
/// Printout
void printOut();
/// Remove single object
void removeObject(void* ptr);
};
/**@class DbObjectSet DbObjectSet.h src/DbObjectSet.h
Description:
Set to hold objects for memory tracing.
@author M.Frank
@version 1.0
*/
template <class T> class DbObjectSet : public DbObjectSetBase {
private:
static void __delete__(void* p) {
T* q=(T*)p;
if ( q ) delete q;
}
public:
/// Constructor
DbObjectSet();
/// Constructor with destroy function
DbObjectSet(dtor_t);
/// Standard destructor
virtual ~DbObjectSet();
/// Add object to set
void add(T* pObj);
/// Remove single object from set
void remove(T* pObj);
};
/// Constructor
template <class T> inline
DbObjectSet<T>::DbObjectSet()
: DbObjectSetBase(__delete__, typeid(T)) { }
/// Constructor
template <class T> inline
DbObjectSet<T>::DbObjectSet(dtor_t dt)
: DbObjectSetBase(dt, typeid(T)) { }
/// Standard destructor
template<class T> inline DbObjectSet<T>::~DbObjectSet() { }
/// Add object to set
template<class T> inline void DbObjectSet<T>::add(T* pObj) {
m_objects.insert(pObj);
}
/// Remove single object from set
template<class T> inline void DbObjectSet<T>::remove(T* pObj) {
removeObject(pObj);
}
} // End namespace pool
#endif // POOL_DBDOMAINOBJ_H
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
0ba562fd8902b537d2632c9ba5b6de7af73b91b2 | a5f1ce9455a0e3f3f29563ac792ad4acfb4302f7 | /SK하이닉스_면접대비/4_ans.cpp | 0cbbc92ce7af9596743a9ee615732045cb4c736e | [] | no_license | hohyunjun/Algorithm | ad426aa8efdc6db6ef8675d183b5da4ca634c4ff | 364811d90ad09d04240482f7e092a77cf9076482 | refs/heads/master | 2021-07-24T13:50:13.692339 | 2020-04-15T14:12:13 | 2020-04-15T14:12:13 | 139,689,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,332 | cpp | #include <iostream>
#include <vector>
#define MAX 8
using namespace std;
/*
4번.
최대 8자리의 숫자 배열이 주어지고, K라는 값이 주어진다.
숫자 배열의 각 원소를 1대 1로 swap하여 최소 횟수의 swap으로 모든 인접 원소 간 차이값이 K이하가 되도록 할 때,
최소 횟수 answer를 구하라.
K이하로 만드는 것이 불가능할 경우, answer는 -1을 반환한다.
*/
/*
1. 숫자 배열에 대한 순열 조합을 모두 구해보고, 그 중에서 조건을 만족하는 순열을 저장한다.
2. 저장된 각각의 순열에 대해서 원래 배열으로부터 몇 번의 최소 swap을 통해 해당 순열이 만들어지는지를 구하고, ans를 update한다.
** 최소 swap을 구하는 방법
- 첫번째 요소를 배열의 값으로, 두번째 요소를 배열 인덱스로 가지는 vector<pair<int,int>> 를 만든다.
- 위에서 만든 vector에서 swap을 연산할 최초 배열 input과 pair의 first 값이 같도록 vector를 정렬한다.
- i=0 부터 배열의 크기만큼 돌면서 pair.second(배열의 인덱스) 와 i 값이 같지 않을 경우, 요소가 원래 배열의 인덱스로 돌아갈 때까지 swapping을 계속 진행하면서 swap횟수를 샌다.
*/
// 입력값
int k, n;
vector<int> input(MAX);
bool visit[MAX];
vector<int> a(MAX);
vector<vector<int>> satisfying;
// 정답
int ans = -1;
// 모든 인접 원소 간 차이값이 K 이하인지 확인하는 함수
bool check(vector<int> b){
for(int i=0; i<n-1; i++){
if(abs(b[i] - b[i+1]) > k) return false;
}
return true;
}
// input 벡터에 대해 순열을 돌린 이후, 순열을 돌린 벡터가 조건을 만족할 경우 satisfying 벡터에 넣어준다.
void permut(int index, int m){
if(index == m){
if(check(a)){
satisfying.push_back(a);
}
return;
}
for(int i=0; i<m; i++){
if(visit[i]) continue;
a[index] = input[i];
visit[i] = true;
permut(index+1, m);
visit[i] = false;
}
}
// 최소스왑을 찾는 함수
void findMinSwap(vector<int> arr){
vector<pair<int,int>> vec(n);
for(int i=0; i<n; i++){
vec[i].first = arr[i];
vec[i].second = i;
}
vector<pair<int,int>> vec2(n);
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(input[i] == vec[j].first){
vec2[i] = vec[j];
break;
}
}
}
int ret = 0;
for(int i=0; i<n; i++){
if(vec2[i].second == i){
continue;
}else{
swap(vec2[i].first, vec2[vec2[i].second].first);
swap(vec2[i].second, vec2[vec2[i].second].second);
}
if(i != vec2[i].second){
--i;
}
ret++;
}
if(ans == -1){
ans = ret;
}else{
ans = min(ans, ret);
}
return;
}
int main(){
cin >> k >> n;
a.resize(n);
input.resize(n);
for(int i=0; i<n; i++){
cin >> input[i];
}
// 모든 순열을 구해보고, 조건을 만족하는 순열을 저장한다.
permut(0, n);
for(int i=0; i<satisfying.size(); i++){
findMinSwap(satisfying[i]);
}
cout << ans << '\n';
return 0;
} | [
"jhh5154@naver.com"
] | jhh5154@naver.com |
b673e3d04adf090133f68bc0d460eed2845b73ba | 1d9e9d4f416607453e7c91c9dc45205bd7cb9e14 | /iqc5/instrument/SerialPortDecode/Electrolyte/zsdec_psd/main.cpp | 61fa337ed1ec6d41b4fd153e1e7f046398530221 | [] | no_license | allan1234569/iqc5 | 5542f2efe3e6eae0a59110ec2863d9beeef8c1cf | 8a026564db0128005f90d3f7ca56787a7bcbbad3 | refs/heads/master | 2020-03-29T09:17:13.715443 | 2018-09-21T10:56:01 | 2018-09-21T10:56:01 | 149,750,494 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | cpp | #include "w_psd.h"
#include <QApplication>
#include "common.h"
#include "single_application.h"
int main(int argc, char *argv[])
{
SingleApplication a(argc, argv,"Electrolyte_PSD");
QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8"));
if (a.isRunning())
{
f_log("一个解码程序已经运行");
exit(1);
}
if (!f_init())
{
exit(1);
}
W_Psd w;
w.show();
return a.exec();
}
| [
"allan1234569@163.com"
] | allan1234569@163.com |
711a79edfdee176a227c6b63cc71e7bae497cf83 | b2988e7451589fe559d398a082b96901bcf9bd27 | /Merge_Sort.cpp | 0ab7a477ca0290a0365af300dad97fbab48120f3 | [] | no_license | Md-Shaquib/Data-Structure-Algorithm | 01d5754c35ad8e547f43e7240891d6976d60b9a4 | ac596826c7e95be61e08003d0dc4154eb172b567 | refs/heads/main | 2023-03-12T12:39:49.448035 | 2021-02-25T05:47:03 | 2021-02-25T05:47:03 | 336,694,158 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | cpp | #include<bits/stdc++.h>
using namespace std;
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
// Create temp arrays
int L[n1], R[n2];
// Copy data to temp arrays L[] and R[]
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
// Merge the temp arrays back into arr[l..r]
// Initial index of first subarray
int i = 0;
// Initial index of second subarray
int j = 0;
// Initial index of merged subarray
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of
// L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of
// R[], if there are any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// l is for left index and r is
// right index of the sub-array
// of arr to be sorted */
void mergeSort(int arr[],int l,int r){
if(l>=r){
return;//returns recursively
}
int m =l+ (r-l)/2;
mergeSort(arr,l,m);
mergeSort(arr,m+1,r);
merge(arr,l,m,r);
}
// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
for (int i = 0; i < size; i++)
cout << A[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
cout << "Given array is \n";
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
cout << "\nSorted array is \n";
printArray(arr, arr_size);
return 0;
}
// This code is contributed by Mayank Tyagi
| [
"noreply@github.com"
] | Md-Shaquib.noreply@github.com |
61e866c6bae934be7c946eca2484b0dd6cab3552 | fd2ddfccadbd932452faf9ac47fb11938260660e | /Codeforces/408_div2/D.cpp | 969a5f3664571f41c7319b0e88b3d3948452072f | [] | no_license | cqj8660/Code_Record | 450c827bf9a98ac8860abafc8fb811b6ee8c221a | 6d148810ce3b0c7b545a4d3061dbe8780626bd9d | refs/heads/master | 2021-12-22T08:37:01.621325 | 2021-11-19T08:09:26 | 2021-11-19T08:09:26 | 149,244,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | cpp | #include <bits/stdc++.h>
#define pii pair<int, int>
using namespace std;
const int maxn = 3e5 + 10;
vector<pii> g[maxn];
bool vis[maxn], vis_edge[maxn];
vector<int> ans;
queue<pii> T;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, k, d, i;
cin >> n >> k >> d;
for(int j = 0; j < k; j++)
{
cin >> i;
T.push(pii(i, 0));
vis[i] = 1;
}
for(int i = 1; i < n; i++)
{
int u, v;
cin >> u >> v;
g[u].push_back(make_pair(v, i));
g[v].push_back(make_pair(u, i));
}
while(T.size())
{
pii now = T.front();
T.pop();
if(now.second == d)
continue;
for(auto id: g[now.first])
if(!vis[id.first])
{
vis[id.first] = 1;
T.push(pii(id.first, now.second + 1));
vis_edge[id.second] = 1;
}
}
for(int i = 1; i <= n - 1; i++)
if(!vis_edge[i])
ans.push_back(i);
cout << ans.size() << endl;
for(auto idx: ans)
cout << idx << ' ';
cout << endl;
return 0;
}
| [
"cqj8660@163.com"
] | cqj8660@163.com |
d8116be2d0adceca57669425e51f5689b2ef8dca | 65e3391b6afbef10ec9429ca4b43a26b5cf480af | /HLT/trigger/AliHLTEmcalElectronMonitor.h | 561da2850ee8e8cab6d2141bb764411c2b334fc5 | [
"GPL-1.0-or-later"
] | permissive | alisw/AliRoot | c0976f7105ae1e3d107dfe93578f819473b2b83f | d3f86386afbaac9f8b8658da6710eed2bdee977f | refs/heads/master | 2023-08-03T11:15:54.211198 | 2023-07-28T12:39:57 | 2023-07-28T12:39:57 | 53,312,169 | 61 | 299 | BSD-3-Clause | 2023-07-28T13:19:50 | 2016-03-07T09:20:12 | C++ | UTF-8 | C++ | false | false | 817 | h | #ifndef ALIHLTEMCALELECTRONMONITOR_H
#define ALIHLTEMCALELECTRONMONITOR_H
#include "TH1F.h"
#include "TObjArray.h"
#include "TString.h"
#include "AliHLTScalars.h"
class AliHLTEmcalElectronMonitor : public TObject
{
public:
// constructor
AliHLTEmcalElectronMonitor();
// destructor
virtual ~AliHLTEmcalElectronMonitor();
// make histos
Int_t MakeHisto(AliHLTScalars *scalar);
// retrieve histograms
TObjArray* GetHistograms();
private:
TObjArray *hList;
TH1F *hTracksPt;
TH1F *hClusterEn;
TH1F *hdEta;
TH1F *hdPhi;
TH1F *hdR;
TH1F *hEoverP;
AliHLTEmcalElectronMonitor(const AliHLTEmcalElectronMonitor &);
AliHLTEmcalElectronMonitor & operator = (const AliHLTEmcalElectronMonitor &);
ClassDef(AliHLTEmcalElectronMonitor, 0);
};
#endif
| [
"fronchet@f7af4fe6-9843-0410-8265-dc069ae4e863"
] | fronchet@f7af4fe6-9843-0410-8265-dc069ae4e863 |
a6dcf1ca632c1ea2dbcd63f545bb847819d6670a | 59d024ebb50697c773524e43cc47d071305de52d | /Motor2D/p2Defs.h | 14048f73716f5ebaee972a3c160240f2f805c6d5 | [] | no_license | traguill/Starcraft-Commandos | 1e4a358ce57af580e63725feca53c25d612db4d0 | 9c481b7a36b5e65888bb4ffc03f1dbc053531bc1 | refs/heads/master | 2021-01-17T18:58:41.055022 | 2016-05-30T21:32:34 | 2016-05-30T21:32:34 | 52,960,704 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | h | #ifndef __P2DEFS_H__
#define __P2DEFS_H__
#include <stdio.h>
#include <algorithm>
// NULL just in case ----------------------
#ifdef NULL
#undef NULL
#endif
#define NULL 0
// Deletes a buffer
#define RELEASE( x ) \
{ \
if( x != NULL ) \
{ \
delete x; \
x = NULL; \
} \
}
// Deletes an array of buffers
#define RELEASE_ARRAY( x ) \
{ \
if( x != NULL ) \
{ \
delete[] x; \
x = NULL; \
} \
\
}
#define IN_RANGE( value, min, max ) ( ((value) >= (min) && (value) <= (max)) ? 1 : 0 )
#define MIN( a, b ) ( ((a) < (b)) ? (a) : (b) )
#define MAX( a, b ) ( ((a) > (b)) ? (a) : (b) )
#define TO_BOOL( a ) ( (a != 0) ? true : false )
typedef unsigned int uint;
typedef unsigned __int32 uint32;
typedef unsigned __int64 uint64;
typedef unsigned char uchar;
template <class VALUE_TYPE> void SWAP(VALUE_TYPE& a, VALUE_TYPE& b)
{
VALUE_TYPE tmp = a;
a = b;
b = tmp;
}
// Standard string size
#define SHORT_STR 32
#define MID_STR 255
#define HUGE_STR 8192
// Joins a path and file
inline const char* const PATH(const char* folder, const char* file)
{
static char path[MID_STR];
sprintf_s(path, MID_STR, "%s/%s", folder, file);
return path;
}
// Performance macros
#define PERF_START(timer) timer.Start()
#define PERF_PEEK(timer) LOG("%s took %f ms", __FUNCTION__, timer.ReadMs())
//Angles
#define DEGTORAD 0.0174532925199432957f
#define RADTODEG 57.295779513082320876f
template <typename T>
T clamp(const T& n, const T& lower, const T&upper)
{
return std::max(lower, std::min(n, upper));
}
#endif | [
"traguill1@gmail.com"
] | traguill1@gmail.com |
f728deefc5f5e5f837fc1780d262eb7a9c5a9006 | 757b3ca08ff7884ac026dbf65deb5f1422330e7f | /Util.cpp | d9cdff769957a9925977ccd7443d1cc533f66504 | [] | no_license | jasondevans/ck2 | 00995c198c48021f9d30cba03d6787d673de964c | 7b3678b2c6a964b89000489d4b8e2cfed3162eec | refs/heads/master | 2021-01-09T06:08:37.882765 | 2017-07-09T19:40:30 | 2017-07-09T19:40:30 | 80,924,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,642 | cpp | #include "ck_common_includes.h"
#include "Util.h"
#include "UtilException.h"
// #include "Crypto.h"
#include <iterator>
// #include <boost/tokenizer.hpp>
// #include <boost/regex.hpp>
// #include <boost/algorithm/string/replace.hpp>
// #include <boost/filesystem.hpp>
using namespace CipherKick;
Util::Util()
{
// Initialize database pointer to null.
db = NULL;
// Define base64 characters.
// base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Start the timer.
// timer = new Timer();
// timer->start();
}
// Attempt to open a database file.
void Util::openDbFile(const std::string& filePath, const std::string& password)
{
// Close the database if it is currently open.
sqlite3_close(db);
db = NULL;
// Open the database.
int status = sqlite3_open(filePath.c_str(), &db);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to open database file (SQLITE status " + std::to_string(status) + ")." };
}
// Set the encrypt password.
char* pragmaSql = 0;
pragmaSql = sqlite3_mprintf("pragma key = %Q", password.c_str());
status = sqlite3_exec(db, pragmaSql, NULL, NULL, NULL);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to set encryption key (SQLITE status " + std::to_string(status) + ")." };
}
// TODO: Clean up pragmaSql properly / figure out how to handle this.
/*
finally
{
// TODO: Erase pragmaSql string to remove key from memory.
if (pragmaSql)
{
sqlite3_free(pragmaSql);
}
}
*/
// Test our connection (mainly to see if our password was correct).
std::string test_conn_query = "select count(*) from sqlite_master;";
status = sqlite3_exec(db, test_conn_query.c_str(), NULL, NULL, NULL);
if (status != SQLITE_OK)
{
try {
sqlite3_close(db);
db = NULL;
}
catch (...) {}
throw UtilException { "Password incorrect (SQLITE status " + std::to_string(status) + ")." };
}
}
/*
// Set up a new database, creating tables and populating initial values.
void Util::setupNewDb(String^ friendlyName)
{
int status;
// Create sites table.
std::string queryStr = "create table sites(id integer primary key autoincrement, site_id integer, name text, url text, user text, password text, notes text, version integer, deleted integer default 0);";
sqlite3_stmt* sqlStmt;
status = sqlite3_prepare_v2(db, (const char*)queryStr.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to create sites table (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to create sites table (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
// Create metadata table.
queryStr = "create table metadata(id integer primary key, guid text, friendly_name text, last_modified_utc text);";
status = sqlite3_prepare_v2(db, (const char*)queryStr.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to create metadata table (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to create metadata table (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
// Populate metadata table.
int id = 1;
std::string guid = msclr::interop::marshal_as<std::string>(Guid::NewGuid().ToString());
std::string friendlyNameStr = msclr::interop::marshal_as<std::string>(friendlyName);
std::string lastModifiedTemp = "LAST MODIFIED PLACEHOLDER";
queryStr = "insert into metadata(id, guid, friendly_name, last_modified_utc) values (?, ?, ?, ?)";
status = sqlite3_prepare_v2(db, (const char*)queryStr.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to populate metadata table (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_bind_int(sqlStmt, 1, id);
if (status == SQLITE_OK) status =
sqlite3_bind_text(sqlStmt, 2, (const char*)guid.c_str(), -1, NULL);
if (status == SQLITE_OK) status =
sqlite3_bind_text(sqlStmt, 3, (const char*)friendlyNameStr.c_str(), -1, NULL);
if (status == SQLITE_OK) status =
sqlite3_bind_text(sqlStmt, 4, (const char*)lastModifiedTemp.c_str(), -1, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to populate metadata table (bind error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to populate metadata table (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
// Update last modified time.
updateLastModifiedTime();
}
*/
// Get metadata.
/*
Metainfo^ Util::getMetadata()
{
Metainfo^ metadata = gcnew Metainfo();
std::string query_str = "select guid, friendly_name, last_modified_utc from metadata where id = 1";
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)query_str.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to get metadata (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status == SQLITE_ROW)
{
std::string guidStr = (char*)sqlite3_column_text(sqlStmt, 0);
metadata->guid = msclr::interop::marshal_as<String^>(guidStr);
std::string friendlyNameStr = (char*)sqlite3_column_text(sqlStmt, 1);
metadata->friendlyName = msclr::interop::marshal_as<String^>(friendlyNameStr);
std::string lastModifiedUtcStr = (char*)sqlite3_column_text(sqlStmt, 2);
metadata->lastModifiedUtc = msclr::interop::marshal_as<String^>(lastModifiedUtcStr);
status = sqlite3_step(sqlStmt);
}
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to get metadata (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
return metadata;
}
*/
// Get a list of all sites.
/*
List<Site^>^ Util::getSiteList()
{
std::string query_str = "select s.name, s.site_id, s.id, s.url, s.version from sites s, "
"(select site_id, max(version) as max_version from sites group by site_id) v "
"where s.site_id = v.site_id and s.version = v.max_version and s.deleted == 0 "
"order by lower(s.name)";
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)query_str.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to get site list (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
List<Site^>^ siteList = gcnew List<Site^>();
while (status == SQLITE_ROW)
{
// Get this result.
Site^ thisSite = gcnew Site();
std::string thisName = (char*)sqlite3_column_text(sqlStmt, 0);
thisSite->name = msclr::interop::marshal_as<String^>(thisName);
thisSite->siteId = sqlite3_column_int(sqlStmt, 1);
thisSite->id = sqlite3_column_int(sqlStmt, 2);
std::string thisUrl = (char*)sqlite3_column_text(sqlStmt, 3);
thisSite->url = msclr::interop::marshal_as<String^>(thisUrl);
thisSite->version = sqlite3_column_int(sqlStmt, 4);
siteList->Add(thisSite);
// Get the next result.
status = sqlite3_step(sqlStmt);
}
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to get site list (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
return siteList;
}
*/
// Search for records with names like search string.
std::shared_ptr<std::vector<CipherKick::Site>> Util::search(const std::string& searchTermParam)
{
std::string query_str = "select s.name, s.site_id, s.id, s.version from sites s, "
"(select site_id, max(version) as max_version from sites group by site_id) v "
"where s.site_id = v.site_id and s.version = v.max_version and s.deleted == 0 "
"and (lower(s.name) like ? escape '\\' or lower(s.url) like ? escape '\\' "
"or lower(s.notes) like ? escape '\\') order by lower(s.name)";
unsigned long pos = 0;
std::string searchTerm = searchTermParam;
std::string charsToEscape = "%_\\";
while (pos < searchTerm.size())
{
if (std::string::npos != charsToEscape.find(searchTerm.substr(pos, 1)))
{
searchTerm.insert(pos, "\\");
pos += 2;
}
else
{
pos++;
}
}
searchTerm.insert(0, "%");
searchTerm.insert(searchTerm.size(), "%");
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)query_str.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to perform search (prepare error " + std::to_string(status) + ")." };
}
status = sqlite3_bind_text(sqlStmt, 1, (const char*)searchTerm.c_str(), -1, NULL);
if (status == SQLITE_OK) sqlite3_bind_text(sqlStmt, 2, (const char*)searchTerm.c_str(), -1, NULL);
if (status == SQLITE_OK) sqlite3_bind_text(sqlStmt, 3, (const char*)searchTerm.c_str(), -1, NULL);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to perform search (bind error " + std::to_string(status) + ")." };
}
status = sqlite3_step(sqlStmt);
std::shared_ptr<std::vector<Site>> siteList = std::make_shared<std::vector<Site>>();
while (status == SQLITE_ROW)
{
// Get this result.
Site thisSite;
std::string thisName = (char*)sqlite3_column_text(sqlStmt, 0);
thisSite.name = thisName;
thisSite.siteId = sqlite3_column_int(sqlStmt, 1);
thisSite.id = sqlite3_column_int(sqlStmt, 2);
thisSite.version = sqlite3_column_int(sqlStmt, 3);
siteList->push_back(thisSite);
// Get the next result.
status = sqlite3_step(sqlStmt);
}
if (status != SQLITE_DONE)
{
throw UtilException { "Failed to get site list (step error " + std::to_string(status) + ")." };
}
sqlite3_finalize(sqlStmt);
return siteList;
}
// Get a specific site.
/*
Site^ Util::getSite(Site^ site)
{
return getSite(site->siteId);
}
*/
// Get a specific site.
std::shared_ptr<CipherKick::Site> Util::getSite(int siteId)
{
std::string query_str = "select id, site_id, name, url, user, password, notes, version "
"from sites where site_id = ? and version in "
"(select max(version) from sites where site_id = ?)";
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)query_str.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to get site (prepare error " + std::to_string(status) + ")." };
}
status = sqlite3_bind_int(sqlStmt, 1, siteId);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to get site (bind error " + std::to_string(status) + ")." };
}
status = sqlite3_bind_int(sqlStmt, 2, siteId);
if (status != SQLITE_OK)
{
throw UtilException { "Failed to get site (bind error " + std::to_string(status) + ")." };
}
auto thisSite = std::make_shared<CipherKick::Site>();
status = sqlite3_step(sqlStmt);
if (status == SQLITE_ROW)
{
thisSite->id = sqlite3_column_int(sqlStmt, 0);
thisSite->siteId = sqlite3_column_int(sqlStmt, 1);
thisSite->name = (char*)sqlite3_column_text(sqlStmt, 2);
thisSite->url = (char*)sqlite3_column_text(sqlStmt, 3);
thisSite->user = (char*)sqlite3_column_text(sqlStmt, 4);
thisSite->password = (char*)sqlite3_column_text(sqlStmt, 5);
thisSite->notes = (char*)sqlite3_column_text(sqlStmt, 6);
thisSite->version = sqlite3_column_int(sqlStmt, 7);
// Attempt to get the next result (there shouldn't be one).
status = sqlite3_step(sqlStmt);
}
if (status != SQLITE_DONE)
{
throw UtilException { "Failed to get site (step error " + std::to_string(status) + ")." };
}
sqlite3_finalize(sqlStmt);
return thisSite;
}
// Copy to the clipboard
void Util::copyToClipboard(const std::string& text)
{
// Array for pipe file descriptors
int pipefds[2];
// Create our pipe
if (pipe(pipefds) == -1)
perror("Error creating pipe");
if ((fork()) == 0) {
/* This is the child process */
/* Close write end of the pipe */
if (close(pipefds[1]) == -1)
perror("Error closing child's write end of the pipe");
/* Close stdin, and reopen bound to read end of pipe; close duplicate fd */
if (pipefds[0] != STDIN_FILENO) {
if (dup2(pipefds[0], STDIN_FILENO) == -1)
perror("Error reopening child's stdin bound to read end of pipe");
if (close(pipefds[0]) == -1)
perror("Error closing child's duplicate pipe read fd");
}
/* Over-write the child process with the pbcopy binary */
execlp("pbcopy", "pbcopy", NULL);
perror("Could not exec pbcopy");
exit(1);
}
/* This is the parent process */
/* Close read end of the pipe */
if (close(pipefds[0]) == -1)
perror("Error closing parent's read end of the pipe");
// printf("<- %s", data);
/* Write some data to the child's input */
write(pipefds[1], text.c_str(), strlen(text.c_str()));
/* We're done, so close our write end of the pipe */
if (close(pipefds[1]) == -1)
perror("Error closing parent's write end of the pipe");
}
// Save a site.
/*
int Util::saveSite(Site^ site)
{
int status;
// If this is a new site, determine the site id.
if (site->version == 1)
{
// Get the current max site id.
int maxSiteId = 0;
std::string query_str = "select max(site_id) from sites;";
sqlite3_stmt* sqlStmt;
status = sqlite3_prepare_v2(db, query_str.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to determine max site id (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status == SQLITE_ROW)
{
maxSiteId = sqlite3_column_int(sqlStmt, 0);
status = sqlite3_step(sqlStmt);
}
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to determine max site id (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
maxSiteId = std::max(0, maxSiteId);
site->siteId = maxSiteId + 1;
}
// Insert the record.
std::string queryStr = "insert into sites (site_id, name, url, user, password, notes, version) values (?, ?, ?, ?, ?, ?, ?)";
sqlite3_stmt* sqlStmt;
status = sqlite3_prepare_v2(db, (const char*)queryStr.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to save site (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_bind_int(sqlStmt, 1, site->siteId);
String^ nameTempS = site->name; std::string nameTemp = msclr::interop::marshal_as<std::string>(nameTempS);
if (status == SQLITE_OK) status = sqlite3_bind_text(sqlStmt, 2, (const char*)nameTemp.c_str(), -1, NULL);
String^ urlTempS = site->url; std::string urlTemp = msclr::interop::marshal_as<std::string>(urlTempS);
if (status == SQLITE_OK) status = sqlite3_bind_text(sqlStmt, 3, (const char*)urlTemp.c_str(), -1, NULL);
String^ userTempS = site->user; std::string userTemp = msclr::interop::marshal_as<std::string>(userTempS);
if (status == SQLITE_OK) status = sqlite3_bind_text(sqlStmt, 4, (const char*)userTemp.c_str(), -1, NULL);
String^ pwTempS = site->password; std::string pwTemp = msclr::interop::marshal_as<std::string>(pwTempS);
if (status == SQLITE_OK) status = sqlite3_bind_text(sqlStmt, 5, (const char*)pwTemp.c_str(), -1, NULL);
String^ notesTempS = site->notes; std::string notesTemp = msclr::interop::marshal_as<std::string>(notesTempS);
if (status == SQLITE_OK) status = sqlite3_bind_text(sqlStmt, 6, (const char*)notesTemp.c_str(), -1, NULL);
if (status == SQLITE_OK) status = sqlite3_bind_int(sqlStmt, 7, site->version);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to save site (bind error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to save site (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
// Update last modified time.
updateLastModifiedTime();
// Return the new site id.
return site->siteId;
}
*/
// Delete site.
/*
void Util::deleteSite(int id)
{
// Insert the record.
std::string queryStr = "update sites set deleted = 1 where id = ?";
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)queryStr.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to delete site (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_bind_int(sqlStmt, 1, id);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to delete site (bind error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to delete site (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
// Update last modified time.
updateLastModifiedTime();
}
*/
// Get export data as a string.
/*
String^ Util::getExportData(System::Security::SecureString^ encryptPassword)
{
std::stringstream ss;
ss << "<?xml version=\"1.0\"?>\n";
ss << "<password-manager>\n";
// Salt.
std::vector<unsigned char> salt;
for (int i = 0; i < 16 /comment bytes comment/; i++) salt.push_back(Crypto::getInstance().genRand());
ss << "<salt>" << base64_encode(&salt[0], (unsigned int) salt.size()) << "</salt>\n";
// Derive encryption and auth keys.
Crypto crypto = Crypto::getInstance();
std::vector<unsigned char> encryptKey;
std::vector<unsigned char> authKey;
crypto.deriveKeys(encryptPassword, salt, encryptKey, authKey);
// Get and write metadata.
Metainfo^ metadata = getMetadata();
ss << "<metadata>\n";
String^ guid = metadata->guid;
ss << "<guid>" << msclr::interop::marshal_as<std::string>(guid) << "</guid>\n";
String^ friendlyName = metadata->friendlyName;
ss << "<friendly-name>" << msclr::interop::marshal_as<std::string>(friendlyName) << "</friendly-name>\n";
String^ lastModifiedUtc = metadata->lastModifiedUtc;
ss << "<last-modified-utc>" << msclr::interop::marshal_as<std::string>(lastModifiedUtc) << "</last-modified-utc>\n";
ss << "</metadata>\n";
// Get and write site data.
std::string query_str = "select s.name, s.url, s.user, s.password, s.notes from sites s, "
"(select site_id, max(version) as max_version from sites group by site_id) v "
"where s.site_id = v.site_id and s.version = v.max_version and s.deleted == 0 "
"order by lower(s.name)";
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)query_str.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to perform search (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
while (status == SQLITE_ROW)
{
ss << "<site>\n";
// Get this result.
unsigned char ch;
const unsigned char* namePtr = sqlite3_column_text(sqlStmt, 0);
int nameBytes = sqlite3_column_bytes(sqlStmt, 0);
std::vector<unsigned char> thisName(namePtr, namePtr + nameBytes);
const unsigned char* urlPtr = sqlite3_column_text(sqlStmt, 1);
int urlBytes = sqlite3_column_bytes(sqlStmt, 1);
std::vector<unsigned char> thisUrl(urlPtr, urlPtr + urlBytes);
const unsigned char* userPtr = sqlite3_column_text(sqlStmt, 2);
int userBytes = sqlite3_column_bytes(sqlStmt, 2);
std::vector<unsigned char> thisUser(userPtr, userPtr + userBytes);
const unsigned char* passwordPtr = sqlite3_column_text(sqlStmt, 3);
int passwordBytes = sqlite3_column_bytes(sqlStmt, 3);
std::vector<unsigned char> thisPassword(passwordPtr, passwordPtr + passwordBytes);
// For now, replace invalid UTF-8 characters with '?'. Eventually,
// should figure out the best way to convert these.
const unsigned char* notesPtr = sqlite3_column_text(sqlStmt, 4);
int notesBytes = sqlite3_column_bytes(sqlStmt, 4);
unsigned char* notesPtrM = new unsigned char[notesBytes + 1];
std::copy(notesPtr, notesPtr + notesBytes + 1, notesPtrM);
int invalidPos = getInvalidUtf8SymbolPosition(notesPtrM, ch);
while (invalidPos != -1)
{
notesPtrM[invalidPos] = '?';
invalidPos = getInvalidUtf8SymbolPosition(notesPtrM, ch);
}
std::vector<unsigned char> thisNotes(notesPtrM, notesPtrM + notesBytes);
// Encrypt and write XML data.
std::vector<unsigned char> encryptedVal;
std::string b64Val;
if (thisName.size() > 0)
{
crypto.encrypt(thisName, encryptKey, authKey, encryptedVal);
b64Val = base64_encode(&encryptedVal[0], (unsigned int) encryptedVal.size());
ss << "<name>" << b64Val << "</name>\n";
}
else ss << "<name/>\n";
if (thisUrl.size() > 0)
{
crypto.encrypt(thisUrl, encryptKey, authKey, encryptedVal);
b64Val = base64_encode(&encryptedVal[0], (unsigned int) encryptedVal.size());
ss << "<url>" << b64Val << "</url>\n";
}
else ss << "<url/>\n";
if (thisUser.size() > 0)
{
crypto.encrypt(thisUser, encryptKey, authKey, encryptedVal);
b64Val = base64_encode(&encryptedVal[0], (unsigned int) encryptedVal.size());
ss << "<user>" << b64Val << "</user>\n";
}
else ss << "<user/>\n";
if (thisPassword.size() > 0)
{
crypto.encrypt(thisPassword, encryptKey, authKey, encryptedVal);
b64Val = base64_encode(&encryptedVal[0], (unsigned int) encryptedVal.size());
ss << "<password>" << b64Val << "</password>\n";
}
else ss << "<password/>\n";
if (thisNotes.size() > 0)
{
crypto.encrypt(thisNotes, encryptKey, authKey, encryptedVal);
b64Val = base64_encode(&encryptedVal[0], (unsigned int) encryptedVal.size());
ss << "<notes>" << b64Val << "</notes>\n";
}
else ss << "<notes/>\n";
ss << "</site>\n";
// Get the next result.
status = sqlite3_step(sqlStmt);
}
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to perform search (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
ss << "</password-manager>\n";
return msclr::interop::marshal_as<String^>(ss.str());
}
*/
// Export to a file.
/*
void Util::exportData(String^ filePath, System::Security::SecureString^ encryptPassword)
{
std::ofstream ofile;
ofile.open(msclr::interop::marshal_as<std::string>(filePath));
ofile << msclr::interop::marshal_as<std::string>(getExportData(encryptPassword));
ofile.close();
}
*/
// Import a CSV.
/*
void Util::importLastPassCSV(String^ csvText)
{
std::string csvTextMutable = msclr::interop::marshal_as<std::string>(csvText);
boost::algorithm::replace_all(csvTextMutable, "&", "&"); // Replace & with &.
boost::char_separator<char> sep("", ",\n", boost::keep_empty_tokens);
boost::tokenizer<boost::char_separator<char>> tokens(csvTextMutable, sep);
bool inQuote = false;
std::string thisField = "";
int currentField = 0; // 0 = url, 1 = user, 2 = password, 3 = notes, 4 = name, 5 = grouping, 6 = fav
bool fieldComplete = false;
Site^ thisSite = gcnew Site();
thisSite->clear();
for (const auto& t : tokens)
{
std::string thisToken = t;
if (thisToken.compare("") == 0)
{
if (!inQuote) fieldComplete = true;
}
if (thisToken.compare("") != 0 && !inQuote)
{
if (thisToken.substr(0, 1).compare("\"") == 0)
{
inQuote = true;
thisToken = thisToken.substr(1);
}
else if (thisToken.compare("\n") == 0 || thisToken.compare(",") == 0)
{
continue; // This is just a delimiter.
}
else
{
fieldComplete = true;
}
}
if (thisToken.compare("") != 0 && inQuote)
{
if (thisToken.compare("\n") == 0 || thisToken.compare(",") == 0)
{
// Leave thisToken = t;
}
else
{
boost::regex e("(\"*)$");
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
if (boost::regex_search(thisToken, what, e, flags) && what[1].length() % 2 == 1)
{
inQuote = false;
fieldComplete = true;
boost::algorithm::replace_all(thisToken, "\"\"", "\"");
thisToken = thisToken.substr(0, thisToken.length() - 1);
}
else
{
boost::algorithm::replace_all(thisToken, "\"\"", "\"");
}
}
}
thisField += thisToken;
if (fieldComplete)
{
fieldComplete = false;
switch (currentField)
{
case 0: thisSite->url = msclr::interop::marshal_as<String^>(thisField); currentField++; break;
case 1: thisSite->user = msclr::interop::marshal_as<String^>(thisField); currentField++; break;
case 2: thisSite->password = msclr::interop::marshal_as<String^>(thisField); currentField++; break;
case 3: thisSite->notes = msclr::interop::marshal_as<String^>(thisField); currentField++; break;
case 4: thisSite->name = msclr::interop::marshal_as<String^>(thisField); currentField++; break;
case 5: currentField++; break;
case 6: saveSite(thisSite); thisSite->clear(); currentField = 0; break;
default: break;
}
thisField = "";
}
}
// Update last modified time.
updateLastModifiedTime();
}
*/
// Change master password.
/*
void Util::changeMasterPassword(System::Security::SecureString^ newPassword)
{
IntPtr password_bstr = IntPtr::Zero;
char* password_utf8 = 0;
int password_utf8_len = 0;
char* setKeySQL_2 = 0;
try
{
char* setKeySQL_1 = "pragma rekey = %Q";
password_bstr = Marshal::SecureStringToBSTR(newPassword);
// Convert UTF-16 to UTF-8.
password_utf8_len = WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)password_bstr.ToPointer(),
-1, password_utf8, 0, NULL, NULL);
password_utf8 = new char[password_utf8_len];
int bytesWritten = WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)password_bstr.ToPointer(),
-1, password_utf8, password_utf8_len, NULL, NULL);
setKeySQL_2 = sqlite3_mprintf(setKeySQL_1, password_utf8);
int status = sqlite3_exec(db, setKeySQL_2, NULL, NULL, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to change master password (rekey status " + std::to_string(status) + ").");
}
}
finally
{
Marshal::ZeroFreeBSTR(password_bstr);
if (password_utf8)
{
SecureZeroMemory(password_utf8, password_utf8_len);
delete password_utf8;
password_utf8 = 0;
}
if (setKeySQL_2)
{
SecureZeroMemory(setKeySQL_2, strlen(setKeySQL_2));
sqlite3_free(setKeySQL_2);
}
}
std::string test_conn_query = "select count(*) from sites;";
int status = sqlite3_exec(db, (const char*)test_conn_query.c_str(), NULL, NULL, NULL);
if (status != SQLITE_OK)
{
try {
sqlite3_close(db);
}
catch (...) {}
throw gcnew UtilException("Failed to change master password (select status " + std::to_string(status) + ").");
}
// Update last modified time.
updateLastModifiedTime();
}
*/
// Update last modified date/time.
/*
void Util::updateLastModifiedTime()
{
// Get the current date/time.
SYSTEMTIME st;
GetSystemTime(&st);
char buffer[24];
sprintf(buffer, "%04d/%02d/%02d %02d:%02d:%02d %03d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
// Insert the record.
std::string queryStr = "update metadata set last_modified_utc = ? where id = 1";
sqlite3_stmt* sqlStmt;
int status = sqlite3_prepare_v2(db, (const char*)queryStr.c_str(), -1, &sqlStmt, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to update last modified time (prepare error " + std::to_string(status) + ").");
}
status = sqlite3_bind_text(sqlStmt, 1, buffer, -1, NULL);
if (status != SQLITE_OK)
{
throw gcnew UtilException("Failed to update last modified time (bind error " + std::to_string(status) + ").");
}
status = sqlite3_step(sqlStmt);
if (status != SQLITE_DONE)
{
throw gcnew UtilException("Failed to update last modified time (step error " + std::to_string(status) + ").");
}
sqlite3_finalize(sqlStmt);
}
*/
// Encode into base64.
/*
std::string Util::base64_encode(unsigned char const* buf, unsigned int bufLen)
{
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (bufLen--) {
char_array_3[i++] = *(buf++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; (i <4); i++)
ret += (char) base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += (char) base64_chars[char_array_4[j]];
while ((i++ < 3))
ret += '=';
}
return ret;
}
*/
// Decode from base64 into bytes.
/*
std::vector<unsigned char> Util::base64_decode(std::string const& encoded_string)
{
int in_len = (int) encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::vector<unsigned char> ret;
while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i == 4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars->IndexOf(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret.push_back(char_array_3[i]);
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars->IndexOf(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);
}
return ret;
}
*/
///Returns -1 if string is valid. Invalid character is put to ch.
/*
int Util::getInvalidUtf8SymbolPosition(const unsigned char *input, unsigned char &ch) {
int nb, na;
const unsigned char *c = input;
for (c = input; *c; c += (nb + 1)) {
if (!(*c & 0x80))
nb = 0;
else if ((*c & 0xc0) == 0x80)
{
ch = *c;
// return (int)c - (int)input;
return (int)(c - input);
}
else if ((*c & 0xe0) == 0xc0)
nb = 1;
else if ((*c & 0xf0) == 0xe0)
nb = 2;
else if ((*c & 0xf8) == 0xf0)
nb = 3;
else if ((*c & 0xfc) == 0xf8)
nb = 4;
else if ((*c & 0xfe) == 0xfc)
nb = 5;
na = nb;
while (na-- > 0)
if ((*(c + nb) & 0xc0) != 0x80)
{
ch = *(c + nb);
// return (int)(c + nb) - (int)input;
return (int)(c + nb - input);
}
}
return -1;
}
*/
// Clean up.
void Util::cleanUp()
{
// Close the database.
sqlite3_close(db);
// Delete the timer.
// delete timer;
}
| [
"jason@emotionistic.com"
] | jason@emotionistic.com |
febcd25f69a7e2487cfdc3d1540a29b55a57e364 | 606c34e2ceae24de9f8331ba8964c493e9d8565d | /CogEye/Engine/src/Memory/SharedPointer.h | 38b8dec55bbeefce9e07d639ed573b856f7637b0 | [
"Apache-2.0"
] | permissive | Bounty556/CogEye_GameJam_Old | b584e6a8e7dd0fe3c09ba4e1489e0ee2d9f4a416 | c4f678cad9542f7d595510849779ffb46f26e016 | refs/heads/main | 2023-06-03T10:22:56.119433 | 2021-06-13T17:51:42 | 2021-06-13T17:51:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | h | #pragma once
#include <Defines.h>
#include <Memory/MemoryManager.h>
#include <Memory/ReferenceCounter.h>
// TODO: SharedPointer should be able to be initialized with no values, as well as be able to be reassigned to new values and behave accordingly. Fo SharedPointers, it should decrease the reference counter pointing to that value and potentially free the memory at that location. At the moment I'm not really using any SharedPointers however, so I'm going to leave this to future Jake.
namespace Soul
{
template <class T>
class SharedPointer
{
public:
SharedPointer(T* pointer);
SharedPointer(const SharedPointer<T>& otherPointer);
SharedPointer(SharedPointer<T>&& otherPointer);
~SharedPointer();
SharedPointer<T>& operator=(const SharedPointer<T>& otherPointer);
SharedPointer<T>& operator=(SharedPointer<T>&& otherPointer);
T* operator->() const;
T& operator*() const;
T& operator[](unsigned int index) const;
private:
T* m_Pointer;
ReferenceCounter* m_References;
};
template <class T>
SharedPointer<T>::SharedPointer(T* pointer) :
m_Pointer(pointer)
{
m_References = PARTITION(ReferenceCounter);
m_References->AddReference();
}
template <class T>
SharedPointer<T>::SharedPointer(const SharedPointer<T>& otherPointer) :
m_Pointer(otherPointer.m_Pointer),
m_References(otherPointer.m_References)
{
m_References->AddReference();
}
template <class T>
SharedPointer<T>::SharedPointer(SharedPointer<T>&& otherPointer) :
m_Pointer(otherPointer.m_Pointer),
m_References(otherPointer.m_References)
{
otherPointer.m_Pointer = nullptr;
otherPointer.m_References = nullptr;
}
template <class T>
SharedPointer<T>::~SharedPointer()
{
if (m_References)
{
if (m_References->RemoveReference() == 0)
{
MemoryManager::FreeMemory(m_References);
MemoryManager::FreeMemory(m_Pointer);
}
}
}
template <class T>
SharedPointer<T>& SharedPointer<T>::operator=(const SharedPointer<T>& otherPointer)
{
// Make sure these are separate pointers
if (m_Pointer != otherPointer.m_Pointer)
{
if (m_Pointer && m_References->RemoveReference() == 0)
{
MemoryManager::FreeMemory(m_References);
MemoryManager::FreeMemory(m_Pointer);
}
m_Pointer = otherPointer.m_Pointer;
m_References = otherPointer.m_References;
m_References->AddReference();
}
return *this;
}
template <class T>
SharedPointer<T>& SharedPointer<T>::operator=(SharedPointer<T>&& otherPointer)
{
if (m_Pointer && m_References->RemoveReference() == 0)
{
MemoryManager::FreeMemory(m_References);
MemoryManager::FreeMemory(m_Pointer);
}
m_Pointer = otherPointer.m_Pointer;
m_References = otherPointer.m_References;
otherPointer.m_Pointer = nullptr;
otherPointer.m_References = nullptr;
}
template <class T>
T* SharedPointer<T>::operator->() const
{
return m_Pointer;
}
template <class T>
T& SharedPointer<T>::operator*() const
{
return *m_Pointer;
}
template <class T>
T& SharedPointer<T>::operator[](unsigned int index) const
{
return m_Pointer[index];
}
} | [
"jacobmayday@gmail.com"
] | jacobmayday@gmail.com |
e3eee8b1cdf191675d49f219832d02856789420b | 1f595fff623f14511bed58b339789150b00d131d | /incs/gui/model/Model.hpp | bfe173e6c4aa93ae77ebd4c5de326463f12d6878 | [] | no_license | q-litzler/gomoku | da4cdddaa99e62299276df31bca8dda01c7375eb | 7a3a8fb18f3c873c4e8ca09186672807e96c9385 | refs/heads/master | 2021-01-21T13:29:55.516473 | 2016-05-03T20:34:56 | 2016-05-03T20:34:56 | 49,002,286 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,526 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Model.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: qlitzler <qlitzler@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/22 00:00:04 by qlitzler #+# #+# */
/* Updated: 2016/01/03 16:32:02 by qlitzler ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MODEL_CLASS_HPP
# define MODEL_CLASS_HPP
# include <libs/glfw/glfw3.h>
# include <libs/glm/glm.hpp>
# include <libs/glm/gtc/matrix_transform.hpp>
class Model
{
public:
Model(GLfloat const & scale, GLfloat const & rotation);
virtual ~Model(void);
virtual glm::mat4 getMatrix(void) const = 0;
glm::mat4 getProjection(void) const;
glm::vec3 getLightPosition(void) const;
private:
Model(void);
protected:
GLfloat const _originScale;
GLfloat const _originRotation;
GLfloat _scale;
GLfloat _rotation;
glm::mat4 _projection;
glm::vec3 _lightPosition;
};
#endif /* ! MODEL_CLASS_HPP */
| [
"qlitzler@gmail.com"
] | qlitzler@gmail.com |
755cad18f61e08d089d538bf93908a9a037b107c | 17bd9472d0b405c5d95084f60c656c2ccb1e4e2c | /font.h | 986b12816a0e64e85c3b8edfcd0e56a1ba29890e | [] | no_license | jeromelebel/BeagleBone-HD44780-SPI | 34b7ffc628833f3e18c4c5f94ed7026d97cdeab3 | 7bbc1bb670fbe9e9bdde61dba607ff97ea3ca296 | refs/heads/master | 2021-01-10T09:06:19.957943 | 2013-03-17T18:44:12 | 2013-03-17T18:44:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | h | #include "graphic.h"
#ifndef FONT_H
#define FONT_H
class Font
{
private:
unsigned char _width;
unsigned char _height;
const unsigned char *_buffer;
unsigned int _charCount;
public:
Font(PixelCoordonate width, PixelCoordonate height, const unsigned char *buffer, int bufferSize);
unsigned char getWidth(void) { return _width; };
unsigned char getHeight(void) { return _height; };
unsigned char pixelsForChar(unsigned char character, unsigned char row) { if (character >= _charCount) { character = 0; } return _buffer[(character * _width) + row]; };
};
extern Font font1;
extern Font font2;
#endif /* FONT_H */
| [
"lebel.jerome@gmail.com"
] | lebel.jerome@gmail.com |
03eec93388898c64d38c8ce61c391f9d99f1cf82 | e3d0e8163acf2f12cb9e7acc0b43056d0d2c9aa7 | /class/HelloTexas/HelloTexas.ino | 9eaa62e5fd3d49f0f7b4cf4b59ae47bd761eff4d | [] | no_license | lajthabalazs/arduino | 637909cf2c505c967ac2610364101290562449ce | 839422874795728cb922a862ed2554f075530a67 | refs/heads/master | 2021-01-23T08:04:40.846171 | 2016-03-05T12:57:10 | 2016-03-05T12:57:10 | 14,390,745 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 252 | ino | #include <OneWire.h>
#include <DallasTemperature.h>
OneWire oneWire(2);
DallasTemperature sensors(&oneWire);
void setup(void)
{
sensors.begin();
}
void loop(void)
{
sensors.requestTemperatures();
int temp = (int)sensors.getTempCByIndex(0);
}
| [
"lajthabalazs@yahoo.com"
] | lajthabalazs@yahoo.com |
3da2e962760d762da0ba569a5b5c243bea2c4d98 | 1289ea27918fafac4a52ad229ab6d5de71e64a8d | /UnixNetwork/进程间通信/使用mmap映射实现匿名共享存储/mmap-shm.cpp | c2036a01572c21f990617a7b0dac2c32bd6fc377 | [] | no_license | VVZzzz/NetworkProg | 8d8ed4c01f8a374fd8dcd35cc0bed57bdf0f5589 | fe05c4e9da27d1d7d79562b2f50ff76fbf538487 | refs/heads/master | 2021-08-10T12:51:56.148807 | 2020-06-15T16:05:26 | 2020-06-15T16:05:26 | 192,701,385 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,386 | cpp | /*
使用/dev/zero存储映射(mmap)实现共享存储
但这种mmap只能用于相关联的进程之间
读/dev/zero这个设备时,它是一个0字节的无限资源
写/dev/zero时,它忽略写向它的数据
*/
#include <errno.h>
#include <fcntl.h>
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <iostream>
#define NLOOPS 1000
#define SIZE sizeof(long)
static int update(long *ptr) { return ((*ptr)++); }
union semun {
int val; // for SETVAL
struct semid_ds
*buf; //每个信号量集合都有一个semid_ds结构,for IPC_STAT and IPC_SET
unsigned short *array; // for GETALL and SETALL
};
// pv操作 , op>0 释放资源 , op<0 获取资源
//这里没设置IPC_NOWAIT标志,所有semop会阻塞
void pv(int sem_id, int op) {
// sem_id:信号量id,op:操作
struct sembuf sem_b; // sembuf为信号量操作结构
sem_b.sem_num = 0; //操作信号量集合中的哪一个信号量(0~nsems-1)
sem_b.sem_op = op;
sem_b.sem_flg = SEM_UNDO; //设置UNDO标志,是当进程exit时能自动释放资源信号量
semop(sem_id, &sem_b, 1);
}
int main(int argc, char **argv) {
int fd = open("/dev/zero", O_RDWR);
//area初始化为0
void *area = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (area == MAP_FAILED) return -1;
//为同步父子进程,这里使用IPC_PRIVATE锁
int sem_id = semget(IPC_PRIVATE, 1, 0666);
//初始化信号量集合
union semun sem_un;
sem_un.val = 1;
semctl(sem_id, 0, SETVAL, sem_un);
//注意这里,一旦/dev/zero映射成功,就要关闭它的fd
close(fd);
int pid;
int counter = 0;
if ((pid = fork()) < 0)
return -1;
else if (pid > 0) {
for (int i = 0; i < NLOOPS; i += 2) {
pv(sem_id, -1); //获取资源
counter = update((long *)area);
printf("in parent counter: %d , i: %d\n", counter, i);
//sleep(1);
pv(sem_id, 1); //释放资源
}
} else {
for (int i = 1; i < NLOOPS + 1; i += 2) {
pv(sem_id, -1); //获取资源
counter = update((long *)area);
printf("in child counter: %d , i: %d\n", counter, i);
//sleep(1);
pv(sem_id, 1); //释放资源
}
exit(0);
}
semctl(sem_id, 0, IPC_RMID, sem_un);
exit(0);
} | [
"vvzz_run@outlook.com"
] | vvzz_run@outlook.com |
7135f73a8dca4508401974c7e8188249899a2231 | 0f0cbe5c3c4e7803f6b91b49f4dbb3fe674aea40 | /ABC/021/A/cpp/test.cpp | 1051c7b880cc63986067699e43614a56063c6884 | [] | no_license | camisoul/atcoder | 855d17266c75de058b1a59c0350b42fdcd0f7dcb | 06ab197f8089f55b91d4439b5e9c4e8420ca6baa | refs/heads/master | 2020-03-18T05:08:15.065063 | 2018-07-20T08:21:09 | 2018-07-20T08:21:09 | 134,326,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 192 | cpp | #include <iostream>
using namespace std;
int main()
{
size_t n;
cin >> n;
cout << n << endl;
for (auto i = 0u; i < n; ++i) {
cout << 1 << endl;
}
return 0;
}
| [
"camisoulmax@gmail.com"
] | camisoulmax@gmail.com |
8ed1e8eb39a2eae3311fc29788384a49f63cfefd | 18452fb77d8d3b9edc52c8a2dcaa4b5938c48d67 | /packml_sm/src/state_machine.cpp | 55125b0833ef13fcb564ded4a05edf92e5cb8651 | [
"Apache-2.0"
] | permissive | dejaniraai/packml_ros2 | 46b3779ff86491012d0f899a9a9054a2c6361672 | 917aad70e05a63863118f172fbd29e4861f58b92 | refs/heads/master | 2020-12-23T12:24:18.913895 | 2020-03-17T05:42:34 | 2020-03-17T05:42:34 | 237,150,707 | 2 | 3 | Apache-2.0 | 2020-01-30T06:10:17 | 2020-01-30T06:10:17 | null | UTF-8 | C++ | false | false | 15,193 | cpp | /**
* @license Software License Agreement (Apache License)
*
* @copyright Copyright (c) 2016 Shaun Edwards
* @copyright Copyright (c) 2019 Dejanira Araiza Illan, ROS-Industrial Asia Pacific
* Modified for ROS2.0 compatibility -> ros::Time, *_STREAM and *_INFO displays
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <string>
#include <memory>
#include "packml_sm/state_machine.h"
#include "packml_sm/transitions.h"
#include "packml_sm/events.h"
namespace packml_sm
{
bool StateMachineInterface::start()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::IDLE:
_start();
return true;
default:
std::cout << "Ignoring START command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::clear()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::ABORTED:
_clear();
return true;
default:
std::cout << "Ignoring CLEAR command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::reset()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::COMPLETE:
case StatesEnum::STOPPED:
_reset();
return true;
default:
std::cout << "Ignoring RESET command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::hold()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::EXECUTE:
_hold();
return true;
default:
std::cout << "Ignoring HOLD command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::unhold()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::HELD:
_unhold();
return true;
default:
std::cout << "Ignoring HELD command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::suspend()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::EXECUTE:
_suspend();
return true;
default:
std::cout << "Ignoring SUSPEND command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::unsuspend()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::SUSPENDED:
_unsuspend();
return true;
default:
std::cout << "Ignoring UNSUSPEND command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::stop()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::STOPPABLE:
case StatesEnum::STARTING:
case StatesEnum::IDLE:
case StatesEnum::SUSPENDED:
case StatesEnum::EXECUTE:
case StatesEnum::HOLDING:
case StatesEnum::HELD:
case StatesEnum::SUSPENDING:
case StatesEnum::UNSUSPENDING:
case StatesEnum::UNHOLDING:
case StatesEnum::COMPLETING:
case StatesEnum::COMPLETE:
_stop();
return true;
default:
std::cout << "Ignoring STOP command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
bool StateMachineInterface::abort()
{
switch(StatesEnum(getCurrentState())) {
case StatesEnum::ABORTABLE:
case StatesEnum::STOPPED:
case StatesEnum::STARTING:
case StatesEnum::IDLE:
case StatesEnum::SUSPENDED:
case StatesEnum::EXECUTE:
case StatesEnum::HOLDING:
case StatesEnum::HELD:
case StatesEnum::SUSPENDING:
case StatesEnum::UNSUSPENDING:
case StatesEnum::UNHOLDING:
case StatesEnum::COMPLETING:
case StatesEnum::COMPLETE:
case StatesEnum::CLEARING:
case StatesEnum::STOPPING:
_abort();
return true;
default:
std::cout << "Ignoring ABORT command in current state: " << getCurrentState() <<
std::endl;
return false;
}
}
QCoreApplication * a;
void init(int argc, char *argv[])
{
if(NULL == QCoreApplication::instance()) {
printf("Starting QCoreApplication\n");
a = new QCoreApplication(argc, argv);
}
}
std::shared_ptr<StateMachine> StateMachine::singleCyleSM()
{
return std::shared_ptr<StateMachine>(new SingleCycle());
}
std::shared_ptr<StateMachine> StateMachine::continuousCycleSM()
{
return std::shared_ptr<StateMachine>(new ContinuousCycle());
}
/*
* NOTES:
* Create factory methods that take std::bind as an argument for
* a custom call back in the "onExit" method.
*
* StateMachine will consist of several public SLOTS for each
* PackML command. The implementations will post events to the SM
* when called.
*
* Specializations of StateMachine (like ROS StateMachine) will use
* state entered events to trigger status publishing via SLOTS
*
* Mode handling will be achieved using a hiearchy of state machines
* that reference/utilize many of the same transitions/states (maybe)
*/
StateMachine::StateMachine()
{
printf("State machine constructor\n");
//printf("Constructiong super states\n");
abortable_ = WaitState::Abortable();
stoppable_ = WaitState::Stoppable(abortable_);
//printf("Constructiong acting/wait states\n");
held_ = WaitState::Held(stoppable_);
idle_ = WaitState::Idle(stoppable_);
complete_ = WaitState::Complete(stoppable_);
suspended_ = WaitState::Suspended(stoppable_);
stopped_ = WaitState::Stopped(abortable_);
aborted_ = WaitState::Aborted();
unholding_ = ActingState::Unholding(stoppable_);
holding_ = ActingState::Holding(stoppable_);
starting_ = ActingState::Starting(stoppable_);
completing_ = ActingState::Completing(stoppable_);
resetting_ = ActingState::Resetting(stoppable_);
unsuspending_ = ActingState::Unsuspending(stoppable_);
suspending_ = ActingState::Suspending(stoppable_);
stopping_ = ActingState::Stopping(abortable_);
clearing_ = ActingState::Clearing(abortable_);
aborting_ = ActingState::Aborting();
execute_ = ActingState::Execute(stoppable_);
connect(abortable_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(stoppable_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(unholding_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(held_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(holding_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(idle_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(starting_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(completing_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(complete_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(resetting_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(unsuspending_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(suspended_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(suspending_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(stopped_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(stopping_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(clearing_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(aborted_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(aborting_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
connect(execute_, SIGNAL(stateEntered(int, QString)), this, SLOT(setState(int, QString)));
printf("Adding states to state machine\n");
sm_internal_.addState(abortable_);
sm_internal_.addState(aborted_);
sm_internal_.addState(aborting_);
}
bool StateMachine::activate()
{
printf("Checking if QCore application is running\n");
if(NULL == QCoreApplication::instance())
{
printf(
"QCore application is not running, QCoreApplication must be created in main");
printf(" thread for state machine to run\n");
return false;
} else {
printf("Moving state machine to Qcore thread\n");
sm_internal_.moveToThread(QCoreApplication::instance()->thread());
this->moveToThread(QCoreApplication::instance()->thread());
sm_internal_.start();
printf("State machine thread created and started\n");
return true;
}
}
bool StateMachine::deactivate()
{
printf("Deactivating state machine\n");
sm_internal_.stop();
return true;
}
void StateMachine::setState(int value, QString name)
{
std::string nameUtf = name.toStdString();
std::cout << "State changed(event) to: " << nameUtf << "(" << value << ")" <<
std::endl;
state_value_ = value;
state_name_ = name;
emit stateChanged(value, name);
}
bool StateMachine::setExecute(std::function<int()> execute_method)
{
printf("Initializing state machine with EXECUTE function pointer\n");
return execute_->setOperationMethod(execute_method);
}
bool StateMachine::setResetting(std::function<int()> resetting_method)
{
printf("Initializing state machine with RESETTING function pointer\n");
return resetting_->setOperationMethod(resetting_method);
}
void StateMachine::_start() {sm_internal_.postEvent(CmdEvent::start());}
void StateMachine::_clear() {sm_internal_.postEvent(CmdEvent::clear());}
void StateMachine::_reset() {sm_internal_.postEvent(CmdEvent::reset());}
void StateMachine::_hold() {sm_internal_.postEvent(CmdEvent::hold());}
void StateMachine::_unhold() {sm_internal_.postEvent(CmdEvent::unhold());}
void StateMachine::_suspend() {sm_internal_.postEvent(CmdEvent::suspend());}
void StateMachine::_unsuspend() {sm_internal_.postEvent(CmdEvent::unsuspend());}
void StateMachine::_stop() {sm_internal_.postEvent(CmdEvent::stop());}
void StateMachine::_abort() {sm_internal_.postEvent(CmdEvent::abort());}
ContinuousCycle::ContinuousCycle()
{
printf("Forming CONTINUOUS CYCLE state machine (states + transitions)\n");
// Naming <from state>_<to state>
CmdTransition * abortable_aborting_on_cmd = CmdTransition::abort(*abortable_, *aborting_);
ErrorTransition * abortable_aborting_on_error = new ErrorTransition(*abortable_, *aborting_);
StateCompleteTransition * aborting_aborted = new StateCompleteTransition(*aborting_, *aborted_);
CmdTransition * aborted_clearing_ = CmdTransition::clear(*aborted_, *clearing_);
StateCompleteTransition * clearing_stopped_ = new StateCompleteTransition(*clearing_, *stopped_);
CmdTransition * stoppable_stopping_ = CmdTransition::stop(*stoppable_, *stopping_);
StateCompleteTransition * stopping_stopped = new StateCompleteTransition(*stopping_, *stopped_);
CmdTransition * stopped_resetting_ = CmdTransition::reset(*stopped_, *resetting_);
StateCompleteTransition * unholding_execute_ = new StateCompleteTransition(*unholding_,
*execute_);
CmdTransition * held_unholding_ = CmdTransition::unhold(*held_, *unholding_);
StateCompleteTransition * holding_held_ = new StateCompleteTransition(*holding_, *held_);
CmdTransition * idle_starting_ = CmdTransition::start(*idle_, *starting_);
StateCompleteTransition * starting_execute_ = new StateCompleteTransition(*starting_,
*execute_);
CmdTransition * execute_holding_ = CmdTransition::hold(*execute_, *holding_);
StateCompleteTransition * execute_execute_ = new StateCompleteTransition(*execute_,
*execute_);
StateCompleteTransition * completing_complete = new StateCompleteTransition(*completing_,
*complete_);
CmdTransition * complete_resetting_ = CmdTransition::reset(*complete_, *resetting_);
StateCompleteTransition * resetting_idle_ = new StateCompleteTransition(*resetting_, *idle_);
CmdTransition * execute_suspending_ = CmdTransition::suspend(*execute_, *suspending_);
StateCompleteTransition * suspending_suspended_ = new StateCompleteTransition(*suspending_,
*suspended_);
CmdTransition * suspended_unsuspending_ = CmdTransition::unsuspend(*suspended_,
*unsuspending_);
StateCompleteTransition * unsuspending_execute_ = new StateCompleteTransition(*unsuspending_,
*execute_);
abortable_->setInitialState(clearing_);
stoppable_->setInitialState(resetting_);
sm_internal_.setInitialState(aborted_);
printf("State machine formed\n");
}
SingleCycle::SingleCycle()
{
printf("Forming SINGLE CYCLE state machine (states + transitions)\n");
// Naming <from state>_<to state>
CmdTransition * abortable_aborting_on_cmd = CmdTransition::abort(*abortable_, *aborting_);
ErrorTransition * abortable_aborting_on_error = new ErrorTransition(*abortable_, *aborting_);
StateCompleteTransition * aborting_aborted = new StateCompleteTransition(*aborting_,
*aborted_);
CmdTransition * aborted_clearing_ = CmdTransition::clear(*aborted_, *clearing_);
StateCompleteTransition * clearing_stopped_ = new StateCompleteTransition(*clearing_,
*stopped_);
CmdTransition * stoppable_stopping_ = CmdTransition::stop(*stoppable_, *stopping_);
StateCompleteTransition * stopping_stopped = new StateCompleteTransition(*stopping_,
*stopped_);
CmdTransition * stopped_resetting_ = CmdTransition::reset(*stopped_, *resetting_);
StateCompleteTransition * unholding_execute_ = new StateCompleteTransition(*unholding_,
*execute_);
CmdTransition * held_unholding_ = CmdTransition::unhold(*held_, *unholding_);
StateCompleteTransition * holding_held_ = new StateCompleteTransition(*holding_, *held_);
CmdTransition * idle_starting_ = CmdTransition::start(*idle_, *starting_);
StateCompleteTransition * starting_execute_ = new StateCompleteTransition(*starting_,
*execute_);
CmdTransition * execute_holding_ = CmdTransition::hold(*execute_, *holding_);
StateCompleteTransition * execute_completing_ = new StateCompleteTransition(*execute_,
*completing_);
StateCompleteTransition * completing_complete = new StateCompleteTransition(*completing_,
*complete_);
CmdTransition * complete_resetting_ = CmdTransition::reset(*complete_, *resetting_);
StateCompleteTransition * resetting_idle_ = new StateCompleteTransition(*resetting_, *idle_);
CmdTransition * execute_suspending_ = CmdTransition::suspend(*execute_, *suspending_);
StateCompleteTransition * suspending_suspended_ = new StateCompleteTransition(*suspending_,
*suspended_);
CmdTransition * suspended_unsuspending_ = CmdTransition::unsuspend(*suspended_,
*unsuspending_);
StateCompleteTransition * unsuspending_execute_ = new StateCompleteTransition(*unsuspending_,
*execute_);
abortable_->setInitialState(clearing_);
stoppable_->setInitialState(resetting_);
sm_internal_.setInitialState(aborted_);
printf("State machine formed\n");
}
} // namespace packml_sm
| [
"dejanira.araiza.i@gmail.com"
] | dejanira.araiza.i@gmail.com |
d11f5f49587dad0028d973c9b9dbe28202ae5ef0 | ce69fb18d8b54c4adcebd3bc2a0399ab475a1da5 | /speedup_dev_src/includes/xtensor/xbuilder.hpp | 113f05796eb579e5159776be99149a4a06faa2ad | [] | no_license | JoachimKoenigslieb/pyhpc-fpga | 1f48a9b2892e942f401c2f91613e5c092bfc3025 | 355df6dd78c4793bc049034362d1c5e6acbc3c4b | refs/heads/master | 2023-04-22T15:23:50.938411 | 2021-05-18T01:55:39 | 2021-05-18T01:55:39 | 310,040,568 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,148 | hpp | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
/**
* @brief standard mathematical functions for xexpressions
*/
#ifndef XTENSOR_BUILDER_HPP
#define XTENSOR_BUILDER_HPP
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <functional>
#include <utility>
#include <vector>
#ifdef X_OLD_CLANG
#include <initializer_list>
#endif
#include <xtl/xclosure.hpp>
#include <xtl/xsequence.hpp>
#include <xtl/xtype_traits.hpp>
#include "xbroadcast.hpp"
#include "xfunction.hpp"
#include "xgenerator.hpp"
#include "xoperation.hpp"
namespace xt
{
/********
* ones *
********/
/**
* Returns an \ref xexpression containing ones of the specified shape.
* @tparam shape the shape of the returned expression.
*/
template <class T, class S>
inline auto ones(S shape) noexcept
{
return broadcast(T(1), std::forward<S>(shape));
}
#ifdef X_OLD_CLANG
template <class T, class I>
inline auto ones(std::initializer_list<I> shape) noexcept
{
return broadcast(T(1), shape);
}
#else
template <class T, class I, std::size_t L>
inline auto ones(const I (&shape)[L]) noexcept
{
return broadcast(T(1), shape);
}
#endif
/*********
* zeros *
*********/
/**
* Returns an \ref xexpression containing zeros of the specified shape.
* @tparam shape the shape of the returned expression.
*/
template <class T, class S>
inline auto zeros(S shape) noexcept
{
return broadcast(T(0), std::forward<S>(shape));
}
#ifdef X_OLD_CLANG
template <class T, class I>
inline auto zeros(std::initializer_list<I> shape) noexcept
{
return broadcast(T(0), shape);
}
#else
template <class T, class I, std::size_t L>
inline auto zeros(const I (&shape)[L]) noexcept
{
return broadcast(T(0), shape);
}
#endif
/**
* Create a xcontainer (xarray, xtensor or xtensor_fixed) with uninitialized values of
* with value_type T and shape. Selects the best container match automatically
* from the supplied shape.
*
* - ``std::vector`` → ``xarray<T>``
* - ``std::array`` or ``initializer_list`` → ``xtensor<T, N>``
* - ``xshape<N...>`` → ``xtensor_fixed<T, xshape<N...>>``
*
* @param shape shape of the new xcontainer
*/
template <class T, layout_type L = XTENSOR_DEFAULT_LAYOUT, class S>
inline xarray<T, L> empty(const S& shape)
{
return xarray<T, L>::from_shape(shape);
}
template <class T, layout_type L = XTENSOR_DEFAULT_LAYOUT, class ST, std::size_t N>
inline xtensor<T, N, L> empty(const std::array<ST, N>& shape)
{
using shape_type = typename xtensor<T, N>::shape_type;
return xtensor<T, N, L>(xtl::forward_sequence<shape_type, decltype(shape)>(shape));
}
#ifndef X_OLD_CLANG
template <class T, layout_type L = XTENSOR_DEFAULT_LAYOUT, class I, std::size_t N>
inline xtensor<T, N, L> empty(const I(&shape)[N])
{
using shape_type = typename xtensor<T, N>::shape_type;
return xtensor<T, N, L>(xtl::forward_sequence<shape_type, decltype(shape)>(shape));
}
#else
template <class T, layout_type L = XTENSOR_DEFAULT_LAYOUT, class I>
inline xarray<T, L> empty(const std::initializer_list<I>& init)
{
return xarray<T, L>::from_shape(init);
}
#endif
template <class T, layout_type L = XTENSOR_DEFAULT_LAYOUT, std::size_t... N>
inline xtensor_fixed<T, fixed_shape<N...>, L> empty(const fixed_shape<N...>& /*shape*/)
{
return xtensor_fixed<T, fixed_shape<N...>, L>();
}
/**
* Create a xcontainer (xarray, xtensor or xtensor_fixed) with uninitialized values of
* the same shape, value type and layout as the input xexpression *e*.
*
* @param e the xexpression from which to extract shape, value type and layout.
*/
template <class E>
inline auto empty_like(const xexpression<E>& e)
{
using xtype = temporary_type_t<typename E::value_type, typename E::shape_type, E::static_layout>;
auto res = xtype::from_shape(e.derived_cast().shape());
return res;
}
/**
* Create a xcontainer (xarray, xtensor or xtensor_fixed), filled with *fill_value* and of
* the same shape, value type and layout as the input xexpression *e*.
*
* @param e the xexpression from which to extract shape, value type and layout.
* @param fill_value the value used to set each element of the returned xcontainer.
*/
template <class E>
inline auto full_like(const xexpression<E>& e, typename E::value_type fill_value)
{
using xtype = temporary_type_t<typename E::value_type, typename E::shape_type, E::static_layout>;
auto res = xtype::from_shape(e.derived_cast().shape());
res.fill(fill_value);
return res;
}
/**
* Create a xcontainer (xarray, xtensor or xtensor_fixed), filled with zeros and of
* the same shape, value type and layout as the input xexpression *e*.
*
* Note: contrary to zeros(shape), this function returns a non-lazy, allocated container!
* Use ``xt::zeros<double>(e.shape());` for a lazy version.
*
* @param e the xexpression from which to extract shape, value type and layout.
*/
template <class E>
inline auto zeros_like(const xexpression<E>& e)
{
return full_like(e, typename E::value_type(0));
}
/**
* Create a xcontainer (xarray, xtensor or xtensor_fixed), filled with ones and of
* the same shape, value type and layout as the input xexpression *e*.
*
* Note: contrary to ones(shape), this function returns a non-lazy, evaluated container!
* Use ``xt::ones<double>(e.shape());`` for a lazy version.
*
* @param e the xexpression from which to extract shape, value type and layout.
*/
template <class E>
inline auto ones_like(const xexpression<E>& e)
{
return full_like(e, typename E::value_type(1));
}
namespace detail
{
template <class T, class S>
struct get_mult_type_impl
{
using type = T;
};
template <class T, class R, class P>
struct get_mult_type_impl<T, std::chrono::duration<R, P>>
{
using type = R;
};
template <class T, class S>
using get_mult_type = typename get_mult_type_impl<T, S>::type;
// These methods should be private methods of arange_generator, however thi leads
// to ICE on VS2015
template <class R, class E, class U, class X, XTL_REQUIRES(xtl::is_integral<X>)>
inline void arange_assign_to(xexpression<E>& e, U start, X step) noexcept
{
auto& de = e.derived_cast();
U value = start;
for (auto&& el : de.storage())
{
el = static_cast<R>(value);
value += step;
}
}
template <class R, class E, class U, class X, XTL_REQUIRES(xtl::negation<xtl::is_integral<X>>)>
inline void arange_assign_to(xexpression<E>& e, U start, X step) noexcept
{
auto& buf = e.derived_cast().storage();
using size_type = decltype(buf.size());
using mult_type = get_mult_type<U, X>;
for(size_type i = 0; i < buf.size(); ++i)
{
buf[i] = static_cast<R>(start + step * mult_type(i));
}
}
template <class T, class R = T, class S = T>
class arange_generator
{
public:
using value_type = R;
using step_type = S;
arange_generator(T start, T stop, S step)
: m_start(start), m_stop(stop), m_step(step)
{
}
template <class... Args>
inline R operator()(Args... args) const
{
return access_impl(args...);
}
template <class It>
inline R element(It first, It) const
{
// Avoids warning when T = char (because char + char => int!)
using mult_type = get_mult_type<T, S>;
return static_cast<R>(m_start + m_step * mult_type(*first));
}
template <class E>
inline void assign_to(xexpression<E>& e) const noexcept
{
arange_assign_to<R>(e, m_start, m_step);
}
private:
T m_start;
T m_stop;
step_type m_step;
template <class T1, class... Args>
inline R access_impl(T1 t, Args...) const
{
using mult_type = get_mult_type<T, S>;
return static_cast<R>(m_start + m_step * mult_type(t));
}
inline R access_impl() const
{
return static_cast<R>(m_start);
}
};
template <class T, class S>
using both_integer = xtl::conjunction<xtl::is_integral<T>, xtl::is_integral<S>>;
template <class T, class S>
using integer_with_signed_integer = xtl::conjunction<both_integer<T, S>, xtl::is_signed<S>>;
template <class T, class S>
using integer_with_unsigned_integer = xtl::conjunction<both_integer<T, S>, std::is_unsigned<S>>;
template <class T, class S = T, XTL_REQUIRES(xtl::negation<both_integer<T, S>>)>
inline auto arange_impl(T start, T stop, S step = 1) noexcept
{
std::size_t shape = static_cast<std::size_t>(std::ceil((stop - start) / step));
return detail::make_xgenerator(detail::arange_generator<T, T, S>(start, stop, step), {shape});
}
template <class T, class S = T, XTL_REQUIRES(integer_with_signed_integer<T, S>)>
inline auto arange_impl(T start, T stop, S step = 1) noexcept
{
bool empty_cond = (stop - start) / step <= 0;
std::size_t shape = 0;
if(!empty_cond)
{
shape = stop > start ? static_cast<std::size_t>((stop - start + step - S(1)) / step)
: static_cast<std::size_t>((start - stop - step - S(1)) / -step);
}
return detail::make_xgenerator(detail::arange_generator<T, T, S>(start, stop, step), {shape});
}
template <class T, class S = T, XTL_REQUIRES(integer_with_unsigned_integer<T, S>)>
inline auto arange_impl(T start, T stop, S step = 1) noexcept
{
bool empty_cond = stop <= start;
std::size_t shape = 0;
if (!empty_cond)
{
shape = static_cast<std::size_t>((stop - start + step - S(1)) / step);
}
return detail::make_xgenerator(detail::arange_generator<T, T, S>(start, stop, step), { shape });
}
template <class F>
class fn_impl
{
public:
using value_type = typename F::value_type;
using size_type = std::size_t;
fn_impl(F&& f)
: m_ft(f)
{
}
inline value_type operator()() const
{
size_type idx[1] = {0ul};
return access_impl(std::begin(idx), std::end(idx));
}
template <class... Args>
inline value_type operator()(Args... args) const
{
size_type idx[sizeof...(Args)] = {static_cast<size_type>(args)...};
return access_impl(std::begin(idx), std::end(idx));
}
template <class It>
inline value_type element(It first, It last) const
{
return access_impl(first, last);
}
private:
F m_ft;
template <class It>
inline value_type access_impl(const It& begin, const It& end) const
{
return m_ft(begin, end);
}
};
template <class T>
class eye_fn
{
public:
using value_type = T;
eye_fn(int k)
: m_k(k)
{
}
template <class It>
inline T operator()(const It& /*begin*/, const It& end) const
{
using lvalue_type = typename std::iterator_traits<It>::value_type;
return *(end - 1) == *(end - 2) + static_cast<lvalue_type>(m_k) ? T(1) : T(0);
}
private:
std::ptrdiff_t m_k;
};
}
/**
* Generates an array with ones on the diagonal.
* @param shape shape of the resulting expression
* @param k index of the diagonal. 0 (default) refers to the main diagonal,
* a positive value refers to an upper diagonal, and a negative
* value to a lower diagonal.
* @tparam T value_type of xexpression
* @return xgenerator that generates the values on access
*/
template <class T = bool>
inline auto eye(const std::vector<std::size_t>& shape, int k = 0)
{
return detail::make_xgenerator(detail::fn_impl<detail::eye_fn<T>>(detail::eye_fn<T>(k)), shape);
}
/**
* Generates a (n x n) array with ones on the diagonal.
* @param n length of the diagonal.
* @param k index of the diagonal. 0 (default) refers to the main diagonal,
* a positive value refers to an upper diagonal, and a negative
* value to a lower diagonal.
* @tparam T value_type of xexpression
* @return xgenerator that generates the values on access
*/
template <class T = bool>
inline auto eye(std::size_t n, int k = 0)
{
return eye<T>({n, n}, k);
}
/**
* Generates numbers evenly spaced within given half-open interval [start, stop).
* @param start start of the interval
* @param stop stop of the interval
* @param step stepsize
* @tparam T value_type of xexpression
* @return xgenerator that generates the values on access
*/
template <class T, class S = T>
inline auto arange(T start, T stop, S step = 1) noexcept
{
return detail::arange_impl(start, stop, step);
}
/**
* Generate numbers evenly spaced within given half-open interval [0, stop)
* with a step size of 1.
* @param stop stop of the interval
* @tparam T value_type of xexpression
* @return xgenerator that generates the values on access
*/
template <class T>
inline auto arange(T stop) noexcept
{
return arange<T>(T(0), stop, T(1));
}
/**
* Generates @a num_samples evenly spaced numbers over given interval
* @param start start of interval
* @param stop stop of interval
* @param num_samples number of samples (defaults to 50)
* @param endpoint if true, include endpoint (defaults to true)
* @tparam T value_type of xexpression
* @return xgenerator that generates the values on access
*/
template <class T>
inline auto linspace(T start, T stop, std::size_t num_samples = 50, bool endpoint = true) noexcept
{
using fp_type = std::common_type_t<T, double>;
fp_type step = fp_type(stop - start) / std::fmax(fp_type(1), fp_type(num_samples - (endpoint ? 1 : 0)));
return detail::make_xgenerator(detail::arange_generator<fp_type, T>(fp_type(start), fp_type(stop), step), {num_samples});
}
/**
* Generates @a num_samples numbers evenly spaced on a log scale over given interval
* @param start start of interval (pow(base, start) is the first value).
* @param stop stop of interval (pow(base, stop) is the final value, except if endpoint = false)
* @param num_samples number of samples (defaults to 50)
* @param base the base of the log space.
* @param endpoint if true, include endpoint (defaults to true)
* @tparam T value_type of xexpression
* @return xgenerator that generates the values on access
*/
template <class T>
inline auto logspace(T start, T stop, std::size_t num_samples, T base = 10, bool endpoint = true) noexcept
{
return pow(std::move(base), linspace(start, stop, num_samples, endpoint));
}
namespace detail
{
template <class... CT>
class concatenate_access
{
public:
using tuple_type = std::tuple<CT...>;
using size_type = std::size_t;
using value_type = xtl::promote_type_t<typename std::decay_t<CT>::value_type...>;
template <class S>
inline value_type access(const tuple_type& t, size_type axis, S index) const
{
auto match = [&index, axis](auto& arr)
{
if (index[axis] >= arr.shape()[axis])
{
index[axis] -= arr.shape()[axis];
return false;
}
return true;
};
auto get = [&index](auto& arr)
{
return arr[index];
};
size_type i = 0;
for (; i < sizeof...(CT); ++i)
{
if (apply<bool>(i, match, t))
{
break;
}
}
return apply<value_type>(i, get, t);
}
};
template <class... CT>
class stack_access
{
public:
using tuple_type = std::tuple<CT...>;
using size_type = std::size_t;
using value_type = xtl::promote_type_t<typename std::decay_t<CT>::value_type...>;
template <class S>
inline value_type access(const tuple_type& t, size_type axis, S index) const
{
auto get_item = [&index](auto& arr)
{
return arr[index];
};
size_type i = index[axis];
index.erase(index.begin() + std::ptrdiff_t(axis));
return apply<value_type>(i, get_item, t);
}
};
template <class... CT>
class vstack_access : private concatenate_access<CT...>,
private stack_access<CT...>
{
public:
using tuple_type = std::tuple<CT...>;
using size_type = std::size_t;
using value_type = xtl::promote_type_t<typename std::decay_t<CT>::value_type...>;
using concatenate_base = concatenate_access<CT...>;
using stack_base = stack_access<CT...>;
template <class S>
inline value_type access(const tuple_type& t, size_type axis, S index) const
{
if (std::get<0>(t).dimension() == 1)
{
return stack_base::access(t, axis, index);
}
else
{
return concatenate_base::access(t, axis, index);
}
}
};
template <template <class...> class F, class... CT>
class concatenate_invoker : private F<CT...>
{
public:
using tuple_type = std::tuple<CT...>;
using size_type = std::size_t;
using value_type = xtl::promote_type_t<typename std::decay_t<CT>::value_type...>;
inline concatenate_invoker(tuple_type&& t, size_type axis)
: m_t(std::move(t)), m_axis(axis)
{
}
template <class... Args>
inline value_type operator()(Args... args) const
{
// TODO: avoid memory allocation
return this->access(m_t, m_axis, xindex({static_cast<size_type>(args)...}));
}
template <class It>
inline value_type element(It first, It last) const
{
// TODO: avoid memory allocation
return this->access(m_t, m_axis, xindex(first, last));
}
private:
tuple_type m_t;
size_type m_axis;
};
template <class... CT>
using concatenate_impl = concatenate_invoker<concatenate_access, CT...>;
template <class... CT>
using stack_impl = concatenate_invoker<stack_access, CT...>;
template <class... CT>
using vstack_impl = concatenate_invoker<vstack_access, CT...>;
template <class CT>
class repeat_impl
{
public:
using xexpression_type = std::decay_t<CT>;
using size_type = typename xexpression_type::size_type;
using value_type = typename xexpression_type::value_type;
template <class CTA>
repeat_impl(CTA&& source, size_type axis)
: m_source(std::forward<CTA>(source)), m_axis(axis)
{
}
template <class... Args>
value_type operator()(Args... args) const
{
std::array<size_type, sizeof...(Args)> args_arr = {static_cast<size_type>(args)...};
return m_source(args_arr[m_axis]);
}
template <class It>
inline value_type element(It first, It) const
{
return m_source(*(first + static_cast<std::ptrdiff_t>(m_axis)));
}
private:
CT m_source;
size_type m_axis;
};
}
/**
* @brief Creates tuples from arguments for \ref concatenate and \ref stack.
* Very similar to std::make_tuple.
*/
template <class... Types>
inline auto xtuple(Types&&... args)
{
return std::tuple<xtl::const_closure_type_t<Types>...>(std::forward<Types>(args)...);
}
namespace detail {
template <bool... values>
using all_true = xtl::conjunction<std::integral_constant<bool, values>...>;
template <class X, class Y, std::size_t axis, class AxesSequence>
struct concat_fixed_shape_impl;
template <class X, class Y, std::size_t axis, std::size_t... Is>
struct concat_fixed_shape_impl<X, Y, axis, std::index_sequence<Is...>>
{
static_assert(X::size() == Y::size(), "Concatenation requires equisized shapes");
static_assert(axis < X::size(), "Concatenation requires a valid axis");
static_assert(all_true<(axis == Is || X::template get<Is>() == Y::template get<Is>())...>::value,
"Concatenation requires compatible shapes and axis");
using type = fixed_shape<(axis == Is ? X::template get<Is>() + Y::template get<Is>()
: X::template get<Is>())...>;
};
template <std::size_t axis, class X, class Y, class... Rest>
struct concat_fixed_shape;
template <std::size_t axis, class X, class Y>
struct concat_fixed_shape<axis, X, Y>
{
using type = typename concat_fixed_shape_impl<X, Y, axis, std::make_index_sequence<X::size()>>::type;
};
template <std::size_t axis, class X, class Y, class... Rest>
struct concat_fixed_shape
{
using type = typename concat_fixed_shape<axis, X, typename concat_fixed_shape<axis, Y, Rest...>::type>::type;
};
template <std::size_t axis, class... Args>
using concat_fixed_shape_t = typename concat_fixed_shape<axis, Args...>::type;
template <class... CT>
using all_fixed_shapes = detail::all_fixed<typename std::decay_t<CT>::shape_type...>;
struct concat_shape_builder_t
{
template <class Shape, bool = detail::is_fixed<Shape>::value>
struct concat_shape;
template <class Shape>
struct concat_shape<Shape, true>
{
// Convert `fixed_shape` to `static_shape` to allow runtime dimension calculation.
using type = static_shape<typename Shape::value_type, Shape::size()>;
};
template <class Shape>
struct concat_shape<Shape, false>
{
using type = Shape;
};
template <class... Args>
static auto build(const std::tuple<Args...>& t, std::size_t axis)
{
using shape_type = promote_shape_t<typename concat_shape<typename std::decay_t<Args>::shape_type>::type...>;
using source_shape_type = decltype(std::get<0>(t).shape());
shape_type new_shape = xtl::forward_sequence<shape_type, source_shape_type>(std::get<0>(t).shape());
auto check_shape = [&axis, &new_shape](auto& arr) {
std::size_t s = new_shape.size();
bool res = s == arr.dimension();
for(std::size_t i = 0; i < s; ++i)
{
res = res && (i == axis || new_shape[i] == arr.shape(i));
}
if(!res)
{
throw_concatenate_error(new_shape, arr.shape());
}
};
for_each(check_shape, t);
auto shape_at_axis = [&axis](std::size_t prev, auto& arr) -> std::size_t {
return prev + arr.shape()[axis];
};
new_shape[axis] += accumulate(shape_at_axis, std::size_t(0), t) - new_shape[axis];
return new_shape;
}
};
} // namespace detail
/***************
* concatenate *
***************/
/**
* @brief Concatenates xexpressions along \em axis.
*
* @param t \ref xtuple of xexpressions to concatenate
* @param axis axis along which elements are concatenated
* @returns xgenerator evaluating to concatenated elements
*
* \code{.cpp}
* xt::xarray<double> a = {{1, 2, 3}};
* xt::xarray<double> b = {{2, 3, 4}};
* xt::xarray<double> c = xt::concatenate(xt::xtuple(a, b)); // => {{1, 2, 3},
* // {2, 3, 4}}
* xt::xarray<double> d = xt::concatenate(xt::xtuple(a, b), 1); // => {{1, 2, 3, 2, 3, 4}}
* \endcode
*/
template <class... CT>
inline auto concatenate(std::tuple<CT...>&& t, std::size_t axis = 0)
{
const auto shape = detail::concat_shape_builder_t::build(t, axis);
return detail::make_xgenerator(detail::concatenate_impl<CT...>(std::move(t), axis), shape);
}
template <std::size_t axis, class... CT, typename = std::enable_if_t<detail::all_fixed_shapes<CT...>::value>>
inline auto concatenate(std::tuple<CT...> &&t)
{
using shape_type = detail::concat_fixed_shape_t<axis, typename std::decay_t<CT>::shape_type...>;
return detail::make_xgenerator(detail::concatenate_impl<CT...>(std::move(t), axis), shape_type{});
}
namespace detail
{
template <class T, std::size_t N>
inline std::array<T, N + 1> add_axis(std::array<T, N> arr, std::size_t axis, std::size_t value)
{
std::array<T, N + 1> temp;
std::copy(arr.begin(), arr.begin() + axis, temp.begin());
temp[axis] = value;
std::copy(arr.begin() + axis, arr.end(), temp.begin() + axis + 1);
return temp;
}
template <class T>
inline T add_axis(T arr, std::size_t axis, std::size_t value)
{
T temp(arr);
temp.insert(temp.begin() + std::ptrdiff_t(axis), value);
return temp;
}
}
/**
* @brief Stack xexpressions along \em axis.
* Stacking always creates a new dimension along which elements are stacked.
*
* @param t \ref xtuple of xexpressions to concatenate
* @param axis axis along which elements are stacked
* @returns xgenerator evaluating to stacked elements
*
* \code{.cpp}
* xt::xarray<double> a = {1, 2, 3};
* xt::xarray<double> b = {5, 6, 7};
* xt::xarray<double> s = xt::stack(xt::xtuple(a, b)); // => {{1, 2, 3},
* // {5, 6, 7}}
* xt::xarray<double> t = xt::stack(xt::xtuple(a, b), 1); // => {{1, 5},
* // {2, 6},
* // {3, 7}}
* \endcode
*/
template <class... CT>
inline auto stack(std::tuple<CT...>&& t, std::size_t axis = 0)
{
using shape_type = promote_shape_t<typename std::decay_t<CT>::shape_type...>;
using source_shape_type = decltype(std::get<0>(t).shape());
auto new_shape = detail::add_axis(xtl::forward_sequence<shape_type, source_shape_type>(std::get<0>(t).shape()), axis, sizeof...(CT));
return detail::make_xgenerator(detail::stack_impl<CT...>(std::move(t), axis), new_shape);
}
/**
* @brief Stack xexpressions in sequence horizontally (column wise).
* This is equivalent to concatenation along the second axis, except for 1-D
* xexpressions where it concatenate along the firts axis.
*
* @param t \ref xtuple of xexpressions to stack
* @return xgenerator evaluating to stacked elements
*/
template <class... CT>
inline auto hstack(std::tuple<CT...>&& t)
{
auto dim = std::get<0>(t).dimension();
std::size_t axis = dim > std::size_t(1) ? 1 : 0;
return concatenate(std::move(t), axis);
}
namespace detail
{
template <class S, class... CT>
inline auto vstack_shape(std::tuple<CT...>& t, const S& shape)
{
using size_type = typename S::value_type;
auto res = shape.size() == size_type(1) ?
S({sizeof...(CT), shape[0]}) :
concat_shape_builder_t::build(std::move(t), size_type(0));
return res;
}
template <class T, class... CT>
inline auto vstack_shape(const std::tuple<CT...>&, std::array<T, 1> shape)
{
std::array<T, 2> res = { sizeof...(CT), shape[0] };
return res;
}
}
/**
* @brief Stack xexpressions in sequence vertically (row wise).
* This is equivalent to concatenation along the first axis after
* 1-D arrays of shape (N) have been reshape to (1, N).
*
* @param t \ref xtuple of xexpressions to stack
* @return xgenerator evaluating to stacked elements
*/
template <class... CT>
inline auto vstack(std::tuple<CT...>&& t)
{
using shape_type = promote_shape_t<typename std::decay_t<CT>::shape_type...>;
using source_shape_type = decltype(std::get<0>(t).shape());
auto new_shape = detail::vstack_shape(t, xtl::forward_sequence<shape_type, source_shape_type>(std::get<0>(t).shape()));
return detail::make_xgenerator(detail::vstack_impl<CT...>(std::move(t), size_t(0)), new_shape);
}
namespace detail
{
template <std::size_t... I, class... E>
inline auto meshgrid_impl(std::index_sequence<I...>, E&&... e) noexcept
{
#if defined X_OLD_CLANG || defined _MSC_VER
const std::array<std::size_t, sizeof...(E)> shape = {e.shape()[0]...};
return std::make_tuple(
detail::make_xgenerator(
detail::repeat_impl<xclosure_t<E>>(std::forward<E>(e), I),
shape
)...
);
#else
return std::make_tuple(
detail::make_xgenerator(
detail::repeat_impl<xclosure_t<E>>(std::forward<E>(e), I),
{e.shape()[0]...}
)...
);
#endif
}
}
/**
* @brief Return coordinate tensors from coordinate vectors.
* Make N-D coordinate tensor expressions for vectorized evaluations of N-D scalar/vector
* fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn.
*
* @param e xexpressions to concatenate
* @returns tuple of xgenerator expressions.
*/
template <class... E>
inline auto meshgrid(E&&... e) noexcept
{
return detail::meshgrid_impl(std::make_index_sequence<sizeof...(E)>(), std::forward<E>(e)...);
}
namespace detail
{
template <class CT>
class diagonal_fn
{
public:
using xexpression_type = std::decay_t<CT>;
using value_type = typename xexpression_type::value_type;
template <class CTA>
diagonal_fn(CTA&& source, int offset, std::size_t axis_1, std::size_t axis_2)
: m_source(std::forward<CTA>(source)), m_offset(offset), m_axis_1(axis_1), m_axis_2(axis_2)
{
}
template <class It>
inline value_type operator()(It begin, It) const
{
xindex idx(m_source.shape().size());
for (std::size_t i = 0; i < idx.size(); i++)
{
if (i != m_axis_1 && i != m_axis_2)
{
idx[i] = *begin++;
}
}
using it_vtype = typename std::iterator_traits<It>::value_type;
it_vtype uoffset = static_cast<it_vtype>(m_offset);
if (m_offset >= 0)
{
idx[m_axis_1] = *(begin);
idx[m_axis_2] = *(begin) + uoffset;
}
else
{
idx[m_axis_1] = *(begin) - uoffset;
idx[m_axis_2] = *(begin);
}
return m_source[idx];
}
private:
CT m_source;
const int m_offset;
const std::size_t m_axis_1;
const std::size_t m_axis_2;
};
template <class CT>
class diag_fn
{
public:
using xexpression_type = std::decay_t<CT>;
using value_type = typename xexpression_type::value_type;
template <class CTA>
diag_fn(CTA&& source, int k)
: m_source(std::forward<CTA>(source)), m_k(k)
{
}
template <class It>
inline value_type operator()(It begin, It) const
{
using it_vtype = typename std::iterator_traits<It>::value_type;
it_vtype umk = static_cast<it_vtype>(m_k);
if (m_k > 0)
{
return *begin + umk == *(begin + 1) ? m_source(*begin) : value_type(0);
}
else
{
return *begin + umk == *(begin + 1) ? m_source(*begin + umk) : value_type(0);
}
}
private:
CT m_source;
const int m_k;
};
template <class CT, class Comp>
class trilu_fn
{
public:
using xexpression_type = std::decay_t<CT>;
using value_type = typename xexpression_type::value_type;
using signed_idx_type = long int;
template <class CTA>
trilu_fn(CTA&& source, int k, Comp comp)
: m_source(std::forward<CTA>(source)), m_k(k), m_comp(comp)
{
}
template <class It>
inline value_type operator()(It begin, It end) const
{
// have to cast to signed int otherwise -1 can lead to overflow
return m_comp(signed_idx_type(*begin) + m_k, signed_idx_type(*(begin + 1))) ? m_source.element(begin, end) : value_type(0);
}
private:
CT m_source;
const signed_idx_type m_k;
const Comp m_comp;
};
}
namespace detail
{
// meta-function returning the shape type for a diagonal
template <class ST, class... S>
struct diagonal_shape_type
{
using type = ST;
};
template <class I, std::size_t L>
struct diagonal_shape_type<std::array<I, L>>
{
using type = std::array<I, L - 1>;
};
}
/**
* @brief Returns the elements on the diagonal of arr
* If arr has more than two dimensions, then the axes specified by
* axis_1 and axis_2 are used to determine the 2-D sub-array whose
* diagonal is returned. The shape of the resulting array can be
* determined by removing axis1 and axis2 and appending an index
* to the right equal to the size of the resulting diagonals.
*
* @param arr the input array
* @param offset offset of the diagonal from the main diagonal. Can
* be positive or negative.
* @param axis_1 Axis to be used as the first axis of the 2-D sub-arrays
* from which the diagonals should be taken.
* @param axis_2 Axis to be used as the second axis of the 2-D sub-arrays
* from which the diagonals should be taken.
* @returns xexpression with values of the diagonal
*
* \code{.cpp}
* xt::xarray<double> a = {{1, 2, 3},
* {4, 5, 6}
* {7, 8, 9}};
* auto b = xt::diagonal(a); // => {1, 5, 9}
* \endcode
*/
template <class E>
inline auto diagonal(E&& arr, int offset = 0, std::size_t axis_1 = 0, std::size_t axis_2 = 1)
{
using CT = xclosure_t<E>;
using shape_type = typename detail::diagonal_shape_type<typename std::decay_t<E>::shape_type>::type;
auto shape = arr.shape();
auto dimension = arr.dimension();
// The following shape calculation code is an almost verbatim adaptation of numpy:
// https://github.com/numpy/numpy/blob/2aabeafb97bea4e1bfa29d946fbf31e1104e7ae0/numpy/core/src/multiarray/item_selection.c#L1799
auto ret_shape = xtl::make_sequence<shape_type>(dimension - 1, 0);
int dim_1 = static_cast<int>(shape[axis_1]);
int dim_2 = static_cast<int>(shape[axis_2]);
offset >= 0 ? dim_2 -= offset : dim_1 += offset;
auto diag_size = std::size_t(dim_2 < dim_1 ? dim_2 : dim_1);
std::size_t i = 0;
for (std::size_t idim = 0; idim < dimension; ++idim)
{
if (idim != axis_1 && idim != axis_2)
{
ret_shape[i++] = shape[idim];
}
}
ret_shape.back() = diag_size;
return detail::make_xgenerator(detail::fn_impl<detail::diagonal_fn<CT>>(detail::diagonal_fn<CT>(std::forward<E>(arr), offset, axis_1, axis_2)),
ret_shape);
}
/**
* @brief xexpression with values of arr on the diagonal, zeroes otherwise
*
* @param arr the 1D input array of length n
* @param k the offset of the considered diagonal
* @returns xexpression function with shape n x n and arr on the diagonal
*
* \code{.cpp}
* xt::xarray<double> a = {1, 5, 9};
* auto b = xt::diag(a); // => {{1, 0, 0},
* // {0, 5, 0},
* // {0, 0, 9}}
* \endcode
*/
template <class E>
inline auto diag(E&& arr, int k = 0)
{
using CT = xclosure_t<E>;
std::size_t sk = std::size_t(std::abs(k));
std::size_t s = arr.shape()[0] + sk;
return detail::make_xgenerator(detail::fn_impl<detail::diag_fn<CT>>(detail::diag_fn<CT>(std::forward<E>(arr), k)),
{s, s});
}
/**
* @brief Extract lower triangular matrix from xexpression. The parameter k selects the
* offset of the diagonal.
*
* @param arr the input array
* @param k the diagonal above which to zero elements. 0 (default) selects the main diagonal,
* k < 0 is below the main diagonal, k > 0 above.
* @returns xexpression containing lower triangle from arr, 0 otherwise
*/
template <class E>
inline auto tril(E&& arr, int k = 0)
{
using CT = xclosure_t<E>;
auto shape = arr.shape();
return detail::make_xgenerator(detail::fn_impl<detail::trilu_fn<CT, std::greater_equal<long int>>>(
detail::trilu_fn<CT, std::greater_equal<long int>>(std::forward<E>(arr), k, std::greater_equal<long int>())),
shape);
}
/**
* @brief Extract upper triangular matrix from xexpression. The parameter k selects the
* offset of the diagonal.
*
* @param arr the input array
* @param k the diagonal below which to zero elements. 0 (default) selects the main diagonal,
* k < 0 is below the main diagonal, k > 0 above.
* @returns xexpression containing lower triangle from arr, 0 otherwise
*/
template <class E>
inline auto triu(E&& arr, int k = 0)
{
using CT = xclosure_t<E>;
auto shape = arr.shape();
return detail::make_xgenerator(detail::fn_impl<detail::trilu_fn<CT, std::less_equal<long int>>>(
detail::trilu_fn<CT, std::less_equal<long int>>(std::forward<E>(arr), k, std::less_equal<long int>())),
shape);
}
}
#endif
| [
"joachim.koenigslieb@gmail.com"
] | joachim.koenigslieb@gmail.com |
4bb2d4b05d633e060484e6b8271c2ca5ed04a7b6 | 61cd8c253bff2ea1c236980a15cc5ce228469f6c | /src/test/test_errors.cxx | 0beb4d143cc983ca1ea834a920bbffffba33c4d7 | [
"BSD-3-Clause"
] | permissive | fermi-lat/rdbModel | 9be1e4bf89c7caeba74cd2780b050071577458ac | b7d0846a2736ff2fb202f4c0c6c50c4f4467ded9 | refs/heads/master | 2022-02-13T23:49:49.594918 | 2019-08-27T17:30:17 | 2019-08-27T17:30:17 | 103,187,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,348 | cxx | // $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/rdbModel/src/test/test_errors.cxx,v 1.6 2008/12/04 20:23:10 jrb Exp $
// Test program for rdbModel primitive buiding blocks
#include <iostream>
#include <string>
#include <cstdlib>
#include "rdbModel/Rdb.h"
#include "rdbModel/RdbException.h"
#include "rdbModel/Management/Manager.h"
#include "rdbModel/Management/XercesBuilder.h"
#include "rdbModel/Db/MysqlConnection.h"
#include "rdbModel/Db/MysqlResults.h"
#include "rdbModel/Tables/Table.h"
#include "rdbModel/Tables/Column.h"
#include "rdbModel/Tables/Datatype.h"
#include "rdbModel/Tables/Assertion.h"
#include "facilities/Util.h"
#include "facilities/commonUtilities.h"
// When TEST_INSERT is defined, use connection which can write
// #define TEST_INSERT
int doBadInsert(rdbModel::Rdb* con);
int doBadUpdate(rdbModel::Rdb*, int serial);
int doUpdate(rdbModel::Rdb*, int serial);
int main(int, char**) {
using rdbModel::FieldVal;
std::string xmlPath = facilities::commonUtilities::getXmlPath("rdbModel");
std::string infile = xmlPath + std::string("/calib_test.xml");
rdbModel::Builder* b = new rdbModel::XercesBuilder;
rdbModel::Rdb* rdb = new rdbModel::Rdb;
int errcode = rdb->build(infile, b);
if (errcode) {
std::cerr << "Build failed with error code " << errcode << std::endl;
return errcode;
}
/* rdbModel::Table* t = */
rdb->getTable("metadata_v2r1");
// mostly don't want to run code doing an insert. For times
// when we do, must connect as user with INSERT priv.
#ifdef TEST_INSERT
std::string connectfileT = xmlPath + std::string("connect/mysqlTester.xml");
#else
// This is glastreader, calib_test
std::string connectfileT = xmlPath + std::string("connect/mysqlSlacT.xml");
#endif
// Connect to production database, read only
rdbModel::MysqlConnection* con = new rdbModel::MysqlConnection();
std::string connectfile = xmlPath + std::string("/connect/mysqlSlac.xml");
if (!(con->open(connectfile)) ) {
std::cerr << "Unable to connect to MySQL database" << std::endl;
return -1;
}
/*
if (!(con->open(connectfileT)) ) {
std::cerr << "Unable to connect to MySQL test database" << std::endl;
return -1;
}
*/
rdbModel::MATCH match = con->matchSchema(rdb, false);
switch (match) {
case rdbModel::MATCHequivalent:
std::cout << "XML schema and MySQL database are equivalent!" << std::endl;
break;
case rdbModel::MATCHcompatible:
std::cout << "XML schema and MySQL database are compatible" << std::endl;
break;
case rdbModel::MATCHfail:
std::cout << "XML schema and MySQL database are NOT compatible"
<< std::endl;
return -2;
case rdbModel::MATCHnoConnection:
std::cout << "Connection failed while attempting match" << std::endl;
return -1;
}
// Make a query
std::string rq[4];
rq[0] ="select * from metadata_v2r1";
rq[1] ="select calib_type from metadata_v2r1";
rq[2] ="select garbage from metadata_v2r1";
// Try a query with improper syntax
rq[3]=" select ser_no from metadata_v2r1 WHERE noSuchColumn='2' ";
for (int i = 0; i < 3; i++) {
try {
rdbModel::ResultHandle* res =
con->dbRequest(rq[i]);
if (res) {
std::cout << "dbRequest '" << rq[i] << "'" << std::endl;
std::cout << "succeeded, returned " << res->getNRows()
<< " rows" << std::endl;
}
else {
std::cout << "dbRequest '" << rq[i] << "'" << std::endl;
std::cout << "succeeded, no returned data expected" << std::endl;
}
}
catch (rdbModel::RdbException ex) {
std::cerr << "dbRequest '" << rq[i] << "'" << std::endl;
std::cerr <<" failed with error: " << ex.getMsg() << std::endl;
// std::cerr << "Code " << ex.getCode() << std::endl;
}
}
// Make a bad query with con->select
std::vector<std::string> getCols;
std::vector<std::string> orderCols;
std::string where(" WHERE ser_no >=< 7");
getCols.push_back("flavor");
try {
// rdbModel::ResultHandle* res =
con->select("metadata_v2r1", getCols, orderCols, where);
}
catch (rdbModel::RdbException ex) {
std::cerr << "select failed with error: " << ex.getMsg() << std::endl;
// std::cerr << "Code " << ex.getCode() << std::endl;
}
doUpdate(rdb, 1); // should fail because we don't have write access
con->close();
// Following will do an insert if disable = set to false.
// To keep from cluttering up the
// database, mostly don't execute
//
# ifdef TEST_INSERT
if (!(con->open(connectfileT)) ) {
std::cerr << "Unable to connect to MySQL test database" << std::endl;
return -1;
}
match = con->matchSchema(rdb, false);
switch (match) {
case rdbModel::MATCHequivalent:
std::cout << "XML schema and MySQL database are equivalent!" << std::endl;
break;
case rdbModel::MATCHcompatible:
std::cout << "XML schema and MySQL database are compatible" << std::endl;
break;
case rdbModel::MATCHfail:
std::cout << "XML schema and MySQL database are NOT compatible"
<< std::endl;
return -2;
case rdbModel::MATCHnoConnection:
std::cout << "Connection failed while attempting match" << std::endl;
return -1;
}
doBadInsert(rdb);
doBadUpdate(rdb, 23);
# endif
return 0;
}
// int doInsert(rdbModel::Connection* con) {
int doBadInsert(rdbModel::Rdb* rdb) {
using rdbModel::FieldVal;
using rdbModel::Row;
std::vector<FieldVal> fields;
fields.reserve(15);
fields.push_back(FieldVal("instrument", "LAT"));
fields.push_back(FieldVal("calib_type","Test_Gen"));
fields.push_back(FieldVal("flavor","berry"));
fields.push_back(FieldVal("data_fmt","nonsense"));
fields.push_back(FieldVal("vstart","2003-02-01"));
fields.push_back(FieldVal("data_size","0"));
fields.push_back(FieldVal("locale","phobos"));
fields.push_back(FieldVal("completion","ABORT"));
fields.push_back(FieldVal("data_ident","$(mycalibs)/test/moreJunk.xml"));
fields.push_back(FieldVal("notes",
"Absurd test item, setting input_desc to NULL"));
fields.push_back(FieldVal("input_desc","", true));
fields.push_back(FieldVal("noSuchField","", true));
int serial = 0;
Row row(fields);
rdb->insertRow("metadata_v2r1", row, &serial);
unsigned errcode = rdb->getConnection()->getLastError();
std::cerr << "From doBadInsert. Last error code was " << errcode
<< std::endl;
if (rdb->duplicateError() ) {
std::cerr << "Last error was duplicate insert " << std::endl;
}
else {
std::cerr << "Last error was NOT duplicate insert " << std::endl;
}
return serial;
}
// int doUpdate(rdbModel::Connection* con, int serial) {
int doBadUpdate(rdbModel::Rdb* rdb, int serial) {
using rdbModel::Column;
using facilities::Util;
using rdbModel::FieldVal;
using rdbModel::Row;
// Set up bad WHERE clause
std::string serialStr;
Util::itoa(serial, serialStr);
std::string where("ser_no = '~");
where += serialStr + std::string("'");
std::vector<FieldVal> fields;
fields.push_back(FieldVal("notes", "1st update: set data_size to non-zero value"));
fields.push_back(FieldVal("data_size", "883"));
Row row(fields);
std::string table("metadata_v2r1");
unsigned nChange = rdb->updateRows(table, row, where);
unsigned errcode = rdb->getConnection()->getLastError();
std::cerr << "From doBadUpdate. Last error code was " << errcode
<< std::endl;
if (rdb->duplicateError() ) {
std::cerr << "Last error was duplicate insert " << std::endl;
}
else {
std::cerr << "Last error was NOT duplicate insert " << std::endl;
}
return (int) nChange;
}
int doUpdate(rdbModel::Rdb* rdb, int serial) {
using rdbModel::Column;
using facilities::Util;
using rdbModel::FieldVal;
using rdbModel::Row;
// WHERE clause
std::string serialStr;
Util::itoa(serial, serialStr);
std::string where(" where ser_no = '");
where += serialStr + std::string("'");
std::vector<FieldVal> fields;
fields.push_back(FieldVal("notes", "Update: set data_size to non-zero value"));
fields.push_back(FieldVal("data_size", "883"));
Row row(fields);
std::string table("metadata_v2r1");
unsigned nChange = rdb->updateRows(table, row, where);
return (int) nChange;
}
| [
""
] | |
b6253b5c60e1747799291a33974bd04b15791a50 | cb7ac15343e3b38303334f060cf658e87946c951 | /source/runtime/SlateCore/Public/Widgets/SWidget.h | c3c9d021b39bfb03516497a1e9702add06acf8ac | [] | no_license | 523793658/Air2.0 | ac07e33273454442936ce2174010ecd287888757 | 9e04d3729a9ce1ee214b58c2296188ec8bf69057 | refs/heads/master | 2021-11-10T16:08:51.077092 | 2021-11-04T13:11:59 | 2021-11-04T13:11:59 | 178,317,006 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68,074 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Misc/Attribute.h"
#include "Misc/FrameValue.h"
#include "Stats/Stats.h"
#include "Styling/SlateColor.h"
#include "Layout/SlateRect.h"
#include "Layout/Visibility.h"
#include "Layout/Clipping.h"
#include "Layout/Geometry.h"
#include "Layout/ArrangedWidget.h"
#include "Layout/LayoutGeometry.h"
#include "Layout/Margin.h"
#include "Layout/FlowDirection.h"
#include "Rendering/SlateLayoutTransform.h"
#include "Input/CursorReply.h"
#include "Input/Reply.h"
#include "Input/NavigationReply.h"
#include "Input/PopupMethodReply.h"
#include "Types/ISlateMetaData.h"
#include "Types/WidgetActiveTimerDelegate.h"
#include "Textures/SlateShaderResource.h"
#include "SlateGlobals.h"
#include "Types/PaintArgs.h"
#include "FastUpdate/WidgetProxy.h"
#include "InvalidateWidgetReason.h"
#include "Widgets/Accessibility/SlateWidgetAccessibleTypes.h"
class FActiveTimerHandle;
class FArrangedChildren;
class FChildren;
class FPaintArgs;
class FSlateWindowElementList;
class FSlotBase;
class FWeakWidgetPath;
class FWidgetPath;
class IToolTip;
class SWidget;
struct FSlateBrush;
struct FSlatePaintElementLists;
DECLARE_DWORD_COUNTER_STAT_EXTERN(TEXT("Widgets Created (Per Frame)"), STAT_SlateTotalWidgetsPerFrame, STATGROUP_Slate, SLATECORE_API);
DECLARE_DWORD_COUNTER_STAT_EXTERN(TEXT("SWidget::Paint (Count)"), STAT_SlateNumPaintedWidgets, STATGROUP_Slate, SLATECORE_API);
DECLARE_DWORD_COUNTER_STAT_EXTERN(TEXT("SWidget::Tick (Count)"), STAT_SlateNumTickedWidgets, STATGROUP_Slate, SLATECORE_API);
DECLARE_CYCLE_STAT_EXTERN(TEXT("Execute Active Timers"), STAT_SlateExecuteActiveTimers, STATGROUP_Slate, SLATECORE_API);
DECLARE_CYCLE_STAT_EXTERN(TEXT("Tick Widgets"), STAT_SlateTickWidgets, STATGROUP_Slate, SLATECORE_API);
DECLARE_CYCLE_STAT_EXTERN(TEXT("SlatePrepass"), STAT_SlatePrepass, STATGROUP_Slate, SLATECORE_API);
DECLARE_DWORD_ACCUMULATOR_STAT_EXTERN(TEXT("Total Widgets"), STAT_SlateTotalWidgets, STATGROUP_SlateMemory, SLATECORE_API);
DECLARE_MEMORY_STAT_EXTERN(TEXT("SWidget Total Allocated Size"), STAT_SlateSWidgetAllocSize, STATGROUP_SlateMemory, SLATECORE_API);
/** Delegate type for handling mouse events */
DECLARE_DELEGATE_RetVal_TwoParams(
FReply, FPointerEventHandler,
/** The geometry of the widget*/
const FGeometry&,
/** The Mouse Event that we are processing */
const FPointerEvent&)
DECLARE_DELEGATE_TwoParams(
FNoReplyPointerEventHandler,
/** The geometry of the widget*/
const FGeometry&,
/** The Mouse Event that we are processing */
const FPointerEvent&)
DECLARE_DELEGATE_OneParam(
FSimpleNoReplyPointerEventHandler,
/** The Mouse Event that we are processing */
const FPointerEvent&)
enum class EPopupMethod : uint8;
namespace SharedPointerInternals
{
template <typename ObjectType>
class TIntrusiveReferenceController;
}
class SLATECORE_API FSlateControlledConstruction
{
public:
FSlateControlledConstruction(){}
virtual ~FSlateControlledConstruction(){}
private:
/** UI objects cannot be copy-constructed */
FSlateControlledConstruction(const FSlateControlledConstruction& Other) = delete;
/** UI objects cannot be copied. */
void operator= (const FSlateControlledConstruction& Other) = delete;
/** Widgets should only ever be constructed via SNew or SAssignNew */
void* operator new ( const size_t InSize )
{
return FMemory::Malloc(InSize);
}
/** Widgets should only ever be constructed via SNew or SAssignNew */
void* operator new ( const size_t InSize, void* Addr )
{
return Addr;
}
template<class WidgetType, bool bIsUserWidget>
friend struct TWidgetAllocator;
template <typename ObjectType>
friend class SharedPointerInternals::TIntrusiveReferenceController;
public:
void operator delete(void* mem)
{
FMemory::Free(mem);
}
};
enum class EAccessibleType : uint8
{
Main,
Summary
};
/**
* An FPopupLayer hosts the pop-up content which could be anything you want to appear on top of a widget.
* The widget must understand how to host pop-ups to make use of this.
*/
class FPopupLayer : public TSharedFromThis<FPopupLayer>
{
public:
FPopupLayer(const TSharedRef<SWidget>& InitHostWidget, const TSharedRef<SWidget>& InitPopupContent)
: HostWidget(InitHostWidget)
, PopupContent(InitPopupContent)
{
}
virtual ~FPopupLayer() { }
virtual TSharedRef<SWidget> GetHost() { return HostWidget; }
virtual TSharedRef<SWidget> GetContent() { return PopupContent; }
virtual FSlateRect GetAbsoluteClientRect() = 0;
virtual void Remove() = 0;
private:
TSharedRef<SWidget> HostWidget;
TSharedRef<SWidget> PopupContent;
};
/**
* Performs the attribute assignment and invalidates the widget minimally based on what actually changed. So if the boundness of the attribute didn't change
* volatility won't need to be recalculated. Returns true if the value changed.
*/
template<typename TargetValueType, typename SourceValueType>
static bool SetWidgetAttribute(SWidget& ThisWidget, TAttribute<TargetValueType>& TargetValue, const TAttribute<SourceValueType>& SourceValue, EInvalidateWidgetReason BaseInvalidationReason);
class IToolTip;
/**
* HOW TO DEPRECATE SLATE_ATTRIBUTES
*
* SLATE_ATTRIBUTE(ECheckBoxState, IsChecked)
*
* UE_DEPRECATED(4.xx, "Please use IsChecked(TAttribute<ECheckBoxState>)")
* FArguments& IsChecked(bool InIsChecked)
* {
* _IsChecked = InIsChecked ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;
* return Me();
* }
*
* // This version would prevent ambiguous conversions.
* FArguments& IsChecked(ECheckBoxState InIsChecked)
* {
* _IsChecked = InIsChecked;
* return Me();
* }
*/
/**
* Abstract base class for Slate widgets.
*
* STOP. DO NOT INHERIT DIRECTLY FROM WIDGET!
*
* Inheritance:
* Widget is not meant to be directly inherited. Instead consider inheriting from LeafWidget or Panel,
* which represent intended use cases and provide a succinct set of methods which to override.
*
* SWidget is the base class for all interactive Slate entities. SWidget's public interface describes
* everything that a Widget can do and is fairly complex as a result.
*
* Events:
* Events in Slate are implemented as virtual functions that the Slate system will call
* on a Widget in order to notify the Widget about an important occurrence (e.g. a key press)
* or querying the Widget regarding some information (e.g. what mouse cursor should be displayed).
*
* Widget provides a default implementation for most events; the default implementation does nothing
* and does not handle the event.
*
* Some events are able to reply to the system by returning an FReply, FCursorReply, or similar
* object.
*/
class SLATECORE_API SWidget
: public FSlateControlledConstruction,
public TSharedFromThis<SWidget> // Enables 'this->AsShared()'
{
friend struct FCurveSequence;
friend class FWidgetProxy;
friend class FSlateInvalidationRoot;
friend class FSlateWindowElementList;
friend class SWindow;
friend struct FSlateCachedElementList;
#if WITH_SLATE_DEBUGGING
friend struct FInvalidatedWidgetDrawer;
#endif
public:
/**
* Construct a SWidget based on initial parameters.
*/
void Construct(
const TAttribute<FText>& InToolTipText,
const TSharedPtr<IToolTip>& InToolTip,
const TAttribute< TOptional<EMouseCursor::Type> >& InCursor,
const TAttribute<bool>& InEnabledState,
const TAttribute<EVisibility>& InVisibility,
const float InRenderOpacity,
const TAttribute<TOptional<FSlateRenderTransform>>& InTransform,
const TAttribute<FVector2D>& InTransformPivot,
const FName& InTag,
const bool InForceVolatile,
const EWidgetClipping InClipping,
const EFlowDirectionPreference InFlowPreference,
const TOptional<FAccessibleWidgetData>& InAccessibleData,
const TArray<TSharedRef<ISlateMetaData>>& InMetaData);
void SWidgetConstruct(const TAttribute<FText>& InToolTipText,
const TSharedPtr<IToolTip>& InToolTip,
const TAttribute< TOptional<EMouseCursor::Type> >& InCursor,
const TAttribute<bool>& InEnabledState,
const TAttribute<EVisibility>& InVisibility,
const float InRenderOpacity,
const TAttribute<TOptional<FSlateRenderTransform>>& InTransform,
const TAttribute<FVector2D>& InTransformPivot,
const FName& InTag,
const bool InForceVolatile,
const EWidgetClipping InClipping,
const EFlowDirectionPreference InFlowPreference,
const TOptional<FAccessibleWidgetData>& InAccessibleData,
const TArray<TSharedRef<ISlateMetaData>>& InMetaData);
//
// GENERAL EVENTS
//
/**
* Called to tell a widget to paint itself (and it's children).
*
* The widget should respond by populating the OutDrawElements array with FDrawElements
* that represent it and any of its children.
*
* @param Args All the arguments necessary to paint this widget (@todo umg: move all params into this struct)
* @param AllottedGeometry The FGeometry that describes an area in which the widget should appear.
* @param MyCullingRect The clipping rectangle allocated for this widget and its children.
* @param OutDrawElements A list of FDrawElements to populate with the output.
* @param LayerId The Layer onto which this widget should be rendered.
* @param InColorAndOpacity Color and Opacity to be applied to all the descendants of the widget being painted
* @param bParentEnabled True if the parent of this widget is enabled.
* @return The maximum layer ID attained by this widget or any of its children.
*/
int32 Paint(const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled) const;
/**
* Ticks this widget with Geometry. Override in derived classes, but always call the parent implementation.
*
* @param AllottedGeometry The space allotted for this widget
* @param InCurrentTime Current absolute real time
* @param InDeltaTime Real time passed since last tick
*/
virtual void Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime);
//
// KEY INPUT
//
/**
* Called when focus is given to this widget. This event does not bubble.
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param InFocusEvent The FocusEvent
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnFocusReceived(const FGeometry& MyGeometry, const FFocusEvent& InFocusEvent);
/**
* Called when this widget loses focus. This event does not bubble.
*
* @param InFocusEvent The FocusEvent
*/
virtual void OnFocusLost(const FFocusEvent& InFocusEvent);
/** Called whenever a focus path is changing on all the widgets within the old and new focus paths */
UE_DEPRECATED(4.13, "Please use the newer version of OnFocusChanging that takes a FocusEvent")
virtual void OnFocusChanging(const FWeakWidgetPath& PreviousFocusPath, const FWidgetPath& NewWidgetPath);
/** Called whenever a focus path is changing on all the widgets within the old and new focus paths */
virtual void OnFocusChanging(const FWeakWidgetPath& PreviousFocusPath, const FWidgetPath& NewWidgetPath, const FFocusEvent& InFocusEvent);
/**
* Called after a character is entered while this widget has keyboard focus
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param InCharacterEvent Character event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnKeyChar(const FGeometry& MyGeometry, const FCharacterEvent& InCharacterEvent);
/**
* Called after a key is pressed when this widget or a child of this widget has focus
* If a widget handles this event, OnKeyDown will *not* be passed to the focused widget.
*
* This event is primarily to allow parent widgets to consume an event before a child widget processes
* it and it should be used only when there is no better design alternative.
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param InKeyEvent Key event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnPreviewKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent);
/**
* Called after a key is pressed when this widget has focus (this event bubbles if not handled)
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param InKeyEvent Key event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent);
/**
* Called after a key is released when this widget has focus
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param InKeyEvent Key event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnKeyUp(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent);
/**
* Called when an analog value changes on a button that supports analog
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param InAnalogInputEvent Analog input event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnAnalogValueChanged(const FGeometry& MyGeometry, const FAnalogInputEvent& InAnalogInputEvent);
//
// MOUSE INPUT
//
/**
* The system calls this method to notify the widget that a mouse button was pressed within it. This event is bubbled.
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param MouseEvent Information about the input event
* @return Whether the event was handled along with possible requests for the system to take action.
*/
virtual FReply OnMouseButtonDown(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/**
* Just like OnMouseButtonDown, but tunnels instead of bubbling.
* If this even is handled, OnMouseButtonDown will not be sent.
*
* Use this event sparingly as preview events generally make UIs more
* difficult to reason about.
*/
virtual FReply OnPreviewMouseButtonDown(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/**
* The system calls this method to notify the widget that a mouse button was release within it. This event is bubbled.
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param MouseEvent Information about the input event
* @return Whether the event was handled along with possible requests for the system to take action.
*/
virtual FReply OnMouseButtonUp(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/**
* The system calls this method to notify the widget that a mouse moved within it. This event is bubbled.
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param MouseEvent Information about the input event
* @return Whether the event was handled along with possible requests for the system to take action.
*/
virtual FReply OnMouseMove(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/**
* The system will use this event to notify a widget that the cursor has entered it. This event is uses a custom bubble strategy.
*
* @param MyGeometry The Geometry of the widget receiving the event
* @param MouseEvent Information about the input event
*/
virtual void OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/**
* The system will use this event to notify a widget that the cursor has left it. This event is uses a custom bubble strategy.
*
* @param MouseEvent Information about the input event
*/
virtual void OnMouseLeave(const FPointerEvent& MouseEvent);
/**
* Called when the mouse wheel is spun. This event is bubbled.
*
* @param MouseEvent Mouse event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnMouseWheel(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
/**
* The system asks each widget under the mouse to provide a cursor. This event is bubbled.
*
* @return FCursorReply::Unhandled() if the event is not handled; return FCursorReply::Cursor() otherwise.
*/
virtual FCursorReply OnCursorQuery(const FGeometry& MyGeometry, const FPointerEvent& CursorEvent) const;
/**
* After OnCursorQuery has specified a cursor type the system asks each widget under the mouse to map that cursor to a widget. This event is bubbled.
*
* @return TOptional<TSharedRef<SWidget>>() if you don't have a mapping otherwise return the Widget to show.
*/
virtual TOptional<TSharedRef<SWidget>> OnMapCursor(const FCursorReply& CursorReply) const;
/**
* Called when a mouse button is double clicked. Override this in derived classes.
*
* @param InMyGeometry Widget geometry
* @param InMouseEvent Mouse button event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnMouseButtonDoubleClick(const FGeometry& InMyGeometry, const FPointerEvent& InMouseEvent);
/**
* Called when Slate wants to visualize tooltip.
* If nobody handles this event, Slate will use default tooltip visualization.
* If you override this event, you should probably return true.
*
* @param TooltipContent The TooltipContent that I may want to visualize.
* @return true if this widget visualized the tooltip content; i.e., the event is handled.
*/
virtual bool OnVisualizeTooltip(const TSharedPtr<SWidget>& TooltipContent);
/**
* Visualize a new pop-up if possible. If it's not possible for this widget to host the pop-up
* content you'll get back an invalid pointer to the layer. The returned FPopupLayer allows you
* to remove the pop-up when you're done with it
*
* @param PopupContent The widget to try and host overlaid on top of the widget.
*
* @return a valid FPopupLayer if this widget supported hosting it. You can call Remove() on this to destroy the pop-up.
*/
virtual TSharedPtr<FPopupLayer> OnVisualizePopup(const TSharedRef<SWidget>& PopupContent);
/**
* Called when Slate detects that a widget started to be dragged.
* Usage:
* A widget can ask Slate to detect a drag.
* OnMouseDown() reply with FReply::Handled().DetectDrag( SharedThis(this) ).
* Slate will either send an OnDragDetected() event or do nothing.
* If the user releases a mouse button or leaves the widget before
* a drag is triggered (maybe user started at the very edge) then no event will be
* sent.
*
* @param InMyGeometry Widget geometry
* @param InMouseEvent MouseMove that triggered the drag
*/
virtual FReply OnDragDetected(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent);
//
// DRAG AND DROP (DragDrop)
//
/**
* Called during drag and drop when the drag enters a widget.
*
* Enter/Leave events in slate are meant as lightweight notifications.
* So we do not want to capture mouse or set focus in response to these.
* However, OnDragEnter must also support external APIs (e.g. OLE Drag/Drop)
* Those require that we let them know whether we can handle the content
* being dragged OnDragEnter.
*
* The concession is to return a can_handled/cannot_handle
* boolean rather than a full FReply.
*
* @param MyGeometry The geometry of the widget receiving the event.
* @param DragDropEvent The drag and drop event.
*
* @return A reply that indicated whether the contents of the DragDropEvent can potentially be processed by this widget.
*/
virtual void OnDragEnter(const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent);
/**
* Called during drag and drop when the drag leaves a widget.
*
* @param DragDropEvent The drag and drop event.
*/
virtual void OnDragLeave(const FDragDropEvent& DragDropEvent);
/**
* Called during drag and drop when the the mouse is being dragged over a widget.
*
* @param MyGeometry The geometry of the widget receiving the event.
* @param DragDropEvent The drag and drop event.
* @return A reply that indicated whether this event was handled.
*/
virtual FReply OnDragOver(const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent);
/**
* Called when the user is dropping something onto a widget; terminates drag and drop.
*
* @param MyGeometry The geometry of the widget receiving the event.
* @param DragDropEvent The drag and drop event.
* @return A reply that indicated whether this event was handled.
*/
virtual FReply OnDrop(const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent);
//
// TOUCH and GESTURES
//
/**
* Called when the user performs a gesture on trackpad. This event is bubbled.
*
* @param GestureEvent gesture event
* @return Returns whether the event was handled, along with other possible actions
*/
virtual FReply OnTouchGesture(const FGeometry& MyGeometry, const FPointerEvent& GestureEvent);
/**
* Called when a touchpad touch is started (finger down)
*
* @param InTouchEvent The touch event generated
*/
virtual FReply OnTouchStarted(const FGeometry& MyGeometry, const FPointerEvent& InTouchEvent);
/**
* Called when a touchpad touch is moved (finger moved)
*
* @param InTouchEvent The touch event generated
*/
virtual FReply OnTouchMoved(const FGeometry& MyGeometry, const FPointerEvent& InTouchEvent);
/**
* Called when a touchpad touch is ended (finger lifted)
*
* @param InTouchEvent The touch event generated
*/
virtual FReply OnTouchEnded(const FGeometry& MyGeometry, const FPointerEvent& InTouchEvent);
/**
* Called when a touchpad touch force changes
*
* @param InTouchEvent The touch event generated
*/
virtual FReply OnTouchForceChanged(const FGeometry& MyGeometry, const FPointerEvent& TouchEvent);
/**
* Called when a touchpad touch first moves after TouchStarted
*
* @param InTouchEvent The touch event generated
*/
virtual FReply OnTouchFirstMove(const FGeometry& MyGeometry, const FPointerEvent& TouchEvent);
/**
* Called when motion is detected (controller or device)
* e.g. Someone tilts or shakes their controller.
*
* @param InMotionEvent The motion event generated
*/
virtual FReply OnMotionDetected(const FGeometry& MyGeometry, const FMotionEvent& InMotionEvent);
/**
* Called to determine if we should render the focus brush.
*
* @param InFocusCause The cause of focus
*/
virtual TOptional<bool> OnQueryShowFocus(const EFocusCause InFocusCause) const;
/**
* Popups can manifest in a NEW OS WINDOW or via an OVERLAY in an existing window.
* This can be set explicitly on SMenuAnchor, or can be determined by a scoping widget.
* A scoping widget can reply to OnQueryPopupMethod() to drive all its descendants'
* poup methods.
*
* e.g. Fullscreen games cannot summon a new window, so game SViewports will reply with
* EPopupMethod::UserCurrentWindow. This makes all the menu anchors within them
* use the current window.
*/
virtual FPopupMethodReply OnQueryPopupMethod() const;
UE_DEPRECATED(4.26, "Renaming to TranslateMouseCoordinateForCustomHitTestChild")
TSharedPtr<FVirtualPointerPosition> TranslateMouseCoordinateFor3DChild(const TSharedRef<SWidget>& ChildWidget, const FGeometry& MyGeometry, const FVector2D& ScreenSpaceMouseCoordinate, const FVector2D& LastScreenSpaceMouseCoordinate) const
{
return TranslateMouseCoordinateForCustomHitTestChild(ChildWidget, MyGeometry, ScreenSpaceMouseCoordinate, LastScreenSpaceMouseCoordinate);
}
virtual TSharedPtr<FVirtualPointerPosition> TranslateMouseCoordinateForCustomHitTestChild(const TSharedRef<SWidget>& ChildWidget, const FGeometry& MyGeometry, const FVector2D& ScreenSpaceMouseCoordinate, const FVector2D& LastScreenSpaceMouseCoordinate) const;
/**
* All the pointer (mouse, touch, stylus, etc.) events from this frame have been routed.
* This is a widget's chance to act on any accumulated data.
*/
virtual void OnFinishedPointerInput();
/**
* All the key (keyboard, gamepay, joystick, etc.) input from this frame has been routed.
* This is a widget's chance to act on any accumulated data.
*/
virtual void OnFinishedKeyInput();
/**
* Called when navigation is requested
* e.g. Left Joystick, Direction Pad, Arrow Keys can generate navigation events.
*
* @param InNavigationEvent The navigation event generated
*/
virtual FNavigationReply OnNavigation(const FGeometry& MyGeometry, const FNavigationEvent& InNavigationEvent);
/**
* Called when the mouse is moved over the widget's window, to determine if we should report whether
* OS-specific features should be active at this location (such as a title bar grip, system menu, etc.)
* Usually you should not need to override this function.
*
* @return The window "zone" the cursor is over, or EWindowZone::Unspecified if no special behavior is needed
*/
virtual EWindowZone::Type GetWindowZoneOverride() const;
#if WITH_ACCESSIBILITY
virtual TSharedRef<class FSlateAccessibleWidget> CreateAccessibleWidget();
#endif
public:
//
// LAYOUT
//
bool NeedsPrepass() const { return bNeedsPrepass; }
/** DEPRECATED version of SlatePrepass that assumes no scaling beyond AppScale*/
//UE_DEPRECATED(4.20, "SlatePrepass requires a layout scale to be accurate.")
void SlatePrepass();
/**
* Descends to leaf-most widgets in the hierarchy and gathers desired sizes on the way up.
* i.e. Caches the desired size of all of this widget's children recursively, then caches desired size for itself.
*/
void SlatePrepass(float InLayoutScaleMultiplier);
void SetCanTick(bool bInCanTick) { bInCanTick ? AddUpdateFlags(EWidgetUpdateFlags::NeedsTick) : RemoveUpdateFlags(EWidgetUpdateFlags::NeedsTick); }
bool GetCanTick() const { return HasAnyUpdateFlags(EWidgetUpdateFlags::NeedsTick); }
const FSlateWidgetPersistentState& GetPersistentState() const { return PersistentState; }
const FWidgetProxyHandle GetProxyHandle() const { return FastPathProxyHandle; }
/** @return the DesiredSize that was computed the last time CacheDesiredSize() was called. */
FVector2D GetDesiredSize() const;
void AssignParentWidget(TSharedPtr<SWidget> InParent);
bool ConditionallyDetatchParentWidget(SWidget* InExpectedParent);
/** */
virtual bool ValidatePathToChild(SWidget* InChild) { return true; }
FORCEINLINE bool IsParentValid() const { return ParentWidgetPtr.IsValid(); }
FORCEINLINE TSharedPtr<SWidget> GetParentWidget() const { return ParentWidgetPtr.Pin(); }
FORCEINLINE TSharedPtr<SWidget> Advanced_GetPaintParentWidget() const { return PersistentState.PaintParent.Pin(); }
/**
* Calculates what if any clipping state changes need to happen when drawing this widget.
* @return the culling rect that should be used going forward.
*/
FSlateRect CalculateCullingAndClippingRules(const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, bool& bClipToBounds, bool& bAlwaysClip, bool& bIntersectClipBounds) const;
protected:
virtual bool CustomPrepass(float LayoutScaleMultiplier) { return false; }
bool AssignIndicesToChildren(FSlateInvalidationRoot& Root, int32 ParentIndex, TArray<FWidgetProxy, TMemStackAllocator<>>& FastPathList, bool bParentVisible, bool bParentVolatile);
/**
* The system calls this method. It performs a breadth-first traversal of every visible widget and asks
* each widget to cache how big it needs to be in order to present all of its content.
*/
virtual void CacheDesiredSize(float InLayoutScaleMultiplier);
/**
* Compute the ideal size necessary to display this widget. For aggregate widgets (e.g. panels) this size should include the
* size necessary to show all of its children. CacheDesiredSize() guarantees that the size of descendants is computed and cached
* before that of the parents, so it is safe to call GetDesiredSize() for any children while implementing this method.
*
* Note that ComputeDesiredSize() is meant as an aide to the developer. It is NOT meant to be very robust in many cases. If your
* widget is simulating a bouncing ball, you should just return a reasonable size; e.g. 160x160. Let the programmer set up a reasonable
* rule of resizing the bouncy ball simulation.
*
* @param LayoutScaleMultiplier This parameter is safe to ignore for almost all widgets; only really affects text measuring.
*
* @return The desired size.
*/
virtual FVector2D ComputeDesiredSize(float LayoutScaleMultiplier) const = 0;
bool HasAnyUpdateFlags(EWidgetUpdateFlags FlagsToCheck) const
{
return EnumHasAnyFlags(UpdateFlags, FlagsToCheck);
}
private:
void UpdateFastPathVisibility(bool bParentVisible, bool bWidgetRemoved, FHittestGrid* ParentHittestGrid);
void UpdateFastPathVolatility(bool bParentVolatile);
/**
* Explicitly set the desired size. This is highly advanced functionality that is meant
* to be used in conjunction with overriding CacheDesiredSize. Use ComputeDesiredSize() instead.
*/
void SetDesiredSize(const FVector2D& InDesiredSize)
{
DesiredSize = InDesiredSize;
}
#if STATS || ENABLE_STATNAMEDEVENTS
void CreateStatID() const;
#endif
void AddUpdateFlags(EWidgetUpdateFlags FlagsToAdd)
{
UpdateFlags |= FlagsToAdd;
if (FastPathProxyHandle.IsValid())
{
FastPathProxyHandle.UpdateWidgetFlags(UpdateFlags);
}
}
void RemoveUpdateFlags(EWidgetUpdateFlags FlagsToRemove)
{
UpdateFlags &= (~FlagsToRemove);
if (FastPathProxyHandle.IsValid())
{
FastPathProxyHandle.UpdateWidgetFlags(UpdateFlags);
}
#if WITH_SLATE_DEBUGGING
if (EnumHasAnyFlags(FlagsToRemove, EWidgetUpdateFlags::NeedsRepaint))
{
Debug_UpdateLastPaintFrame();
}
#endif
}
void UpdateWidgetProxy(int32 NewLayerId, FSlateCachedElementsHandle& CacheHandle);
#if WITH_SLATE_DEBUGGING
uint32 Debug_GetLastPaintFrame() const { return LastPaintFrame; }
void Debug_UpdateLastPaintFrame() { LastPaintFrame = GFrameNumber; }
#endif
public:
FORCEINLINE TStatId GetStatID() const
{
#if STATS
// this is done to avoid even registering stats for a disabled group (unless we plan on using it later)
if (FThreadStats::IsCollectingData())
{
if (!StatID.IsValidStat())
{
CreateStatID();
}
return StatID;
}
#elif ENABLE_STATNAMEDEVENTS
if (!StatID.IsValidStat() && GCycleStatsShouldEmitNamedEvents)
{
CreateStatID();
}
return StatID;
#endif
return TStatId(); // not doing stats at the moment, or ever
}
UE_DEPRECATED(4.24, "GetRelativeLayoutScale(int32 ChildIndex, float LayoutScaleMultiplier), your widget will also need to set bHasRelativeLayoutScale in their Construct/ctor.")
virtual float GetRelativeLayoutScale(const FSlotBase& Child, float LayoutScaleMultiplier) const { return 1.0f; }
/** What is the Child's scale relative to this widget. */
virtual float GetRelativeLayoutScale(const int32 ChildIndex, float LayoutScaleMultiplier) const;
/**
* Non-virtual entry point for arrange children. ensures common work is executed before calling the virtual
* ArrangeChildren function.
* Compute the Geometry of all the children and add populate the ArrangedChildren list with their values.
* Each type of Layout panel should arrange children based on desired behavior.
*
* @param AllottedGeometry The geometry allotted for this widget by its parent.
* @param ArrangedChildren The array to which to add the WidgetGeometries that represent the arranged children.
*/
void ArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const;
/**
* Every widget that has children must implement this method. This allows for iteration over the Widget's
* children regardless of how they are actually stored.
*/
// @todo Slate: Consider renaming to GetVisibleChildren (not ALL children will be returned in all cases)
virtual FChildren* GetChildren() = 0;
virtual FChildren* GetAllChildren() { return GetChildren(); }
/**
* Checks to see if this widget supports keyboard focus. Override this in derived classes.
*
* @return True if this widget can take keyboard focus
*/
virtual bool SupportsKeyboardFocus() const;
/**
* Checks to see if this widget currently has the keyboard focus
*
* @return True if this widget has keyboard focus
*/
virtual bool HasKeyboardFocus() const;
/**
* Gets whether or not the specified users has this widget focused, and if so the type of focus.
*
* @return The optional will be set with the focus cause, if unset this widget doesn't have focus.
*/
TOptional<EFocusCause> HasUserFocus(int32 UserIndex) const;
/**
* Gets whether or not any users have this widget focused, and if so the type of focus (first one found).
*
* @return The optional will be set with the focus cause, if unset this widget doesn't have focus.
*/
TOptional<EFocusCause> HasAnyUserFocus() const;
/**
* Gets whether or not the specified users has this widget or any descendant focused.
*
* @return The optional will be set with the focus cause, if unset this widget doesn't have focus.
*/
bool HasUserFocusedDescendants(int32 UserIndex) const;
/**
* @return Whether this widget has any descendants with keyboard focus
*/
bool HasFocusedDescendants() const;
/**
* @return whether or not any users have this widget focused, or any descendant focused.
*/
bool HasAnyUserFocusOrFocusedDescendants() const;
/**
* Checks to see if this widget is the current mouse captor
*
* @return True if this widget has captured the mouse
*/
bool HasMouseCapture() const;
/**
* Checks to see if this widget has mouse capture from the provided user.
*
* @return True if this widget has captured the mouse
*/
bool HasMouseCaptureByUser(int32 UserIndex, TOptional<int32> PointerIndex = TOptional<int32>()) const;
protected:
/** Called when this widget had captured the mouse, but that capture has been revoked for some reason. */
UE_DEPRECATED(4.20, "Please use OnMouseCaptureLost(const FCaptureLostEvent& CaptureLostEvent)")
void OnMouseCaptureLost() { }
public:
/** Called when this widget had captured the mouse, but that capture has been revoked for some reason. */
virtual void OnMouseCaptureLost(const FCaptureLostEvent& CaptureLostEvent);
/**
* Sets the enabled state of this widget
*
* @param InEnabledState An attribute containing the enabled state or a delegate to call to get the enabled state.
*/
void SetEnabled(const TAttribute<bool>& InEnabledState)
{
SetAttribute(EnabledState, InEnabledState, EInvalidateWidgetReason::Paint);
}
/** @return Whether or not this widget is enabled */
FORCEINLINE bool IsEnabled() const
{
return EnabledState.Get();
}
/** @return Is this widget interactive or not? Defaults to false */
virtual bool IsInteractable() const
{
return false;
}
/** @return The tool tip associated with this widget; Invalid reference if there is not one */
virtual TSharedPtr<IToolTip> GetToolTip();
/** Called when a tooltip displayed from this widget is being closed */
virtual void OnToolTipClosing();
/**
* Sets whether this widget is a "tool tip force field". That is, tool-tips should never spawn over the area
* occupied by this widget, and will instead be repelled to an outside edge
*
* @param bEnableForceField True to enable tool tip force field for this widget
*/
void EnableToolTipForceField(const bool bEnableForceField);
/** @return True if a tool tip force field is active on this widget */
bool HasToolTipForceField() const
{
return bToolTipForceFieldEnabled;
}
/** @return True if this widget hovered */
virtual bool IsHovered() const
{
return bIsHovered;
}
/** @return True if this widget is directly hovered */
virtual bool IsDirectlyHovered() const;
/** @return is this widget visible, hidden or collapsed */
FORCEINLINE EVisibility GetVisibility() const { return Visibility.Get(); }
/** @param InVisibility should this widget be */
virtual void SetVisibility(TAttribute<EVisibility> InVisibility);
#if WITH_ACCESSIBILITY
/**
* Get the text that should be reported to the user when attempting to access this widget.
*
* @param AccessibleType Whether the widget is being accessed directly or through a summary query.
* @return The text that should be conveyed to the user describing this widget.
*/
FText GetAccessibleText(EAccessibleType AccessibleType = EAccessibleType::Main) const;
/**
* Traverse all child widgets and concat their results of GetAccessibleText(Summary).
*
* @return The combined text of all child widget's summary text.
*/
FText GetAccessibleSummary() const;
/**
* Whether this widget is considered accessible or not. A widget is accessible if its behavior
* is set to something other than NotAccessible, and all of its parent widgets support accessible children.
*
* @return true if an accessible widget should be created for this widget.
*/
bool IsAccessible() const;
/**
* Get the behavior describing how the accessible text of this widget should be retrieved.
*
* @param AccessibleType Whether the widget is being accessed directly or through a summary query.
* @return The accessible behavior of the widget.
*/
EAccessibleBehavior GetAccessibleBehavior(EAccessibleType AccessibleType = EAccessibleType::Main) const;
/**
* Checks whether this widget allows its children to be accessible or not.
*
* @return true if children can be accessible.
*/
bool CanChildrenBeAccessible() const;
/**
* Set a new accessible behavior, and if the behavior is custom, new accessible text to go along with it.
*
* @param InBehavior The new behavior for the widget. If the new behavior is custom, InText should also be set.
* @param InText, If the new behavior is custom, this will be the custom text assigned to the widget.
* @param AccessibleType Whether the widget is being accessed directly or through a summary query.
*/
void SetAccessibleBehavior(EAccessibleBehavior InBehavior, const TAttribute<FText>& InText = TAttribute<FText>(), EAccessibleType AccessibleType = EAccessibleType::Main);
/**
* Sets whether children are allowed to be accessible or not.
* Warning: Calling this function after accessibility is enabled will cause the accessibility tree to become unsynced.
*
* @param InCanChildrenBeAccessible Whether children should be accessible or not.
*/
void SetCanChildrenBeAccessible(bool InCanChildrenBeAccessible);
/**
* Assign AccessibleText with a default value that can be used when AccessibleBehavior is set to Auto or Custom.
*
* @param AccessibleType Whether the widget is being accessed directly or through a summary query.
*/
virtual TOptional<FText> GetDefaultAccessibleText(EAccessibleType AccessibleType = EAccessibleType::Main) const;
#endif
/** Whether or not a widget is volatile and will update every frame without being invalidated */
FORCEINLINE bool IsVolatile() const { return bCachedVolatile; }
/**
* This widget is volatile because its parent or some ancestor is volatile
*/
FORCEINLINE bool IsVolatileIndirectly() const { return bInheritedVolatility; }
/**
* Should this widget always appear as volatile for any layout caching host widget. A volatile
* widget's geometry and layout data will never be cached, and neither will any children.
* @param bForce should we force the widget to be volatile?
*/
FORCEINLINE void ForceVolatile(bool bForce)
{
if (bForceVolatile != bForce)
{
bForceVolatile = bForce;
Invalidate(EInvalidateWidgetReason::Volatility);
}
}
FORCEINLINE bool ShouldInvalidatePrepassDueToVolatility() { return bVolatilityAlwaysInvalidatesPrepass; }
/**
* Invalidates the widget from the view of a layout caching widget that may own this widget.
* will force the owning widget to redraw and cache children on the next paint pass.
*/
void Invalidate(EInvalidateWidgetReason InvalidateReason);
/**
* Recalculates volatility of the widget and caches the result. Should be called any time
* anything examined by your implementation of ComputeVolatility is changed.
*/
FORCEINLINE void CacheVolatility()
{
bCachedVolatile = bForceVolatile || ComputeVolatility();
}
void InvalidatePrepass();
protected:
#if SLATE_CULL_WIDGETS
/**
* Tests if an arranged widget should be culled.
* @param MyCullingRect the culling rect of the widget currently doing the culling.
* @param ArrangedChild the arranged widget in the widget currently attempting to cull children.
*/
bool IsChildWidgetCulled(const FSlateRect& MyCullingRect, const FArrangedWidget& ArrangedChild) const;
#else
FORCEINLINE bool IsChildWidgetCulled(const FSlateRect&, const FArrangedWidget&) const { return false; }
#endif
protected:
/**
* Called when a child is removed from the tree parent's widget tree either by removing it from a slot. This can also be called manually if you've got some non-slot based what of no longer reporting children
* An example of a widget that needs manual calling is SWidgetSwitcher. It keeps all its children but only arranges and paints a single "active" one. Once a child becomes inactive, its cached data should be removed.
*/
void InvalidateChildRemovedFromTree(SWidget& Child);
/**
* Recalculates and caches volatility and returns 'true' if the volatility changed.
*/
FORCEINLINE bool Advanced_InvalidateVolatility()
{
const bool bWasDirectlyVolatile = IsVolatile();
CacheVolatility();
return bWasDirectlyVolatile != IsVolatile();
}
public:
/** @return the render opacity of the widget. */
FORCEINLINE float GetRenderOpacity() const
{
return RenderOpacity;
}
/** @param InOpacity The opacity of the widget during rendering. */
FORCEINLINE void SetRenderOpacity(float InRenderOpacity)
{
if(RenderOpacity != InRenderOpacity)
{
RenderOpacity = InRenderOpacity;
Invalidate(EInvalidateWidget::Paint);
}
}
FORCEINLINE void SetTag(FName InTag)
{
Tag = InTag;
}
/** @return the render transform of the widget. */
FORCEINLINE const TOptional<FSlateRenderTransform>& GetRenderTransform() const
{
return RenderTransform.Get();
}
FORCEINLINE TOptional<FSlateRenderTransform> GetRenderTransformWithRespectToFlowDirection() const
{
if (LIKELY(GSlateFlowDirection == EFlowDirection::LeftToRight))
{
return RenderTransform.Get();
}
else
{
// If we're going right to left, flip the X translation on render transforms.
TOptional<FSlateRenderTransform> Transform = RenderTransform.Get();
if (Transform.IsSet())
{
FVector2D Translation = Transform.GetValue().GetTranslation();
Transform.GetValue().SetTranslation(FVector2D(-Translation.X, Translation.Y));
}
return Transform;
}
}
FORCEINLINE FVector2D GetRenderTransformPivotWithRespectToFlowDirection() const
{
if (LIKELY(GSlateFlowDirection == EFlowDirection::LeftToRight))
{
return RenderTransformPivot.Get();
}
else
{
// If we're going right to left, flip the X's pivot mirrored about 0.5.
FVector2D TransformPivot = RenderTransformPivot.Get();
TransformPivot.X = 0.5f + (0.5f - TransformPivot.X);
return TransformPivot;
}
}
/** @param InTransform the render transform to set for the widget (transforms from widget's local space). TOptional<> to allow code to skip expensive overhead if there is no render transform applied. */
FORCEINLINE void SetRenderTransform(TAttribute<TOptional<FSlateRenderTransform>> InTransform)
{
SetAttribute(RenderTransform, InTransform, EInvalidateWidgetReason::Layout | EInvalidateWidgetReason::RenderTransform);
}
/** @return the pivot point of the render transform. */
FORCEINLINE FVector2D GetRenderTransformPivot() const
{
return RenderTransformPivot.Get();
}
/** @param InTransformPivot Sets the pivot point of the widget's render transform (in normalized local space). */
FORCEINLINE void SetRenderTransformPivot(TAttribute<FVector2D> InTransformPivot)
{
SetAttribute(RenderTransformPivot, InTransformPivot, EInvalidateWidgetReason::Layout | EInvalidateWidgetReason::RenderTransform);
}
/**
* Sets the clipping to bounds rules for this widget.
*/
FORCEINLINE void SetClipping(EWidgetClipping InClipping)
{
if (Clipping != InClipping)
{
Clipping = InClipping;
OnClippingChanged();
// @todo - Fast path should this be Paint?
Invalidate(EInvalidateWidget::Layout);
}
}
/** @return The current clipping rules for this widget. */
FORCEINLINE EWidgetClipping GetClipping() const
{
return Clipping;
}
/**
* Sets an additional culling padding that is added to a widget to give more leeway when culling widgets. Useful if
* several child widgets have rendering beyond their bounds.
*/
FORCEINLINE void SetCullingBoundsExtension(const FMargin& InCullingBoundsExtension)
{
if (CullingBoundsExtension != InCullingBoundsExtension)
{
CullingBoundsExtension = InCullingBoundsExtension;
// @todo - Fast path should this be Paint?
Invalidate(EInvalidateWidget::Layout);
}
}
/** @return CullingBoundsExtension */
FORCEINLINE FMargin GetCullingBoundsExtension() const
{
return CullingBoundsExtension;
}
/**
* Sets how content should flow in this panel, based on the current culture. By default all panels inherit
* the state of the widget above. If they set a new flow direction it will be inherited down the tree.
*/
void SetFlowDirectionPreference(EFlowDirectionPreference InFlowDirectionPreference)
{
if (FlowDirectionPreference != InFlowDirectionPreference)
{
FlowDirectionPreference = InFlowDirectionPreference;
Invalidate(EInvalidateWidget::Paint);
}
}
/** Gets the desired flow direction for the layout. */
EFlowDirectionPreference GetFlowDirectionPreference() const { return FlowDirectionPreference; }
/**
* Set the tool tip that should appear when this widget is hovered.
*
* @param InToolTipText the text that should appear in the tool tip
*/
void SetToolTipText(const TAttribute<FText>& ToolTipText);
void SetToolTipText( const FText& InToolTipText );
/**
* Set the tool tip that should appear when this widget is hovered.
*
* @param InToolTip the widget that should appear in the tool tip
*/
void SetToolTip( const TSharedPtr<IToolTip>& InToolTip );
/**
* Set the cursor that should appear when this widget is hovered
*/
void SetCursor( const TAttribute< TOptional<EMouseCursor::Type> >& InCursor );
/**
* Used by Slate to set the runtime debug info about this widget.
*/
void SetDebugInfo( const ANSICHAR* InType, const ANSICHAR* InFile, int32 OnLine, size_t InAllocSize );
/**
* Get the metadata of the type provided.
* @return the first metadata of the type supplied that we encounter
*/
template<typename MetaDataType>
TSharedPtr<MetaDataType> GetMetaData() const
{
for (const auto& MetaDataEntry : MetaData)
{
if (MetaDataEntry->IsOfType<MetaDataType>())
{
return StaticCastSharedRef<MetaDataType>(MetaDataEntry);
}
}
return TSharedPtr<MetaDataType>();
}
/**
* Get all metadata of the type provided.
* @return all the metadata found of the specified type.
*/
template<typename MetaDataType>
TArray<TSharedRef<MetaDataType>> GetAllMetaData() const
{
TArray<TSharedRef<MetaDataType>> FoundMetaData;
for (const auto& MetaDataEntry : MetaData)
{
if (MetaDataEntry->IsOfType<MetaDataType>())
{
FoundMetaData.Add(StaticCastSharedRef<MetaDataType>(MetaDataEntry));
}
}
return FoundMetaData;
}
/**
* Add metadata to this widget.
* @param AddMe the metadata to add to the widget.
*/
template<typename MetaDataType>
void AddMetadata(const TSharedRef<MetaDataType>& AddMe)
{
AddMetadataInternal(AddMe);
}
private:
void AddMetadataInternal(const TSharedRef<ISlateMetaData>& AddMe);
public:
/** See OnMouseButtonDown event */
void SetOnMouseButtonDown(FPointerEventHandler EventHandler);
/** See OnMouseButtonUp event */
void SetOnMouseButtonUp(FPointerEventHandler EventHandler);
/** See OnMouseMove event */
void SetOnMouseMove(FPointerEventHandler EventHandler);
/** See OnMouseDoubleClick event */
void SetOnMouseDoubleClick(FPointerEventHandler EventHandler);
/** See OnMouseEnter event */
void SetOnMouseEnter(FNoReplyPointerEventHandler EventHandler);
/** See OnMouseLeave event */
void SetOnMouseLeave(FSimpleNoReplyPointerEventHandler EventHandler);
public:
// Widget Inspector and debugging methods
/** @return A String representation of the widget */
virtual FString ToString() const;
/** @return A String of the widget's type */
FString GetTypeAsString() const;
/** @return The widget's type as an FName ID */
FName GetType() const;
/** @return A String of the widget's code location in readable format "BaseFileName(LineNumber)" */
virtual FString GetReadableLocation() const;
/** @return An FName of the widget's code location (full path with number == line number of the file) */
FName GetCreatedInLocation() const;
/** @return The name this widget was tagged with */
virtual FName GetTag() const;
#if UE_SLATE_WITH_WIDGET_UNIQUE_IDENTIFIER
/** @return The widget's id */
uint64 GetId() const { return UniqueIdentifier; }
#endif
/** @return the Foreground color that this widget sets; unset options if the widget does not set a foreground color */
virtual FSlateColor GetForegroundColor() const;
//UE_DEPRECATED(4.23, "GetCachedGeometry has been deprecated, use GetTickSpaceGeometry instead")
const FGeometry& GetCachedGeometry() const;
/**
* Gets the last geometry used to Tick the widget. This data may not exist yet if this call happens prior to
* the widget having been ticked/painted, or it may be out of date, or a frame behind.
*
* We recommend not to use this data unless there's no other way to solve your problem. Normally in Slate we
* try and handle these issues by making a dependent widget part of the hierarchy, as to avoid frame behind
* or what are referred to as hysteresis problems, both caused by depending on geometry from the previous frame
* being used to advise how to layout a dependent object the current frame.
*/
const FGeometry& GetTickSpaceGeometry() const;
/**
* Gets the last geometry used to Tick the widget. This data may not exist yet if this call happens prior to
* the widget having been ticked/painted, or it may be out of date, or a frame behind.
*/
const FGeometry& GetPaintSpaceGeometry() const;
/** Returns the clipping state to clip this widget against its parent */
const TOptional<FSlateClippingState>& GetCurrentClippingState() const { return PersistentState.InitialClipState; }
/** Is this widget derivative of SWindow */
virtual bool Advanced_IsWindow() const { return false; }
virtual bool Advanced_IsInvalidationRoot() const { return false; }
protected:
/**
* Hidden default constructor.
*
* Use SNew(WidgetClassName) to instantiate new widgets.
*
* @see SNew
*/
SWidget();
/**
* Find the geometry of a descendant widget. This method assumes that WidgetsToFind are a descendants of this widget.
* Note that not all widgets are guaranteed to be found; OutResult will contain null entries for missing widgets.
*
* @param MyGeometry The geometry of this widget.
* @param WidgetsToFind The widgets whose geometries we wish to discover.
* @param OutResult A map of widget references to their respective geometries.
* @return True if all the WidgetGeometries were found. False otherwise.
*/
bool FindChildGeometries( const FGeometry& MyGeometry, const TSet< TSharedRef<SWidget> >& WidgetsToFind, TMap<TSharedRef<SWidget>, FArrangedWidget>& OutResult ) const;
/**
* Actual implementation of FindChildGeometries.
*
* @param MyGeometry The geometry of this widget.
* @param WidgetsToFind The widgets whose geometries we wish to discover.
* @param OutResult A map of widget references to their respective geometries.
*/
void FindChildGeometries_Helper( const FGeometry& MyGeometry, const TSet< TSharedRef<SWidget> >& WidgetsToFind, TMap<TSharedRef<SWidget>, FArrangedWidget>& OutResult ) const;
/**
* Find the geometry of a descendant widget. This method assumes that WidgetToFind is a descendant of this widget.
*
* @param MyGeometry The geometry of this widget.
* @param WidgetToFind The widget whose geometry we wish to discover.
* @return the geometry of WidgetToFind.
*/
FGeometry FindChildGeometry( const FGeometry& MyGeometry, TSharedRef<SWidget> WidgetToFind ) const;
/** @return The index of the child that the mouse is currently hovering */
static int32 FindChildUnderMouse( const FArrangedChildren& Children, const FPointerEvent& MouseEvent );
/** @return The index of the child that is under the specified position */
static int32 FindChildUnderPosition(const FArrangedChildren& Children, const FVector2D& ArrangedSpacePosition);
/**
* Determines if this widget should be enabled.
*
* @param InParentEnabled true if the parent of this widget is enabled
* @return true if the widget is enabled
*/
bool ShouldBeEnabled( bool InParentEnabled ) const
{
// This widget should be enabled if its parent is enabled and it is enabled
return InParentEnabled && IsEnabled();
}
/** @return a brush to draw focus, nullptr if no focus drawing is desired */
virtual const FSlateBrush* GetFocusBrush() const;
/**
* Recomputes the volatility of the widget. If you have additional state you automatically want to make
* the widget volatile, you should sample that information here.
*/
virtual bool ComputeVolatility() const
{
return Visibility.IsBound() || EnabledState.IsBound() || RenderTransform.IsBound();
}
/**
* Protected static helper to allow widgets to access the visibility attribute of other widgets directly
*
* @param Widget The widget to get the visibility attribute of
*/
static const TAttribute<EVisibility>& AccessWidgetVisibilityAttribute(const TSharedRef<SWidget>& Widget)
{
return Widget->Visibility;
}
/**
* Called when clipping is changed. Should be used to forward clipping states onto potentially
* hidden children that actually are responsible for clipping the content.
*/
virtual void OnClippingChanged();
private:
/**
* The widget should respond by populating the OutDrawElements array with FDrawElements
* that represent it and any of its children. Called by the non-virtual OnPaint to enforce pre/post conditions
* during OnPaint.
*
* @param Args All the arguments necessary to paint this widget (@todo umg: move all params into this struct)
* @param AllottedGeometry The FGeometry that describes an area in which the widget should appear.
* @param MyCullingRect The rectangle representing the bounds currently being used to completely cull widgets. Unless IsChildWidgetCulled(...) returns true, you should paint the widget.
* @param OutDrawElements A list of FDrawElements to populate with the output.
* @param LayerId The Layer onto which this widget should be rendered.
* @param InColorAndOpacity Color and Opacity to be applied to all the descendants of the widget being painted
* @param bParentEnabled True if the parent of this widget is enabled.
* @return The maximum layer ID attained by this widget or any of its children.
*/
virtual int32 OnPaint(const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled) const = 0;
/**
* Compute the Geometry of all the children and add populate the ArrangedChildren list with their values.
* Each type of Layout panel should arrange children based on desired behavior.
*
* @param AllottedGeometry The geometry allotted for this widget by its parent.
* @param ArrangedChildren The array to which to add the WidgetGeometries that represent the arranged children.
*/
virtual void OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const = 0;
void Prepass_Internal(float LayoutScaleMultiplier);
protected:
float GetPrepassLayoutScaleMultiplier() const { return PrepassLayoutScaleMultiplier.Get(1.0f); }
public:
/**
* Registers an "active timer" delegate that will execute at some regular interval. TickFunction will not be called until the specified interval has elapsed once.
* A widget can register as many delegates as it needs. Be careful when registering to avoid duplicate active timers.
*
* An active timer can be UnRegistered in one of three ways:
* 1. Call UnRegisterActiveTimer using the active timer handle that is returned here.
* 2. Have your delegate return EActiveTimerReturnType::Stop.
* 3. Destroying the widget
*
* Active Timers
* --------------
* Slate may go to sleep when there is no user interaction for some time to save power.
* However, some UI elements may need to "drive" the UI even when the user is not providing any input
* (ie, animations, viewport rendering, async polling, etc). A widget notifies Slate of this by
* registering an "Active Timer" that is executed at a specified frequency to drive the UI.
* In this way, slate can go to sleep when there is no input and no active timer needs to fire.
* When any active timer needs to fire, all of Slate will do a Tick and Paint pass.
*
* @param Period The time period to wait between each execution of the timer. Pass zero to fire the timer once per frame.
* If an interval is missed, the delegate is NOT called more than once.
* @param TimerFunction The active timer delegate to call every Period seconds.
* @return An active timer handle that can be used to UnRegister later.
*/
TSharedRef<FActiveTimerHandle> RegisterActiveTimer( float TickPeriod, FWidgetActiveTimerDelegate TickFunction );
/**
* Unregisters an active timer handle. This is optional, as the delegate can UnRegister itself by returning EActiveTimerReturnType::Stop.
*/
void UnRegisterActiveTimer( const TSharedRef<FActiveTimerHandle>& ActiveTimerHandle );
/** Does this widget have any active timers? */
bool HasActiveTimers() const { return ActiveTimers.Num() > 0; }
private:
/** Iterates over the active timer handles on the widget and executes them if their interval has elapsed. */
void ExecuteActiveTimers(double CurrentTime, float DeltaTime);
const FPointerEventHandler* GetPointerEvent(const FName EventName) const;
void SetPointerEvent(const FName EventName, FPointerEventHandler& InEvent);
protected:
/**
* Performs the attribute assignment and invalidates the widget minimally based on what actually changed. So if the boundness of the attribute didn't change
* volatility won't need to be recalculated. Returns true if the value changed.
*/
template<typename TargetValueType, typename SourceValueType>
bool SetAttribute(TAttribute<TargetValueType>& TargetValue, const TAttribute<SourceValueType>& SourceValue, EInvalidateWidgetReason BaseInvalidationReason)
{
return SetWidgetAttribute(*this, TargetValue, SourceValue, BaseInvalidationReason);
}
protected:
/** Dtor ensures that active timer handles are UnRegistered with the SlateApplication. */
virtual ~SWidget();
private:
/** Handle to the proxy when on the fast path */
mutable FWidgetProxyHandle FastPathProxyHandle;
protected:
/** Is this widget hovered? */
uint8 bIsHovered : 1;
/** Can the widget ever support keyboard focus */
uint8 bCanSupportFocus : 1;
/**
* Can the widget ever support children? This will be false on SLeafWidgets,
* rather than setting this directly, you should probably inherit from SLeafWidget.
*/
uint8 bCanHaveChildren : 1;
/**
* Some widgets might be a complex hierarchy of child widgets you never see. Some of those widgets
* would expose their clipping option normally, but may not personally be responsible for clipping
* so even though it may be set to clip, this flag is used to inform painting that this widget doesn't
* really do the clipping.
*/
uint8 bClippingProxy : 1;
private:
/**
* Whether this widget is a "tool tip force field". That is, tool-tips should never spawn over the area
* occupied by this widget, and will instead be repelled to an outside edge
*/
uint8 bToolTipForceFieldEnabled : 1;
/** Should we be forcing this widget to be volatile at all times and redrawn every frame? */
uint8 bForceVolatile : 1;
/** The last cached volatility of this widget. Cached so that we don't need to recompute volatility every frame. */
uint8 bCachedVolatile : 1;
/** If we're owned by a volatile widget, we need inherit that volatility and use as part of our volatility, but don't cache it. */
uint8 bInheritedVolatility : 1;
/** If the widget is hidden or collapsed to ancestor visibility */
uint8 bInvisibleDueToParentOrSelfVisibility : 1;
/** Are we currently updating the desired size? */
uint8 bNeedsPrepass : 1;
uint8 bNeedsDesiredSize : 1;
/** Are we currently updating the desired size? */
mutable uint8 bUpdatingDesiredSize : 1;
protected:
uint8 bHasCustomPrepass : 1;
uint8 bHasRelativeLayoutScale : 1;
/** if this widget should always invalidate the prepass step when volatile */
uint8 bVolatilityAlwaysInvalidatesPrepass : 1;
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
UE_DEPRECATED(4.21, "Setting bCanTick on a widget directly is deprecated and will not function. Call SetCanTick instead")
uint8 bCanTick : 1;
#endif
#if WITH_ACCESSIBILITY
/** All variables surrounding how this widget is exposed to the platform's accessibility API. */
uint8 bCanChildrenBeAccessible : 1;
EAccessibleBehavior AccessibleBehavior;
EAccessibleBehavior AccessibleSummaryBehavior;
#endif
/**
* Set to true if all content of the widget should clip to the bounds of this widget.
*/
EWidgetClipping Clipping;
protected:
/** Establishes a new flow direction potentially, if this widget has a particular preference for it and all its children. */
EFlowDirection ComputeFlowDirection() const
{
switch (FlowDirectionPreference)
{
case EFlowDirectionPreference::Culture:
return FLayoutLocalization::GetLocalizedLayoutDirection();
case EFlowDirectionPreference::LeftToRight:
return EFlowDirection::LeftToRight;
case EFlowDirectionPreference::RightToLeft:
return EFlowDirection::RightToLeft;
}
return GSlateFlowDirection;
}
private:
/** Flow direction preference */
EFlowDirectionPreference FlowDirectionPreference;
/** The different updates this widget needs next frame. */
EWidgetUpdateFlags UpdateFlags;
#if WITH_SLATE_DEBUGGING
/** The last time this widget got painted. */
uint32 LastPaintFrame = 0;
#endif
mutable FSlateWidgetPersistentState PersistentState;
/** Stores the ideal size this widget wants to be. */
TOptional<FVector2D> DesiredSize;
/** The list of active timer handles for this widget. */
TArray<TSharedRef<FActiveTimerHandle>> ActiveTimers;
protected:
TOptional<float> PrepassLayoutScaleMultiplier;
/**
* Can be used to enlarge the culling bounds of this widget (pre-intersection), this can be useful if you've got
* children that you know are using rendering transforms to render outside their standard bounds, if that happens
* it's possible the parent might be culled before the descendant widget is entirely off screen. For those cases,
* you should extend the bounds of the culling area to add a bit more slack to how culling is performed to this panel.
*/
FMargin CullingBoundsExtension;
/** Whether or not this widget is enabled */
TAttribute< bool > EnabledState;
/** Is this widget visible, hidden or collapsed */
TAttribute< EVisibility > Visibility;
/** The opacity of the widget. Automatically applied during rendering. */
float RenderOpacity;
/** Render transform of this widget. TOptional<> to allow code to skip expensive overhead if there is no render transform applied. */
TAttribute< TOptional<FSlateRenderTransform> > RenderTransform;
/** Render transform pivot of this widget (in normalized local space) */
TAttribute< FVector2D > RenderTransformPivot;
/** Debugging information on the type of widget we're creating for the Widget Reflector. */
FName TypeOfWidget;
#if !UE_BUILD_SHIPPING
/** Full file path (and line) in which this widget was created */
FName CreatedInLocation;
#endif
/** Tag for this widget */
FName Tag;
/** Metadata associated with this widget */
TArray<TSharedRef<ISlateMetaData>> MetaData;
/** The cursor to show when the mouse is hovering over this widget. */
TAttribute< TOptional<EMouseCursor::Type> > Cursor;
private:
/** Tool tip content for this widget */
TSharedPtr<IToolTip> ToolTip;
/** Pointer to this widgets parent widget. If it is null this is a root widget or it is not in the widget tree */
TWeakPtr<SWidget> ParentWidgetPtr;
// Events
TArray<TPair<FName, FPointerEventHandler>> PointerEvents;
FNoReplyPointerEventHandler MouseEnterHandler;
FSimpleNoReplyPointerEventHandler MouseLeaveHandler;
#if UE_SLATE_WITH_WIDGET_UNIQUE_IDENTIFIER
/** The widget's id */
uint64 UniqueIdentifier;
#endif
STAT(size_t AllocSize;)
#if STATS || ENABLE_STATNAMEDEVENTS
/** Stat id of this object, 0 if nobody asked for it yet */
mutable TStatId StatID;
#endif
#if ENABLE_STATNAMEDEVENTS
mutable PROFILER_CHAR* StatIDStringStorage;
#endif
};
//=================================================================
// FGeometry Arranged Widget Inlined Functions
//=================================================================
FORCEINLINE_DEBUGGABLE FArrangedWidget FGeometry::MakeChild(const TSharedRef<SWidget>& ChildWidget, const FVector2D& InLocalSize, const FSlateLayoutTransform& LayoutTransform) const
{
// If there is no render transform set, use the simpler MakeChild call that doesn't bother concatenating the render transforms.
// This saves a significant amount of overhead since every widget does this, and most children don't have a render transform.
const TOptional<FSlateRenderTransform> RenderTransform = ChildWidget->GetRenderTransformWithRespectToFlowDirection();
if (RenderTransform.IsSet() )
{
const FVector2D RenderTransformPivot = ChildWidget->GetRenderTransformPivotWithRespectToFlowDirection();
return FArrangedWidget(ChildWidget, MakeChild(InLocalSize, LayoutTransform, RenderTransform.GetValue(), RenderTransformPivot));
}
else
{
return FArrangedWidget(ChildWidget, MakeChild(InLocalSize, LayoutTransform));
}
}
FORCEINLINE_DEBUGGABLE FArrangedWidget FGeometry::MakeChild(const TSharedRef<SWidget>& ChildWidget, const FLayoutGeometry& LayoutGeometry) const
{
return MakeChild(ChildWidget, LayoutGeometry.GetSizeInLocalSpace(), LayoutGeometry.GetLocalToParentTransform());
}
FORCEINLINE_DEBUGGABLE FArrangedWidget FGeometry::MakeChild(const TSharedRef<SWidget>& ChildWidget, const FVector2D& ChildOffset, const FVector2D& InLocalSize, float ChildScale) const
{
// Since ChildOffset is given as a LocalSpaceOffset, we MUST convert this offset into the space of the parent to construct a valid layout transform.
// The extra TransformPoint below does this by converting the local offset to an offset in parent space.
return MakeChild(ChildWidget, InLocalSize, FSlateLayoutTransform(ChildScale, TransformPoint(ChildScale, ChildOffset)));
}
template<typename TargetValueType, typename SourceValueType>
bool SetWidgetAttribute(SWidget& ThisWidget, TAttribute<TargetValueType>& TargetValue, const TAttribute<SourceValueType>& SourceValue, EInvalidateWidgetReason BaseInvalidationReason)
{
if (!TargetValue.IdenticalTo(SourceValue))
{
const bool bWasBound = TargetValue.IsBound();
const bool bBoundnessChanged = bWasBound != SourceValue.IsBound();
TargetValue = SourceValue;
EInvalidateWidgetReason InvalidateReason = BaseInvalidationReason;
if (bBoundnessChanged)
{
InvalidateReason |= EInvalidateWidgetReason::Volatility;
}
ThisWidget.Invalidate(InvalidateReason);
return true;
}
return false;
}
| [
"523793658@qq.com"
] | 523793658@qq.com |
2aaf01f0c803ad28d1f5bbd96cb2819ef0d26523 | cf15dac0951eaa82c67a7ddecdb84d7e96a9b2a7 | /lib/ratrac/ArgParse.cpp | cb16aea50f981fdc7646c8a6845f34213cf01445 | [
"Apache-2.0"
] | permissive | Arnaud-de-Grandmaison/ratrac | d269a1c08818c7cbc16528264ac5e673769de5af | 5c6df1593d1594867a3883de8068c723e20c176c | refs/heads/main | 2023-06-30T09:22:38.338041 | 2023-06-15T07:05:47 | 2023-06-15T07:05:47 | 278,571,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,049 | cpp | #include "ratrac/ArgParse.h"
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <sstream>
using std::cerr;
using std::clog;
using std::ostringstream;
using std::string;
using std::vector;
namespace ratrac {
ArgParse::ArgParse(const string &programName, const string &description)
: m_shortOptions(), m_longOptions(), m_options(),
m_programName(programName), m_description(description) {}
void ArgParse::processOptionNames(vector<char> &shortNames,
vector<string> &longNames,
const vector<string> &names, size_t idx) {
shortNames.clear();
longNames.clear();
for (const auto &n : names) {
size_t numDashes = n.find_first_not_of("-");
switch (numDashes) {
default:
error(
string("unexpected number of leading dashes for option '" + n + "'"));
case 1:
if (n.size() > 2)
error(string("unexpected short option format (a single character is "
"expected) for option '" +
n + "'"));
shortNames.push_back(n[1]);
break;
case 2:
if (n.size() == 2)
error(string("unexpected long option format (name must be non empty) "
"for option '" +
n + "'"));
longNames.emplace_back(n.substr(2));
break;
}
}
// Add the short option names to the known short options iff there is no
// duplicates.
for (const auto &c : shortNames) {
if (m_shortOptions.count(c) > 0)
error(string("short option '") + c + "' appears multiple times");
m_shortOptions.insert(std::make_pair(c, idx));
}
// Add the long option names to the known long options iff there is no
// duplicates.
for (const auto &n : longNames) {
if (m_longOptions.count(n) > 0)
error(string("long option '") + n + "' appears multiple times");
m_longOptions.insert(std::make_pair(n, idx));
}
}
void ArgParse::addOption(const vector<string> &names, const string &help,
actionNoArgFn action) {
vector<char> shortNames;
vector<string> longNames;
processOptionNames(shortNames, longNames, names, m_options.size());
m_options.emplace_back(Option::noValueOption(
std::move(shortNames), std::move(longNames), help, action));
}
void ArgParse::addOptionWithValue(const vector<string> &names,
const string &metavar, const string &help,
actionOneArgFn action) {
vector<char> shortNames;
vector<string> longNames;
processOptionNames(shortNames, longNames, names, m_options.size());
m_options.emplace_back(Option::oneValueOption(
std::move(shortNames), std::move(longNames), metavar, help, action));
}
bool ArgParse::parse(size_t argc, const char *argv[]) const {
for (size_t i = 0; i < argc; i++) {
string arg = argv[i];
size_t idx;
string value;
size_t numDashes = arg.find_first_not_of("-");
switch (numDashes) {
default:
error(string("unexpected number of dashes for argument '") + arg + "'");
case 1:
// Process this argument as a short option.
{
if (arg.size() != 2)
error(string("malformed short option argument '") + arg + "'");
const auto p = m_shortOptions.find(arg[1]);
if (p == m_shortOptions.end())
error(string("unrecognized short option for argument '") + arg + "'");
idx = p->second;
if (m_options[idx]->m_kind == Option::OneValue) {
if (i + 1 >= argc)
error(string("short option '") + arg + "' is missing an argument");
i++;
value = argv[i];
}
break;
}
case 2:
// Process this argument as a long option.
{
if (arg.size() <= 2)
error(string("malformed long option argument '") + arg + "'");
// Support both forms: "--long=t" and "--long t"
size_t pos = arg.find_first_of("=");
string name;
if (pos == string::npos)
name = arg.substr(2);
else
name = arg.substr(2, pos - 2);
const auto p = m_longOptions.find(name);
if (p == m_longOptions.end())
error(string("unrecognized long option for argument '") + arg + "'");
idx = p->second;
if (m_options[idx]->m_kind == Option::OneValue) {
if (pos == string::npos) {
if (i + 1 >= argc)
error(string("long option '") + arg + "' is missing an argument");
i++;
value = argv[i];
} else
value = arg.substr(pos + 1);
}
break;
}
}
switch (m_options[idx]->m_kind) {
case Option::NoValue:
if (!value.empty())
error(string("got a value for an option with no value ('") + arg + ")");
if (!m_options[idx]->m_actionNoArg())
return false;
break;
case Option::OneValue:
if (value.empty())
error(string("got no value for an option that takes a value ('") + arg + ")");
if (!m_options[idx]->m_actionOneArg(value))
return false;
break;
}
}
return true;
}
string ArgParse::help() const {
ostringstream h;
h << m_programName << ' ' << m_description;
if (!m_options.empty()) {
h << "\n\nOptions:";
for (const auto &o : m_options) {
const char *sep = "";
h << "\n ";
for (const auto &n : o->m_longNames) {
h << sep << "--" << n;
if (o->m_kind == Option::OneValue)
h << '=' << o->m_metavar;
sep = ", ";
}
for (const auto &n : o->m_shortNames) {
h << sep << "-" << n;
if (o->m_kind == Option::OneValue)
h << ' ' << o->m_metavar;
sep = ", ";
}
h << ": " << o->m_help;
}
}
return h.str();
}
void ArgParse::warn(const string &text) { clog << "Warning: " << text << '\n'; }
void ArgParse::error(const string &text) const {
cerr << "Error: " << text << '\n';
exit(EXIT_FAILURE);
}
} // namespace ratrac | [
"arnaud.adegm@gmail.com"
] | arnaud.adegm@gmail.com |
12e6c0105befc754efccb57322eab86cf5884c66 | 470642a337ee3b3f120720d23d715aff62fe3ab9 | /worm_demo/main.cpp | 31b88fff77e683a697c93e3d8f332b16b4d5503f | [] | no_license | huqinwei/windows_service_daemon | 177eb4da279eb309c414e0f12849b51bba26a0c9 | c7a6e7baf58fffa58e5ec48068d18cf321c032e8 | refs/heads/main | 2023-04-25T07:28:56.864959 | 2021-05-20T14:04:02 | 2021-05-20T14:04:02 | 369,117,594 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,815 | cpp | #pragma warning(disable:4996)
#include "CHttp.h"
#include <urlmon.h>
#pragma comment(lib, "urlmon.lib")
queue<string> q;//url队列
queue<string> p;//图片url队列
void StartCatch(string url);
int main()
{
//创建一个文件夹,点表示当前目录
CreateDirectory("./image", NULL);
string url;//cin>>url;
//下载地址,但是是zip:https://codeload.github.com/huqinwei/nomeaning2/zip/refs/heads/master
url = "https://blog.csdn.net/huqinweI987/article/details/116894555";// "https://github.com/huqinwei/nomeaning2/blob/master/order.txt";
//;//"https://blog.csdn.net/electech6/article/details/85331364"; "https://github.com/huqinwei/nomeaning2/blob/master/order.txt";// "http://desk.zol.com.cn/";//爬的是这个网站,可自行修改
//开始抓取
StartCatch(url);
system("pause");
return 0;
}
void StartCatch(string url)
{
q.push(url);
while (!q.empty())
{
//取出url
string currenturl = q.front();
q.pop();
CHttp http;
//发送一个Get请求
string html = http.FetchGet(currenturl);
//cout<<html;
http.AnalyseHtml(html);
}
}
//下载图片的线程
static int num = 0;
void loadImage()
{
while (!p.empty())
{
string currenturl = p.front();
p.pop();
char Name[20] = { 0 };
num++;
sprintf(Name, "./image/%d.jpg", num);
if (S_OK == URLDownloadToFile(NULL, currenturl.c_str(), Name, 0, 0))
{
cout << "download ok" << endl;
if (num == 24)//爬24张就结束了,也可以去掉这句话
{
exit(0);
}
}
else
{
cout << "download error" << endl;
}
}
}
| [
"huqinwei@airlook.com"
] | huqinwei@airlook.com |
2b54855710ea70dad548dd2ebdb5445af58a819f | 239091e0ea1412e76e29c43acdfb969bc6a5f1dc | /OpenPass_Source_Code/openPASS_GUI/openPASS-System/Models/SystemComponentInputMapModel.h | 8b486154d456cea3358d43416af65fd6ea0b111d | [] | no_license | hlrs-vis/openpass | 080a2625d6427ffff835bdc122954df8d022f382 | 7375cb9cd5bd77c8aad5094766169ddb225c7f13 | refs/heads/master | 2021-05-15T14:00:49.331352 | 2019-11-05T14:20:55 | 2019-11-05T14:20:55 | 107,249,522 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,658 | h | /******************************************************************************
* Copyright (c) 2017 Volkswagen Group of America.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
******************************************************************************/
#ifndef SYSTEMCOMPONENTINPUTMAPMODEL_H
#define SYSTEMCOMPONENTINPUTMAPMODEL_H
#include "openPASS-Component/ComponentInputMapInterface.h"
#include "openPASS-System/SystemComponentInputMapInterface.h"
class SystemComponentInputMapModel : public SystemComponentInputMapInterface
{
Q_OBJECT
public:
explicit SystemComponentInputMapModel(ComponentInputMapInterface const * const inputs,
QObject * const parent = nullptr);
virtual ~SystemComponentInputMapModel() = default;
public:
virtual SystemComponentInputMapInterface::Iterator begin() override;
virtual SystemComponentInputMapInterface::ConstIterator begin() const override;
public:
virtual SystemComponentInputMapInterface::Iterator end() override;
virtual SystemComponentInputMapInterface::ConstIterator end() const override;
public:
virtual SystemComponentInputMapInterface::ID getID(SystemComponentInputMapInterface::Item * const item) const override;
virtual SystemComponentInputMapInterface::Item * getItem(SystemComponentInputMapInterface::ID const & id) const override;
protected:
SystemComponentInputMapInterface::Map inputs;
};
#endif // SYSTEMCOMPONENTINPUTMAPMODEL_H
| [
"dmitri.fix@itk-engineering.de"
] | dmitri.fix@itk-engineering.de |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.