hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
โ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
โ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
โ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
โ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
โ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
โ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
โ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
โ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
โ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af5e21470c196899820ebe9cf8bd7082c1cde99a
| 834
|
cpp
|
C++
|
Language_Coder/๋ฌธ์์ด2/ํ์ฑํ๊ฐ/FormativeString201.cpp
|
NadanKim/CodingTest_JUNGOL
|
f1f448eb5a107b59bfa196c2682ba89e89431358
|
[
"MIT"
] | null | null | null |
Language_Coder/๋ฌธ์์ด2/ํ์ฑํ๊ฐ/FormativeString201.cpp
|
NadanKim/CodingTest_JUNGOL
|
f1f448eb5a107b59bfa196c2682ba89e89431358
|
[
"MIT"
] | null | null | null |
Language_Coder/๋ฌธ์์ด2/ํ์ฑํ๊ฐ/FormativeString201.cpp
|
NadanKim/CodingTest_JUNGOL
|
f1f448eb5a107b59bfa196c2682ba89e89431358
|
[
"MIT"
] | null | null | null |
๏ปฟ#include "FormativeString201.h"
/// <summary>
/// ๋ฌธ์
/// ๊ณต๋ฐฑ์ ํฌํจํ ๋ฌธ์์ด์ ์
๋ ฅ๋ฐ์ ๊ฐ ๋จ์ด๋ก ๋ถ๋ฆฌํ์ฌ ๋ฌธ์์ด ๋ฐฐ์ด์ ์ ์ฅํ ํ ์
๋ ฅ์์์ ๋ฐ๋ ์์๋ก ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
/// ๋ฌธ์์ด์ ๊ธธ์ด๋ 100์ ์ดํ์ด๋ค.
///
/// ์
๋ ฅ ์
/// C++ Programing jjang!!
///
/// ์ถ๋ ฅ ์
/// jjang!!
/// Programing
/// C++
///
/// Hint!
/// [๋ฌธ์ฅ์ ๋จ์ด๋ก ๋๋๊ธฐ](http://comkiwer.tistory.com/entry/C-CPP-%EA%B3%B5%EB%B0%B1%EC%9D%84-%ED%8F%AC%ED%95%A8%ED%95%9C-%EB%AC%B8%EC%9E%90%EC%97%B4-split%ED%95%98%EA%B8%B0?category=734118)
///
/// http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=89&sca=10f0
/// </summary>
void FormativeString201::Code()
{
string str;
std::getline(std::cin, str);
string word;
vector<string> words;
for (stringstream ss{ str }; ss >> word;)
{
words.push_back(word);
}
for (int i = static_cast<int>(words.size()) - 1; i >= 0; i--)
{
std::cout << words[i] << '\n';
}
}
| 21.947368
| 182
| 0.609113
|
NadanKim
|
af60f971a6f1c6055b70c3a18f62b8330d3fd656
| 439
|
cpp
|
C++
|
libs/libc/source/string/memccpy.cpp
|
zhiayang/nx
|
0d9da881f67ec351244abd72e1f3884816b48f5b
|
[
"Apache-2.0"
] | 16
|
2019-03-14T19:45:02.000Z
|
2022-02-06T19:18:08.000Z
|
libs/libc/source/string/memccpy.cpp
|
zhiayang/nx
|
0d9da881f67ec351244abd72e1f3884816b48f5b
|
[
"Apache-2.0"
] | 1
|
2020-05-08T08:40:02.000Z
|
2020-05-08T13:27:59.000Z
|
libs/libc/source/string/memccpy.cpp
|
zhiayang/nx
|
0d9da881f67ec351244abd72e1f3884816b48f5b
|
[
"Apache-2.0"
] | 2
|
2021-01-16T20:42:05.000Z
|
2021-12-01T23:37:18.000Z
|
// memccpy.cpp
// Copyright (c) 2014 - 2016, zhiayang
// Licensed under the Apache License Version 2.0.
#include <stddef.h>
extern "C" void* memccpy(void* dest_ptr, const void* src_ptr, int c, size_t n)
{
unsigned char* dest = (unsigned char*) dest_ptr;
const unsigned char* src = (const unsigned char*) src_ptr;
for(size_t i = 0; i < n; i++)
{
if((dest[i] = src[i]) == (unsigned char) c)
return dest + i + 1;
}
return NULL;
}
| 25.823529
| 78
| 0.649203
|
zhiayang
|
af661942888ffecea18cb24d30e3d05615c1592e
| 3,693
|
cpp
|
C++
|
gm/daa.cpp
|
NearTox/Skia
|
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
|
[
"BSD-3-Clause"
] | null | null | null |
gm/daa.cpp
|
NearTox/Skia
|
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
|
[
"BSD-3-Clause"
] | null | null | null |
gm/daa.cpp
|
NearTox/Skia
|
8b7e0616161fff86ecbd8938b90600d72b8d5c1d
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPathBuilder.h"
#include "include/core/SkPoint.h"
#include "include/core/SkTypes.h"
// This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.).
// See also the bottom of dashing4 and skia:6886.
static const int K = 49;
DEF_SIMPLE_GM(daa, canvas, K + 350, 5 * K) {
SkPaint paint;
paint.setAntiAlias(true);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Should be a green square with no red showing through.", K * 1.5f, K * 0.5f, SkFont(),
paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
SkPoint tri1[] = {{0, 0}, {K, K}, {0, K}, {0, 0}};
SkPoint tri2[] = {{0, 0}, {K, K}, {K, 0}, {0, 0}};
SkPath path = SkPathBuilder()
.addPolygon(tri1, SK_ARRAY_COUNT(tri1), false)
.addPolygon(tri2, SK_ARRAY_COUNT(tri2), false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, two draws. Blue then green, no red?", K * 1.5f, K * 0.5f, SkFont(),
paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPath::Polygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false);
paint.setColor(SK_ColorBLUE);
canvas->drawPath(path, paint);
}
{
SkPath path = SkPath::Polygon({{K * 0.5f, 0}, {K * 0.5f, K}, {K, K}, {K, 0}}, false);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, wound together. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPathBuilder()
.addPolygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false)
.addPolygon({{K * 0.5f, 0}, {K * 0.5f, K}, {K, K}, {K, 0}}, false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, wound opposite. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPathBuilder()
.addPolygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false)
.addPolygon({{K * 0.5f, 0}, {K, 0}, {K, K}, {K * 0.5f, K}}, false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"One poly, wound opposite. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
SkPath path = SkPath::Polygon(
{{K * 0.5f, 0},
{0, 0},
{0, K},
{K * 0.5f, K},
{K * 0.5f, 0},
{K, 0},
{K, K},
{K * 0.5f, K}},
false);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
| 27.766917
| 94
| 0.541565
|
NearTox
|
af6865b70dca6d51f0e12fc6ac104705796886d2
| 1,670
|
hpp
|
C++
|
apps/stochastic_lasso/src/prox_grad.hpp
|
daiwei89/wdai_petuum_public
|
4068859897061201d0a63630a3da6011b0d0f75f
|
[
"BSD-3-Clause"
] | null | null | null |
apps/stochastic_lasso/src/prox_grad.hpp
|
daiwei89/wdai_petuum_public
|
4068859897061201d0a63630a3da6011b0d0f75f
|
[
"BSD-3-Clause"
] | null | null | null |
apps/stochastic_lasso/src/prox_grad.hpp
|
daiwei89/wdai_petuum_public
|
4068859897061201d0a63630a3da6011b0d0f75f
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <vector>
#include <ml/include/ml.hpp>
#include <petuum_ps_common/include/petuum_ps.hpp>
#include <random>
namespace lasso {
struct ProxGradConfig {
int worker_rank = -1;
int feature_start = 0;
int feature_end = 0;
int num_samples = 0;
int num_reps = 1;
};
class ProxGrad {
public:
ProxGrad(const ProxGradConfig& config);
void ProxStep(
const std::vector<petuum::ml::SparseFeature<float>*>& X_cols,
const petuum::ml::DenseFeature<float>& y,
float lr, int my_clock);
float EvalSqLoss(
const petuum::ml::DenseFeature<float>& y);
float EvalL1Penalty() const;
// Cound # of non-zeros in beta (sharded to workers).
int EvalBetaNNZ() const;
int GetSampleSize() const {
return num_feature_samples_;
}
private:
void SoftThreshold(float threshold,
petuum::ml::DenseFeature<float>* x);
private:
int worker_rank_;
int num_workers_;
int num_samples_;
int feature_start_;
int feature_end_;
int num_features_; // # features in this worker.
// stochastic version uses only this many coordinates in each step
int num_feature_samples_;
int num_reps_;
petuum::ml::DenseFeature<float> beta_; // [num_features_ x 1]
petuum::ml::DenseFeature<float> r_; // [num_samples_ x 1]
//petuum::ml::DenseFeature<float> delta_; // [num_features_ x 1]
petuum::Table<float> w_table_;
petuum::Table<float> unused_table_;
petuum::Table<int64_t> staleness_table_;
std::random_device r;
std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 rand_eng{seed2};
std::uniform_real_distribution<float> uniform_dist{0, 1};
};
} // namespace lasso
| 25.30303
| 68
| 0.691617
|
daiwei89
|
af69030ff4cfb16d97d5be413074405e5b354d61
| 883
|
cxx
|
C++
|
panda/src/gobj/timerQueryContext.cxx
|
cmarshall108/panda3d-python3
|
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
|
[
"PHP-3.0",
"PHP-3.01"
] | null | null | null |
panda/src/gobj/timerQueryContext.cxx
|
cmarshall108/panda3d-python3
|
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
|
[
"PHP-3.0",
"PHP-3.01"
] | null | null | null |
panda/src/gobj/timerQueryContext.cxx
|
cmarshall108/panda3d-python3
|
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
|
[
"PHP-3.0",
"PHP-3.01"
] | null | null | null |
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file timerQueryContext.cxx
* @author rdb
* @date 2014-08-22
*/
#include "timerQueryContext.h"
TypeHandle TimerQueryContext::_type_handle;
/**
* Returns the timestamp that is the result of this timer query. There's no
* guarantee about which clock this uses, the only guarantee is that
* subtracting a start time from an end time should yield a time in seconds.
* If is_answer_ready() did not return true, this function may block before it
* returns.
*
* It is only valid to call this from the draw thread.
*/
double TimerQueryContext::
get_timestamp() const {
return 0.0;
}
| 28.483871
| 78
| 0.730464
|
cmarshall108
|
af6c046a383a54748e3ec6ccb3a3a7a5f9d7014b
| 18,315
|
cpp
|
C++
|
termsrv/newclient/clshell/propperf.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
termsrv/newclient/clshell/propperf.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
termsrv/newclient/clshell/propperf.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//
// propperf.cpp: local resources property sheet dialog proc
//
// Tab E
//
// Copyright Microsoft Corporation 2000
// nadima
#include "stdafx.h"
#define TRC_GROUP TRC_GROUP_UI
#define TRC_FILE "propperf"
#include <atrcapi.h>
#include "sh.h"
#include "commctrl.h"
#include "propperf.h"
CPropPerf* CPropPerf::_pPropPerfInstance = NULL;
//
// Lookup tables
//
//
// Controls that need to be disabled/enabled
// during connection (for progress animation)
//
CTL_ENABLE connectingDisableCtlsPPerf[] = {
{UI_IDC_STATIC_CHOOSE_SPEED, FALSE},
{IDC_COMBO_PERF_OPTIMIZE, FALSE},
{UI_IDC_STATIC_OPTIMIZE_PERF, FALSE},
{IDC_CHECK_DESKTOP_BKND, FALSE},
{IDC_CHECK_SHOW_FWD, FALSE},
{IDC_CHECK_MENU_ANIMATIONS, FALSE},
{IDC_CHECK_THEMES, FALSE},
{IDC_CHECK_BITMAP_CACHING, FALSE},
{IDC_CHECK_ENABLE_ARC, FALSE}
};
const UINT numConnectingDisableCtlsPPerf =
sizeof(connectingDisableCtlsPPerf)/
sizeof(connectingDisableCtlsPPerf[0]);
//
// MAP from optimization level to disabled feature list
// Disabled features list
//
// Index is the optimization level, entry is the disabled feature list
//
DWORD g_dwMapOptLevelToDisabledList[NUM_PERF_OPTIMIZATIONS] =
{
// 28K
TS_PERF_DISABLE_WALLPAPER |
TS_PERF_DISABLE_FULLWINDOWDRAG |
TS_PERF_DISABLE_MENUANIMATIONS |
TS_PERF_DISABLE_THEMING,
// 56K
TS_PERF_DISABLE_WALLPAPER |
TS_PERF_DISABLE_FULLWINDOWDRAG |
TS_PERF_DISABLE_MENUANIMATIONS,
// Broadband
TS_PERF_DISABLE_WALLPAPER,
// LAN
TS_PERF_DISABLE_NOTHING,
//
// CUSTOM (defaults to same as 56K
// 56K
//
// NOTE: This value gets changed at runtime
// to reflect the current custom settings
//
TS_PERF_DISABLE_WALLPAPER |
TS_PERF_DISABLE_FULLWINDOWDRAG |
TS_PERF_DISABLE_MENUANIMATIONS
};
//
// Mask of flags that can be set by checkboxes
//
#define CHECK_BOX_PERF_MASK (TS_PERF_DISABLE_WALLPAPER | \
TS_PERF_DISABLE_FULLWINDOWDRAG | \
TS_PERF_DISABLE_MENUANIMATIONS | \
TS_PERF_DISABLE_THEMING | \
TS_PERF_DISABLE_BITMAPCACHING | \
TS_PERF_DISABLE_CURSORSETTINGS) \
CPropPerf::CPropPerf(HINSTANCE hInstance, CTscSettings* pTscSet, CSH* pSh)
{
DC_BEGIN_FN("CPropPerf");
_hInstance = hInstance;
CPropPerf::_pPropPerfInstance = this;
_pTscSet = pTscSet;
_hwndDlg = NULL;
_fSyncingCheckboxes = FALSE;
_pSh = pSh;
TRC_ASSERT(_pTscSet,(TB,_T("_pTscSet is null")));
TRC_ASSERT(_pSh,(TB,_T("_pSh is null")));
DC_END_FN();
}
CPropPerf::~CPropPerf()
{
CPropPerf::_pPropPerfInstance = NULL;
}
INT_PTR CALLBACK CPropPerf::StaticPropPgPerfDialogProc(HWND hwndDlg,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
//
// Delegate to appropriate instance (only works for single instance dialogs)
//
DC_BEGIN_FN("StaticDialogBoxProc");
DCINT retVal = 0;
TRC_ASSERT(_pPropPerfInstance, (TB,
_T("perf dialog has NULL static instance ptr\n")));
retVal = _pPropPerfInstance->PropPgPerfDialogProc( hwndDlg,
uMsg,
wParam,
lParam);
DC_END_FN();
return retVal;
}
INT_PTR CALLBACK CPropPerf::PropPgPerfDialogProc (HWND hwndDlg,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
DC_BEGIN_FN("PropPgPerfDialogProc");
switch(uMsg)
{
case WM_INITDIALOG:
{
#ifndef OS_WINCE
int i;
#endif
_hwndDlg = hwndDlg;
//
// Position the dialog within the tab
//
SetWindowPos( hwndDlg, HWND_TOP,
_rcTabDispayArea.left, _rcTabDispayArea.top,
_rcTabDispayArea.right - _rcTabDispayArea.left,
_rcTabDispayArea.bottom - _rcTabDispayArea.top,
0);
InitPerfCombo();
SyncCheckBoxesToPerfFlags(
_pTscSet->GetPerfFlags());
//
// AutoReconnection checkbox
//
CheckDlgButton(hwndDlg, IDC_CHECK_ENABLE_ARC,
_pTscSet->GetEnableArc() ?
BST_CHECKED : BST_UNCHECKED);
_pSh->SH_ThemeDialogWindow(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
break; //WM_INITDIALOG
case WM_TSC_ENABLECONTROLS:
{
//
// wParam is TRUE to enable controls,
// FALSE to disable them
//
CSH::EnableControls( hwndDlg,
connectingDisableCtlsPPerf,
numConnectingDisableCtlsPPerf,
wParam ? TRUE : FALSE);
}
break;
case WM_SAVEPROPSHEET: //Intentional fallthru
case WM_DESTROY:
{
BOOL fEnableArc;
//
// Save page settings
//
DWORD dwCheckBoxPerfFlags = GetPerfFlagsFromCheckboxes();
DWORD dwPerfFlags = MergePerfFlags( dwCheckBoxPerfFlags,
_pTscSet->GetPerfFlags(),
CHECK_BOX_PERF_MASK );
fEnableArc = IsDlgButtonChecked(hwndDlg, IDC_CHECK_ENABLE_ARC);
_pTscSet->SetEnableArc(fEnableArc);
_pTscSet->SetPerfFlags(dwPerfFlags);
}
break; //WM_DESTROY
case WM_COMMAND:
{
switch(DC_GET_WM_COMMAND_ID(wParam))
{
case IDC_COMBO_PERF_OPTIMIZE:
{
if(HIWORD(wParam) == CBN_SELCHANGE)
{
OnPerfComboSelChange();
}
}
break;
default:
{
if (HIWORD(wParam) == BN_CLICKED)
{
//
// One of the checkboxes has been checked
// (prevent recursive looping due to feedback)
//
if (!_fSyncingCheckboxes)
{
OnCheckBoxStateChange((int)LOWORD(wParam));
}
}
}
break;
}
}
break;
}
DC_END_FN();
return 0;
}
BOOL CPropPerf::InitPerfCombo()
{
INT ret = 1;
DC_BEGIN_FN("InitPerfCombo");
TRC_ASSERT(g_fPropPageStringMapInitialized,
(TB,_T("Perf strings not loaded")));
TRC_ASSERT(_hwndDlg,
(TB,_T("_hwndDlg not set")));
if (!g_fPropPageStringMapInitialized)
{
return FALSE;
}
#ifndef OS_WINCE
while (ret && ret != CB_ERR)
{
ret = SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CBEM_DELETEITEM,
0,0);
}
#else
SendDlgItemMessage(_hwndDlg, IDC_COMBO_PERF_OPTIMIZE, CB_RESETCONTENT, 0, 0);
#endif
//
// Only set up to the last but one string in the table
// as the last string is only used in the perf page
//
for (int i=0; i<NUM_PERF_OPTIMIZATIONS+1; i++)
{
if (NUM_PERF_OPTIMIZATIONS-1 == i)
{
//
// Skip the last but one string it's the
// custom entry for the main dialog
//
continue;
}
SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CB_ADDSTRING,
0,
(LPARAM)(PDCTCHAR)g_PerfOptimizeStringTable[i].szString);
}
//
// Set the optimization level according to the disabled feature list
//
DWORD dwPerfFlags = _pTscSet->GetPerfFlags();
int optLevel = MapPerfFlagsToOptLevel(dwPerfFlags);
TRC_ASSERT(optLevel >= 0 && optLevel < NUM_PERF_OPTIMIZATIONS,
(TB,_T("optlevel %d out of range"), optLevel));
SendDlgItemMessage(_hwndDlg, IDC_COMBO_PERF_OPTIMIZE,CB_SETCURSEL,
(WPARAM)optLevel,0);
DC_END_FN();
return TRUE;
}
//
// Notification that the perf combo's selection has changed
//
VOID CPropPerf::OnPerfComboSelChange()
{
int curSel = 0;
DWORD dwDisableFeatureList = 0;
DC_BEGIN_FN("OnPerfComboSelChange");
//
// Figure out what the new selected item is
//
curSel = SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CB_GETCURSEL,
0,0);
if (curSel < 0)
{
curSel = 0;
}
TRC_ASSERT(curSel < NUM_PERF_OPTIMIZATIONS,
(TB,_T("curSel (%d) > NUM_PERF_OPTIMIZATIONS (%d)"),
curSel,NUM_PERF_OPTIMIZATIONS));
if (curSel >= NUM_PERF_OPTIMIZATIONS)
{
curSel = NUM_PERF_OPTIMIZATIONS - 1;
}
//
// Map that to a list of disabled features
//
dwDisableFeatureList = MapOptimizationLevelToPerfFlags(curSel);
//
// Check and uncheck the checkboxes
//
SyncCheckBoxesToPerfFlags(dwDisableFeatureList);
DC_END_FN();
}
//
// Static method. Maps an optimization to the disabled feature list
// (packed in a DWORD)
// Params:
// [in] optLevel - optimization level from 0 to NUM_PERF_OPTIMIZATIONS-1
// [return] DWORD feature list
//
DWORD CPropPerf::MapOptimizationLevelToPerfFlags(int optLevel)
{
DWORD dwPerfFlags = 0;
DC_BEGIN_FN("MapOptimizationLevelToPerfFlags");
if (optLevel < 0)
{
TRC_ERR((TB,_T("Opt level out of range %d"),optLevel));
optLevel = 0;
}
if (optLevel >= NUM_PERF_OPTIMIZATIONS)
{
TRC_ERR((TB,_T("Opt level out of range %d"),optLevel));
optLevel = NUM_PERF_OPTIMIZATIONS - 1;
}
dwPerfFlags = g_dwMapOptLevelToDisabledList[optLevel];
TRC_NRM((TB,_T("Return disable list 0x%x"),dwPerfFlags));
DC_END_FN();
return dwPerfFlags;
}
//
// Toggles checkboxes to match the disabled feature list
// NOTE: the checkboxes represent 'enabled' features i.e the negation
// of the list
//
VOID CPropPerf::SyncCheckBoxesToPerfFlags(DWORD dwPerfFlagss)
{
DC_BEGIN_FN("SyncCheckBoxesToPerfFlags");
//
// Prevent recursive sets based on change notifications
// for the checkboxes (As they could change the combo leading
// to a subsequent change in the checkboxes, etc...)
//
_fSyncingCheckboxes = TRUE;
//
// Wallpaper (Desktop background)
//
CheckDlgButton(_hwndDlg, IDC_CHECK_DESKTOP_BKND,
(dwPerfFlagss & TS_PERF_DISABLE_WALLPAPER ?
BST_UNCHECKED : BST_CHECKED));
//
// Fullwindow drag
//
CheckDlgButton(_hwndDlg, IDC_CHECK_SHOW_FWD,
(dwPerfFlagss & TS_PERF_DISABLE_FULLWINDOWDRAG ?
BST_UNCHECKED : BST_CHECKED));
//
// Menu animations
//
CheckDlgButton(_hwndDlg, IDC_CHECK_MENU_ANIMATIONS,
(dwPerfFlagss & TS_PERF_DISABLE_MENUANIMATIONS ?
BST_UNCHECKED : BST_CHECKED));
//
// Theming
//
CheckDlgButton(_hwndDlg, IDC_CHECK_THEMES,
(dwPerfFlagss & TS_PERF_DISABLE_THEMING ?
BST_UNCHECKED : BST_CHECKED));
//
// Bitmap caching
//
CheckDlgButton(_hwndDlg, IDC_CHECK_BITMAP_CACHING,
(dwPerfFlagss & TS_PERF_DISABLE_BITMAPCACHING ?
BST_UNCHECKED : BST_CHECKED));
_fSyncingCheckboxes = FALSE;
DC_END_FN();
}
//
// Maps the disabled feature list to the appropriate optimization level
//
INT CPropPerf::MapPerfFlagsToOptLevel(DWORD dwPerfFlags)
{
DC_BEGIN_FN("MapPerfFlagsToOptLevel");
for (int i=0;i<NUM_PERF_OPTIMIZATIONS;i++)
{
if (g_dwMapOptLevelToDisabledList[i] == dwPerfFlags)
{
return i;
}
}
DC_END_FN();
//
// Didn't find an entry so return the last optimization level (custom)
//
return (NUM_PERF_OPTIMIZATIONS-1);
}
//
// Called whenever a checkbox's state changes (Checked or unchecked)
//
//
VOID CPropPerf::OnCheckBoxStateChange(int checkBoxID)
{
DWORD dwCheckBoxPerfFlags = 0;
DWORD dwPerfFlags = 0;
int optLevel = 0;
int curSel = 0;
DC_BEGIN_FN("OnCheckBoxStateChange");
//
// Pickup the current disabled feature list from the
// checkboxes
//
dwCheckBoxPerfFlags = GetPerfFlagsFromCheckboxes();
dwPerfFlags = MergePerfFlags( dwCheckBoxPerfFlags,
_pTscSet->GetPerfFlags(),
CHECK_BOX_PERF_MASK );
//
// Figure out the optimization level
//
optLevel = MapPerfFlagsToOptLevel(dwPerfFlags);
TRC_ASSERT(optLevel >= 0 && optLevel < NUM_PERF_OPTIMIZATIONS,
(TB,_T("optlevel %d out of range"), optLevel));
//
// If the combo is at a different opt level then switch it to
// the new level
//
curSel = SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CB_GETCURSEL,
0,0);
//
// Update the custom disabled list based on the current
// settings
//
UpdateCustomDisabledList(dwPerfFlags);
if (curSel != optLevel)
{
SendDlgItemMessage(_hwndDlg, IDC_COMBO_PERF_OPTIMIZE,CB_SETCURSEL,
(WPARAM)optLevel,0);
}
DC_END_FN();
}
//
// Queries the checkboxes and returns the disabled feature list
// as a DWORD of flags
//
DWORD CPropPerf::GetPerfFlagsFromCheckboxes()
{
DWORD dwPerfFlags = 0;
DC_BEGIN_FN("GetPerfFlagsFromCheckboxes");
//
// Wallpaper (Desktop background)
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_DESKTOP_BKND))
{
dwPerfFlags |= TS_PERF_DISABLE_WALLPAPER;
}
//
// Fullwindow drag
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_SHOW_FWD))
{
dwPerfFlags |= TS_PERF_DISABLE_FULLWINDOWDRAG;
}
//
// Menu animations
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_MENU_ANIMATIONS))
{
dwPerfFlags |= TS_PERF_DISABLE_MENUANIMATIONS;
}
//
// Themeing
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_THEMES))
{
dwPerfFlags |= TS_PERF_DISABLE_THEMING;
}
//
// Bitmap caching
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_BITMAP_CACHING))
{
dwPerfFlags |= TS_PERF_DISABLE_BITMAPCACHING;
}
TRC_NRM((TB,_T("Return disable list 0x%x"),dwPerfFlags));
DC_END_FN();
return dwPerfFlags;
}
//
// Called to initialize the 'custom' disabled property
// list (e.g called at initialization time or after loading
// new settings
//
VOID CPropPerf::UpdateCustomDisabledList(DWORD dwPerfFlags)
{
DC_BEGIN_FN("InitCustomDisabledList");
//
//
//
INT optLevel = MapPerfFlagsToOptLevel(dwPerfFlags);
if (CUSTOM_OPTIMIZATION_LEVEL == optLevel)
{
//
// Store this as the new set of custom settings
//
TRC_NRM((TB,_T("Recording new custom setting: 0x%x"),
dwPerfFlags));
g_dwMapOptLevelToDisabledList[CUSTOM_OPTIMIZATION_LEVEL] =
dwPerfFlags;
}
DC_END_FN();
}
BOOL CPropPerf::EnableCheckBoxes(BOOL fEnable)
{
DC_BEGIN_FN("EnableCheckBoxes");
//
// Wallpaper (Desktop background)
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_DESKTOP_BKND),
fEnable );
//
// Fullwindow drag
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_SHOW_FWD),
fEnable );
//
// Menu animations
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_MENU_ANIMATIONS),
fEnable );
//
// Theming
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_THEMES),
fEnable );
//
// Bitmap caching
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_BITMAP_CACHING),
fEnable );
//
// Title static control
//
EnableWindow( GetDlgItem(_hwndDlg, UI_IDC_STATIC_OPTIMIZE_PERF),
fEnable );
DC_END_FN();
return TRUE;
}
//
// Merge perf flags from two sources
// 1) dwCheckBoxFlags - flags that come from the checkboxes
// 2) dwOrig set of passed in flags
//
// Use dwMask to preserve original flags that should not be affected
// by the checkboxes
//
// return - merged flags
//
DWORD CPropPerf::MergePerfFlags(DWORD dwCheckBoxFlags,
DWORD dwOrig,
DWORD dwMask)
{
DWORD dwNewFlags;
DC_BEGIN_FN("MergePerfFlags");
dwNewFlags = (dwOrig & ~dwMask) | (dwCheckBoxFlags & dwMask);
DC_END_FN();
return dwNewFlags;
}
| 27.173591
| 82
| 0.546219
|
npocmaka
|
af6c3a5fa03dab6a87d9a3abe48f4804956e52cf
| 1,287
|
hpp
|
C++
|
library/sha256/sha256.hpp
|
shuyangsun/ssy_blockchain
|
846c3758ddeb6717b8e7425a9ad89eda5eceb7ab
|
[
"MIT"
] | null | null | null |
library/sha256/sha256.hpp
|
shuyangsun/ssy_blockchain
|
846c3758ddeb6717b8e7425a9ad89eda5eceb7ab
|
[
"MIT"
] | null | null | null |
library/sha256/sha256.hpp
|
shuyangsun/ssy_blockchain
|
846c3758ddeb6717b8e7425a9ad89eda5eceb7ab
|
[
"MIT"
] | null | null | null |
/*********************************************************************
* Filename: sha256.h
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Defines the API for the corresponding SHA1 implementation.
*********************************************************************/
#ifndef SSYBC_LIBRARY_SHA256_SHA256_HPP_
#define SSYBC_LIBRARY_SHA256_SHA256_HPP_
/*************************** HEADER FILES ***************************/
#include <stddef.h>
/****************************** MACROS ******************************/
#define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest
/**************************** DATA TYPES ****************************/
typedef unsigned char BYTE; // 8-bit byte
typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines
typedef struct {
BYTE data[64];
WORD datalen;
unsigned long long bitlen;
WORD state[8];
} SHA256_CTX;
/*********************** FUNCTION DECLARATIONS **********************/
void sha256_init(SHA256_CTX *ctx);
void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len);
void sha256_final(SHA256_CTX *ctx, BYTE hash[]);
#endif // SSYBC_LIBRARY_SHA256_SHA256_HPP_
| 36.771429
| 92
| 0.523699
|
shuyangsun
|
af6de3fd4345760aea98549bb776b82adb22984a
| 603
|
cpp
|
C++
|
VehicleIR.cpp
|
tcklpl/remotevehicle-vehicle
|
49c9a7fd455e9c9246077b20bf192f3805d6c873
|
[
"MIT"
] | null | null | null |
VehicleIR.cpp
|
tcklpl/remotevehicle-vehicle
|
49c9a7fd455e9c9246077b20bf192f3805d6c873
|
[
"MIT"
] | null | null | null |
VehicleIR.cpp
|
tcklpl/remotevehicle-vehicle
|
49c9a7fd455e9c9246077b20bf192f3805d6c873
|
[
"MIT"
] | null | null | null |
/*
RemoteVehicle - library for controlling a remote vehicle using a ESP32CAM board.
Created by Luan Negroni Sibinel, August 24, 2021.
Released under the MIT license.
*/
#include "VehicleIR.h"
VehicleIR::VehicleIR(int8_t panalog, int8_t pdigital) {
_panalog = panalog;
_pdigital = pdigital;
if (_pdigital != -1)
pinMode(_pdigital, INPUT);
if (_panalog != -1)
pinMode(_panalog, INPUT);
}
int VehicleIR::digital() {
return _pdigital == -1 ? -1 : digitalRead(_pdigital);
}
int VehicleIR::analog() {
return _panalog == -1 ? -1 : analogRead(_panalog);
}
| 25.125
| 84
| 0.660033
|
tcklpl
|
af6e73cb9cc01c2facf801835c69d271e7115792
| 7,182
|
cpp
|
C++
|
src/wmecore/UiObjectOld.cpp
|
retrowork/wme
|
54cf8905091736aef0a35fe6d3e05b818441f3c8
|
[
"MIT"
] | null | null | null |
src/wmecore/UiObjectOld.cpp
|
retrowork/wme
|
54cf8905091736aef0a35fe6d3e05b818441f3c8
|
[
"MIT"
] | null | null | null |
src/wmecore/UiObjectOld.cpp
|
retrowork/wme
|
54cf8905091736aef0a35fe6d3e05b818441f3c8
|
[
"MIT"
] | null | null | null |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "Wme.h"
#include "UiObjectOld.h"
#include "UiObjectFactory.h"
#include "ContentManager.h"
#include "ElementCollection.h"
#include "Sprite.h"
#include "XmlUtil.h"
namespace Wme
{
//////////////////////////////////////////////////////////////////////////
UiObjectOld::UiObjectOld(GuiStage* parentStage)
{
m_ParentStage = parentStage;
m_Parent = NULL;
m_ZOrder = 0;
m_PixelPerfect = false;
m_Disabled = false;
m_Visible = true;
m_PosX = m_PosY = 0;
m_Width = m_Height = 0;
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld::~UiObjectOld()
{
foreach (UiObjectOld* child, m_Children)
{
SAFE_DELETE(child);
}
m_Children.clear();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Create()
{
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Display(ElementCollection* elementCol, const SpriteDrawingParams& params)
{
foreach (UiObjectOld* child, m_Children)
{
child->Display(elementCol, params);
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Update()
{
foreach (UiObjectOld* child, m_Children)
{
child->Update();
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::AddChild(UiObjectOld* child)
{
UiObjectList::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) return;
m_Children.push_back(child);
child->SetParent(this);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::RemoveChild(UiObjectOld* child)
{
UiObjectList::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end())
{
(*it)->SetParent(NULL);
m_Children.erase(it);
}
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::MoveChildAfter(UiObjectOld* child, UiObjectOld* pos)
{
UiObjectList::iterator it;
it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) m_Children.erase(it);
it = std::find(m_Children.begin(), m_Children.end(), pos);
if (it != m_Children.end())
{
it++;
m_Children.insert(it, child);
}
else m_Children.push_back(child);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::MoveChildBefore(UiObjectOld* child, UiObjectOld* pos)
{
UiObjectList::iterator it;
it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) m_Children.erase(it);
it = std::find(m_Children.begin(), m_Children.end(), pos);
if (it != m_Children.end()) m_Children.insert(it, child);
else m_Children.push_front(child);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld* UiObjectOld::GetChild(size_t index)
{
foreach (UiObjectOld* child, m_Children)
{
if (child->GetZOrder() == index) return child;
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld* UiObjectOld::GetChild(const WideString& name)
{
foreach (UiObjectOld* child, m_Children)
{
if (child->GetName() == name) return child;
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::UpdateChildrenZOrder()
{
size_t order = 0;
foreach (UiObjectOld* child, m_Children)
{
child->SetZOrder(order);
order++;
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::GetOffset(int& offsetX, int& offsetY) const
{
if (m_Parent) m_Parent->GetOffset(offsetX, offsetY);
offsetX += m_PosX;
offsetY += m_PosY;
}
//////////////////////////////////////////////////////////////////////////
int UiObjectOld::GetAbsoluteX() const
{
int posX = 0;
int posY = 0;
GetOffset(posX, posY);
return posX;
}
//////////////////////////////////////////////////////////////////////////
int UiObjectOld::GetAbsoluteY() const
{
int posX = 0;
int posY = 0;
GetOffset(posX, posY);
return posY;
}
//////////////////////////////////////////////////////////////////////////
// DocumentAwareObject
//////////////////////////////////////////////////////////////////////////
bool UiObjectOld::LoadFromXml(TiXmlElement* rootNode)
{
ScriptableObject::LoadFromXml(rootNode);
for (TiXmlElement* elem = rootNode->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())
{
if (elem->ValueStr() == "Position")
{
m_PosX = XmlUtil::AttrToInt(elem, "X", 0);
m_PosY = XmlUtil::AttrToInt(elem, "Y", 0);
}
else if (elem->ValueStr() == "Size")
{
m_Width = XmlUtil::AttrToInt(elem, "Width", 0);
m_Height = XmlUtil::AttrToInt(elem, "Height", 0);
}
else if (elem->ValueStr() == "PixelPerfect")
{
m_PixelPerfect = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Disabled")
{
m_Disabled = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Visible")
{
m_Visible = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Text")
{
m_Text = XmlUtil::TextToString(elem);
}
// load children
else if (elem->ValueStr() == "Children")
{
for (TiXmlElement* childNode = elem->FirstChildElement(); childNode != NULL; childNode = childNode->NextSiblingElement())
{
UiObjectOld* child = UiObjectFactory::GetInstance()->CreateInstance(m_ParentStage, childNode->ValueStr());
if (!child) continue;
child->Create();
child->LoadFromXml(childNode);
AddChild(child);
}
}
}
UpdateChildrenZOrder();
return true;
}
//////////////////////////////////////////////////////////////////////////
bool UiObjectOld::SaveToXml(TiXmlElement* rootNode)
{
ScriptableObject::SaveToXml(rootNode);
TiXmlElement* elem;
elem = XmlUtil::AddElem("Position", rootNode);
XmlUtil::SetAttr(elem, "X", m_PosX);
XmlUtil::SetAttr(elem, "Y", m_PosY);
elem = XmlUtil::AddElem("Size", rootNode);
XmlUtil::SetAttr(elem, "Width", m_Width);
XmlUtil::SetAttr(elem, "Height", m_Height);
elem = XmlUtil::AddElem("PixelPerfect", rootNode);
XmlUtil::SetText(elem, m_PixelPerfect);
elem = XmlUtil::AddElem("Disabled", rootNode);
XmlUtil::SetText(elem, m_Disabled);
elem = XmlUtil::AddElem("Visible", rootNode);
XmlUtil::SetText(elem, m_Visible);
elem = XmlUtil::AddElem("Text", rootNode);
XmlUtil::SetText(elem, m_Text, true);
// save children
elem = XmlUtil::AddElem("Children", rootNode);
foreach (UiObjectOld* child, m_Children)
{
TiXmlElement* childNode = XmlUtil::AddElem(child->GetDocRootName(), elem);
child->SaveToXml(childNode);
}
return true;
}
} // namespace Wme
| 25.468085
| 125
| 0.536062
|
retrowork
|
af6e84b677151341d0b68349539afe102963feb1
| 413
|
cpp
|
C++
|
cpp/ql/src/jsf/4.17 Types/AV Rule 147.cpp
|
vadi2/codeql
|
a806a4f08696d241ab295a286999251b56a6860c
|
[
"MIT"
] | 4,036
|
2020-04-29T00:09:57.000Z
|
2022-03-31T14:16:38.000Z
|
cpp/ql/src/jsf/4.17 Types/AV Rule 147.cpp
|
vadi2/codeql
|
a806a4f08696d241ab295a286999251b56a6860c
|
[
"MIT"
] | 2,970
|
2020-04-28T17:24:18.000Z
|
2022-03-31T22:40:46.000Z
|
cpp/ql/src/jsf/4.17 Types/AV Rule 147.cpp
|
ScriptBox99/github-codeql
|
2ecf0d3264db8fb4904b2056964da469372a235c
|
[
"MIT"
] | 794
|
2020-04-29T00:28:25.000Z
|
2022-03-30T08:21:46.000Z
|
// Wrong: floating point bit implementation exposed by union with bit field.
// Endianness and different floating-point implementations across architectures
// as well as different packing methods across compilers could make this behave
// incorrectly.
typedef union {
float float_num;
struct {
unsigned sign : 1;
unsigned exp : 8;
unsigned fraction : 23;
} bits;
} floatbits;
| 31.769231
| 79
| 0.711864
|
vadi2
|
af73ccd755f8939eaefe068d90b89b9d27790bde
| 5,783
|
cpp
|
C++
|
XFree86-3.3/xc/lib/pex5/PEX5-def.cpp
|
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
|
1b0172cdb78757fd17898503aaf6ce03d940ef28
|
[
"Apache-1.1"
] | 46
|
2015-12-04T17:12:58.000Z
|
2022-03-11T04:30:49.000Z
|
XFree86-3.3/xc/lib/pex5/PEX5-def.cpp
|
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
|
1b0172cdb78757fd17898503aaf6ce03d940ef28
|
[
"Apache-1.1"
] | null | null | null |
XFree86-3.3/xc/lib/pex5/PEX5-def.cpp
|
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
|
1b0172cdb78757fd17898503aaf6ce03d940ef28
|
[
"Apache-1.1"
] | 23
|
2016-10-24T09:18:14.000Z
|
2022-02-25T02:11:35.000Z
|
LIBRARY PEX5
VERSION LIBRARY_VERSION
EXPORTS
PEXAccumulateState
PEXAddToNameSet
PEXAnnotationText
PEXAnnotationText2D
PEXApplicationData
PEXBeginPickAll
PEXBeginPickOne
PEXBeginRendering
PEXBeginStructure
PEXBuildTransform
PEXBuildTransform2D
PEXCellArray
PEXCellArray2D
PEXChangeNameSet
PEXChangePickDevice
PEXChangePipelineContext
PEXChangeRenderer
PEXChangeSearchContext
PEXChangeStructureRefs
PEXCopyBytesToOC
PEXCopyElements
PEXCopyLookupTable
PEXCopyNameSet
PEXCopyPipelineContext
PEXCopySearchContext
PEXCopyStructure
PEXCountOCs
PEXCreateLookupTable
PEXCreateNameSet
PEXCreatePickMeasure
PEXCreatePipelineContext
PEXCreateRenderer
PEXCreateSearchContext
PEXCreateStructure
PEXCreateWorkstation
PEXDecodeOCs
PEXDeleteBetweenLabels
PEXDeleteElements
PEXDeleteTableEntries
PEXDeleteToLabel
PEXDestroyStructures
PEXElementSearch
PEXEncodeOCs
PEXEncodedAnnoText
PEXEncodedAnnoText2D
PEXEncodedText
PEXEncodedText2D
PEXEndPickAll
PEXEndPickOne
PEXEndRendering
PEXEndStructure
PEXEscape
PEXEscapeWithReply
PEXExecuteDeferredActions
PEXExecuteStructure
PEXExtendedCellArray
PEXFetchElements
PEXFetchElementsAndSend
PEXFillArea
PEXFillArea2D
PEXFillAreaSet
PEXFillAreaSet2D
PEXFillAreaSetWithData
PEXFillAreaWithData
PEXFinishOCs
PEXFreeEnumInfo
PEXFreeFontInfo
PEXFreeFontNames
PEXFreeLookupTable
PEXFreeNameSet
PEXFreeOCData
PEXFreePCAttributes
PEXFreePDAttributes
PEXFreePMAttributes
PEXFreePickMeasure
PEXFreePickPaths
PEXFreePipelineContext
PEXFreeRenderer
PEXFreeRendererAttributes
PEXFreeSCAttributes
PEXFreeSearchContext
PEXFreeStructurePaths
PEXFreeTableEntries
PEXFreeWorkstation
PEXFreeWorkstationAttributes
PEXGDP
PEXGDP2D
PEXGSE
PEXGeoNormFillArea
PEXGeoNormFillAreaSet
PEXGeoNormQuadrilateralMesh
PEXGeoNormSetOfFillAreaSets
PEXGeoNormTriangleStrip
PEXGetAncestors
PEXGetDefinedIndices
PEXGetDescendants
PEXGetElementInfo
PEXGetEnumTypeInfo
PEXGetExtensionInfo
PEXGetImpDepConstants
PEXGetNameSet
PEXGetOCAddr
PEXGetPickDevice
PEXGetPickMeasure
PEXGetPipelineContext
PEXGetPredefinedEntries
PEXGetProtocolFloatFormat
PEXGetRendererAttributes
PEXGetRendererDynamics
PEXGetSearchContext
PEXGetSizeOCs
PEXGetStructureInfo
PEXGetStructuresInNetwork
PEXGetTableEntries
PEXGetTableEntry
PEXGetTableInfo
PEXGetWorkstationAttributes
PEXGetWorkstationDynamics
PEXGetWorkstationPostings
PEXGetWorkstationViewRep
PEXIdentityMatrix
PEXIdentityMatrix2D
PEXInitialize
PEXInvertMatrix
PEXInvertMatrix2D
PEXLabel
PEXListFonts
PEXListFontsWithInfo
PEXLoadFont
PEXLookAtViewMatrix
PEXMapDCToWC
PEXMapWCToDC
PEXMapXCToNPC
PEXMapXCToNPC2D
PEXMarkers
PEXMarkers2D
PEXMatchRenderingTargets
PEXMatrixMult
PEXMatrixMult2D
PEXNPCToXCTransform
PEXNPCToXCTransform2D
PEXNURBCurve
PEXNURBSurface
PEXNoop
PEXNormalizeVectors
PEXNormalizeVectors2D
PEXOrthoProjMatrix
PEXPerspProjMatrix
PEXPickAll
PEXPickOne
PEXPolarViewMatrix
PEXPolyline
PEXPolyline2D
PEXPolylineSetWithData
PEXPostStructure
PEXQuadrilateralMesh
PEXQueryEncodedTextExtents
PEXQueryFont
PEXQueryTextExtents
PEXRedrawAllStructures
PEXRedrawClipRegion
PEXRemoveFromNameSet
PEXRenderElements
PEXRenderNetwork
PEXRestoreModelClipVolume
PEXRotate
PEXRotate2D
PEXRotateGeneral
PEXScale
PEXScale2D
PEXSearchNetwork
PEXSendOCs
PEXSetATextAlignment
PEXSetATextHeight
PEXSetATextPath
PEXSetATextStyle
PEXSetATextUpVector
PEXSetBFInteriorStyle
PEXSetBFInteriorStyleIndex
PEXSetBFReflectionAttributes
PEXSetBFReflectionModel
PEXSetBFSurfaceColor
PEXSetBFSurfaceColorIndex
PEXSetBFSurfaceInterpMethod
PEXSetCharExpansion
PEXSetCharHeight
PEXSetCharSpacing
PEXSetCharUpVector
PEXSetColorApproxIndex
PEXSetCurveApprox
PEXSetDepthCueIndex
PEXSetEchoColor
PEXSetEdgeBundleIndex
PEXSetEditingMode
PEXSetElementPtr
PEXSetElementPtrAtLabel
PEXSetFacetCullingMode
PEXSetFacetDistinguishFlag
PEXSetGlobalTransform
PEXSetGlobalTransform2D
PEXSetHLHSRID
PEXSetIndividualASF
PEXSetInteriorBundleIndex
PEXSetInteriorStyle
PEXSetInteriorStyleIndex
PEXSetLightSourceState
PEXSetLineBundleIndex
PEXSetLineColor
PEXSetLineColorIndex
PEXSetLineType
PEXSetLineWidth
PEXSetLocalTransform
PEXSetLocalTransform2D
PEXSetMarkerBundleIndex
PEXSetMarkerColor
PEXSetMarkerColorIndex
PEXSetMarkerScale
PEXSetMarkerType
PEXSetModelClipFlag
PEXSetModelClipVolume
PEXSetModelClipVolume2D
PEXSetOfFillAreaSets
PEXSetParaSurfCharacteristics
PEXSetPatternAttributes
PEXSetPatternAttributes2D
PEXSetPatternSize
PEXSetPickID
PEXSetPolylineInterpMethod
PEXSetReflectionAttributes
PEXSetReflectionModel
PEXSetRenderingColorModel
PEXSetSurfaceApprox
PEXSetSurfaceColor
PEXSetSurfaceColorIndex
PEXSetSurfaceEdgeColor
PEXSetSurfaceEdgeColorIndex
PEXSetSurfaceEdgeFlag
PEXSetSurfaceEdgeType
PEXSetSurfaceEdgeWidth
PEXSetSurfaceInterpMethod
PEXSetTableEntries
PEXSetTextAlignment
PEXSetTextBundleIndex
PEXSetTextColor
PEXSetTextColorIndex
PEXSetTextFontIndex
PEXSetTextPath
PEXSetTextPrecision
PEXSetViewIndex
PEXSetWorkstationBufferMode
PEXSetWorkstationDisplayUpdateMode
PEXSetWorkstationHLHSRMode
PEXSetWorkstationViewPriority
PEXSetWorkstationViewRep
PEXSetWorkstationViewport
PEXSetWorkstationWindow
PEXStartOCs
PEXText
PEXText2D
PEXTransformPoints
PEXTransformPoints2D
PEXTransformPoints2DH
PEXTransformPoints4D
PEXTransformVectors
PEXTransformVectors2D
PEXTranslate
PEXTranslate2D
PEXTriangleStrip
PEXUnloadFont
PEXUnpostAllStructures
PEXUnpostStructure
PEXUpdatePickMeasure
PEXUpdateWorkstation
PEXViewMappingMatrix
PEXViewMappingMatrix2D
PEXViewOrientationMatrix
PEXViewOrientationMatrix2D
PEXXCToNPCTransform
PEXXCToNPCTransform2D
/* $XConsortium: PEX5-def.cpp /main/2 1996/05/07 13:15:18 kaleb $ */
| 20.362676
| 68
| 0.898496
|
tharindusathis
|
af774e896c3c26f1dd8eac933d891f0007b6d59f
| 3,048
|
cpp
|
C++
|
source/buffer.cpp
|
gnader/glutils
|
d80ec61eecfc1ea2555efd5f52317a54a86289cd
|
[
"MIT"
] | null | null | null |
source/buffer.cpp
|
gnader/glutils
|
d80ec61eecfc1ea2555efd5f52317a54a86289cd
|
[
"MIT"
] | null | null | null |
source/buffer.cpp
|
gnader/glutils
|
d80ec61eecfc1ea2555efd5f52317a54a86289cd
|
[
"MIT"
] | null | null | null |
/**
* This file is part of gltoolbox
*
* MIT License
*
* Copyright (c) 2021 Georges Nader
*
* 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 <gltoolbox/buffer.h>
using namespace gltoolbox;
Buffer::Buffer(GLenum target, GLsizei elementsize, GLenum usage)
: mId(0), mOwned(false), mUsage(usage), mTarget(target), mElementSize(elementsize)
{
create();
}
Buffer::Buffer(Buffer &&temp)
{
//delete whatever was there
destroy();
//move buffer ownership
mId = temp.mId;
mOwned = temp.mOwned;
mUsage = temp.mUsage;
mTarget = temp.mTarget;
mElementSize = temp.mElementSize;
temp.mId = 0;
temp.mOwned = false;
}
Buffer::~Buffer()
{
destroy();
}
Buffer &Buffer::operator=(Buffer &other)
{
//delete whatever was there
destroy();
//move buffer ownership
mId = other.mId;
mOwned = other.mOwned;
mUsage = other.mUsage;
mTarget = other.mTarget;
mElementSize = other.mElementSize;
other.mId = 0;
other.mOwned = false;
return *this;
}
void Buffer::upload(void *ptr, GLsizei count) const
{
bind();
glBufferData(target(), count * element_size(), ptr, usage());
}
void Buffer::upload(void *ptr, GLsizei offset, GLsizei count) const
{
bind();
glBufferSubData(target(), offset * element_size(), count * element_size(), ptr);
}
void Buffer::download(void *ptr, GLsizei size) const
{
bind();
glGetBufferSubData(target(), 0, size, ptr);
}
void Buffer::download(void *ptr, GLsizei offset, GLsizei size) const
{
bind();
glGetBufferSubData(target(), offset, size, ptr);
}
void Buffer::create()
{
if (!mOwned || !is_valid())
{
glCreateBuffers(1, &mId);
bind(); // this will actually trigger the buffer creation
mOwned = true;
}
}
void Buffer::destroy()
{
if (mOwned && is_valid())
{
glDeleteBuffers(1, &mId);
mId = 0;
mOwned = false;
}
}
GLint Buffer::get_parameter(const GLenum param) const
{
GLint result;
bind();
glGetBufferParameteriv(target(), param, &result);
return result;
}
| 23.8125
| 86
| 0.69521
|
gnader
|
af7b6ea6d128439d18c9fff9b840644ddb98f9d1
| 2,779
|
cpp
|
C++
|
10.1.1.cpp
|
luckylove/extra
|
8d27ec0e62bdc2ab6a261d197b455fea07120a55
|
[
"CC-BY-4.0",
"MIT"
] | null | null | null |
10.1.1.cpp
|
luckylove/extra
|
8d27ec0e62bdc2ab6a261d197b455fea07120a55
|
[
"CC-BY-4.0",
"MIT"
] | null | null | null |
10.1.1.cpp
|
luckylove/extra
|
8d27ec0e62bdc2ab6a261d197b455fea07120a55
|
[
"CC-BY-4.0",
"MIT"
] | null | null | null |
// program to quick short the linked list
// first of all create the linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node **head,int data1)
{
struct node* newnode=NULL;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data1;
newnode->next=*head;
*head=newnode;
}
void printlinkedlist(struct node* head)
{
while(head!=NULL)
{
printf("%d",head->data);
head=head->next;
}
}
struct node* gettail(struct node* head)
{
struct node* current =head;
while(current!=NULL&¤t->next!=NULL)
{
current=current->next;
}
return current;
}
struct node* partitionof(struct node*head1,struct node*end1,struct node**newhead,struct node**newend)
{
struct node*previous=NULL;
struct node*pivot=end1;
struct node*current = head1;
struct node*tail=pivot;
while(current!=pivot)
{
printf("ss");
if(current->data < pivot->data)
{
if((*newhead)==NULL)
{
(*newhead)=current;
}
previous=current;
current=current->next;
}
else
{
if(previous!=NULL)
{
previous->next=current->next;
}
struct node* temp=current->next;
current->next=NULL;
tail->next=current;
// tail=tail->next;
tail=current;
current=temp;
}
if((*newhead)==NULL)
{
(*newhead)=pivot;
}
(*newend)=tail;
printlinkedlist(pivot);
printf("\n");
return pivot;
}
}
struct node*quicksortrecursive(struct node*head,struct node*end1)
{
if(head==NULL||head==end1)
{
return head;
}
struct node*newend=NULL;
struct node*newhead=NULL;
struct node*pivot=partitionof(head,end1,&newhead,&newend);
if(newhead!=pivot)
{
struct node*temp=newhead;
while(temp->next!=pivot)
{
temp=temp->next;
}
temp->next=NULL;
newhead=quicksortrecursive(newhead,temp);
temp=gettail(newhead);
temp->next=pivot;
}
pivot->next=quicksortrecursive(pivot->next,newend);
return newhead;
}
void quicksort(struct node**head)
{
(*head)=quicksortrecursive((*head),gettail(*head));
return;
}
int main()
{
struct node*head=NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
printlinkedlist(head);
printf("\n");
// struct node* nodee=head->next->next->next;
// struct node* one=NULL;
// struct node* two=NULL;
quicksort(&head);
// printf("SS");
printlinkedlist(head);
printf("\n");
}
| 21.21374
| 101
| 0.558834
|
luckylove
|
af7d7ff58aa66834699fd90068f50fdaa921635a
| 4,318
|
cpp
|
C++
|
Engine/Source/Runtime/Engine/Private/SpotLight.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | 1
|
2022-01-29T18:36:12.000Z
|
2022-01-29T18:36:12.000Z
|
Engine/Source/Runtime/Engine/Private/SpotLight.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
Engine/Source/Runtime/Engine/Private/SpotLight.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Engine/SpotLight.h"
#include "Components/ArrowComponent.h"
#include "Components/SpotLightComponent.h"
ASpotLight::ASpotLight(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer.SetDefaultSubobjectClass<USpotLightComponent>(TEXT("LightComponent0")))
{
// Structure to hold one-time initialization
struct FConstructorStatics
{
FName ID_Lighting;
FText NAME_Lighting;
FConstructorStatics()
: ID_Lighting(TEXT("Lighting"))
, NAME_Lighting(NSLOCTEXT( "SpriteCategory", "Lighting", "Lighting" ))
{
}
};
static FConstructorStatics ConstructorStatics;
SpotLightComponent = CastChecked<USpotLightComponent>(GetLightComponent());
SpotLightComponent->Mobility = EComponentMobility::Stationary;
SpotLightComponent->RelativeRotation = FRotator(-90, 0, 0);
RootComponent = SpotLightComponent;
#if WITH_EDITORONLY_DATA
ArrowComponent = CreateEditorOnlyDefaultSubobject<UArrowComponent>(TEXT("ArrowComponent0"));
if (ArrowComponent)
{
ArrowComponent->ArrowColor = GetLightColor().ToFColor(true);
ArrowComponent->bTreatAsASprite = true;
ArrowComponent->SpriteInfo.Category = ConstructorStatics.ID_Lighting;
ArrowComponent->SpriteInfo.DisplayName = ConstructorStatics.NAME_Lighting;
ArrowComponent->SetupAttachment(SpotLightComponent);
ArrowComponent->bLightAttachment = true;
ArrowComponent->bIsScreenSizeScaled = true;
}
#endif // WITH_EDITORONLY_DATA
}
void ASpotLight::PostLoad()
{
Super::PostLoad();
if (GetLightComponent()->Mobility == EComponentMobility::Static)
{
GetLightComponent()->LightFunctionMaterial = NULL;
}
#if WITH_EDITORONLY_DATA
if(ArrowComponent)
{
ArrowComponent->ArrowColor = GetLightColor().ToFColor(true);
}
#endif
}
#if WITH_EDITOR
void ASpotLight::LoadedFromAnotherClass(const FName& OldClassName)
{
Super::LoadedFromAnotherClass(OldClassName);
if(GetLinkerUE4Version() < VER_UE4_REMOVE_LIGHT_MOBILITY_CLASSES)
{
static FName SpotLightStatic_NAME(TEXT("SpotLightStatic"));
static FName SpotLightMovable_NAME(TEXT("SpotLightMovable"));
static FName SpotLightStationary_NAME(TEXT("SpotLightStationary"));
check(GetLightComponent() != NULL);
if(OldClassName == SpotLightStatic_NAME)
{
GetLightComponent()->Mobility = EComponentMobility::Static;
}
else if(OldClassName == SpotLightMovable_NAME)
{
GetLightComponent()->Mobility = EComponentMobility::Movable;
}
else if(OldClassName == SpotLightStationary_NAME)
{
GetLightComponent()->Mobility = EComponentMobility::Stationary;
}
}
}
#endif // WITH_EDITOR
void ASpotLight::SetInnerConeAngle(float NewInnerConeAngle)
{
SpotLightComponent->SetInnerConeAngle(NewInnerConeAngle);
}
void ASpotLight::SetOuterConeAngle(float NewOuterConeAngle)
{
SpotLightComponent->SetOuterConeAngle(NewOuterConeAngle);
}
// Disable for now
//void ASpotLight::SetLightShaftConeAngle(float NewLightShaftConeAngle)
//{
// SpotLightComponent->SetLightShaftConeAngle(NewLightShaftConeAngle);
//}
#if WITH_EDITOR
void ASpotLight::EditorApplyScale(const FVector& DeltaScale, const FVector* PivotLocation, bool bAltDown, bool bShiftDown, bool bCtrlDown)
{
const FVector ModifiedScale = DeltaScale * ( AActor::bUsePercentageBasedScaling ? 10000.0f : 100.0f );
if ( bCtrlDown )
{
FMath::ApplyScaleToFloat( SpotLightComponent->OuterConeAngle, ModifiedScale, 0.01f );
SpotLightComponent->OuterConeAngle = FMath::Min( 89.0f, SpotLightComponent->OuterConeAngle );
SpotLightComponent->InnerConeAngle = FMath::Min( SpotLightComponent->OuterConeAngle, SpotLightComponent->InnerConeAngle );
}
else if ( bAltDown )
{
FMath::ApplyScaleToFloat( SpotLightComponent->InnerConeAngle, ModifiedScale, 0.01f );
SpotLightComponent->InnerConeAngle = FMath::Min( 89.0f, SpotLightComponent->InnerConeAngle );
SpotLightComponent->OuterConeAngle = FMath::Max( SpotLightComponent->OuterConeAngle, SpotLightComponent->InnerConeAngle );
}
else
{
FMath::ApplyScaleToFloat( SpotLightComponent->AttenuationRadius, ModifiedScale );
}
PostEditChange();
}
void ASpotLight::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if(ArrowComponent)
{
ArrowComponent->ArrowColor = GetLightColor().ToFColor(true);
}
}
#endif
| 30.408451
| 138
| 0.787633
|
windystrife
|
502d2f4ef3dfaf8e96f415818e968aa727d067f8
| 26,232
|
cpp
|
C++
|
vuecepc/client/VueceNativeClientImplWin.cpp
|
vuece/vuece-hub-win
|
9d09ca44ec44b48e4ef422872f27572d06a1b140
|
[
"MIT"
] | null | null | null |
vuecepc/client/VueceNativeClientImplWin.cpp
|
vuece/vuece-hub-win
|
9d09ca44ec44b48e4ef422872f27572d06a1b140
|
[
"MIT"
] | null | null | null |
vuecepc/client/VueceNativeClientImplWin.cpp
|
vuece/vuece-hub-win
|
9d09ca44ec44b48e4ef422872f27572d06a1b140
|
[
"MIT"
] | null | null | null |
#include "VueceNativeClientImplWin.h"
#include <cstdio>
#include <iostream>
#include <time.h>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "talk/xmpp/constants.h"
#include "talk/base/logging.h"
#include "talk/base/flags.h"
#include "talk/base/pathutils.h"
#include "talk/base/stream.h"
#include "talk/base/thread.h"
#include "talk/base/helpers.h"
#include "talk/base/base64.h"
#include "talk/base/stringdigest.h"
#include "talk/session/fileshare/VueceMediaStream.h"
#include "VueceCoreClient.h"
#include "VueceConstants.h"
#include "VueceGlobalSetting.h"
#include "VueceMediaDBManager.h"
#include "VueceMediaItem.h"
#include "VueceLogger.h"
#include "libjson.h"
#include "json/json.h"
#include "tinyxml2.h"
#include "DebugLog.h"
using namespace tinyxml2;
using namespace vuece;
static const int DEFAULT_PORT = 5222;
VueceNativeClientImplWin::VueceNativeClientImplWin(vuece::InitData* init_data) {
LOG(INFO) << "VueceNativeClientImplWin()";
client = NULL;
exitReason = VueceEvent_Client_SignedOut;
}
VueceNativeClientImplWin::~VueceNativeClientImplWin() {
LOG(INFO) << "VueceNativeClientImplWin - De-constructor called, exit reason: " << exitReason;
//NOTE: DONT TRY TO DELETE ANY THING HERE!!!!
}
RosterMap* VueceNativeClientImplWin::GetRosterMap() {
if (client == NULL) {
return NULL;
}
return client->GetRosterMap();
}
void VueceNativeClientImplWin::AddBuddy(const std::string& jid) {
if (client == NULL) {
return;
}
client->InviteFriend(jid);
}
int VueceNativeClientImplWin::InitiateMediaStream(
const std::string& share_id,
const std::string& jid,
const std::string& targetUri,
const std::string& width,
const std::string& height,
const std::string& preview_file_path,
const std::string& start_pos,
const std::string& need_preview,
VueceStreamType stream_type,
VueceMediaItem* mediaItem
)
{
int errCode = VueceStreamSessionInitErrType_None;
LOG(INFO) << "---------------------------------------------------------------------------------------------------------------";
LOG(INFO)
<< "VueceNativeClientImplWin::InitiateMediaStream: VueceShareId=" << share_id << ", Jid=" << jid << ", TargetUri=" << targetUri;
LOG(INFO) << "---------------------------------------------------------------------------------------------------------------";
//here we use ascii code FS to separate param1 and param2 and param3 in one string
switch(stream_type)
{
case VueceStreamType_File:
{
errCode = client->SendFile(share_id, jid, targetUri, width, height, preview_file_path, start_pos, need_preview);
break;
}
case VueceStreamType_Music:
{
errCode = client->InitiateMusicStreamDB(share_id, jid, targetUri, width, height, preview_file_path, start_pos, need_preview, mediaItem);
break;
}
default:
{
break;
}
}
return errCode;
}
void VueceNativeClientImplWin::CancelFileShare(const std::string& share_id){
LOG(INFO) << "VueceNativeClientImplWin::CancelFileShare: " << share_id;
SigVueuceCommandMessage(VUECE_CMD_CANCEL_FILE, share_id.c_str());
}
void VueceNativeClientImplWin::AcceptFileShare(const std::string& share_id,const std::string& target_folder, const std::string& target_file_name){
//dummy value for PC impl
std::string sample_rate("0");
LOG(INFO) << "VueceNativeClientImplWin::AcceptFileShare: " << share_id << "; sample rate: " << sample_rate;
int i;
char buf[128];
//here we use ascii code FS to separate param1 and param2 and param3 in one string
memset(buf, '\0', sizeof(buf));
strcpy(buf, share_id.c_str());
i = strlen(buf);
buf[i] = 0x1C;
strcat(buf, sample_rate.c_str());
i = strlen(buf);
buf[i] = 0x1C;
strcat(buf, target_folder.c_str());
i = strlen(buf);
buf[i] = 0x1C;
strcat(buf, target_file_name.c_str());
SigVueuceCommandMessage(VUECE_CMD_ACCEPT_FILE, buf);
}
void VueceNativeClientImplWin::DeclineFileShare(const std::string& share_id){
LOG(INFO) << "VueceNativeClientImplWin::DeclineFileShare: " << share_id;
SigVueuceCommandMessage(VUECE_CMD_DECLINE_FILE, share_id.c_str());
}
void VueceNativeClientImplWin::SendSubscriptionMessage(const std::string& jid, int type) {
if (client == NULL) {
return;
}
client->SendSubscriptionMessage(jid, type);
}
void VueceNativeClientImplWin::SendPresence(const std::string& status)
{
if (client == NULL) {
return;
}
client->SendPresence(status);
}
void VueceNativeClientImplWin::SendPresence(const std::string& status, const std::string& signature) {
if (client == NULL) {
return;
}
client->SendPresence(status, signature);
}
void VueceNativeClientImplWin::SendSignature(const std::string& sig) {
if (client == NULL) {
return;
}
client->SendSignature(sig);
}
vuece::ClientState VueceNativeClientImplWin::GetClientState(void)
{
return client->GetClientState();
}
int VueceNativeClientImplWin::Start(const char* name, const char* pwd, const int auth_type) {
bool debug = true;
bool bIsLoginFailed = false;
std::string protocol = "hybrid";
std::string secure = "disable";
LOG(INFO) << "VueceNativeClientImplWin::SignIn - Start";
if(client != NULL)
{
VueceLogger::Fatal("VueceNativeClientImplWin::Start - VueceCoreClient instance should be null, abort now!");
return RESULT_FUNC_NOT_ALLOWED;
}
client = new VueceCoreClient(this, name);
SigVueuceCommandMessage.connect(client, &VueceCoreClient::OnVueceCommandReceived);
client->SignalVueceEvent.connect(this, &VueceNativeClientImplWin::OnVueceEvent);
//a blocking call
client->Start(name, pwd, auth_type);
delete client;
client = NULL;
LOG(INFO) << "====================================================";
LOG(INFO) << "VueceNativeClientImplWin::Start:Call client finalized!!!!!";
LOG(INFO) << "====================================================";
if(bIsLoginFailed)
{
return RESULT_UNAUTHORIZED;
}
return RESULT_OK;
}
//Note - Make sure this method call is the ONLY entry point of logging out precedure.
int VueceNativeClientImplWin::LogOut()
{
LOG(INFO) << "VueceNativeClientImplWin::LogOut";
return client->LogOut();
}
void VueceNativeClientImplWin::OnClientStateChanged(vuece::ClientEvent event, vuece::ClientState state)
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - event = " << event << ", state = " << state ;
VueceNativeInterface::LogClientEvent(event);
VueceNativeInterface::LogClientState(state);
switch(event)
{
case CLIENT_EVENT_LOGGING_IN:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_IN";
break;
}
case CLIENT_EVENT_LOGIN_OK:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_OK";
SigUserEvent(VueceEvent_Client_SignedIn);
break;
}
case CLIENT_EVENT_AUTH_ERR:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - AUTH_ERR";
exitReason = VueceEvent_Client_AuthFailed;
SigUserEvent(VueceEvent_Client_AuthFailed);
break;
}
case CLIENT_EVENT_NETWORK_ERR:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - NETWORK_ERR";
exitReason = VueceEvent_Connection_Failed;
//Note - This call will eventually make the UI layer trigger a call to LogOut on VueceCoreClient instance
SigUserEvent(VueceEvent_Connection_Failed);
break;
}
case CLIENT_EVENT_LOGGING_OUT:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_OUT";
break;
}
case CLIENT_EVENT_LOGOUT_OK:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_OK";
SigUserEvent(VueceEvent_Client_SignedOut);
break;
}
}
}
void VueceNativeClientImplWin::OnVueceEvent(int code, const char* jid, const char* other)
{
std::string jid_s (jid);
LOG(INFO) << "VueceNativeClientImplWin::OnVueceEvent, code = " << code << ", jid = " << jid << ", other value = " << other;
switch(code)
{
//TODO - Use a separate signal to handle this event, don't mix it with FSM
case VueceEvent_FileAccess_Denied:
{
std::ostringstream os;
os << "{'action':'play', 'reply':'error','category':'music','control':'start','reason':'Access denied.', 'uri':'";
os << other;
os << "'}";
LOG(INFO) << "VueceNativeClientImplWin::OnVueceEvent - VueceEvent_FileAccess_Denied";
client->SendVHubMessage(jid_s, "result", os.str());
break;
}
default:
{
VueceLogger::Fatal("VueceNativeClientImplWin::OnVueceEvent - Unexpected event notification, code: %d, abort now.", code);
break;
}
}
}
int VueceNativeClientImplWin::SendVHubMessage(const std::string& to, const std::string& type,const std::string& message)
{
return RESULT_GENERAL_ERR;
}
void VueceNativeClientImplWin::OnRosterStatusUpdate(const buzz::Status& status) {
// LOG(INFO) << "VueceNativeClientImplWin: OnRosterStatusUpdate";
// LOG(INFO) << "VueceNativeClientImplWin:OnRosterStatusUpdate:Jid:[" << status.jid().Str().c_str() << "]";
// LOG(INFO) << "VueceNativeClientImplWin:OnRosterStatusUpdate:Status:[" << status.status().c_str() << "]";
//
//#ifdef VCARD_ENABLED
// SendVCardRequest(status.jid().Str());
//#endif
}
#ifdef CHAT_ENABLED
void VueceNativeClientImplWin::SendChat(const std::string& to, const std::string& msg) {
if (client == NULL) {
return;
}
client->SendChat(to, msg);
}
void VueceNativeClientImplWin::OnChatMessageReceived(const buzz::Jid& from, const std::string& msg) {
LOG(LS_VERBOSE) << "OnChatMessageReceived:Received a msg from: " << from.node();
LOG(LS_VERBOSE) << "OnChatMessageReceived:Message content:\n-------------------\n" <<
msg << "\n-------------------\n";
}
#endif
#ifdef VCARD_ENABLED
void VueceNativeClientImplWin::OnRosterVCardReceived(const std::string& jid, const std::string& fn, const std::string& img_data)
{
LOG(LS_VERBOSE) << "OnRosterVCardReceived:Received a vcard query result for: " << jid;
LOG(LS_VERBOSE) << "OnRosterVCardReceived:Full name:" << fn;
SigRosterVCardReceived(jid, fn, img_data);
}
void VueceNativeClientImplWin::SendVCardRequest(const std::string& to) {
if (client == NULL) {
return;
}
client->SendVCardRequest(to);
}
#endif
void VueceNativeClientImplWin::ShareMusicDBFile(const buzz::Jid& jid)
{
std::string db_path = VueceMediaDBManager::GetFullDBFilePath();
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:ShareMusicDBFile - Full db file path: " << db_path;
InitiateMediaStream(
talk_base::ToString(talk_base::CreateRandomId()), //session id
jid.Str(), //jid
db_path.c_str() , //file path
"0", //image width
"0", //image height
"", //preview image path
"0", //start position in seconds
"0",
VueceStreamType_File,
NULL
);
}
void VueceNativeClientImplWin::OnVHubGetMessageReceived(const buzz::Jid& jid, const std::string& message)
{
LOG(LS_INFO)
<< "VueceNativeClientImplWin::VHub Msg Received - jid: " << jid.Str().c_str() << ", message: " << message;
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
std::string msg(message);
std::replace( msg.begin(), msg.end(), '\'', '"');
bool parsingSuccessful = reader.parse( msg.c_str(), root );
VueceGlobalSetting* iVueceGlobalSetting = VueceGlobalContext::Instance();
const char* accountUserName = VueceGlobalContext::GetAccountUserName();
char remote_bare_jid[128+1];
bool access_allowed = false;
bool config_allowFriendsAccess = (bool)VueceGlobalContext::GetAllowFriendAccess();
memset(remote_bare_jid, 0, sizeof(remote_bare_jid));
strcpy(remote_bare_jid, jid.BareJid().Str().c_str());
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
LOG(LS_ERROR) << "VueceNativeClientImplWin::VHub Msg Received - Failed to parse configuration\n"
<< reader.getFormattedErrorMessages();
return;
}
std::string action = root.get("action","").asString();
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::VHub Msg Received - action: " << action << ", checking access now...";
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Performing access control - Owner's hub jid: " << accountUserName << ", bare_remote_jid: " << remote_bare_jid;
if(strcmp(accountUserName, remote_bare_jid) != 0)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is not owner's device: " << remote_bare_jid;
if(!config_allowFriendsAccess)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is not owner's device and access is NOT allowed";
access_allowed = false;
}
else
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is not owner's device but access is allowed";
access_allowed = true;
}
}
else
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is running on owner's device";
access_allowed = true;
}
if(access_allowed)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Access is allowed";
}
else
{
char err_resp [128+1];
memset(err_resp, 0, sizeof(err_resp));
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Access is NOT allowed, sending error response";
sprintf(err_resp, "{'action':'%s', 'reply':'noaccess','reason':'You are not allowed to access this hub.'}", action.c_str());
client->SendVHubMessage(jid.Str().c_str(), "result", err_resp);
return;
}
if (action.compare("probe")==0)
{
//get all categories, etc. music, video, camera
std::string db_md5 = VueceMediaDBManager::RetrieveDBFileChecksum(false);
std::string message="{'action':'probe', 'reply':'ok','categories':['music'],'db-cache-chksum':'";
message.append(db_md5);
message.append("'}");
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
else if (action.compare("browse")==0)
{
// browse resources
std::string category = root.get("category","").asString();
std::string uri = root.get("uri","").asString();
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - category: " << category;
if (category.compare("music")==0)
{
std::ostringstream resp;
LOG(INFO) << "VueceNativeClientImplWin::VHub Msg Received - Start browsing target uri: " << uri;
client->BrowseMediaItem(uri, resp);
LOG(INFO) << "VueceNativeClientImplWin::VHub Msg Received - Shared media info string len: " << resp.str().length();
LOG(INFO) << "VueceNativeClientImplWin::VHub Msg Received - Shared media info string: " << resp.str();
client->SendVHubMessage(jid.Str().c_str(), "result", resp.str());
}
}
else if (action.compare("play")==0)
{
// control
std::string category = root.get("category","").asString();
std::string control = root.get("control","").asString();
std::string uri = root.get("uri","").asString();
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - category: " << category << ", control: " << control << ", uri: " << uri;
if (uri.compare("")==0)
{
std::string message="{'action':'play', 'reply':'error','category':'music','control':'"+control+"', 'reason':'URI cannot be empty'}";
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
else
{
if (category.compare("music")==0)
{
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - This message belongs to MUSIC category.";
if (control.compare("start")==0)
{
//TODO - Implement error handling here
//If we are currently streaming file and meanwhile we receive another play request from remote client
//this is unexpected because remote client is supposed to send a STOP before sending a new START, but
//we don't trust remote client so we need to protect ourselves from crashing, so in this case, we abort
//current streaming and return an ACCESS DENIED response to remove client, the we go back to idle state
std::string previewImagePath("");
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - Received a START request from remote client, preview image path is: " << previewImagePath ;
std::string start_position = root.get("start","0").asString();
std::string need_preview = root.get("need_preview","0").asString();
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - start_position: " << start_position << ";need preview?" << need_preview;
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - Enter media streaming mode.";
//query the actual file path according to the file URL
//if target item cannot be found, a vuece event VueceEvent_FileAccess_Denied
//will be fired and error response will be sent back
// std::string absFilePath = client->LocateMediaItemInDB(jid.Str().c_str(), uri);
VueceMediaItem* targetItem = client->LocateMediaItemInDB(jid.Str().c_str(), uri);
if(targetItem != NULL)
{
int errCode = VueceStreamSessionInitErrType_None;
if(targetItem->IsFolder())
{
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - This is folder, cannot be played, return an error. ";
errCode = VueceStreamSessionInitErrType_NotAFile;
}
else
{
std::string absFilePath = talk_base::Base64::Decode(targetItem->Path(), talk_base::Base64::DO_STRICT);
errCode = InitiateMediaStream(
talk_base::ToString(talk_base::CreateRandomId()), //session id
jid.Str().c_str(), //jid
absFilePath,//uri, //target uri
"128", //image width
"128", //image height
previewImagePath.c_str(), //preview image path
start_position, //start position in seconds
need_preview, //need preview or not,
VueceStreamType_Music,
targetItem
);
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - InitiateMediaStream() returned: " << errCode;
}
if(errCode != VueceStreamSessionInitErrType_OK)
{
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - Target cannot be found or played, return an error msg now.";
std::string message = "";
if(errCode == VueceStreamSessionInitErrType_NodeBusy)
{
message="{'action':'play', 'reply':'error','category':'music','control':'"+control+"', 'reason':'" + VHUB_MSG_BUSY_NOW +"'}";
}
else
{
message="{'action':'play', 'reply':'error','category':'music','control':'"+control+"', 'reason':'" + VHUB_MSG_STREAMING_TARGET_INVALID +"'}";
}
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
}
}
}
else
{
std::string message="{'action':'play', 'reply':'error','category':'unknown','control':'"+control+"', 'reason':'Invalid request'}";
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
}
}
else if (action.compare("sync-cache")==0)
{
client->SendVHubMessage(jid.Str().c_str(), "result", "{'action':'sync-cache', 'reply':'ok'}");
ShareMusicDBFile(jid);
}
}
void VueceNativeClientImplWin::OnVHubResultMessageReceived(const buzz::Jid& jid, const std::string& message)
{
LOG(LS_INFO)
<< "VueceNativeClientImplWin::OnVHubResultMessageReceived:jid: " << jid.Str().c_str() << ", message: " << message << " - Empty impl";
}
void VueceNativeClientImplWin::OnRosterSubRespReceived(VueceRosterSubscriptionMsg* m) {
LOG(LS_VERBOSE) << "OnRosterSubRespReceived";
SigRosterSubscriptionMsgReceived(m);
}
void VueceNativeClientImplWin::OnRosterReceived(const buzz::XmlElement* stanza) {
LOG(INFO) << "OnRosterReceived - Do nothing";
}
void VueceNativeClientImplWin::OnFileSharePreviewReceived(const std::string& share_id, const std::string& path, int w, int h)
{
LOG(LS_VERBOSE)
<< "VueceNativeClientImplWin:OnFileSharePreviewReceived:share_id: " << share_id << ", path: " << path << ", w: " << w << ", h: " << h<< ", do nothing";
}
void VueceNativeClientImplWin::OnFileShareProgressUpdated(const std::string& share_id, int percent)
{
LOG(LS_VERBOSE)
<< "VueceNativeClientImplWin:OnFileShareProgressUpdated:share_id: " << share_id << ", progress: " << percent << ", do nothing";
}
void VueceNativeClientImplWin::OnFileShareStateChanged(const std::string& remote_jid, const std::string& sid, int state)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareStateChanged:state: " << state << ", remote_jid: " << remote_jid << ", session id: " << sid;
if(state == (int)cricket::FS_RESOURCE_RELEASED)
{
std::ostringstream os;
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareStateChanged:state - FS_RESOURCE_RELEASED";
os << "{'action':'notification', 'category':'music', 'type':'streaming-resource-released', 'sid':'";
os << sid;
os << "'}";
client->RemoveStreamingNode(remote_jid);
client->SendVHubMessage(remote_jid, "get", os.str());
}
else
{
//do nothing for now if the notification state is not FS_RESOURCE_RELEASED
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareStateChanged:state - do nothing for now because the notification state is not FS_RESOURCE_RELEASED";
}
}
void VueceNativeClientImplWin::OnFileShareRequestReceived(const std::string& share_id, const buzz::Jid& target, int type, const std::string& fileName, int size, bool needPreview)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareRequestReceived:fileName: " << fileName;
}
void VueceNativeClientImplWin::OnFileSystemChanged()
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::OnFileSystemChanged";
}
void VueceNativeClientImplWin::OnRemoteDeviceActivity(VueceStreamingDevice* d)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::OnRemoteDeviceActivity - User id: " << d->user_id
<< ", Activity type: " << d->activity << ", File url: " << d->file_url;
SigRemoteDeviceActivity(d);
}
//music playing
void VueceNativeClientImplWin::OnStreamPlayerStateChanged(const std::string& share_id, int state)
{
LOG(LS_INFO) << "VueceNativeClientImplWin::OnStreamPlayerStateChanged:share_id: " << share_id << ", state: " << state<< ", do nothing";
}
void VueceNativeClientImplWin::StopStreamPlayer(const std::string& pos)
{
VueceLogger::Fatal("VueceNativeClientImplWin - StopStreamPlayer is not supported, abort!");
}
void VueceNativeClientImplWin::ResumeStreamPlayer(const std::string& pos)
{
VueceLogger::Fatal("VueceNativeClientImplWin - ResumeStreamPlayer is not supported, abort!");
}
vuece::NetworkPlayerState VueceNativeClientImplWin::GetNetworkPlayerState(void)
{
VueceLogger::Fatal("VueceNativeClientImplWin - GetNetworkPlayerState is not supported, abort!");
return vuece::NetworkPlayerState_Idle;
}
void VueceNativeClientImplWin::OnNetworkPlayerStateChanged(vuece::NetworkPlayerEvent e, vuece::NetworkPlayerState s)
{
VueceLogger::Fatal("VueceNativeClientImplWin - OnNetworkPlayerStateChanged is not supported, abort!");
}
bool VueceNativeClientImplWin::IsMusicStreaming(void)
{
VueceLogger::Fatal("VueceNativeClientImplWin - IsMusicStreaming is not supported, abort!");
return false;
}
int VueceNativeClientImplWin::GetCurrentPlayingProgress(void)
{
VueceLogger::Fatal("VueceNativeClientImplWin - GetCurrentPlayingProgress is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Play(const std::string &jid, const std::string &song_uuid)
{
VueceLogger::Fatal("VueceNativeClientImplWin - Play is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Pause()
{
VueceLogger::Fatal("VueceNativeClientImplWin - Pause is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Resume()
{
VueceLogger::Fatal("VueceNativeClientImplWin - Resume is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Seek(const int position)
{
VueceLogger::Fatal("VueceNativeClientImplWin - Seek is not supported, abort!");
return -1;
}
void VueceNativeClientImplWin::OnMusicStreamingProgressUpdated(const std::string& share_id, int progress)
{
VueceLogger::Fatal("VueceNativeClientImplWin - OnMusicStreamingProgressUpdated is not supported, abort!");
}
int VueceNativeClientImplWin::GetCurrentMusicStreamingProgress(const std::string& share_id)
{
VueceLogger::Fatal("VueceNativeClientImplWin - GetCurrentMusicStreamingProgress is not supported, abort!");
return -1;
}
cricket::CallOptions* VueceNativeClientImplWin::GetCurrentCallOption(void)
{
return NULL;
}
buzz::Jid VueceNativeClientImplWin::GetCurrentJidInCall(void)
{
buzz::Jid jid;
return jid;
}
//Test method
void VueceNativeClientImplWin::TestMusicStreaming()
{
//input not used for sender
int sample_rate = -1;
int bit_rate = -1;
int nchannels = -1;
int duration = -1;
bool fOpend = 0;
char readBuf[2048];
size_t read_len = 0;
int read_err;
talk_base::StreamResult sr =talk_base:: SR_ERROR;
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:TestMusicStreaming - Start";
talk_base::VueceMediaStream* file = new talk_base::VueceMediaStream("", sample_rate, bit_rate, nchannels, duration);
fOpend = (file->Open("D:\\STREAM_SAMPLES\\SHORT.mp3", "rb", 0));
if ( !fOpend )
{
LOG(LS_ERROR) << "VueceNativeClientImplWin:OnHttpRequest:Meida hub - File cannot be opened";
return;
}
while(true)
{
sr = file->Read(readBuf, 2048, &read_len, &read_err);
if(sr == talk_base::SR_ERROR || sr == talk_base::SR_EOS)
{
break;
}
}
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:TestMusicStreaming - Done";
}
int VueceNativeClientImplWin::SendVHubPlayRequest(const std::string& to, const std::string& type,const std::string& message, const std::string& uri)
{
return 0;
}
| 32.06846
| 179
| 0.679437
|
vuece
|
5038382f91b12e996e0a51390909ea21e6dce422
| 4,239
|
cpp
|
C++
|
source/primitive/Box.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/primitive/Box.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/primitive/Box.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
#include "raytracing/primitive/Box.h"
#include "raytracing/maths/Ray.h"
#include "raytracing/maths/Normal.h"
#include "raytracing/utilities/ShadeRec.h"
#include "raytracing/utilities/Constants.h"
namespace rt
{
Box::Box(const Point3D& min, const Point3D& max)
{
x0 = min.x;
y0 = min.y;
z0 = min.z;
x1 = max.x;
y1 = max.y;
z1 = max.z;
}
bool Box::Hit(const Ray& ray, double& tmin, ShadeRec& sr) const
{
double ox = ray.ori.x; double oy = ray.ori.y; double oz = ray.ori.z;
double dx = ray.dir.x; double dy = ray.dir.y; double dz = ray.dir.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
} else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
} else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
} else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
int face_in, face_out;
// find largest entering t value
if (tx_min > ty_min) {
t0 = tx_min;
face_in = (a >= 0.0) ? 0 : 3;
} else {
t0 = ty_min;
face_in = (b >= 0.0) ? 1 : 4;
}
if (tz_min > t0) {
t0 = tz_min;
face_in = (c >= 0.0) ? 2 : 5;
}
// find smallest exiting t value
if (tx_max < ty_max) {
t1 = tx_max;
face_out = (a >= 0.0) ? 3 : 0;
} else {
t1 = ty_max;
face_out = (b >= 0.0) ? 4 : 1;
}
if (tz_max < t1) {
t1 = tz_max;
face_out = (c >= 0.0) ? 5 : 2;
}
if (t0 < t1 && t1 > EPSILON) { // condition for a hit
if (t0 > EPSILON) {
tmin = t0; // ray hits outside surface
sr.normal = GetNormal(face_in);
}
else {
tmin = t1; // ray hits inside surface
sr.normal = GetNormal(face_out);
}
sr.local_hit_point = ray.ori + tmin * ray.dir;
return true;
} else {
return false;
}
}
bool Box::ShadowHit(const Ray& ray, float& tmin) const
{
if (!m_shadows) {
return false;
}
double ox = ray.ori.x; double oy = ray.ori.y; double oz = ray.ori.z;
double dx = ray.dir.x; double dy = ray.dir.y; double dz = ray.dir.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
} else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
} else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
} else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
int face_in, face_out;
// find largest entering t value
if (tx_min > ty_min) {
t0 = tx_min;
face_in = (a >= 0.0) ? 0 : 3;
} else {
t0 = ty_min;
face_in = (b >= 0.0) ? 1 : 4;
}
if (tz_min > t0) {
t0 = tz_min;
face_in = (c >= 0.0) ? 2 : 5;
}
// find smallest exiting t value
if (tx_max < ty_max) {
t1 = tx_max;
face_out = (a >= 0.0) ? 3 : 0;
} else {
t1 = ty_max;
face_out = (b >= 0.0) ? 4 : 1;
}
if (tz_max < t1) {
t1 = tz_max;
face_out = (c >= 0.0) ? 5 : 2;
}
if (t0 < t1 && t1 > EPSILON) { // condition for a hit
if (t0 > EPSILON)
tmin = static_cast<float>(t0); // ray hits outside surface
else
tmin = static_cast<float>(t1); // ray hits inside surface
return true;
} else {
return false;
}
}
AABB Box::GetBoundingBox() const
{
AABB aabb;
aabb.x0 = x0;
aabb.y0 = y0;
aabb.z0 = z0;
aabb.x1 = x1;
aabb.y1 = y1;
aabb.z1 = z1;
return aabb;
}
void Box::SetSize(const Point3D& min, const Point3D& max)
{
x0 = min.x;
y0 = min.y;
z0 = min.z;
x1 = max.x;
y1 = max.y;
z1 = max.z;
}
Normal Box::GetNormal(const int face_hit) const
{
switch (face_hit)
{
case 0: return (Normal(-1, 0, 0)); // -x face
case 1: return (Normal(0, -1, 0)); // -y face
case 2: return (Normal(0, 0, -1)); // -z face
case 3: return (Normal(1, 0, 0)); // +x face
case 4: return (Normal(0, 1, 0)); // +y face
case 5: return (Normal(0, 0, 1)); // +z face
default: return Normal(-999, -999, -999);
}
}
}
| 18.592105
| 69
| 0.538099
|
xzrunner
|
5039bf2a4c5eb2fd363d549f3197c97c53c2b558
| 1,142
|
cpp
|
C++
|
viewastrattapubblicazionestampata.cpp
|
mtodescato/ProgettoPAO
|
b73e871381e56d6b2917db8a7d227213c514f35b
|
[
"BSD-3-Clause"
] | null | null | null |
viewastrattapubblicazionestampata.cpp
|
mtodescato/ProgettoPAO
|
b73e871381e56d6b2917db8a7d227213c514f35b
|
[
"BSD-3-Clause"
] | null | null | null |
viewastrattapubblicazionestampata.cpp
|
mtodescato/ProgettoPAO
|
b73e871381e56d6b2917db8a7d227213c514f35b
|
[
"BSD-3-Clause"
] | null | null | null |
#include "viewastrattapubblicazionestampata.h"
viewAstrattaPubblicazioneStampata::viewAstrattaPubblicazioneStampata(astrattaPubblicazione *p , QWidget* parent): viewAstrattaPubblicazione(p,parent){}
void viewAstrattaPubblicazioneStampata::caricaCampiDati() {
viewAstrattaPubblicazione::caricaCampiDati();
astrattaPubblicazioneStampata* tmp = dynamic_cast<astrattaPubblicazioneStampata*>(pub);
casaEditrice = new QLineEdit(QString::fromStdString(tmp->getCasaEditrice()),this);
viewLayout->addRow("Casa editrice: ", casaEditrice);
casaEditrice->setCursorPosition(0);
connect(casaEditrice,SIGNAL(textEdited(QString)),this,SLOT(valueChanged()));
}
void viewAstrattaPubblicazioneStampata::setEditablility(bool editable) {
viewAstrattaPubblicazione::setEditablility(editable);
casaEditrice->setReadOnly(!editable);
}
bool viewAstrattaPubblicazioneStampata::checkAndSet() {
astrattaPubblicazioneStampata* tmp = dynamic_cast<astrattaPubblicazioneStampata*>(pub);
if(viewAstrattaPubblicazione::checkAndSet()) {
tmp->setCasaEditrice(casaEditrice->text().toStdString());
return true;
}
else
return false;
}
| 40.785714
| 151
| 0.801226
|
mtodescato
|
503c2a584d5c9e29ceb89ad561296769117282b3
| 900
|
cpp
|
C++
|
Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp
|
othneildrew/CPP-Programming-Practices
|
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
|
[
"MIT"
] | 1
|
2020-12-03T15:26:20.000Z
|
2020-12-03T15:26:20.000Z
|
Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp
|
othneildrew/CPP-Programming-Practices
|
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
|
[
"MIT"
] | null | null | null |
Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp
|
othneildrew/CPP-Programming-Practices
|
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
|
[
"MIT"
] | null | null | null |
// Chapter 4: Program 3
/***
Write a C++ program to read diameter of a circle. Find perimeter and area
of the circle.
**/
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main(void)
{
const double PI = 3.141592;
double Diameter, Radius, Perimeter, Area;
cout << "\n\t This program finds the perimeter and area of a circle";
cout << "\n\t To get started, please enter the diameter of the circle \n";
cin >> Diameter;
// Calculate perimeter and area using diameter and radius
Perimeter = Diameter * PI;
Radius = Diameter / 2;
Area = pow(Diameter, 2) * PI;
// Display correct values
cout << "Using a diameter of " << Diameter << endl;
cout << "The Perimeter is = " << Perimeter << endl;
cout << "The Area is = " << Area << endl;
system("pause");
return 0;
}
// Code written by: Othneil Drew
| 25
| 78
| 0.625556
|
othneildrew
|
50408d093de66e680842e2a1f4f0f26a9a96ebbf
| 1,569
|
cpp
|
C++
|
oneflow/api/python/framework/py_distribute.cpp
|
jackalcooper/oneflow-1
|
16d261ea52a56c28db8e79dbbc79032b4804d09e
|
[
"Apache-2.0"
] | 2
|
2021-09-10T00:19:49.000Z
|
2021-11-16T11:27:20.000Z
|
oneflow/api/python/framework/py_distribute.cpp
|
jackalcooper/oneflow-1
|
16d261ea52a56c28db8e79dbbc79032b4804d09e
|
[
"Apache-2.0"
] | null | null | null |
oneflow/api/python/framework/py_distribute.cpp
|
jackalcooper/oneflow-1
|
16d261ea52a56c28db8e79dbbc79032b4804d09e
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2020 The OneFlow 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.
*/
#include <pybind11/pybind11.h>
#include "oneflow/core/common/container_util.h"
#include "oneflow/api/python/of_api_registry.h"
#include "oneflow/core/framework/py_distribute.h"
namespace py = pybind11;
namespace oneflow {
namespace compatible_py {
ONEFLOW_API_PYBIND11_MODULE("distribute", m) {
py::class_<Distribute, std::shared_ptr<Distribute>>(m, "Distribute");
py::class_<AutoDistribute, Distribute, std::shared_ptr<AutoDistribute>>(m, "AutoDistribute");
py::class_<BroadcastDistribute, Distribute, std::shared_ptr<BroadcastDistribute>>(
m, "BroadcastDistribute");
py::class_<SplitDistribute, Distribute, std::shared_ptr<SplitDistribute>>(m, "SplitDistribute")
.def_property_readonly("axis", &SplitDistribute::axis);
m.def("auto", &GlobalAutoDistribute);
m.def("broadcast", &GlobalBroadcastDistribute);
m.def("split", [](int axis) { return GlobalSplitDistribute(axis).GetPtrOrThrow(); });
}
} // namespace compatible_py
} // namespace oneflow
| 37.357143
| 97
| 0.765456
|
jackalcooper
|
50534627e9e01b4312b826745b1493b5659a67cb
| 471
|
hpp
|
C++
|
src/Util/ImGui.hpp
|
D3r3k23/DrkCraft
|
5eaae66f558ce84f18de702b4227ca8d2cfe534f
|
[
"MIT"
] | 1
|
2022-02-10T04:41:57.000Z
|
2022-02-10T04:41:57.000Z
|
src/Util/ImGui.hpp
|
D3r3k23/DrkCraft
|
5eaae66f558ce84f18de702b4227ca8d2cfe534f
|
[
"MIT"
] | null | null | null |
src/Util/ImGui.hpp
|
D3r3k23/DrkCraft
|
5eaae66f558ce84f18de702b4227ca8d2cfe534f
|
[
"MIT"
] | null | null | null |
#ifndef DRK_UTIL_IMGUI_HPP
#define DRK_UTIL_IMGUI_HPP
#include "Core/Base.hpp"
#include <imgui/imgui.h>
#include <string_view>
namespace DrkCraft::DrkImGui
{
void BeginFullscreen(std::string_view name, ImGuiWindowFlags flags=0);
void BeginCentered(std::string_view name, const ImVec2& size, ImGuiWindowFlags flags=0);
void TextCentered(std::string_view text);
bool ButtonCentered(const char* text, const ImVec2& size);
}
#endif // DRK_UTIL_IMGUI_HPP
| 24.789474
| 92
| 0.766454
|
D3r3k23
|
5053ea1a70f91478eda466acf7088a52a44b6e56
| 1,030
|
hpp
|
C++
|
include/deferred/detail/deferred_type_helper.hpp
|
JohnJocoo/deferred_heap
|
700510b62bec42c77b52016ac15091b77d5dc619
|
[
"BSL-1.0"
] | null | null | null |
include/deferred/detail/deferred_type_helper.hpp
|
JohnJocoo/deferred_heap
|
700510b62bec42c77b52016ac15091b77d5dc619
|
[
"BSL-1.0"
] | null | null | null |
include/deferred/detail/deferred_type_helper.hpp
|
JohnJocoo/deferred_heap
|
700510b62bec42c77b52016ac15091b77d5dc619
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <typeinfo>
namespace def::detail
{
struct memory_chunk_header;
/// Base for helper for deferred-enabled type.
class type_helper
{
public:
explicit type_helper(const std::type_info& info,
std::size_t bytes_object,
std::size_t bytes_allocator)
: type_info{info}
, bytes_per_object{bytes_object}
, bytes_per_allocator{bytes_allocator}
{ }
/// Traverse through deferred pointers known to
/// deferred-enabled type and recursively mark them as visited.
virtual void mark_recursive(memory_chunk_header&) const = 0;
/// Run destructor(s).
void destroy(memory_chunk_header&) const;
/// Free memory.
virtual void deallocate(memory_chunk_header*) const = 0;
private:
virtual void destroy_impl(memory_chunk_header&) const = 0;
public:
const std::type_info& type_info;
const std::size_t bytes_per_object;
const std::size_t bytes_per_allocator;
}; // class type_helper
} // namespace def::detail
| 23.953488
| 67
| 0.691262
|
JohnJocoo
|
50558d1556bcc275404f44ab2c051caf2b0aac33
| 10,708
|
cpp
|
C++
|
SPHINXsys/src/shared/particles/base_particles.cpp
|
SoftwareImpacts/SIMPAC-2020-34
|
eb2d69e61548eaa11b5a9c20e312d135c5d857f5
|
[
"Apache-2.0"
] | 2
|
2020-09-24T07:39:22.000Z
|
2021-04-24T22:12:49.000Z
|
SPHINXsys/src/shared/particles/base_particles.cpp
|
SoftwareImpacts/SIMPAC-2020-34
|
eb2d69e61548eaa11b5a9c20e312d135c5d857f5
|
[
"Apache-2.0"
] | null | null | null |
SPHINXsys/src/shared/particles/base_particles.cpp
|
SoftwareImpacts/SIMPAC-2020-34
|
eb2d69e61548eaa11b5a9c20e312d135c5d857f5
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file base_particles.cpp
* @brief Definition of funcitons declared in base_particles.h
* @author Xiangyu Hu and Chi Zhang
* @version 0.1
*/
/**
* @file base_particles.cpp
* @author Luhui Han, Chi ZHang and Xiangyu Hu
* @version 0.1
*/
#include "base_particles.h"
#include "base_material.h"
#include "base_body.h"
#include "all_particle_generators.h"
#include "mesh_cell_linked_list.h"
namespace SPH
{
//=================================================================================================//
size_t BaseParticleData::total_number_of_particles_ = 0;
//=================================================================================================//
BaseParticleData::BaseParticleData()
: vel_n_(0), pos_n_(0), pos_0_(0), Vol_(0), Vol_0_(0), sigma_0_(0),
dvel_dt_others_(0), dvel_dt_(0), is_sortable_(true),
particle_id_(0)
{
total_number_of_particles_++;
}
//=================================================================================================//
BaseParticleData::BaseParticleData(Vecd position, Real Vol_0, Real sigma_0)
: vel_n_(0), pos_n_(position), pos_0_(position), Vol_(Vol_0), Vol_0_(Vol_0),
sigma_0_(sigma_0), dvel_dt_others_(0), dvel_dt_(0), is_sortable_(true), particle_id_(0)
{
total_number_of_particles_++;
}
//=================================================================================================//
BaseParticles::BaseParticles(SPHBody* body, BaseMaterial* base_material)
: body_(body), base_material_(base_material),
body_name_(body->GetBodyName()), speed_max_(0.0),
signal_speed_max_(0.0)
{
body->base_particles_ = this;
base_material->assignParticles(this);
body->base_mesh_cell_linked_list_->assignParticles(this);
ParticleGenerator* particle_generator;
switch (body->particle_generator_op_)
{
case ParticlesGeneratorOps::lattice: {
particle_generator = new ParticleGeneratorLattice(*body);
break;
}
case ParticlesGeneratorOps::direct: {
particle_generator = new ParticleGeneratorDirect(*body);
break;
}
case ParticlesGeneratorOps::regularized: {
particle_generator = new ParticleGeneratorRegularized(*body);
break;
}
default: {
std::cout << "\n FAILURE: the type of particle generator is undefined!" << std::endl;
std::cout << __FILE__ << ':' << __LINE__ << std::endl;
exit(1);
break;
}
}
particle_generator->CreateBaseParticles(this);
delete particle_generator;
real_particles_bound_ = body_->number_of_particles_;
number_of_ghost_particles_ = 0;
body->AllocateMemoryCellLinkedList();
}
//=================================================================================================//
BaseParticles::BaseParticles(SPHBody* body)
: BaseParticles(body, new BaseMaterial()) {}
//=================================================================================================//
void BaseParticles::InitializeABaseParticle(Vecd pnt, Real Vol_0, Real sigma_0)
{
size_t particle_index = base_particle_data_.size();
base_particle_data_.push_back(BaseParticleData(pnt, Vol_0, sigma_0));
base_particle_data_[particle_index].particle_id_ = particle_index;
}
//=================================================================================================//
void BaseParticles::AddABufferParticle()
{
size_t particle_index = base_particle_data_.size();
base_particle_data_.push_back(BaseParticleData());
base_particle_data_[particle_index].particle_id_ = particle_index;
}
//=================================================================================================//
void BaseParticles::CopyFromAnotherParticle(size_t this_particle_index, size_t another_particle_index)
{
size_t particle_id = base_particle_data_[this_particle_index].particle_id_;
base_particle_data_[this_particle_index] = base_particle_data_[another_particle_index];
base_particle_data_[this_particle_index].particle_id_ = particle_id;
}
//=================================================================================================//
void BaseParticles::UpdateFromAnotherParticle(size_t this_particle_index, size_t another_particle_index)
{
base_particle_data_[this_particle_index].pos_n_ = base_particle_data_[another_particle_index].pos_n_;
base_particle_data_[this_particle_index].vel_n_ = base_particle_data_[another_particle_index].vel_n_;
}
//=================================================================================================//
void BaseParticles::swapParticles(size_t this_particle_index, size_t that_particle_index)
{
std::swap(base_particle_data_[this_particle_index], base_particle_data_[that_particle_index]);
}
//=================================================================================================//
bool BaseParticles::isSwappingAllowed(size_t this_particle_index, size_t that_particle_index)
{
return base_particle_data_[this_particle_index].is_sortable_
&& base_particle_data_[that_particle_index].is_sortable_;
}
//=================================================================================================//
size_t BaseParticles ::insertAGhostParticle(size_t index_particle_i)
{
number_of_ghost_particles_ += 1;
size_t expected_size = real_particles_bound_ + number_of_ghost_particles_;
size_t expected_particle_index = expected_size - 1;
if (expected_size <= base_particle_data_.size()) {
CopyFromAnotherParticle(expected_particle_index, index_particle_i);
base_particle_data_[expected_particle_index].particle_id_
= base_particle_data_[index_particle_i].particle_id_;
}
else {
AddABufferParticle();
CopyFromAnotherParticle(expected_particle_index, index_particle_i);
base_particle_data_[expected_particle_index].particle_id_
= base_particle_data_[index_particle_i].particle_id_;
}
return expected_particle_index;
}
//=================================================================================================//
SPHBody* BaseParticles::getSPHBody()
{
return body_;
}
//=================================================================================================//
void BaseParticles::WriteParticlesToVtuFile(ofstream& output_file)
{
size_t number_of_particles = body_->number_of_particles_;
//write coordinates of particles
output_file << " <Points>\n";
output_file << " <DataArray Name=\"Position\" type=\"Float32\" NumberOfComponents=\"3\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
Vec3d particle_position = upgradeToVector3D(base_particle_data_[i].pos_n_);
output_file << particle_position[0] << " " << particle_position[1] << " " << particle_position[2] << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
output_file << " </Points>\n";
//write data of particles
output_file << " <PointData Vectors=\"vector\">\n";
output_file << " <DataArray Name=\"Particle_ID\" type=\"Int32\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
output_file << i << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
output_file << " <DataArray Name=\"Number Density\" type=\"Float32\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
output_file << fixed << setprecision(9) << base_particle_data_[i].sigma_0_ << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
base_material_->WriteMaterialPropertyToVtuFile(output_file);
output_file << " <DataArray Name=\"Velocity\" type=\"Float32\" NumberOfComponents=\"3\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
Vec3d particle_velocity = upgradeToVector3D(base_particle_data_[i].vel_n_);
output_file << particle_velocity[0] << " " << particle_velocity[1] << " " << particle_velocity[2] << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
}
//=================================================================================================//
void BaseParticles::WriteToXmlForReloadParticle(std::string &filefullpath)
{
const SimTK::String xml_name("particles_xml"), ele_name("particles");
unique_ptr<XmlEngine> reload_xml(new XmlEngine(xml_name, ele_name));
for (size_t i = 0; i != body_->number_of_particles_; ++i)
{
reload_xml->CreatXmlElement("particle");
reload_xml->AddAttributeToElement<Vecd>("Position", base_particle_data_[i].pos_n_);
reload_xml->AddAttributeToElement<Real>("Volume", base_particle_data_[i].Vol_);
reload_xml->AddAttributeToElement<Real>("NumberDensity", base_particle_data_[i].sigma_0_);
reload_xml->AddElementToXmlDoc();
}
reload_xml->WriteToXmlFile(filefullpath);
}
//=================================================================================================//
void BaseParticles::ReadFromXmlForReloadParticle(std::string &filefullpath)
{
size_t number_of_particles = 0;
unique_ptr<XmlEngine> read_xml(new XmlEngine());
read_xml->LoadXmlFile(filefullpath);
SimTK::Xml::element_iterator ele_ite_ = read_xml->root_element_.element_begin();
for (; ele_ite_ != read_xml->root_element_.element_end(); ++ele_ite_)
{
Vecd position = read_xml->GetRequiredAttributeValue<Vecd>(ele_ite_, "Position");
base_particle_data_[number_of_particles].pos_n_ = position;
Real volume = read_xml->GetRequiredAttributeValue<Real>(ele_ite_, "Volume");
base_particle_data_[number_of_particles].Vol_ = volume;
Real sigma = read_xml->GetRequiredAttributeValue<Real>(ele_ite_, "NumberDensity");
base_particle_data_[number_of_particles].sigma_0_ = sigma;
number_of_particles++;
}
if(number_of_particles != base_particle_data_.size())
{
std::cout << "\n Error: reload particle number does not matrch" << std::endl;
std::cout << __FILE__ << ':' << __LINE__ << std::endl;
exit(1);
}
}
//=================================================================================================//
BaseParticles* BaseParticles::PointToThisObject()
{
return this;
}
//=================================================================================================//
void BaseParticles::mirrorInAxisDirection(size_t particle_index_i, Vecd body_bound, int axis_direction)
{
BaseParticleData& base_particle_data_i = base_particle_data_[particle_index_i];
base_particle_data_i.pos_n_[axis_direction]
= 2.0 * body_bound[axis_direction] - base_particle_data_i.pos_n_[axis_direction];
base_particle_data_i.vel_n_[axis_direction] *= -1.0;
}
//=================================================================================================//
}
| 43.004016
| 115
| 0.607677
|
SoftwareImpacts
|
5055bedb072381a75762b2d8ba9b253cba5b000f
| 4,331
|
cpp
|
C++
|
src/test/value_parser_path_test.cpp
|
RichardCory/svgpp
|
801e0142c61c88cf2898da157fb96dc04af1b8b0
|
[
"BSL-1.0"
] | 428
|
2015-01-05T17:13:54.000Z
|
2022-03-31T08:25:47.000Z
|
src/test/value_parser_path_test.cpp
|
andrew2015/svgpp
|
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
|
[
"BSL-1.0"
] | 61
|
2015-01-08T14:32:27.000Z
|
2021-12-06T16:55:11.000Z
|
src/test/value_parser_path_test.cpp
|
andrew2015/svgpp
|
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
|
[
"BSL-1.0"
] | 90
|
2015-05-19T04:56:46.000Z
|
2022-03-26T16:42:50.000Z
|
#include <svgpp/parser/path_data.hpp>
// Only compilation is checked
using namespace svgpp;
namespace
{
struct PathContext1
{
public:
void path_move_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to(double x, double y, tag::coordinate::absolute)
{}
void path_cubic_bezier_to(
double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void path_close_subpath()
{}
void path_exit()
{}
};
struct PathContext2
{
void path_move_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to_ortho(double coord, bool horizontal, tag::coordinate::absolute)
{}
void path_cubic_bezier_to(double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_cubic_bezier_to(
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x, double y,
tag::coordinate::absolute)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void path_move_to(double x, double y, tag::coordinate::relative)
{}
void path_line_to(double x, double y, tag::coordinate::relative)
{}
void path_line_to_ortho(double coord, bool horizontal, tag::coordinate::relative)
{}
void path_cubic_bezier_to(double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::relative)
{}
void path_cubic_bezier_to(
double x2, double y2,
double x, double y,
tag::coordinate::relative)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::relative)
{}
void path_quadratic_bezier_to(
double x, double y,
tag::coordinate::relative)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::relative)
{}
void path_close_subpath()
{}
void path_exit()
{}
};
}
void check_path()
{
std::string testStr;
{
PathContext1 ctx;
value_parser<tag::type::path_data>::parse(
tag::attribute::d(), ctx, testStr, tag::source::attribute());
}
{
PathContext2 ctx;
value_parser<
tag::type::path_data,
path_policy<policy::path::raw>
>::parse(
tag::attribute::d(), ctx, testStr, tag::source::attribute());
}
}
| 28.682119
| 87
| 0.471946
|
RichardCory
|
506105a73ca0d4f36849cca455ce3168ace87b90
| 2,920
|
cpp
|
C++
|
src/GUI/GHGUINotchedSliderMonitorXMLLoader.cpp
|
GoldenHammerSoftware/GH
|
757213f479c0fc80ed1a0f59972bf3e9d92b7526
|
[
"MIT"
] | null | null | null |
src/GUI/GHGUINotchedSliderMonitorXMLLoader.cpp
|
GoldenHammerSoftware/GH
|
757213f479c0fc80ed1a0f59972bf3e9d92b7526
|
[
"MIT"
] | null | null | null |
src/GUI/GHGUINotchedSliderMonitorXMLLoader.cpp
|
GoldenHammerSoftware/GH
|
757213f479c0fc80ed1a0f59972bf3e9d92b7526
|
[
"MIT"
] | null | null | null |
// Copyright Golden Hammer Software
#include "GHGUINotchedSliderMonitorXMLLoader.h"
#include "GHGUINotchedSliderMonitor.h"
#include "GHXMLNode.h"
#include "GHPlatform/GHDebugMessage.h"
#include "GHXMLObjFactory.h"
GHGUINotchedSliderMonitorXMLLoader::GHGUINotchedSliderMonitorXMLLoader(GHPropertyContainer& appProps, const GHXMLObjFactory& xmlObjFactory, const GHStringIdFactory& hashtable)
: mAppProps(appProps)
, mXMLObjFactory(xmlObjFactory)
, mIdFactory(hashtable)
{
}
//<guiNotchedSliderMonitor prop = "GP_DIFFICULTYSLIDERVAL">
// <notches>
// <notch val = "0">
// <transitions>
// <transitionsGoHere/>
// </transitions>
// </notch>
// </notches>
//</guiNotchedSliderMonitor/>
void* GHGUINotchedSliderMonitorXMLLoader::create(const GHXMLNode& node, GHPropertyContainer& extraData) const
{
GHIdentifier propId;
if (!node.readAttrIdentifier("prop", propId, mIdFactory))
{
GHDebugMessage::outputString("Failed to load a guiNotchedSliderMonitor because there is no \"prop\" identifier to monitor");
return 0;
}
GHGUINotchedSliderMonitor* ret = 0;
const GHXMLNode* notchesNode = node.getChild("notches", false);
if (notchesNode)
{
ret = new GHGUINotchedSliderMonitor(mAppProps, propId);
bool didLoadAnyNotches = false;
const std::vector<GHXMLNode*>& notchesList = notchesNode->getChildren();
size_t numNotches = notchesList.size();
for (size_t i = 0; i < numNotches; ++i)
{
const GHXMLNode& notchNode = *notchesList[i];
float val = 0;
if (notchNode.readAttrFloat("val", val))
{
didLoadAnyNotches = true;
GHGUINotchedSliderMonitor::Notch& notch = ret->createNotch(val);
const GHXMLNode* transitionListNode = notchNode.getChild("transitions", false);
if (transitionListNode)
{
const std::vector<GHXMLNode*>& transitionList = transitionListNode->getChildren();
size_t numTransitions = transitionList.size();
notch.mTransitions.reserve(numTransitions);
for (size_t j = 0; j < numTransitions; ++j)
{
const GHXMLNode& transitionNode = *transitionList[j];
GHTransition* transition = (GHTransition*)mXMLObjFactory.load(transitionNode, &extraData);
if (transition)
{
notch.mTransitions.push_back(transition);
}
else
{
GHDebugMessage::outputString("Failed to load a transition in a guiNotchedSliderMonitor. XML Node Name: %s", transitionNode.getName().getChars());
}
}
}
}
else
{
GHDebugMessage::outputString("Failed to load a notch in a guiNotchedSliderMonitor because it did not have a \"val\" attribute");
}
}
if (!didLoadAnyNotches)
{
delete ret;
ret = 0;
GHDebugMessage::outputString("Failed to load a guiNotchedSliderMonitor because no notches were able to be loaded");
}
}
else
{
GHDebugMessage::outputString("Failed to load a guiNotchedSliderMonitor because there is no \"notches\" xml node");
}
return ret;
}
| 31.397849
| 175
| 0.719521
|
GoldenHammerSoftware
|
50667bb533ec77b5b334e531e0a1994367d5e6f8
| 729
|
cpp
|
C++
|
rtx/core/material/lambert.cpp
|
musyoku/chainer-gqn-playground
|
657bb931d2c531ff8f078fcb1686bbf1999afa7f
|
[
"MIT"
] | 28
|
2018-09-06T18:08:28.000Z
|
2021-12-19T13:30:41.000Z
|
rtx/core/material/lambert.cpp
|
musyoku/chainer-gqn-playground
|
657bb931d2c531ff8f078fcb1686bbf1999afa7f
|
[
"MIT"
] | 3
|
2019-03-01T02:50:15.000Z
|
2019-06-25T08:12:21.000Z
|
rtx/core/material/lambert.cpp
|
musyoku/chainer-gqn-playground
|
657bb931d2c531ff8f078fcb1686bbf1999afa7f
|
[
"MIT"
] | 8
|
2018-10-26T12:05:52.000Z
|
2019-09-04T05:14:24.000Z
|
#include "lambert.h"
#include "../header/enum.h"
#include "../header/struct.h"
#include <cstring>
namespace rtx {
LambertMaterial::LambertMaterial(float albedo)
{
_albedo = albedo;
}
float LambertMaterial::albedo() const
{
return _albedo;
}
int LambertMaterial::type() const
{
return RTXMaterialTypeLambert;
}
int LambertMaterial::attribute_bytes() const
{
return sizeof(rtxLambertMaterialAttribute);
}
void LambertMaterial::serialize_attributes(rtx::array<rtxMaterialAttributeByte>& array, int offset) const
{
rtxLambertMaterialAttribute attr;
attr.albedo = _albedo;
rtxMaterialAttributeByte* pointer = array.data();
std::memcpy(&pointer[offset], &attr, sizeof(rtxLambertMaterialAttribute));
}
}
| 24.3
| 105
| 0.748971
|
musyoku
|
506c250b70618bfcc89ad1ff716504527bdbcba2
| 315
|
cpp
|
C++
|
json-parser002/lib/json_null.cpp
|
syohex/cpp-study
|
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
|
[
"MIT"
] | null | null | null |
json-parser002/lib/json_null.cpp
|
syohex/cpp-study
|
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
|
[
"MIT"
] | null | null | null |
json-parser002/lib/json_null.cpp
|
syohex/cpp-study
|
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
|
[
"MIT"
] | null | null | null |
#include "json_null.h"
JsonNull::JsonNull() : JsonValue(JsonType::kNull) {
}
bool JsonNull::IsNull() const noexcept {
return true;
}
bool JsonNull::operator==(const JsonValue &value) const noexcept {
return type_ == value.Type();
}
std::nullptr_t JsonNull::Value() const noexcept {
return nullptr;
}
| 19.6875
| 66
| 0.695238
|
syohex
|
506ef4cf2c88601c2d36fd1a64a0e4ca520d25ad
| 1,586
|
hpp
|
C++
|
rds/src/rds_3.hpp
|
epfl-lasa/rds
|
574b3881dbaf4fdcd785dd96ba4c451928454b40
|
[
"MIT"
] | 12
|
2020-08-18T09:01:50.000Z
|
2022-03-17T19:53:30.000Z
|
rds/src/rds_3.hpp
|
epfl-lasa/rds
|
574b3881dbaf4fdcd785dd96ba4c451928454b40
|
[
"MIT"
] | null | null | null |
rds/src/rds_3.hpp
|
epfl-lasa/rds
|
574b3881dbaf4fdcd785dd96ba4c451928454b40
|
[
"MIT"
] | 1
|
2021-08-25T13:12:55.000Z
|
2021-08-25T13:12:55.000Z
|
#ifndef RDS_3_HPP
#define RDS_3_HPP
#include "geometry.hpp"
#include "capsule.hpp"
#include <vector>
namespace Geometry2D
{
struct RDS3
{
RDS3(float tau, float delta, float v_max);
void computeCorrectedVelocity(const Capsule& robot_shape, const Vec2& p_ref, const Vec2& v_nominal_p_ref,
const std::vector<AdditionalPrimitives2D::Circle>& objects, Vec2* v_corrected_p_ref);
void computeCorrectedVelocity(const AdditionalPrimitives2D::Circle& robot_shape, const Vec2& p_ref,
const Vec2& v_nominal_p_ref, const std::vector<AdditionalPrimitives2D::Circle>& circle_objects,
const std::vector<Capsule>& capsule_objects, Vec2* v_corrected_p_ref);
float tau, delta, v_max, v_max_sqrt_2;
std::vector<Geometry2D::HalfPlane2> constraints;
private:
void generateConstraints(const Capsule& robot_shape, const Vec2& p_ref, const Vec2& v_nominal_p_ref,
const std::vector<AdditionalPrimitives2D::Circle>& objects, std::vector<HalfPlane2>* constraints);
void generateConstraints(const AdditionalPrimitives2D::Circle& robot_shape, const Vec2& p_ref,
const Vec2& v_nominal_p_ref, const std::vector<AdditionalPrimitives2D::Circle>& circle_objects,
const std::vector<Capsule>& capsule_objects, std::vector<HalfPlane2>* constraints);
void generateAndAddConstraint(const Vec2& robot_point, float robot_radius,
const Vec2& object_point, float object_radius, const Vec2& p_ref,
const Vec2& v_nominal_p_ref, std::vector<HalfPlane2>* constraints);
void solve(const Vec2& v_nominal, std::vector<HalfPlane2>& constraints, Vec2* v_corrected);
};
}
#endif
| 36.883721
| 107
| 0.77995
|
epfl-lasa
|
507098b06484c39551ae4b05fd71ecee34241a0a
| 1,078
|
cpp
|
C++
|
core/dawn_player/error.cpp
|
lxrite/DawnPlayer
|
ba3c7f1f01d7609213492f4c9ba4a91454fb7365
|
[
"MIT"
] | 55
|
2015-03-22T16:19:03.000Z
|
2022-03-18T18:11:39.000Z
|
core/dawn_player/error.cpp
|
lxrite/DawnPlayer
|
ba3c7f1f01d7609213492f4c9ba4a91454fb7365
|
[
"MIT"
] | 2
|
2015-04-09T07:42:08.000Z
|
2015-07-26T02:56:06.000Z
|
core/dawn_player/error.cpp
|
lxrite/DawnPlayer
|
ba3c7f1f01d7609213492f4c9ba4a91454fb7365
|
[
"MIT"
] | 11
|
2015-04-29T04:52:19.000Z
|
2019-12-31T09:36:53.000Z
|
/*
* error.cpp:
*
* Copyright (C) 2015-2017 Light Lin <blog.poxiao.me> All Rights Reserved.
*
*/
#include "error.hpp"
namespace dawn_player {
open_error::open_error(const std::string& what_arg, open_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* open_error::what() const
{
return this->what_msg.c_str();
}
open_error_code open_error::code() const
{
return this->error_code;
}
get_sample_error::get_sample_error(const std::string& what_arg, get_sample_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* get_sample_error::what() const {
return this->what_msg.c_str();
}
get_sample_error_code get_sample_error::code() const {
return this->error_code;
}
seek_error::seek_error(const std::string& what_arg, seek_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* seek_error::what() const
{
return this->what_msg.c_str();
}
seek_error_code seek_error::code() const
{
return this->error_code;
}
} // namespace dawn_player
| 20.339623
| 90
| 0.67718
|
lxrite
|
507124ab12997218d83444d5919d7225bc69a457
| 996
|
cpp
|
C++
|
UVa 10454 - Trexpression/sample/10454 - Trexpression.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | 1
|
2020-11-24T03:17:21.000Z
|
2020-11-24T03:17:21.000Z
|
UVa 10454 - Trexpression/sample/10454 - Trexpression.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | null | null | null |
UVa 10454 - Trexpression/sample/10454 - Trexpression.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | 1
|
2021-04-11T16:22:31.000Z
|
2021-04-11T16:22:31.000Z
|
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int MAXN = 256;
long long dp[MAXN][MAXN];
char s[MAXN];
long long dfs(int l, int r) {
if (l == r) return 1;
if (dp[l][r] != -1) return dp[l][r];
long long &ret = dp[l][r];
ret = 0;
int left = 0, o1 = 0, o2 = 0;
for (int i = l; i <= r; i++) {
if (s[i] == '(')
left++;
else if (s[i] == ')')
left--;
else {
if (left == 0) {
if (s[i] == '+')
o1 = 1;
if (s[i] == '*')
o2 = 1;
}
}
}
if (o1 == 0 && o2 == 0)
ret += dfs(l+1, r-1);
for (int i = l; i <= r; i++) {
if (s[i] == '(')
left++;
else if (s[i] == ')')
left--;
else {
if (left == 0) {
if (s[i] == '+')
ret += dfs(l, i-1) * dfs(i+1, r);
if (s[i] == '*' && o1 == 0)
ret += dfs(l, i-1) * dfs(i+1, r);
}
}
}
return ret;
}
int main() {
while (gets(s)) {
memset(dp, -1, sizeof(dp));
long long v = dfs(0, strlen(s) - 1);
printf("%lld\n", v);
}
return 0;
}
| 17.785714
| 38
| 0.422691
|
tadvi
|
5072d895de952d882d7d0940f0497c0c83e79859
| 17,031
|
cc
|
C++
|
lib/matrices/wimax_864_0_66B.cc
|
iamviji/wimax_ldpc_lib
|
e07f102eb9eefb5c906345ec024aa08f7db871e9
|
[
"MIT"
] | 8
|
2018-10-29T14:56:05.000Z
|
2022-02-10T09:42:21.000Z
|
lib/matrices/wimax_864_0_66B.cc
|
iamviji/wimax_ldpc_lib
|
e07f102eb9eefb5c906345ec024aa08f7db871e9
|
[
"MIT"
] | null | null | null |
lib/matrices/wimax_864_0_66B.cc
|
iamviji/wimax_ldpc_lib
|
e07f102eb9eefb5c906345ec024aa08f7db871e9
|
[
"MIT"
] | 4
|
2018-10-16T20:12:56.000Z
|
2020-10-19T07:37:05.000Z
|
#include "matrices.h"
#ifdef Z_36
unsigned int wimax_864_0_66B_D = 35;
unsigned int wimax_864_0_66B_X = 6;
int16_t wimax_864_0_66B[288][11] = {
{0, 79, 161, 234, 301, 390, 449, 509, 611, 612, -1},
{1, 80, 162, 235, 302, 391, 450, 510, 576, 613, -1},
{2, 81, 163, 236, 303, 392, 451, 511, 577, 614, -1},
{3, 82, 164, 237, 304, 393, 452, 512, 578, 615, -1},
{4, 83, 165, 238, 305, 394, 453, 513, 579, 616, -1},
{5, 84, 166, 239, 306, 395, 454, 514, 580, 617, -1},
{6, 85, 167, 240, 307, 360, 455, 515, 581, 618, -1},
{7, 86, 168, 241, 308, 361, 456, 516, 582, 619, -1},
{8, 87, 169, 242, 309, 362, 457, 517, 583, 620, -1},
{9, 88, 170, 243, 310, 363, 458, 518, 584, 621, -1},
{10, 89, 171, 244, 311, 364, 459, 519, 585, 622, -1},
{11, 90, 172, 245, 312, 365, 460, 520, 586, 623, -1},
{12, 91, 173, 246, 313, 366, 461, 521, 587, 624, -1},
{13, 92, 174, 247, 314, 367, 462, 522, 588, 625, -1},
{14, 93, 175, 248, 315, 368, 463, 523, 589, 626, -1},
{15, 94, 176, 249, 316, 369, 464, 524, 590, 627, -1},
{16, 95, 177, 250, 317, 370, 465, 525, 591, 628, -1},
{17, 96, 178, 251, 318, 371, 466, 526, 592, 629, -1},
{18, 97, 179, 216, 319, 372, 467, 527, 593, 630, -1},
{19, 98, 144, 217, 320, 373, 432, 528, 594, 631, -1},
{20, 99, 145, 218, 321, 374, 433, 529, 595, 632, -1},
{21, 100, 146, 219, 322, 375, 434, 530, 596, 633, -1},
{22, 101, 147, 220, 323, 376, 435, 531, 597, 634, -1},
{23, 102, 148, 221, 288, 377, 436, 532, 598, 635, -1},
{24, 103, 149, 222, 289, 378, 437, 533, 599, 636, -1},
{25, 104, 150, 223, 290, 379, 438, 534, 600, 637, -1},
{26, 105, 151, 224, 291, 380, 439, 535, 601, 638, -1},
{27, 106, 152, 225, 292, 381, 440, 536, 602, 639, -1},
{28, 107, 153, 226, 293, 382, 441, 537, 603, 640, -1},
{29, 72, 154, 227, 294, 383, 442, 538, 604, 641, -1},
{30, 73, 155, 228, 295, 384, 443, 539, 605, 642, -1},
{31, 74, 156, 229, 296, 385, 444, 504, 606, 643, -1},
{32, 75, 157, 230, 297, 386, 445, 505, 607, 644, -1},
{33, 76, 158, 231, 298, 387, 446, 506, 608, 645, -1},
{34, 77, 159, 232, 299, 388, 447, 507, 609, 646, -1},
{35, 78, 160, 233, 300, 389, 448, 508, 610, 647, -1},
{61, 141, 192, 253, 330, 409, 483, 558, 612, 648, -1},
{62, 142, 193, 254, 331, 410, 484, 559, 613, 649, -1},
{63, 143, 194, 255, 332, 411, 485, 560, 614, 650, -1},
{64, 108, 195, 256, 333, 412, 486, 561, 615, 651, -1},
{65, 109, 196, 257, 334, 413, 487, 562, 616, 652, -1},
{66, 110, 197, 258, 335, 414, 488, 563, 617, 653, -1},
{67, 111, 198, 259, 336, 415, 489, 564, 618, 654, -1},
{68, 112, 199, 260, 337, 416, 490, 565, 619, 655, -1},
{69, 113, 200, 261, 338, 417, 491, 566, 620, 656, -1},
{70, 114, 201, 262, 339, 418, 492, 567, 621, 657, -1},
{71, 115, 202, 263, 340, 419, 493, 568, 622, 658, -1},
{36, 116, 203, 264, 341, 420, 494, 569, 623, 659, -1},
{37, 117, 204, 265, 342, 421, 495, 570, 624, 660, -1},
{38, 118, 205, 266, 343, 422, 496, 571, 625, 661, -1},
{39, 119, 206, 267, 344, 423, 497, 572, 626, 662, -1},
{40, 120, 207, 268, 345, 424, 498, 573, 627, 663, -1},
{41, 121, 208, 269, 346, 425, 499, 574, 628, 664, -1},
{42, 122, 209, 270, 347, 426, 500, 575, 629, 665, -1},
{43, 123, 210, 271, 348, 427, 501, 540, 630, 666, -1},
{44, 124, 211, 272, 349, 428, 502, 541, 631, 667, -1},
{45, 125, 212, 273, 350, 429, 503, 542, 632, 668, -1},
{46, 126, 213, 274, 351, 430, 468, 543, 633, 669, -1},
{47, 127, 214, 275, 352, 431, 469, 544, 634, 670, -1},
{48, 128, 215, 276, 353, 396, 470, 545, 635, 671, -1},
{49, 129, 180, 277, 354, 397, 471, 546, 636, 672, -1},
{50, 130, 181, 278, 355, 398, 472, 547, 637, 673, -1},
{51, 131, 182, 279, 356, 399, 473, 548, 638, 674, -1},
{52, 132, 183, 280, 357, 400, 474, 549, 639, 675, -1},
{53, 133, 184, 281, 358, 401, 475, 550, 640, 676, -1},
{54, 134, 185, 282, 359, 402, 476, 551, 641, 677, -1},
{55, 135, 186, 283, 324, 403, 477, 552, 642, 678, -1},
{56, 136, 187, 284, 325, 404, 478, 553, 643, 679, -1},
{57, 137, 188, 285, 326, 405, 479, 554, 644, 680, -1},
{58, 138, 189, 286, 327, 406, 480, 555, 645, 681, -1},
{59, 139, 190, 287, 328, 407, 481, 556, 646, 682, -1},
{60, 140, 191, 252, 329, 408, 482, 557, 647, 683, -1},
{3, 104, 167, 226, 319, 366, 444, 531, 648, 684, -1},
{4, 105, 168, 227, 320, 367, 445, 532, 649, 685, -1},
{5, 106, 169, 228, 321, 368, 446, 533, 650, 686, -1},
{6, 107, 170, 229, 322, 369, 447, 534, 651, 687, -1},
{7, 72, 171, 230, 323, 370, 448, 535, 652, 688, -1},
{8, 73, 172, 231, 288, 371, 449, 536, 653, 689, -1},
{9, 74, 173, 232, 289, 372, 450, 537, 654, 690, -1},
{10, 75, 174, 233, 290, 373, 451, 538, 655, 691, -1},
{11, 76, 175, 234, 291, 374, 452, 539, 656, 692, -1},
{12, 77, 176, 235, 292, 375, 453, 504, 657, 693, -1},
{13, 78, 177, 236, 293, 376, 454, 505, 658, 694, -1},
{14, 79, 178, 237, 294, 377, 455, 506, 659, 695, -1},
{15, 80, 179, 238, 295, 378, 456, 507, 660, 696, -1},
{16, 81, 144, 239, 296, 379, 457, 508, 661, 697, -1},
{17, 82, 145, 240, 297, 380, 458, 509, 662, 698, -1},
{18, 83, 146, 241, 298, 381, 459, 510, 663, 699, -1},
{19, 84, 147, 242, 299, 382, 460, 511, 664, 700, -1},
{20, 85, 148, 243, 300, 383, 461, 512, 665, 701, -1},
{21, 86, 149, 244, 301, 384, 462, 513, 666, 702, -1},
{22, 87, 150, 245, 302, 385, 463, 514, 667, 703, -1},
{23, 88, 151, 246, 303, 386, 464, 515, 668, 704, -1},
{24, 89, 152, 247, 304, 387, 465, 516, 669, 705, -1},
{25, 90, 153, 248, 305, 388, 466, 517, 670, 706, -1},
{26, 91, 154, 249, 306, 389, 467, 518, 671, 707, -1},
{27, 92, 155, 250, 307, 390, 432, 519, 672, 708, -1},
{28, 93, 156, 251, 308, 391, 433, 520, 673, 709, -1},
{29, 94, 157, 216, 309, 392, 434, 521, 674, 710, -1},
{30, 95, 158, 217, 310, 393, 435, 522, 675, 711, -1},
{31, 96, 159, 218, 311, 394, 436, 523, 676, 712, -1},
{32, 97, 160, 219, 312, 395, 437, 524, 677, 713, -1},
{33, 98, 161, 220, 313, 360, 438, 525, 678, 714, -1},
{34, 99, 162, 221, 314, 361, 439, 526, 679, 715, -1},
{35, 100, 163, 222, 315, 362, 440, 527, 680, 716, -1},
{0, 101, 164, 223, 316, 363, 441, 528, 681, 717, -1},
{1, 102, 165, 224, 317, 364, 442, 529, 682, 718, -1},
{2, 103, 166, 225, 318, 365, 443, 530, 683, 719, -1},
{46, 120, 210, 262, 357, 397, 489, 553, 684, 720, -1},
{47, 121, 211, 263, 358, 398, 490, 554, 685, 721, -1},
{48, 122, 212, 264, 359, 399, 491, 555, 686, 722, -1},
{49, 123, 213, 265, 324, 400, 492, 556, 687, 723, -1},
{50, 124, 214, 266, 325, 401, 493, 557, 688, 724, -1},
{51, 125, 215, 267, 326, 402, 494, 558, 689, 725, -1},
{52, 126, 180, 268, 327, 403, 495, 559, 690, 726, -1},
{53, 127, 181, 269, 328, 404, 496, 560, 691, 727, -1},
{54, 128, 182, 270, 329, 405, 497, 561, 692, 728, -1},
{55, 129, 183, 271, 330, 406, 498, 562, 693, 729, -1},
{56, 130, 184, 272, 331, 407, 499, 563, 694, 730, -1},
{57, 131, 185, 273, 332, 408, 500, 564, 695, 731, -1},
{58, 132, 186, 274, 333, 409, 501, 565, 696, 732, -1},
{59, 133, 187, 275, 334, 410, 502, 566, 697, 733, -1},
{60, 134, 188, 276, 335, 411, 503, 567, 698, 734, -1},
{61, 135, 189, 277, 336, 412, 468, 568, 699, 735, -1},
{62, 136, 190, 278, 337, 413, 469, 569, 700, 736, -1},
{63, 137, 191, 279, 338, 414, 470, 570, 701, 737, -1},
{64, 138, 192, 280, 339, 415, 471, 571, 702, 738, -1},
{65, 139, 193, 281, 340, 416, 472, 572, 703, 739, -1},
{66, 140, 194, 282, 341, 417, 473, 573, 704, 740, -1},
{67, 141, 195, 283, 342, 418, 474, 574, 705, 741, -1},
{68, 142, 196, 284, 343, 419, 475, 575, 706, 742, -1},
{69, 143, 197, 285, 344, 420, 476, 540, 707, 743, -1},
{70, 108, 198, 286, 345, 421, 477, 541, 708, 744, -1},
{71, 109, 199, 287, 346, 422, 478, 542, 709, 745, -1},
{36, 110, 200, 252, 347, 423, 479, 543, 710, 746, -1},
{37, 111, 201, 253, 348, 424, 480, 544, 711, 747, -1},
{38, 112, 202, 254, 349, 425, 481, 545, 712, 748, -1},
{39, 113, 203, 255, 350, 426, 482, 546, 713, 749, -1},
{40, 114, 204, 256, 351, 427, 483, 547, 714, 750, -1},
{41, 115, 205, 257, 352, 428, 484, 548, 715, 751, -1},
{42, 116, 206, 258, 353, 429, 485, 549, 716, 752, -1},
{43, 117, 207, 259, 354, 430, 486, 550, 717, 753, -1},
{44, 118, 208, 260, 355, 431, 487, 551, 718, 754, -1},
{45, 119, 209, 261, 356, 396, 488, 552, 719, 755, -1},
{8, 82, 149, 227, 312, 369, 450, 527, 720, 756, -1},
{9, 83, 150, 228, 313, 370, 451, 528, 721, 757, -1},
{10, 84, 151, 229, 314, 371, 452, 529, 722, 758, -1},
{11, 85, 152, 230, 315, 372, 453, 530, 723, 759, -1},
{12, 86, 153, 231, 316, 373, 454, 531, 724, 760, -1},
{13, 87, 154, 232, 317, 374, 455, 532, 725, 761, -1},
{14, 88, 155, 233, 318, 375, 456, 533, 726, 762, -1},
{15, 89, 156, 234, 319, 376, 457, 534, 727, 763, -1},
{16, 90, 157, 235, 320, 377, 458, 535, 728, 764, -1},
{17, 91, 158, 236, 321, 378, 459, 536, 729, 765, -1},
{18, 92, 159, 237, 322, 379, 460, 537, 730, 766, -1},
{19, 93, 160, 238, 323, 380, 461, 538, 731, 767, -1},
{20, 94, 161, 239, 288, 381, 462, 539, 732, 768, -1},
{21, 95, 162, 240, 289, 382, 463, 504, 733, 769, -1},
{22, 96, 163, 241, 290, 383, 464, 505, 734, 770, -1},
{23, 97, 164, 242, 291, 384, 465, 506, 735, 771, -1},
{24, 98, 165, 243, 292, 385, 466, 507, 736, 772, -1},
{25, 99, 166, 244, 293, 386, 467, 508, 737, 773, -1},
{26, 100, 167, 245, 294, 387, 432, 509, 738, 774, -1},
{27, 101, 168, 246, 295, 388, 433, 510, 739, 775, -1},
{28, 102, 169, 247, 296, 389, 434, 511, 740, 776, -1},
{29, 103, 170, 248, 297, 390, 435, 512, 741, 777, -1},
{30, 104, 171, 249, 298, 391, 436, 513, 742, 778, -1},
{31, 105, 172, 250, 299, 392, 437, 514, 743, 779, -1},
{32, 106, 173, 251, 300, 393, 438, 515, 744, 780, -1},
{33, 107, 174, 216, 301, 394, 439, 516, 745, 781, -1},
{34, 72, 175, 217, 302, 395, 440, 517, 746, 782, -1},
{35, 73, 176, 218, 303, 360, 441, 518, 747, 783, -1},
{0, 74, 177, 219, 304, 361, 442, 519, 748, 784, -1},
{1, 75, 178, 220, 305, 362, 443, 520, 749, 785, -1},
{2, 76, 179, 221, 306, 363, 444, 521, 750, 786, -1},
{3, 77, 144, 222, 307, 364, 445, 522, 751, 787, -1},
{4, 78, 145, 223, 308, 365, 446, 523, 752, 788, -1},
{5, 79, 146, 224, 309, 366, 447, 524, 753, 789, -1},
{6, 80, 147, 225, 310, 367, 448, 525, 754, 790, -1},
{7, 81, 148, 226, 311, 368, 449, 526, 755, 791, -1},
{47, 132, 200, 257, 324, 407, 495, 540, 756, 792, -1},
{48, 133, 201, 258, 325, 408, 496, 541, 757, 793, -1},
{49, 134, 202, 259, 326, 409, 497, 542, 758, 794, -1},
{50, 135, 203, 260, 327, 410, 498, 543, 759, 795, -1},
{51, 136, 204, 261, 328, 411, 499, 544, 760, 796, -1},
{52, 137, 205, 262, 329, 412, 500, 545, 761, 797, -1},
{53, 138, 206, 263, 330, 413, 501, 546, 762, 798, -1},
{54, 139, 207, 264, 331, 414, 502, 547, 763, 799, -1},
{55, 140, 208, 265, 332, 415, 503, 548, 764, 800, -1},
{56, 141, 209, 266, 333, 416, 468, 549, 765, 801, -1},
{57, 142, 210, 267, 334, 417, 469, 550, 766, 802, -1},
{58, 143, 211, 268, 335, 418, 470, 551, 767, 803, -1},
{59, 108, 212, 269, 336, 419, 471, 552, 768, 804, -1},
{60, 109, 213, 270, 337, 420, 472, 553, 769, 805, -1},
{61, 110, 214, 271, 338, 421, 473, 554, 770, 806, -1},
{62, 111, 215, 272, 339, 422, 474, 555, 771, 807, -1},
{63, 112, 180, 273, 340, 423, 475, 556, 772, 808, -1},
{64, 113, 181, 274, 341, 424, 476, 557, 773, 809, -1},
{65, 114, 182, 275, 342, 425, 477, 558, 774, 810, -1},
{66, 115, 183, 276, 343, 426, 478, 559, 775, 811, -1},
{67, 116, 184, 277, 344, 427, 479, 560, 776, 812, -1},
{68, 117, 185, 278, 345, 428, 480, 561, 777, 813, -1},
{69, 118, 186, 279, 346, 429, 481, 562, 778, 814, -1},
{70, 119, 187, 280, 347, 430, 482, 563, 779, 815, -1},
{71, 120, 188, 281, 348, 431, 483, 564, 780, 816, -1},
{36, 121, 189, 282, 349, 396, 484, 565, 781, 817, -1},
{37, 122, 190, 283, 350, 397, 485, 566, 782, 818, -1},
{38, 123, 191, 284, 351, 398, 486, 567, 783, 819, -1},
{39, 124, 192, 285, 352, 399, 487, 568, 784, 820, -1},
{40, 125, 193, 286, 353, 400, 488, 569, 785, 821, -1},
{41, 126, 194, 287, 354, 401, 489, 570, 786, 822, -1},
{42, 127, 195, 252, 355, 402, 490, 571, 787, 823, -1},
{43, 128, 196, 253, 356, 403, 491, 572, 788, 824, -1},
{44, 129, 197, 254, 357, 404, 492, 573, 789, 825, -1},
{45, 130, 198, 255, 358, 405, 493, 574, 790, 826, -1},
{46, 131, 199, 256, 359, 406, 494, 575, 791, 827, -1},
{12, 72, 149, 237, 319, 361, 434, 523, 576, 792, 828},
{13, 73, 150, 238, 320, 362, 435, 524, 577, 793, 829},
{14, 74, 151, 239, 321, 363, 436, 525, 578, 794, 830},
{15, 75, 152, 240, 322, 364, 437, 526, 579, 795, 831},
{16, 76, 153, 241, 323, 365, 438, 527, 580, 796, 832},
{17, 77, 154, 242, 288, 366, 439, 528, 581, 797, 833},
{18, 78, 155, 243, 289, 367, 440, 529, 582, 798, 834},
{19, 79, 156, 244, 290, 368, 441, 530, 583, 799, 835},
{20, 80, 157, 245, 291, 369, 442, 531, 584, 800, 836},
{21, 81, 158, 246, 292, 370, 443, 532, 585, 801, 837},
{22, 82, 159, 247, 293, 371, 444, 533, 586, 802, 838},
{23, 83, 160, 248, 294, 372, 445, 534, 587, 803, 839},
{24, 84, 161, 249, 295, 373, 446, 535, 588, 804, 840},
{25, 85, 162, 250, 296, 374, 447, 536, 589, 805, 841},
{26, 86, 163, 251, 297, 375, 448, 537, 590, 806, 842},
{27, 87, 164, 216, 298, 376, 449, 538, 591, 807, 843},
{28, 88, 165, 217, 299, 377, 450, 539, 592, 808, 844},
{29, 89, 166, 218, 300, 378, 451, 504, 593, 809, 845},
{30, 90, 167, 219, 301, 379, 452, 505, 594, 810, 846},
{31, 91, 168, 220, 302, 380, 453, 506, 595, 811, 847},
{32, 92, 169, 221, 303, 381, 454, 507, 596, 812, 848},
{33, 93, 170, 222, 304, 382, 455, 508, 597, 813, 849},
{34, 94, 171, 223, 305, 383, 456, 509, 598, 814, 850},
{35, 95, 172, 224, 306, 384, 457, 510, 599, 815, 851},
{0, 96, 173, 225, 307, 385, 458, 511, 600, 816, 852},
{1, 97, 174, 226, 308, 386, 459, 512, 601, 817, 853},
{2, 98, 175, 227, 309, 387, 460, 513, 602, 818, 854},
{3, 99, 176, 228, 310, 388, 461, 514, 603, 819, 855},
{4, 100, 177, 229, 311, 389, 462, 515, 604, 820, 856},
{5, 101, 178, 230, 312, 390, 463, 516, 605, 821, 857},
{6, 102, 179, 231, 313, 391, 464, 517, 606, 822, 858},
{7, 103, 144, 232, 314, 392, 465, 518, 607, 823, 859},
{8, 104, 145, 233, 315, 393, 466, 519, 608, 824, 860},
{9, 105, 146, 234, 316, 394, 467, 520, 609, 825, 861},
{10, 106, 147, 235, 317, 395, 432, 521, 610, 826, 862},
{11, 107, 148, 236, 318, 360, 433, 522, 611, 827, 863},
{36, 125, 184, 274, 355, 416, 497, 555, 611, 828, -1},
{37, 126, 185, 275, 356, 417, 498, 556, 576, 829, -1},
{38, 127, 186, 276, 357, 418, 499, 557, 577, 830, -1},
{39, 128, 187, 277, 358, 419, 500, 558, 578, 831, -1},
{40, 129, 188, 278, 359, 420, 501, 559, 579, 832, -1},
{41, 130, 189, 279, 324, 421, 502, 560, 580, 833, -1},
{42, 131, 190, 280, 325, 422, 503, 561, 581, 834, -1},
{43, 132, 191, 281, 326, 423, 468, 562, 582, 835, -1},
{44, 133, 192, 282, 327, 424, 469, 563, 583, 836, -1},
{45, 134, 193, 283, 328, 425, 470, 564, 584, 837, -1},
{46, 135, 194, 284, 329, 426, 471, 565, 585, 838, -1},
{47, 136, 195, 285, 330, 427, 472, 566, 586, 839, -1},
{48, 137, 196, 286, 331, 428, 473, 567, 587, 840, -1},
{49, 138, 197, 287, 332, 429, 474, 568, 588, 841, -1},
{50, 139, 198, 252, 333, 430, 475, 569, 589, 842, -1},
{51, 140, 199, 253, 334, 431, 476, 570, 590, 843, -1},
{52, 141, 200, 254, 335, 396, 477, 571, 591, 844, -1},
{53, 142, 201, 255, 336, 397, 478, 572, 592, 845, -1},
{54, 143, 202, 256, 337, 398, 479, 573, 593, 846, -1},
{55, 108, 203, 257, 338, 399, 480, 574, 594, 847, -1},
{56, 109, 204, 258, 339, 400, 481, 575, 595, 848, -1},
{57, 110, 205, 259, 340, 401, 482, 540, 596, 849, -1},
{58, 111, 206, 260, 341, 402, 483, 541, 597, 850, -1},
{59, 112, 207, 261, 342, 403, 484, 542, 598, 851, -1},
{60, 113, 208, 262, 343, 404, 485, 543, 599, 852, -1},
{61, 114, 209, 263, 344, 405, 486, 544, 600, 853, -1},
{62, 115, 210, 264, 345, 406, 487, 545, 601, 854, -1},
{63, 116, 211, 265, 346, 407, 488, 546, 602, 855, -1},
{64, 117, 212, 266, 347, 408, 489, 547, 603, 856, -1},
{65, 118, 213, 267, 348, 409, 490, 548, 604, 857, -1},
{66, 119, 214, 268, 349, 410, 491, 549, 605, 858, -1},
{67, 120, 215, 269, 350, 411, 492, 550, 606, 859, -1},
{68, 121, 180, 270, 351, 412, 493, 551, 607, 860, -1},
{69, 122, 181, 271, 352, 413, 494, 552, 608, 861, -1},
{70, 123, 182, 272, 353, 414, 495, 553, 609, 862, -1},
{71, 124, 183, 273, 354, 415, 496, 554, 610, 863, -1}
};
#endif
| 57.151007
| 59
| 0.509424
|
iamviji
|
5074b492e1d6cad9623d045c0e74c142a9cf7662
| 299
|
cpp
|
C++
|
c2017/wd/wd186/main.cpp
|
wmjtxt/c-exercise
|
d22336460cab825dd7ae98297bbe46febedfcece
|
[
"MIT"
] | null | null | null |
c2017/wd/wd186/main.cpp
|
wmjtxt/c-exercise
|
d22336460cab825dd7ae98297bbe46febedfcece
|
[
"MIT"
] | null | null | null |
c2017/wd/wd186/main.cpp
|
wmjtxt/c-exercise
|
d22336460cab825dd7ae98297bbe46febedfcece
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char a[100], b[100];
gets(a);
gets(b);
int lena = -1, i = 0;
while(a[++lena] != '\0');
while(b[i] != '\0'){
a[lena++] = b[i++];
}
a[lena] = '\0';
cout << a << endl;
return 0;
}
| 15.736842
| 29
| 0.441472
|
wmjtxt
|
5077ad214c26a83540c8a9dd7d899a649af72049
| 18,125
|
cxx
|
C++
|
main/stoc/source/proxy_factory/proxyfac.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 679
|
2015-01-06T06:34:58.000Z
|
2022-03-30T01:06:03.000Z
|
main/stoc/source/proxy_factory/proxyfac.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 102
|
2017-11-07T08:51:31.000Z
|
2022-03-17T12:13:49.000Z
|
main/stoc/source/proxy_factory/proxyfac.cxx
|
Grosskopf/openoffice
|
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
|
[
"Apache-2.0"
] | 331
|
2015-01-06T11:40:55.000Z
|
2022-03-14T04:07:51.000Z
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "osl/diagnose.h"
#include "osl/interlck.h"
#include "osl/doublecheckedlocking.h"
#include "osl/mutex.hxx"
#include "rtl/ref.hxx"
#include "uno/dispatcher.hxx"
#include "uno/data.h"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "typelib/typedescription.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/factory.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/registry/XRegistryKey.hpp"
#include "com/sun/star/reflection/XProxyFactory.hpp"
#include "com/sun/star/uno/RuntimeException.hpp"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
#define SERVICE_NAME "com.sun.star.reflection.ProxyFactory"
#define IMPL_NAME "com.sun.star.comp.reflection.ProxyFactory"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace
{
static rtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;
static OUString proxyfac_getImplementationName()
{
return OUSTR(IMPL_NAME);
}
static Sequence< OUString > proxyfac_getSupportedServiceNames()
{
OUString str_name = OUSTR(SERVICE_NAME);
return Sequence< OUString >( &str_name, 1 );
}
//==============================================================================
struct FactoryImpl : public ::cppu::WeakImplHelper2< lang::XServiceInfo,
reflection::XProxyFactory >
{
Environment m_uno_env;
Environment m_cpp_env;
Mapping m_uno2cpp;
Mapping m_cpp2uno;
UnoInterfaceReference binuno_queryInterface(
UnoInterfaceReference const & unoI,
typelib_InterfaceTypeDescription * pTypeDescr );
FactoryImpl();
virtual ~FactoryImpl();
// XServiceInfo
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const OUString & rServiceName )
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
throw (RuntimeException);
// XProxyFactory
virtual Reference< XAggregation > SAL_CALL createProxy(
Reference< XInterface > const & xTarget )
throw (RuntimeException);
};
//______________________________________________________________________________
UnoInterfaceReference FactoryImpl::binuno_queryInterface(
UnoInterfaceReference const & unoI,
typelib_InterfaceTypeDescription * pTypeDescr )
{
// init queryInterface() td
static typelib_TypeDescription * s_pQITD = 0;
if (s_pQITD == 0)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (s_pQITD == 0)
{
typelib_TypeDescription * pTXInterfaceDescr = 0;
TYPELIB_DANGER_GET(
&pTXInterfaceDescr,
::getCppuType( reinterpret_cast< Reference< XInterface >
const * >(0) ).getTypeLibType() );
typelib_TypeDescription * pQITD = 0;
typelib_typedescriptionreference_getDescription(
&pQITD, reinterpret_cast< typelib_InterfaceTypeDescription * >(
pTXInterfaceDescr )->ppAllMembers[ 0 ] );
TYPELIB_DANGER_RELEASE( pTXInterfaceDescr );
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
s_pQITD = pQITD;
}
}
else
{
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
}
void * args[ 1 ];
args[ 0 ] = &reinterpret_cast< typelib_TypeDescription * >(
pTypeDescr )->pWeakRef;
uno_Any ret_val, exc_space;
uno_Any * exc = &exc_space;
unoI.dispatch( s_pQITD, &ret_val, args, &exc );
if (exc == 0)
{
UnoInterfaceReference ret;
if (ret_val.pType->eTypeClass == typelib_TypeClass_INTERFACE)
{
ret.set( *reinterpret_cast< uno_Interface ** >(ret_val.pData),
SAL_NO_ACQUIRE );
typelib_typedescriptionreference_release( ret_val.pType );
}
else
{
uno_any_destruct( &ret_val, 0 );
}
return ret;
}
else
{
// exception occurred:
OSL_ENSURE(
typelib_typedescriptionreference_isAssignableFrom(
::getCppuType( reinterpret_cast<
RuntimeException const * >(0) ).getTypeLibType(),
exc->pType ),
"### RuntimeException expected!" );
Any cpp_exc;
uno_type_copyAndConvertData(
&cpp_exc, exc, ::getCppuType( &cpp_exc ).getTypeLibType(),
m_uno2cpp.get() );
uno_any_destruct( exc, 0 );
::cppu::throwException( cpp_exc );
OSL_ASSERT( 0 ); // way of no return
return UnoInterfaceReference(); // for dummy
}
}
//==============================================================================
struct ProxyRoot : public ::cppu::OWeakAggObject
{
// XAggregation
virtual Any SAL_CALL queryAggregation( Type const & rType )
throw (RuntimeException);
virtual ~ProxyRoot();
inline ProxyRoot( ::rtl::Reference< FactoryImpl > const & factory,
Reference< XInterface > const & xTarget );
::rtl::Reference< FactoryImpl > m_factory;
private:
UnoInterfaceReference m_target;
};
//==============================================================================
struct binuno_Proxy : public uno_Interface
{
oslInterlockedCount m_nRefCount;
::rtl::Reference< ProxyRoot > m_root;
UnoInterfaceReference m_target;
OUString m_oid;
TypeDescription m_typeDescr;
inline binuno_Proxy(
::rtl::Reference< ProxyRoot > const & root,
UnoInterfaceReference const & target,
OUString const & oid, TypeDescription const & typeDescr );
};
extern "C"
{
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_free(
uno_ExtEnvironment * pEnv, void * pProxy )
{
(void) pEnv; // avoid warning about unused parameter
binuno_Proxy * proxy = static_cast< binuno_Proxy * >(
reinterpret_cast< uno_Interface * >( pProxy ) );
OSL_ASSERT( proxy->m_root->m_factory->m_uno_env.get()->pExtEnv == pEnv );
delete proxy;
}
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_acquire( uno_Interface * pUnoI )
{
binuno_Proxy * that = static_cast< binuno_Proxy * >( pUnoI );
if (osl_incrementInterlockedCount( &that->m_nRefCount ) == 1)
{
// rebirth of zombie
uno_ExtEnvironment * uno_env =
that->m_root->m_factory->m_uno_env.get()->pExtEnv;
OSL_ASSERT( uno_env != 0 );
(*uno_env->registerProxyInterface)(
uno_env, reinterpret_cast< void ** >( &pUnoI ), binuno_proxy_free,
that->m_oid.pData,
reinterpret_cast< typelib_InterfaceTypeDescription * >(
that->m_typeDescr.get() ) );
OSL_ASSERT( that == static_cast< binuno_Proxy * >( pUnoI ) );
}
}
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_release( uno_Interface * pUnoI )
{
binuno_Proxy * that = static_cast< binuno_Proxy * >( pUnoI );
if (osl_decrementInterlockedCount( &that->m_nRefCount ) == 0)
{
uno_ExtEnvironment * uno_env =
that->m_root->m_factory->m_uno_env.get()->pExtEnv;
OSL_ASSERT( uno_env != 0 );
(*uno_env->revokeInterface)( uno_env, pUnoI );
}
}
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_dispatch(
uno_Interface * pUnoI, const typelib_TypeDescription * pMemberType,
void * pReturn, void * pArgs [], uno_Any ** ppException )
{
binuno_Proxy * that = static_cast< binuno_Proxy * >( pUnoI );
switch (reinterpret_cast< typelib_InterfaceMemberTypeDescription const * >(
pMemberType )->nPosition)
{
case 0: // queryInterface()
{
try
{
Type const & rType =
*reinterpret_cast< Type const * >( pArgs[ 0 ] );
Any ret( that->m_root->queryInterface( rType ) );
uno_type_copyAndConvertData(
pReturn, &ret, ::getCppuType( &ret ).getTypeLibType(),
that->m_root->m_factory->m_cpp2uno.get() );
*ppException = 0; // no exc
}
catch (RuntimeException &)
{
Any exc( ::cppu::getCaughtException() );
uno_type_any_constructAndConvert(
*ppException, const_cast< void * >(exc.getValue()),
exc.getValueTypeRef(),
that->m_root->m_factory->m_cpp2uno.get() );
}
break;
}
case 1: // acquire()
binuno_proxy_acquire( pUnoI );
*ppException = 0; // no exc
break;
case 2: // release()
binuno_proxy_release( pUnoI );
*ppException = 0; // no exc
break;
default:
that->m_target.dispatch( pMemberType, pReturn, pArgs, ppException );
break;
}
}
}
//______________________________________________________________________________
inline binuno_Proxy::binuno_Proxy(
::rtl::Reference< ProxyRoot > const & root,
UnoInterfaceReference const & target,
OUString const & oid, TypeDescription const & typeDescr )
: m_nRefCount( 1 ),
m_root( root ),
m_target( target ),
m_oid( oid ),
m_typeDescr( typeDescr )
{
uno_Interface::acquire = binuno_proxy_acquire;
uno_Interface::release = binuno_proxy_release;
uno_Interface::pDispatcher = binuno_proxy_dispatch;
}
//______________________________________________________________________________
ProxyRoot::~ProxyRoot()
{
}
//______________________________________________________________________________
inline ProxyRoot::ProxyRoot(
::rtl::Reference< FactoryImpl > const & factory,
Reference< XInterface > const & xTarget )
: m_factory( factory )
{
m_factory->m_cpp2uno.mapInterface(
reinterpret_cast< void ** >( &m_target.m_pUnoI ), xTarget.get(),
::getCppuType( &xTarget ) );
OSL_ENSURE( m_target.is(), "### mapping interface failed!" );
}
//______________________________________________________________________________
Any ProxyRoot::queryAggregation( Type const & rType )
throw (RuntimeException)
{
Any ret( OWeakAggObject::queryAggregation( rType ) );
if (! ret.hasValue())
{
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, rType.getTypeLibType() );
try
{
Reference< XInterface > xProxy;
uno_ExtEnvironment * cpp_env = m_factory->m_cpp_env.get()->pExtEnv;
OSL_ASSERT( cpp_env != 0 );
// mind a new delegator, calculate current root:
Reference< XInterface > xRoot(
static_cast< OWeakObject * >(this), UNO_QUERY_THROW );
OUString oid;
(*cpp_env->getObjectIdentifier)( cpp_env, &oid.pData, xRoot.get() );
OSL_ASSERT( oid.getLength() > 0 );
(*cpp_env->getRegisteredInterface)(
cpp_env, reinterpret_cast< void ** >( &xProxy ),
oid.pData, reinterpret_cast<
typelib_InterfaceTypeDescription * >(pTypeDescr) );
if (! xProxy.is())
{
// perform query on target:
UnoInterfaceReference proxy_target(
m_factory->binuno_queryInterface(
m_target, reinterpret_cast<
typelib_InterfaceTypeDescription * >(pTypeDescr) ) );
if (proxy_target.is())
{
// ensure root's object entries:
UnoInterfaceReference root;
m_factory->m_cpp2uno.mapInterface(
reinterpret_cast< void ** >( &root.m_pUnoI ),
xRoot.get(), ::getCppuType( &xRoot ) );
UnoInterfaceReference proxy(
// ref count initially 1:
new binuno_Proxy( this, proxy_target, oid, pTypeDescr ),
SAL_NO_ACQUIRE );
uno_ExtEnvironment * uno_env =
m_factory->m_uno_env.get()->pExtEnv;
OSL_ASSERT( uno_env != 0 );
(*uno_env->registerProxyInterface)(
uno_env, reinterpret_cast< void ** >( &proxy.m_pUnoI ),
binuno_proxy_free, oid.pData,
reinterpret_cast< typelib_InterfaceTypeDescription * >(
pTypeDescr ) );
m_factory->m_uno2cpp.mapInterface(
reinterpret_cast< void ** >( &xProxy ),
proxy.get(), pTypeDescr );
}
}
if (xProxy.is())
ret.setValue( &xProxy, pTypeDescr );
}
catch (...) // finally
{
TYPELIB_DANGER_RELEASE( pTypeDescr );
throw;
}
TYPELIB_DANGER_RELEASE( pTypeDescr );
}
return ret;
}
//##############################################################################
//______________________________________________________________________________
FactoryImpl::FactoryImpl()
{
OUString uno = OUSTR(UNO_LB_UNO);
OUString cpp = OUSTR(CPPU_CURRENT_LANGUAGE_BINDING_NAME);
uno_getEnvironment(
reinterpret_cast< uno_Environment ** >( &m_uno_env ), uno.pData, 0 );
OSL_ENSURE( m_uno_env.is(), "### cannot get binary uno env!" );
uno_getEnvironment(
reinterpret_cast< uno_Environment ** >( &m_cpp_env ), cpp.pData, 0 );
OSL_ENSURE( m_cpp_env.is(), "### cannot get C++ uno env!" );
uno_getMapping(
reinterpret_cast< uno_Mapping ** >( &m_uno2cpp ),
m_uno_env.get(), m_cpp_env.get(), 0 );
OSL_ENSURE( m_uno2cpp.is(), "### cannot get bridge uno <-> C++!" );
uno_getMapping(
reinterpret_cast< uno_Mapping ** >( &m_cpp2uno ),
m_cpp_env.get(), m_uno_env.get(), 0 );
OSL_ENSURE( m_cpp2uno.is(), "### cannot get bridge C++ <-> uno!" );
g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}
//______________________________________________________________________________
FactoryImpl::~FactoryImpl()
{
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
// XProxyFactory
//______________________________________________________________________________
Reference< XAggregation > FactoryImpl::createProxy(
Reference< XInterface > const & xTarget )
throw (RuntimeException)
{
return new ProxyRoot( this, xTarget );
}
// XServiceInfo
//______________________________________________________________________________
OUString FactoryImpl::getImplementationName()
throw (RuntimeException)
{
return proxyfac_getImplementationName();;
}
//______________________________________________________________________________
sal_Bool FactoryImpl::supportsService( const OUString & rServiceName )
throw (RuntimeException)
{
Sequence< OUString > const & rSNL = getSupportedServiceNames();
OUString const * pArray = rSNL.getConstArray();
for ( sal_Int32 nPos = rSNL.getLength(); nPos--; )
{
if (rServiceName.equals( pArray[ nPos ] ))
return true;
}
return false;
}
//______________________________________________________________________________
Sequence< OUString > FactoryImpl::getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException)
{
return proxyfac_getSupportedServiceNames();
}
//==============================================================================
static Reference< XInterface > SAL_CALL proxyfac_create(
Reference< XComponentContext > const & )
throw (Exception)
{
Reference< XInterface > xRet;
{
::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
static WeakReference < XInterface > rwInstance;
xRet = rwInstance;
if (! xRet.is())
{
xRet = static_cast< ::cppu::OWeakObject * >(new FactoryImpl);
rwInstance = xRet;
}
}
return xRet;
}
static ::cppu::ImplementationEntry g_entries [] =
{
{
proxyfac_create, proxyfac_getImplementationName,
proxyfac_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
&g_moduleCount.modCnt, 0
},
{ 0, 0, 0, 0, 0, 0 }
};
}
extern "C"
{
sal_Bool SAL_CALL component_canUnload( TimeValue * pTime )
{
return g_moduleCount.canUnload( &g_moduleCount, pTime );
}
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return ::cppu::component_getFactoryHelper(
pImplName, pServiceManager, pRegistryKey, g_entries );
}
}
| 33.941948
| 80
| 0.613517
|
Grosskopf
|
507cdeacfef76c4f63da9a526dbb2de19e2ae25d
| 5,139
|
cpp
|
C++
|
src/vulkan/vulkan-upload.cpp
|
Impulse21/nvrhi
|
f272a6595dd0768a8e3419f0075f0edf40d00391
|
[
"MIT"
] | 2
|
2021-08-28T23:02:30.000Z
|
2021-08-28T23:26:21.000Z
|
src/vulkan/vulkan-upload.cpp
|
Impulse21/nvrhi
|
f272a6595dd0768a8e3419f0075f0edf40d00391
|
[
"MIT"
] | null | null | null |
src/vulkan/vulkan-upload.cpp
|
Impulse21/nvrhi
|
f272a6595dd0768a8e3419f0075f0edf40d00391
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* 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 "vulkan-backend.h"
#include <nvrhi/common/misc.h>
namespace nvrhi::vulkan
{
std::shared_ptr<BufferChunk> UploadManager::CreateChunk(uint64_t size)
{
std::shared_ptr<BufferChunk> chunk = std::make_shared<BufferChunk>();
if (m_IsScratchBuffer)
{
BufferDesc desc;
desc.byteSize = size;
desc.cpuAccess = CpuAccessMode::None;
desc.debugName = "ScratchBufferChunk";
chunk->buffer = m_Device->createBuffer(desc);
chunk->mappedMemory = nullptr;
chunk->bufferSize = size;
}
else
{
BufferDesc desc;
desc.byteSize = size;
desc.cpuAccess = CpuAccessMode::Write;
desc.debugName = "UploadChunk";
// The upload manager buffers are used in buildTopLevelAccelStruct to store instance data
desc.isAccelStructBuildInput = m_Device->queryFeatureSupport(Feature::RayTracingAccelStruct);
chunk->buffer = m_Device->createBuffer(desc);
chunk->mappedMemory = m_Device->mapBuffer(chunk->buffer, CpuAccessMode::Write);
chunk->bufferSize = size;
}
return chunk;
}
bool UploadManager::suballocateBuffer(uint64_t size, Buffer** pBuffer, uint64_t* pOffset, void** pCpuVA,
uint64_t currentVersion, uint32_t alignment)
{
std::shared_ptr<BufferChunk> chunkToRetire;
if (m_CurrentChunk)
{
uint64_t alignedOffset = align(m_CurrentChunk->writePointer, (uint64_t)alignment);
uint64_t endOfDataInChunk = alignedOffset + size;
if (endOfDataInChunk <= m_CurrentChunk->bufferSize)
{
m_CurrentChunk->writePointer = endOfDataInChunk;
*pBuffer = checked_cast<Buffer*>(m_CurrentChunk->buffer.Get());
*pOffset = alignedOffset;
if (pCpuVA && m_CurrentChunk->mappedMemory)
*pCpuVA = (char*)m_CurrentChunk->mappedMemory + alignedOffset;
return true;
}
chunkToRetire = m_CurrentChunk;
m_CurrentChunk.reset();
}
CommandQueue queue = VersionGetQueue(currentVersion);
uint64_t completedInstance = m_Device->queueGetCompletedInstance(queue);
for (auto it = m_ChunkPool.begin(); it != m_ChunkPool.end(); ++it)
{
std::shared_ptr<BufferChunk> chunk = *it;
if (VersionGetSubmitted(chunk->version)
&& VersionGetInstance(chunk->version) <= completedInstance)
{
chunk->version = 0;
}
if (chunk->version == 0 && chunk->bufferSize >= size)
{
m_ChunkPool.erase(it);
m_CurrentChunk = chunk;
break;
}
}
if (chunkToRetire)
{
m_ChunkPool.push_back(chunkToRetire);
}
if (!m_CurrentChunk)
{
uint64_t sizeToAllocate = align(std::max(size, m_DefaultChunkSize), BufferChunk::c_sizeAlignment);
if ((m_MemoryLimit > 0) && (m_AllocatedMemory + sizeToAllocate > m_MemoryLimit))
return false;
m_CurrentChunk = CreateChunk(sizeToAllocate);
}
m_CurrentChunk->version = currentVersion;
m_CurrentChunk->writePointer = size;
*pBuffer = checked_cast<Buffer*>(m_CurrentChunk->buffer.Get());
*pOffset = 0;
if (pCpuVA)
*pCpuVA = m_CurrentChunk->mappedMemory;
return true;
}
void UploadManager::submitChunks(uint64_t currentVersion, uint64_t submittedVersion)
{
if (m_CurrentChunk)
{
m_ChunkPool.push_back(m_CurrentChunk);
m_CurrentChunk.reset();
}
for (const auto& chunk : m_ChunkPool)
{
if (chunk->version == currentVersion)
chunk->version = submittedVersion;
}
}
}
| 34.26
| 110
| 0.622884
|
Impulse21
|
5081c7d33af9647d83b7b6a0905c91a566c1685a
| 856
|
cpp
|
C++
|
codeforces/587div3/B.cpp
|
xenowits/cp
|
963b3c7df65b5328d5ce5ef894a46691afefb98c
|
[
"MIT"
] | null | null | null |
codeforces/587div3/B.cpp
|
xenowits/cp
|
963b3c7df65b5328d5ce5ef894a46691afefb98c
|
[
"MIT"
] | null | null | null |
codeforces/587div3/B.cpp
|
xenowits/cp
|
963b3c7df65b5328d5ce5ef894a46691afefb98c
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define fori(i,a,b) for (long int i = a; i <= b ; ++i)
#define ford(i,a,b) for(long int i = a;i >= b ; --i)
#define mk make_pair
#define mod 1000000007
#define pb push_back
#define vec vector<long long int>
#define ll long long
#define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count())
#define pi pair<long long int,long long int>
#define sc second
#define fs first
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n,temp;
cin >> n;
vector<pi> v;
fori(i,1,n)
{
cin >> temp;
v.pb(mk(temp,i));
}
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
ll ans = 0, hell = 0;
fori(i,0,n-1)
{
ans += (v[i].fs*hell);
hell += 1;
}
cout << ans+n << endl;
fori(i,0,n-1)
cout << v[i].sc << " ";
return 0;
}
| 17.12
| 91
| 0.593458
|
xenowits
|
5088bd07be39f03921292ee9a9af76c4f3883ed7
| 1,067
|
cpp
|
C++
|
competitive programming/leetcode/905. Sort Array By Parity.cpp
|
kashyap99saksham/Code
|
96658d0920eb79c007701d2a3cc9dbf453d78f96
|
[
"MIT"
] | 16
|
2020-06-02T19:22:45.000Z
|
2022-02-05T10:35:28.000Z
|
competitive programming/leetcode/905. Sort Array By Parity.cpp
|
codezoned/Code
|
de91ffc7ef06812a31464fb40358e2436734574c
|
[
"MIT"
] | null | null | null |
competitive programming/leetcode/905. Sort Array By Parity.cpp
|
codezoned/Code
|
de91ffc7ef06812a31464fb40358e2436734574c
|
[
"MIT"
] | 2
|
2020-08-27T17:40:06.000Z
|
2022-02-05T10:33:52.000Z
|
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
// Without extra space
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n=A.size();
int j=0;
for(int i=0;i<n;i++){
if(A[i]%2==0){
swap(A[i], A[j]);
j++;
}
}
return A;
}
};
// Extra space
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n=A.size();
vector<int> res(n);
int start=0, last=n-1;
for(int i=0;i<n;i++){
if(A[i]%2==0){
res[start++]=A[i];
} else {
res[last--]=A[i];
}
}
return res;
}
};
| 16.936508
| 139
| 0.492971
|
kashyap99saksham
|
5089af9edf6629885ea3f89dd4f8105bc13337a7
| 1,585
|
hpp
|
C++
|
infra/util/Allocator.hpp
|
oguzcanphilips/embeddedinfralib
|
f1b083d61a34d123d34ab7cd51267377aa2f7855
|
[
"Unlicense"
] | 54
|
2019-04-02T14:42:54.000Z
|
2022-03-20T23:02:19.000Z
|
infra/util/Allocator.hpp
|
oguzcanphilips/embeddedinfralib
|
f1b083d61a34d123d34ab7cd51267377aa2f7855
|
[
"Unlicense"
] | 32
|
2019-03-26T06:57:29.000Z
|
2022-03-25T00:04:44.000Z
|
infra/util/Allocator.hpp
|
oguzcanphilips/embeddedinfralib
|
f1b083d61a34d123d34ab7cd51267377aa2f7855
|
[
"Unlicense"
] | 20
|
2019-03-25T15:49:49.000Z
|
2022-03-20T23:02:22.000Z
|
#ifndef INFRA_ALLOCATOR_HPP
#define INFRA_ALLOCATOR_HPP
#include <memory>
namespace infra
{
class AllocatorBase
{
protected:
AllocatorBase() = default;
AllocatorBase(const AllocatorBase& other) = delete;
AllocatorBase& operator=(const AllocatorBase& other) = delete;
~AllocatorBase() = default;
public:
virtual void Deallocate(void* object) = 0;
};
class Deallocator
{
public:
Deallocator() = default;
explicit Deallocator(AllocatorBase& allocator);
void operator()(void* object);
private:
AllocatorBase* allocator = nullptr;
};
template<class T>
using UniquePtr = std::unique_ptr<T, Deallocator>;
template<class T>
UniquePtr<T> MakeUnique(T* object, AllocatorBase& allocator);
template<class T, class ConstructionArgs>
class Allocator;
template<class T, class... ConstructionArgs>
class Allocator<T, void(ConstructionArgs...)>
: public AllocatorBase
{
public:
virtual UniquePtr<T> Allocate(ConstructionArgs... args) = 0;
protected:
~Allocator() = default;
};
//// Implementation ////
inline Deallocator::Deallocator(AllocatorBase& allocator)
: allocator(&allocator)
{}
inline void Deallocator::operator()(void* object)
{
allocator->Deallocate(object);
}
template<class T>
UniquePtr<T> MakeUnique(T* object, AllocatorBase& allocator)
{
return infra::UniquePtr<T>(object, Deallocator(allocator));
}
}
#endif
| 22.323944
| 70
| 0.634069
|
oguzcanphilips
|
50906cdb433c4f11ffd5eb9ae7025dfe569be67a
| 5,564
|
cxx
|
C++
|
templates/ws/src/clan/lang.cxx
|
roadnarrows-robotics/rnmake
|
6446cda6b36d66f6ee945db128a052caaf9c89ee
|
[
"MIT"
] | null | null | null |
templates/ws/src/clan/lang.cxx
|
roadnarrows-robotics/rnmake
|
6446cda6b36d66f6ee945db128a052caaf9c89ee
|
[
"MIT"
] | null | null | null |
templates/ws/src/clan/lang.cxx
|
roadnarrows-robotics/rnmake
|
6446cda6b36d66f6ee945db128a052caaf9c89ee
|
[
"MIT"
] | null | null | null |
/*! \file
*
* \brief Languages spoken back in the day.
*
* \pkgfile{@FILENAME@}
* \pkgcomponent{Application,clan}
* \author @PKG_AUTHOR@
*
* \LegalBegin
* @PKG_LICENSE@
* \LegalEnd
*/
#include <string>
#include "@PKG_NAME@/stone_tools.h"
#include "@PKG_NAME@/fire.h"
#include "utils.h"
#include "grammar.h"
#include "lang.h"
namespace clan
{
namespace troglodese
{
/*!
* \brief The Troglodese language.
*
* This is the static component of the language.
*
* \sa clan::Grammar::load
*/
Language Troglodese =
{
// name
"Troglodese",
// dictionary symbols
{ "s:Terry the Terror Bird",
"s:A rock",
"s:CLAN[Trog, Mini Trog, Baby Trog]",
"s:ADULTS[Trog]",
"s:URCHINS[Mini Trog]",
"s:CAVIES[Baby Trog]",
"v:DAILY_TASKS[gathers, grinds, makes, builds, cooks, eats, sleeps]",
"v:DANGEROUS[hunts, scavenges]",
"v:LOCOMOTION[walks, ambles, trots, runs]",
"v:CREEP[crawls, creeps, waddles]",
"v:steals",
"v:ROCKS[rolls, drops, is thrown]",
"v:is",
"v:is feeling",
"v:is a",
"v:likes",
"v:not like",
"o:PREY[glyptodon, capybara, titi monkey, hippidion, "
"lestodon ground sloth, toxodon]",
"o:GATHERED[grubs, tool stones, wood, eggs, termites, teosinte, "
"quinoa, amaranth]",
"o:CARRION[rotting gomphothere thigh, arctotherium rump, "
"questionable carrion]",
"o:STONE_TOOLS_MADE[broken stone]",
"o:FOOD[glyptodon, capybara, titi monkey, hippidion, "
"lestodon ground sloth, toxodon, grubs, eggs, termites, "
"teosinte, quinoa, amaranth, rotting gomphothere thigh, "
"arctotherium rump, questionable carrion]",
"o:COOKING_FOOD[glyptodon, capybara, titi monkey, hippidion, "
"lestodon ground sloth, toxodon, eggs, "
"rotting gomphothere thigh, arctotherium rump, "
"questionable carrion]",
"o:GRINDING_FOOD[teosinte, quinoa, amaranth]",
"o:EMOTION[happy, sad, mad, an existential crisis]",
"o:a fire",
"o:a troglodyte",
"o:LOOT[table scraps, a rock, a troglodyte]",
"o:DEST[to the cave, along the river, in the forest, backwards]",
"o:ART[cave painting, hand shadow puppet, shell ornament, shiny rock]",
"p:by the tail",
"p:at the creek",
"p:using a stick",
"p:WHEN[at dawn, when sun up high, when me hungry]",
"p:with a stalk of grass",
"p:WITH_WEAPON[with hands and teeth, with a rock, with a hand axe, "
"with old spear, by abusive name calling]",
"p:FIRE_METHOD[with fuel oxygen heat as like triangle]",
},
// production rules
{ "s:ADULTS -> v:DAILY_TASKS",
"s:ADULTS -> v:LOCOMOTION",
"s:ADULTS -> v:DANGEROUS",
"s:URCHINS -> v:DAILY_TASKS",
"s:URCHINS -> v:LOCOMOTION",
"s:CAVIES -> v:CREEP",
"s:CLAN -> v:is feeling",
"s:Terry the Terror Bird -> v:steals",
"s:A rock -> v:ROCKS",
"s:CLAN -> v:likes",
"s:CLAN -> v:not like",
"v:is -> o:a troglodyte",
"v:is feeling -> o:EMOTION",
"v:hunts -> o:PREY",
"v:scavenges -> o:CARRION",
"v:gathers -> o:GATHERED",
"v:gathers -> p:using a stick",
"v:makes -> o:STONE_TOOLS_MADE",
"v:builds -> o:a fire",
"v:eats -> o:FOOD",
"v:grinds -> o:GRINDING_FOOD",
"v:cooks -> o:COOKING_FOOD",
"v:steals -> o:LOOT",
"v:LOCOMOTION -> o:DEST",
"v:likes -> o:ART",
"v:not like -> o:ART",
"o:PREY -> p:WHEN",
"o:PREY -> p:WITH_WEAPON",
"o:GATHERED -> p:WHEN",
"o:grubs -> p:using a stick",
"o:termites -> p:with a stalk of grass",
"o:a fire -> p:FIRE_METHOD",
}
};
bool add_stone_tools(Grammar &g)
{
STONE_TOOL first = STONE_TOOL((int)STONE_TOOL_UNKNOWN + 1);
STONE_TOOL numof = NUMOF_STONE_TOOLS;
STONE_TOOL made[] =
{
STONE_TOOL_HAMMERSTONE, STONE_TOOL_FLAKE, STONE_TOOL_HAND_AXE,
STONE_TOOL_BLADE, STONE_TOOL_POINT, STONE_TOOL_AWL,
STONE_TOOL_SCRAPPER, STONE_TOOL_BURIN,
STONE_TOOL_UNKNOWN
};
STONE_TOOL grind[] =
{
STONE_TOOL_QUERN, STONE_TOOL_MULLER, STONE_TOOL_UNKNOWN
};
STONE_TOOL discard[] = {STONE_TOOL_CORE, STONE_TOOL_UNKNOWN};
//StrVec names;
StrVec vec;
int tool;
//for(tool=first; tool<numof; ++tool)
//{
// names.push_back(name_of_stone_tool((STONE_TOOL)tool));
//}
//if( !g.add_symbol(Grammar::ESVO::SUBJECT, "STONE_TOOLS", names) )
//{
// return false;
//}
for(tool=0; made[tool]!=STONE_TOOL_UNKNOWN; ++tool)
{
vec.push_back(name_of_stone_tool(made[tool]));
}
if( !g.add_symbol(Grammar::ESVO::OBJECT, "STONE_TOOLS_MADE", vec) )
{
return false;
}
return true;
}
bool add_fire(Grammar &g)
{
int way;
StrVec methods;
for(way=0; way<num_ways_me_get_fire(); ++way)
{
methods.push_back(me_get_fire(way));
}
if( !g.add_symbol(Grammar::ESVO::PVP, "FIRE_METHOD", methods) )
{
return false;
}
return true;
}
} // namespace troglodese
} // namespace clan
| 28.387755
| 79
| 0.550324
|
roadnarrows-robotics
|
509162b1e05af53522a2ceacc5e9f25212b7add7
| 1,862
|
hpp
|
C++
|
Simple++/MemoryAllocation.hpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
Simple++/MemoryAllocation.hpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
Simple++/MemoryAllocation.hpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
MemoryAllocation::MemoryAllocation( void ) {
}
MemoryAllocation::MemoryAllocation( unsigned long memoryAddress, unsigned long memorySize, const StringASCII & allocationFileName, unsigned int lineNumber ) {
this -> memoryAddress = memoryAddress;
this -> memorySize = memorySize;
this -> allocationFileName = allocationFileName;
this -> allocationLineNumber = lineNumber;
this -> bAllocated = true;
}
MemoryAllocation::~MemoryAllocation( void ) {
}
void MemoryAllocation::setAllocationFileName( const StringASCII & fileName ) {
this -> allocationFileName = fileName;
}
void MemoryAllocation::setAllocationLineNumber( int lineNumber ) {
this -> allocationFileName = lineNumber;
}
void MemoryAllocation::setDeleteFileName( const StringASCII & fileName ) {
this -> deleteFileName = fileName;
}
void MemoryAllocation::setDeleteLineNumber( int lineNumber ) {
this -> deleteLineNumber = lineNumber;
}
void MemoryAllocation::setMemoryAddress( unsigned long long address ) {
this -> memoryAddress = address;
}
void MemoryAllocation::setMemorySize( unsigned long long size ) {
this -> memorySize = size;
}
const StringASCII & MemoryAllocation::getAllocationFileName() const {
return this -> allocationFileName;
}
int MemoryAllocation::getAllocationLineNumber() const {
return this -> allocationLineNumber;
}
const StringASCII & MemoryAllocation::getDeleteFileName() const {
return this -> deleteFileName;
}
int MemoryAllocation::getDeleteLineNumber() const {
return this -> deleteLineNumber;
}
unsigned long long MemoryAllocation::getMemoryAddress() const {
return this -> memoryAddress;
}
unsigned long long MemoryAllocation::getMemorySize() const {
return this -> memorySize;
}
bool MemoryAllocation::isAllocated() const {
return this -> bAllocated;
}
void MemoryAllocation::setAllocated( bool value ) {
this -> bAllocated = value;
}
| 25.861111
| 158
| 0.767991
|
Oriode
|
5092b7a93fb0f11d68b4be55fba304143508ec79
| 3,454
|
cc
|
C++
|
homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc
|
padomu/NPDECODES
|
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
|
[
"MIT"
] | 15
|
2019-04-29T11:28:56.000Z
|
2022-03-22T05:10:58.000Z
|
homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc
|
padomu/NPDECODES
|
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
|
[
"MIT"
] | 12
|
2020-02-29T15:05:58.000Z
|
2022-02-21T13:51:07.000Z
|
homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc
|
padomu/NPDECODES
|
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
|
[
"MIT"
] | 26
|
2020-01-09T15:59:23.000Z
|
2022-03-24T16:27:33.000Z
|
/**
* @file
* @brief NPDE homework NonConformingCrouzeixRaviartFiniteElements code
* @author Anian Ruoss
* @date 18.03.2019
* @copyright Developed at ETH Zurich
*/
#include <gtest/gtest.h>
#include <lf/base/base.h>
#include <lf/mesh/mesh.h>
#include <lf/mesh/test_utils/test_meshes.h>
#include <Eigen/Core>
#include "../crfespace.h"
#include "../crl2errordirichletbvp.h"
using namespace NonConformingCrouzeixRaviartFiniteElements;
TEST(CRReferenceFiniteElement, RefEl) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_TRUE(cr_ref_el.RefEl() == lf::base::RefEl::kTria());
}
TEST(CRReferenceFiniteElement, Degree) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_EQ(cr_ref_el.Degree(), 1);
}
TEST(CRReferenceFiniteElement, NumRefShapeFunctions) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(), 3);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(0), 0);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1), 1);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(2), 0);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 0), 1);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 1), 1);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 2), 1);
}
TEST(CRReferenceFiniteElement, EvalReferenceShapeFunctions) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd ref_coords(2, 3);
ref_coords << 0, 1, 2, 3, 4, 5;
Eigen::MatrixXd ref_fun_evals(3, 3);
ref_fun_evals << -5, -7, -9, 5, 9, 13, 1, -1, -3;
EXPECT_EQ(cr_ref_el.EvalReferenceShapeFunctions(ref_coords), ref_fun_evals);
}
TEST(CRReferenceFiniteElement, GradientsReferenceShapeFunctions) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd ref_coords(2, 3);
ref_coords << 0, 1, 2, 3, 4, 5;
Eigen::MatrixXd ref_fun_grads(3, 6);
ref_fun_grads << 0, -2, 0, -2, 0, -2, 2, 2, 2, 2, 2, 2, -2, 0, -2, 0, -2, 0;
EXPECT_EQ(cr_ref_el.GradientsReferenceShapeFunctions(ref_coords),
ref_fun_grads);
}
TEST(CRReferenceFiniteElement, EvaluationNodes) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd eval_nodes(2, 3);
eval_nodes << .5, .5, 0, 0, .5, .5;
EXPECT_EQ(cr_ref_el.EvaluationNodes(), eval_nodes);
}
TEST(CRReferenceFiniteElement, NumEvaluationNodes) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_EQ(cr_ref_el.NumEvaluationNodes(), 3);
}
TEST(CRReferenceFiniteElement, NodalValuesToDofs) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd nodvals(1, 3);
nodvals << 0, 1, 2;
EXPECT_EQ(cr_ref_el.NodalValuesToDofs(nodvals), nodvals);
}
TEST(CRFeSpace, Constructor) {
std::shared_ptr<lf::mesh::Mesh> mesh_ptr =
lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);
CRFeSpace fe_space(mesh_ptr);
EXPECT_EQ(fe_space.ShapeFunctionLayout(lf::base::RefEl::kSegment()), nullptr);
EXPECT_EQ(typeid(*(fe_space.ShapeFunctionLayout(lf::base::RefEl::kTria()))),
typeid(CRReferenceFiniteElement));
EXPECT_EQ(fe_space.ShapeFunctionLayout(lf::base::RefEl::kQuad()), nullptr);
}
TEST(NonConformingCrouzeixRaviartFiniteElements,
L2errorCRDiscretizationDirichletBVP) {
std::vector<double> l2_errors = {0.0227969, 0.00579489, 0.0014546923,
0.000364046};
// Loop over meshes
for (int i = 1; i <= 4; ++i) {
std::string mesh_file = CURRENT_SOURCE_DIR "/../../meshes/refined_square" +
std::to_string(i) + ".msh";
EXPECT_FLOAT_EQ(L2errorCRDiscretizationDirichletBVP(mesh_file),
l2_errors[i - 1]);
}
}
| 30.034783
| 80
| 0.718587
|
padomu
|
5092c1c3cc00fc3ec505ba5fe0f40c04f6f003dd
| 1,891
|
hpp
|
C++
|
lab_4/matrixline_methods.hpp
|
DrStarland/bmstu_AA_2020
|
acbb0c76d5763c06db0230025423e0fbb4382a9f
|
[
"Apache-2.0"
] | null | null | null |
lab_4/matrixline_methods.hpp
|
DrStarland/bmstu_AA_2020
|
acbb0c76d5763c06db0230025423e0fbb4382a9f
|
[
"Apache-2.0"
] | null | null | null |
lab_4/matrixline_methods.hpp
|
DrStarland/bmstu_AA_2020
|
acbb0c76d5763c06db0230025423e0fbb4382a9f
|
[
"Apache-2.0"
] | null | null | null |
#ifndef MATRIXLINE_METHODS_HPP
#define MATRIXLINE_METHODS_HPP
#include "matrix.h"
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(size_t len) : MatrixLine(len, nullptr) {}
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(MatrixLine &©) { this->_move(std::move(copy)); }
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(const MatrixLine ©) : MatrixLine(copy.m_len, ©) {}
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(size_t n, const MatrixLine* source) {
this->m_len = n, this->alloc_ptr();
if (source != nullptr)
for (size_t i = 0; i < this->m_len; i++)
this->m_ptr[i] = source->m_ptr[i];
}
template <typename T>
void Matrix<T>::MatrixLine::alloc_ptr() {
T* temp = new (std::nothrow) T[m_len];
time_t _time = time(NULL);
if (!temp)
throw MemoryException(__FILE__, typeid(*this).name(), __LINE__, ctime(&_time));
m_ptr = shared_ptr<T[]> (temp);
}
template <typename T>
typename Matrix<T>::MatrixLine& Matrix<T>::MatrixLine::operator=(MatrixLine&& copy) {
this->_move(std::move(copy));
return *this;
}
template <typename T>
T& Matrix<T>::MatrixLine::operator[](size_t ind) {
time_t _time = time(NULL);
if (this->m_len <= ind)
throw IndexException(__FILE__, typeid(*this).name(), __LINE__, ctime(&_time));
return this->m_ptr[ind];
}
template <typename T>
const T& Matrix<T>::MatrixLine::operator[](size_t ind) const {
time_t _time = time(NULL);
if (this->m_len <= ind)
throw IndexException(__FILE__, typeid(*this).name(), __LINE__, ctime(&_time));
return this->m_ptr[ind];
}
template <typename T>
void Matrix<T>::MatrixLine::_move(MatrixLine &©) {
this->m_len = copy.m_len, this->m_ptr = copy.m_ptr;
copy.m_ptr = nullptr, copy.m_len = 0;
}
#endif // MATRIXLINE_METHODS_HPP
| 32.603448
| 93
| 0.649392
|
DrStarland
|
50a14eb15659a1a668e106113a140777c86b501d
| 5,979
|
cpp
|
C++
|
test/android/jni.cpp
|
10110111/GLFFT
|
78176d4480bc3675327bf2bcfd80d5dae1820081
|
[
"MIT"
] | 176
|
2015-08-17T20:47:10.000Z
|
2022-03-30T09:14:33.000Z
|
test/android/jni.cpp
|
10110111/GLFFT
|
78176d4480bc3675327bf2bcfd80d5dae1820081
|
[
"MIT"
] | 6
|
2017-09-21T15:55:44.000Z
|
2020-11-07T03:15:44.000Z
|
test/android/jni.cpp
|
10110111/GLFFT
|
78176d4480bc3675327bf2bcfd80d5dae1820081
|
[
"MIT"
] | 28
|
2016-02-28T04:37:50.000Z
|
2022-02-27T12:35:55.000Z
|
/* Copyright (C) 2015 Hans-Kristian Arntzen <maister@archlinux.us>
*
* 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 "glfft_gl_interface.hpp"
#include "glfft_context.hpp"
#include "glfft_cli.hpp"
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "net_themaister_glfft_Native.h"
#include <memory>
#include <vector>
using namespace GLFFT;
using namespace std;
struct AndroidEGLContext : GLContext
{
EGLContext ctx = EGL_NO_CONTEXT;
EGLSurface surf = EGL_NO_SURFACE;
EGLDisplay dpy = EGL_NO_SURFACE;
EGLConfig conf = 0;
~AndroidEGLContext()
{
if (dpy)
{
teardown();
eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (ctx)
eglDestroyContext(dpy, ctx);
if (surf)
eglDestroySurface(dpy, surf);
eglTerminate(dpy);
}
}
};
unique_ptr<Context> GLFFT::create_cli_context()
{
unique_ptr<AndroidEGLContext> egl(new AndroidEGLContext);
static const EGLint attr[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 0,
EGL_DEPTH_SIZE, 0,
EGL_STENCIL_SIZE, 0,
EGL_NONE,
};
static const EGLint context_attr[] = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL_NONE,
};
static const EGLint surface_attr[] = {
EGL_WIDTH, 64,
EGL_HEIGHT, 64,
EGL_NONE,
};
egl->dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (egl->dpy == EGL_NO_DISPLAY)
{
egl->log("Failed to create display.\n");
return nullptr;
}
eglInitialize(egl->dpy, nullptr, nullptr);
EGLint num_configs = 0;
eglChooseConfig(egl->dpy, attr, &egl->conf, 1, &num_configs);
if (num_configs != 1)
{
egl->log("Failed to get EGL config.\n");
return nullptr;
}
egl->ctx = eglCreateContext(egl->dpy, egl->conf, EGL_NO_CONTEXT, context_attr);
if (egl->ctx == EGL_NO_CONTEXT)
{
egl->log("Failed to create GLES context.\n");
return nullptr;
}
egl->surf = eglCreatePbufferSurface(egl->dpy, egl->conf, surface_attr);
if (egl->surf == EGL_NO_SURFACE)
{
egl->log("Failed to create Pbuffer surface.\n");
return nullptr;
}
if (!eglMakeCurrent(egl->dpy, egl->surf, egl->surf, egl->ctx))
{
egl->log("Failed to make EGL context current.\n");
return nullptr;
}
const char *version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
unsigned major = 0, minor = 0;
sscanf(version, "OpenGL ES %u.%u", &major, &minor);
unsigned ctx_version = major * 1000 + minor;
if (ctx_version < 3001)
{
egl->log("OpenGL ES 3.1 not supported (got %u.%u context).\n",
major, minor);
return nullptr;
}
egl->log("Version: %s\n", version);
return unique_ptr<Context>(move(egl));
}
void glfft_log(const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
__android_log_vprint(ANDROID_LOG_INFO, "GLFFT", fmt, va);
va_end(va);
#ifdef GLFFT_CLI_ASYNC
char buffer[16 * 1024];
va_start(va, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, va);
GLFFT::get_async_task()->push_message(buffer);
#endif
}
static int start_task(const vector<const char*> &argv)
{
GLFFT::set_async_task([argv] {
return GLFFT::cli_main(
GLFFT::get_async_context(),
argv.size() - 1, (char**)argv.data());
});
GLFFT::get_async_task()->start();
return 0;
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_beginRunTestSuiteTask(JNIEnv *, jclass)
{
vector<const char*> argv = {
"glfft_cli",
"test",
"--test-all",
nullptr,
};
return start_task(argv);
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_beginBenchTask
(JNIEnv *, jclass)
{
vector<const char*> argv = {
"glfft_cli",
"bench",
"--width",
"2048",
"--height",
"2048",
"--fp16",
nullptr,
};
return start_task(argv);
}
JNIEXPORT jstring JNICALL Java_net_themaister_glfft_Native_pull
(JNIEnv *env, jclass)
{
string str;
auto *task = GLFFT::get_async_task();
bool ret = task->pull(str);
return ret ? env->NewStringUTF(str.c_str()) : nullptr;
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_getExitCode
(JNIEnv *, jclass)
{
auto *task = GLFFT::get_async_task();
return task->get_exit_code();
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_isComplete
(JNIEnv *, jclass)
{
auto *task = GLFFT::get_async_task();
return task->is_completed();
}
JNIEXPORT void JNICALL Java_net_themaister_glfft_Native_endTask
(JNIEnv *, jclass)
{
GLFFT::end_async_task();
}
| 26.811659
| 129
| 0.646596
|
10110111
|
50a3fa8ab19998e82f47f1c1c383e3b87fac989a
| 1,752
|
hpp
|
C++
|
src/ScreenServer.hpp
|
RobinSinghNanda/Home-assistant-display
|
6f59104012c0956b54d4b55e190aa89941c2c1af
|
[
"MIT"
] | 2
|
2020-10-23T19:53:56.000Z
|
2020-11-06T08:59:48.000Z
|
src/ScreenServer.hpp
|
RobinSinghNanda/Home-assistant-display
|
6f59104012c0956b54d4b55e190aa89941c2c1af
|
[
"MIT"
] | null | null | null |
src/ScreenServer.hpp
|
RobinSinghNanda/Home-assistant-display
|
6f59104012c0956b54d4b55e190aa89941c2c1af
|
[
"MIT"
] | null | null | null |
#ifndef __SCREENSERVER_H__
#define __SCREENSERVER_H__
#include "Arduino.h"
#include "TFT_eSPI.h"
//====================================================================================
// Definitions
//====================================================================================
#define PIXEL_TIMEOUT 100 // 100ms Time-out between pixel requests
#define START_TIMEOUT 10000 // 10s Maximum time to wait at start transfer
#define BITS_PER_PIXEL 16 // 24 for RGB colour format, 16 for 565 colour format
// File names must be alpha-numeric characters (0-9, a-z, A-Z) or "/" underscore "_"
// other ascii characters are stripped out by client, including / generates
// sub-directories
#define DEFAULT_FILENAME "tft_screenshots/screenshot" // In case none is specified
#define FILE_TYPE "png" // jpg, bmp, png, tif are valid
// Filename extension
// '#' = add incrementing number, '@' = add timestamp, '%' add millis() timestamp,
// '*' = add nothing
// '@' and '%' will generate new unique filenames, so beware of cluttering up your
// hard drive with lots of images! The PC client sketch is set to limit the number of
// saved images to 1000 and will then prompt for a restart.
#define FILE_EXT '@'
// Number of pixels to send in a burst (minimum of 1), no benefit above 8
// NPIXELS values and render times:
// NPIXELS 1 = use readPixel() = >5s and 16 bit pixels only
// NPIXELS >1 using rectRead() 2 = 1.75s, 4 = 1.68s, 8 = 1.67s
#define NPIXELS 8 // Must be integer division of both TFT width and TFT height
bool screenServer(void);
bool screenServer(String filename);
bool serialScreenServer(String filename);
void sendParameters(String filename);
#endif // __SCREENSERVER_H__
| 42.731707
| 86
| 0.639269
|
RobinSinghNanda
|
50a45c4fbd2c43884473a27479cb5a6ba43ee08e
| 2,841
|
cpp
|
C++
|
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/tv/CTvStreamConfigBuilder.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 7
|
2017-07-13T10:34:54.000Z
|
2021-04-16T05:40:35.000Z
|
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/tv/CTvStreamConfigBuilder.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | null | null | null |
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/tv/CTvStreamConfigBuilder.cpp
|
jingcao80/Elastos
|
d0f39852356bdaf3a1234743b86364493a0441bc
|
[
"Apache-2.0"
] | 9
|
2017-07-13T12:33:20.000Z
|
2021-06-19T02:46:48.000Z
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/media/tv/CTvStreamConfigBuilder.h"
#include "elastos/droid/media/tv/CTvStreamConfig.h"
using Elastos::Core::CInteger32;
namespace Elastos {
namespace Droid {
namespace Media {
namespace Tv {
CAR_INTERFACE_IMPL(CTvStreamConfigBuilder, Object, ITvStreamConfigBuilder)
CAR_OBJECT_IMPL(CTvStreamConfigBuilder)
CTvStreamConfigBuilder::CTvStreamConfigBuilder()
{
}
CTvStreamConfigBuilder::~CTvStreamConfigBuilder()
{
}
ECode CTvStreamConfigBuilder::constructor()
{
return NOERROR;
}
ECode CTvStreamConfigBuilder::StreamId(
/* [in] */ Int32 streamId)
{
return CInteger32::New(streamId, (IInteger32**)&mStreamId);
}
ECode CTvStreamConfigBuilder::Type(
/* [in] */ Int32 type)
{
return CInteger32::New(type, (IInteger32**)&mType);
}
ECode CTvStreamConfigBuilder::MaxWidth(
/* [in] */ Int32 maxWidth)
{
return CInteger32::New(maxWidth, (IInteger32**)&mMaxWidth);
}
ECode CTvStreamConfigBuilder::MaxHeight(
/* [in] */ Int32 maxHeight)
{
return CInteger32::New(maxHeight, (IInteger32**)&mMaxHeight);
}
ECode CTvStreamConfigBuilder::Generation(
/* [in] */ Int32 generation)
{
return CInteger32::New(generation, (IInteger32**)&mGeneration);
}
ECode CTvStreamConfigBuilder::Build(
/* [out] */ ITvStreamConfig** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
if (mStreamId == NULL || mType == NULL || mMaxWidth == NULL
|| mMaxHeight == NULL || mGeneration == NULL) {
// throw new UnsupportedOperationException();
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
AutoPtr<CTvStreamConfig> config;
CTvStreamConfig::NewByFriend((CTvStreamConfig**)&config);
mStreamId->GetValue(&config->mStreamId);
mType->GetValue(&config->mType);
mMaxWidth->GetValue(&config->mMaxWidth);
mMaxHeight->GetValue(&config->mMaxHeight);
mGeneration->GetValue(&config->mGeneration);
*result = ITvStreamConfig::Probe(config);
REFCOUNT_ADD(*result)
return NOERROR;
}
} // namespace Tv
} // namespace Media
} // namepsace Droid
} // namespace Elastos
| 28.128713
| 75
| 0.67969
|
jingcao80
|
50a62b87724180c6555f2d0fdc10c3b01f22255d
| 2,388
|
cpp
|
C++
|
dia/ParserEditorUndoCommand.cpp
|
BKEngine/Creator
|
5cc08fb828866cfa970951a14e41c38ecd471a8d
|
[
"CNRI-Python"
] | 25
|
2016-11-20T15:33:09.000Z
|
2022-02-22T09:35:20.000Z
|
dia/ParserEditorUndoCommand.cpp
|
BKEngine/Creator
|
5cc08fb828866cfa970951a14e41c38ecd471a8d
|
[
"CNRI-Python"
] | 3
|
2017-05-25T23:19:44.000Z
|
2019-07-10T02:18:58.000Z
|
dia/ParserEditorUndoCommand.cpp
|
BKEngine/Creator
|
5cc08fb828866cfa970951a14e41c38ecd471a8d
|
[
"CNRI-Python"
] | 8
|
2016-12-23T22:40:04.000Z
|
2021-08-09T04:43:11.000Z
|
#include "ParserEditorUndoCommand.h"
#include "ParserEditorTreeModel.h"
#include "ParserEditorTreeItem.h"
InsertRowsCommand::InsertRowsCommand(ParserEditorTreeModel *model, int row, int count, const QModelIndex &parent)
: model(model)
, row(row)
, count(count)
, parent(parent)
{
}
void InsertRowsCommand::undo()
{
model->removeRowsInternal(row, count, parent);
}
void InsertRowsCommand::redo()
{
model->insertRowsInternal(row, count, parent);
}
RemoveRowsCommand::RemoveRowsCommand(ParserEditorTreeModel *model, int row, int count, const QModelIndex &parent)
: model(model)
, row(row)
, count(count)
, parent(parent)
{
items = model->itemsForRows(row, count, parent);
for (auto &&item : items)
{
item = item->duplicate();
}
}
RemoveRowsCommand::~RemoveRowsCommand()
{
qDeleteAll(items);
}
void RemoveRowsCommand::undo()
{
QList<ParserEditorTreeItem *> items;
for (auto item : this->items)
{
items << item->duplicate();
}
model->insertDataInternal(row, items, parent);
}
void RemoveRowsCommand::redo()
{
model->removeRowsInternal(row, count, parent);
}
InsertDataCommand::InsertDataCommand(ParserEditorTreeModel * model, int row, const QList<ParserEditorTreeItem*>& items, const QModelIndex & parent)
: model(model)
, row(row)
, items(items)
, parent(parent)
{
}
InsertDataCommand::~InsertDataCommand()
{
qDeleteAll(items);
}
void InsertDataCommand::undo()
{
model->removeRowsInternal(row, items.count(), parent);
}
void InsertDataCommand::redo()
{
QList<ParserEditorTreeItem *> items;
for (auto item : this->items)
{
items << item->duplicate();
}
model->insertDataInternal(row, items, parent);
}
ModifyDataCommand::ModifyDataCommand(ParserEditorTreeModel *model, const QModelIndex &index, const QVariant &data)
: model(model)
, index(index)
, data(data)
{
oldData = model->data(index, Qt::DisplayRole);
}
void ModifyDataCommand::undo()
{
model->setDataInternal(index, oldData);
}
void ModifyDataCommand::redo()
{
model->setDataInternal(index, data);
}
ChangeTypeCommand::ChangeTypeCommand(ParserEditorTreeModel *model, const QModelIndex &index, const QVariant &data)
: model(model)
, index(index)
, data(data)
{
item = model->item(index)->duplicate();
}
ChangeTypeCommand::~ChangeTypeCommand()
{
delete item;
}
void ChangeTypeCommand::undo()
{
}
void ChangeTypeCommand::redo()
{
model->setDataInternal(index, data);
}
| 19.258065
| 147
| 0.730318
|
BKEngine
|
50ad8d9aaf234fe34a638dc709ead023c6ee48dd
| 6,631
|
cc
|
C++
|
src/image-utils.cc
|
kyawakyawa/image-utils
|
af1ab717da7934555f701067f1d69077a69c35b0
|
[
"MIT"
] | null | null | null |
src/image-utils.cc
|
kyawakyawa/image-utils
|
af1ab717da7934555f701067f1d69077a69c35b0
|
[
"MIT"
] | null | null | null |
src/image-utils.cc
|
kyawakyawa/image-utils
|
af1ab717da7934555f701067f1d69077a69c35b0
|
[
"MIT"
] | null | null | null |
/*
MIT License
Copyright (c) 2020 kyawakyawa
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 "image-utils.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
#if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include)
#if __has_include(<filesystem>)
#define GHC_USE_STD_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif
#endif
#ifndef GHC_USE_STD_FS
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#endif
#include "stb_image.h"
#include "stb_image_write.h"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
namespace image_utils {
template <typename T>
static T sRGBToLiner(const T c_srgb) {
T c_liner;
if (c_srgb <= static_cast<T>(0.04045)) {
c_liner = c_srgb / static_cast<T>(12.92);
} else {
const T a = static_cast<T>(0.055);
c_liner =
std::pow((c_srgb + a) / (static_cast<T>(1.0) + a), static_cast<T>(2.4));
}
return c_liner;
}
template <typename T>
static T LinerTosRGB(const T c_liner) {
T c_srgb;
if (c_liner <= static_cast<T>(0.0031308)) {
c_srgb = static_cast<T>(12.92) * c_liner;
} else {
const T a = static_cast<T>(0.055);
c_srgb = std::pow((static_cast<T>(1.0) + a) * c_liner,
static_cast<T>(1.0 / 2.4)) -
a;
}
return c_srgb;
}
template <typename T>
static std::tuple<std::vector<T>, size_t, size_t, size_t> LoadImage(
const std::string& filename) {
// TODO : EXR file
int tmp_w = 0;
int tmp_h = 0;
int tmp_c = 0;
float* pixelf = stbi_loadf(filename.c_str(), &tmp_w, &tmp_h, &tmp_c, 0);
const size_t width = (pixelf != nullptr) ? static_cast<size_t>(tmp_w) : 0;
const size_t height = (pixelf != nullptr) ? static_cast<size_t>(tmp_h) : 0;
const size_t channel = (pixelf != nullptr) ? static_cast<size_t>(tmp_c) : 0;
std::vector<T> ret(width * height * channel);
for (size_t i = 0; i < width * height * channel; i++) {
ret[i] = static_cast<T>(pixelf[i]);
}
stbi_image_free(pixelf);
return std::make_tuple(ret, width, height, channel);
}
template <typename T>
std::tuple<std::vector<T>, size_t, size_t, size_t> LoadAndConvertImage(
const std::string& filename, ConvertOption convert_option) {
auto ret = LoadImage<T>(filename);
std::vector<T>& pixels = std::get<0>(ret);
const size_t width = std::get<1>(ret);
const size_t height = std::get<2>(ret);
const size_t channel = std::get<3>(ret);
const fs::path filepath = filename;
const std::string file_extension = filepath.extension();
const bool is_hdr = (file_extension == ".hdr" || file_extension == ".HDR" ||
file_extension == ".exr" || file_extension == ".EXR");
if (convert_option != ConvertOption::FORCE_NO_CONVERT &&
(!is_hdr || convert_option == ConvertOption::FORCE_CONVERT)) {
std::cerr << "Start sRGBToLiner" << std::endl;
for (size_t i = 0; i < width * height; i++) {
for (size_t c = 0; c < std::min<size_t>(channel, 3); c++) {
pixels[i * channel + c] = sRGBToLiner(pixels[i * channel + c]);
}
}
std::cerr << "End sRGBToLiner" << std::endl;
}
return ret;
}
template std::tuple<std::vector<float>, size_t, size_t, size_t>
LoadAndConvertImage(const std::string& filename, ConvertOption convert_option);
template std::tuple<std::vector<double>, size_t, size_t, size_t>
LoadAndConvertImage(const std::string& filename, ConvertOption convert_option);
template <typename T>
bool WritePNG(std::vector<T> pixels, const size_t width, const size_t height,
const size_t channel, const std::string& filename,
ConvertOption convert_option) {
const fs::path filepath = filename;
const std::string file_extension = filepath.extension();
if (file_extension != ".png" && file_extension != ".PNG") {
std::cerr << "warning! the file extension is not \"png\"" << std::endl;
}
if (pixels.size() == 0 || pixels.size() != width * height * channel) {
std::cerr << "the image data is broken" << std::endl;
return false;
}
if (convert_option != ConvertOption::FORCE_NO_CONVERT) {
std::cerr << "Start LinerTosRGB" << std::endl;
for (size_t i = 0; i < width * height; i++) {
for (size_t c = 0; c < std::min<size_t>(channel, 3); c++) {
pixels[i * channel + c] = LinerTosRGB(pixels[i * channel + c]);
}
}
std::cerr << "Finish LinerTosRGB" << std::endl;
}
std::vector<unsigned char> pixel8(width * height * channel);
for (size_t i = 0; i < width * height * channel; i++) {
pixel8[i] = static_cast<unsigned char>(std::max(
static_cast<T>(0.0),
std::min(static_cast<T>(255.0), pixels[i] * static_cast<T>(256.0))));
}
int ret = stbi_write_png(filename.c_str(), int(width), int(height),
int(channel), pixel8.data(), int(width * channel));
if (!ret) {
std::cerr << "faild save image" << std::endl;
return false;
}
std::cerr << "write png file [ " << filename << " ]" << std::endl;
return true;
}
template bool WritePNG(std::vector<float> pixels, const size_t width,
const size_t height, const size_t channel,
const std::string& filename,
ConvertOption convert_option);
template bool WritePNG(std::vector<double> pixels, const size_t width,
const size_t height, const size_t channel,
const std::string& filename,
ConvertOption convert_option);
} // namespace image_utils
| 32.346341
| 80
| 0.655708
|
kyawakyawa
|
27084f8412eae86805d019686bfd70a04db14971
| 6,627
|
hpp
|
C++
|
dof-mgr/src/Panzer_IntrepidFieldPattern.hpp
|
hillyuan/Panzer
|
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
|
[
"BSD-3-Clause"
] | 1
|
2022-03-22T03:49:50.000Z
|
2022-03-22T03:49:50.000Z
|
dof-mgr/src/Panzer_IntrepidFieldPattern.hpp
|
hillyuan/Panzer
|
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
|
[
"BSD-3-Clause"
] | null | null | null |
dof-mgr/src/Panzer_IntrepidFieldPattern.hpp
|
hillyuan/Panzer
|
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
|
[
"BSD-3-Clause"
] | null | null | null |
// @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#ifndef __Panzer_IntrepidFieldPattern_hpp__
#define __Panzer_IntrepidFieldPattern_hpp__
#include "Panzer_FieldPattern.hpp"
// Trilinos includes
#include "Kokkos_Core.hpp"
#include "Kokkos_DynRankView.hpp"
#include "Intrepid2_Basis.hpp"
#include "Phalanx_KokkosDeviceTypes.hpp"
#include "Teuchos_RCP.hpp"
#include <set>
namespace panzer {
/** This is a derived class that specializes based
* on a single intrepid basis function.
*/
class Intrepid2FieldPattern : public FieldPattern {
public:
Intrepid2FieldPattern(const Teuchos::RCP< Intrepid2::Basis<PHX::Device,double,double> > &intrepidBasis);
virtual int getSubcellCount(int dim) const;
virtual const std::vector<int> & getSubcellIndices(int dim, int cellIndex) const;
virtual int getDimension() const;
virtual shards::CellTopology getCellTopology() const;
virtual void getSubcellClosureIndices(int dim,int cellIndex,std::vector<int> & indices) const;
// static functions for examining shards objects
/** For a given sub cell find the set of sub cells at all dimensions contained
* internally. This is inclusive, so that (dim,subCell) will be in the set.
*
* \param[in] cellTopo Parent cell topology being used.
* \param[in] dim Dimension of sub cell
* \param[in] subCell Ordinal of sub cell at specified dimension
* \param[in,out] closure Set of sub cells associated with specified sub cell.
*
* \note Sub cell dimension and ordinals are inserted into <code>closure</code>.
* Previous information will not be removed.
*/
static void buildSubcellClosure(const shards::CellTopology & cellTopo,unsigned dim,unsigned subCell,
std::set<std::pair<unsigned,unsigned> > & closure);
/** Search a cell topology for sub cells containing a specfic set of nodes.
* This is a downward search (inclusive) from a user specified dimension.
*
* \param[in] cellTopo Parent cell topology being used.
* \param[in] dim Dimension of sub cell
* \param[in] nodes Nodes forming the super set
* \param[in,out] subCells Specific sub cells containing the nodes.
*
* \note Sub cell dimension and ordinals are inserted into <code>subCells</code>.
* Previous information will not be removed.
*/
static void findContainedSubcells(const shards::CellTopology & cellTopo,unsigned dim,
const std::vector<unsigned> & nodes,
std::set<std::pair<unsigned,unsigned> > & subCells);
/** Get the set of nodes making up the user specified sub cells.
*
* \param[in] cellTopo Parent cell topology being used.
* \param[in] dim Dimension of sub cell
* \param[in] subCell Ordinal of sub cell at specified dimension
* \param[in,out] nodes Nodes associated with sub cell.
*/
static void getSubcellNodes(const shards::CellTopology & cellTopo,unsigned dim,unsigned subCell,
std::vector<unsigned> & nodes);
/** \brief Does this field pattern support interpolatory coordinates?
*
* If this method returns true then <code>getInterpolatoryCoordinates</code> will
* succeed, otherwise it will throw.
*
* \returns True if this pattern supports interpolatory coordinates.
*/
bool supportsInterpolatoryCoordinates() const;
/** Get the local coordinates for this field. This is independent of element
* locations.
*
* \param[in,out] coords Coordinates associated with this field type.
*/
void getInterpolatoryCoordinates(Kokkos::DynRankView<double,PHX::Device> & coords) const;
/** Get the local coordinates for this field.
*
* \param[in] cellVertices Coordinates associated with this field type.
* \param[in,out] coords Coordinates associated with this field type.
*/
void getInterpolatoryCoordinates(const Kokkos::DynRankView<double,PHX::Device> & cellVertices,
Kokkos::DynRankView<double,PHX::Device> & coords) const;
/// Returns the underlying Intrepid2::Basis object
Teuchos::RCP< Intrepid2::Basis<PHX::Device,double,double> > getIntrepidBasis() const;
protected:
Teuchos::RCP< Intrepid2::Basis<PHX::Device,double,double> > intrepidBasis_;
//mutable std::vector<int> subcellIndices_;
mutable std::vector<std::vector<std::vector<int> > > subcellIndicies_;
std::vector<int> empty_;
};
}
#endif
| 43.598684
| 108
| 0.689
|
hillyuan
|
270aff09f7b49dba066873ece2b73065be1fbf58
| 13,021
|
hpp
|
C++
|
include/boost/gil/io/device.hpp
|
sdebionne/gil-reformated
|
7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2
|
[
"BSL-1.0"
] | null | null | null |
include/boost/gil/io/device.hpp
|
sdebionne/gil-reformated
|
7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2
|
[
"BSL-1.0"
] | null | null | null |
include/boost/gil/io/device.hpp
|
sdebionne/gil-reformated
|
7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright 2007-2012 Christian Henning, Andreas Pokorny
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_IO_DEVICE_HPP
#define BOOST_GIL_IO_DEVICE_HPP
#include <boost/gil/detail/mp11.hpp>
#include <boost/gil/io/base.hpp>
#include <cstdio>
#include <memory>
#include <type_traits>
namespace boost {
namespace gil {
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(push)
#pragma warning(disable : 4512) // assignment operator could not be generated
#endif
namespace detail {
template <typename T> struct buff_item {
static const unsigned int size = sizeof(T);
};
template <> struct buff_item<void> { static const unsigned int size = 1; };
/*!
* Implements the IODevice concept c.f. to \ref IODevice required by Image
* libraries like libjpeg and libpng.
*
* \todo switch to a sane interface as soon as there is
* something good in boost. I.E. the IOChains library
* would fit very well here.
*
* This implementation is based on FILE*.
*/
template <typename FormatTag> class file_stream_device {
public:
using format_tag_t = FormatTag;
public:
/// Used to overload the constructor.
struct read_tag {};
struct write_tag {};
///
/// Constructor
///
file_stream_device(const std::string &file_name, read_tag tag = read_tag())
: file_stream_device(file_name.c_str(), tag) {}
///
/// Constructor
///
file_stream_device(const char *file_name, read_tag = read_tag()) {
FILE *file = nullptr;
io_error_if((file = fopen(file_name, "rb")) == nullptr,
"file_stream_device: failed to open file for reading");
_file = file_ptr_t(file, file_deleter);
}
///
/// Constructor
///
file_stream_device(const std::string &file_name, write_tag tag)
: file_stream_device(file_name.c_str(), tag) {}
///
/// Constructor
///
file_stream_device(const char *file_name, write_tag) {
FILE *file = nullptr;
io_error_if((file = fopen(file_name, "wb")) == nullptr,
"file_stream_device: failed to open file for writing");
_file = file_ptr_t(file, file_deleter);
}
///
/// Constructor
///
file_stream_device(FILE *file) : _file(file, file_deleter) {}
FILE *get() { return _file.get(); }
const FILE *get() const { return _file.get(); }
int getc_unchecked() { return std::getc(get()); }
char getc() {
int ch;
io_error_if((ch = std::getc(get())) == EOF,
"file_stream_device: unexpected EOF");
return (char)ch;
}
///@todo: change byte_t* to void*
std::size_t read(byte_t *data, std::size_t count) {
std::size_t num_elements = fread(data, 1, static_cast<int>(count), get());
///@todo: add compiler symbol to turn error checking on and off.
io_error_if(ferror(get()), "file_stream_device: file read error");
// libjpeg sometimes reads blocks in 4096 bytes even when the file is
// smaller than that. return value indicates how much was actually read
// returning less than "count" is not an error
return num_elements;
}
/// Reads array
template <typename T, int N> void read(T (&buf)[N]) {
io_error_if(read(buf, N) < N, "file_stream_device: file read error");
}
/// Reads byte
uint8_t read_uint8() {
byte_t m[1];
read(m);
return m[0];
}
/// Reads 16 bit little endian integer
uint16_t read_uint16() {
byte_t m[2];
read(m);
return (m[1] << 8) | m[0];
}
/// Reads 32 bit little endian integer
uint32_t read_uint32() {
byte_t m[4];
read(m);
return (m[3] << 24) | (m[2] << 16) | (m[1] << 8) | m[0];
}
/// Writes number of elements from a buffer
template <typename T> std::size_t write(const T *buf, std::size_t count) {
std::size_t num_elements = fwrite(buf, buff_item<T>::size, count, get());
// return value indicates how much was actually written
// returning less than "count" is not an error
return num_elements;
}
/// Writes array
template <typename T, std::size_t N> void write(const T (&buf)[N]) {
io_error_if(write(buf, N) < N, "file_stream_device: file write error");
return;
}
/// Writes byte
void write_uint8(uint8_t x) {
byte_t m[1] = {x};
write(m);
}
/// Writes 16 bit little endian integer
void write_uint16(uint16_t x) {
byte_t m[2];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
write(m);
}
/// Writes 32 bit little endian integer
void write_uint32(uint32_t x) {
byte_t m[4];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
m[2] = byte_t(x >> 16);
m[3] = byte_t(x >> 24);
write(m);
}
void seek(long count, int whence = SEEK_SET) {
io_error_if(fseek(get(), count, whence) != 0,
"file_stream_device: file seek error");
}
long int tell() {
long int pos = ftell(get());
io_error_if(pos == -1L, "file_stream_device: file position error");
return pos;
}
void flush() { fflush(get()); }
/// Prints formatted ASCII text
void print_line(const std::string &line) {
std::size_t num_elements =
fwrite(line.c_str(), sizeof(char), line.size(), get());
io_error_if(num_elements < line.size(),
"file_stream_device: line print error");
}
int error() { return ferror(get()); }
private:
static void file_deleter(FILE *file) {
if (file) {
fclose(file);
}
}
private:
using file_ptr_t = std::shared_ptr<FILE>;
file_ptr_t _file;
};
/**
* Input stream device
*/
template <typename FormatTag> class istream_device {
public:
istream_device(std::istream &in) : _in(in) {
// does the file exists?
io_error_if(!in, "istream_device: Stream is not valid.");
}
int getc_unchecked() { return _in.get(); }
char getc() {
int ch;
io_error_if((ch = _in.get()) == EOF, "istream_device: unexpected EOF");
return (char)ch;
}
std::size_t read(byte_t *data, std::size_t count) {
std::streamsize cr = 0;
do {
_in.peek();
std::streamsize c = _in.readsome(reinterpret_cast<char *>(data),
static_cast<std::streamsize>(count));
count -= static_cast<std::size_t>(c);
data += c;
cr += c;
} while (count && _in);
return static_cast<std::size_t>(cr);
}
/// Reads array
template <typename T, int N> void read(T (&buf)[N]) { read(buf, N); }
/// Reads byte
uint8_t read_uint8() {
byte_t m[1];
read(m);
return m[0];
}
/// Reads 16 bit little endian integer
uint16_t read_uint16() {
byte_t m[2];
read(m);
return (m[1] << 8) | m[0];
}
/// Reads 32 bit little endian integer
uint32_t read_uint32() {
byte_t m[4];
read(m);
return (m[3] << 24) | (m[2] << 16) | (m[1] << 8) | m[0];
}
void seek(long count, int whence = SEEK_SET) {
_in.seekg(count, whence == SEEK_SET ? std::ios::beg
: (whence == SEEK_CUR ? std::ios::cur
: std::ios::end));
}
void write(const byte_t *, std::size_t) {
io_error("istream_device: Bad io error.");
}
void flush() {}
private:
std::istream &_in;
};
/**
* Output stream device
*/
template <typename FormatTag> class ostream_device {
public:
ostream_device(std::ostream &out) : _out(out) {}
std::size_t read(byte_t *, std::size_t) {
io_error("ostream_device: Bad io error.");
return 0;
}
void seek(long count, int whence) {
_out.seekp(count,
whence == SEEK_SET
? std::ios::beg
: (whence == SEEK_CUR ? std::ios::cur : std::ios::end));
}
void write(const byte_t *data, std::size_t count) {
_out.write(reinterpret_cast<char const *>(data),
static_cast<std::streamsize>(count));
}
/// Writes array
template <typename T, std::size_t N> void write(const T (&buf)[N]) {
write(buf, N);
}
/// Writes byte
void write_uint8(uint8_t x) {
byte_t m[1] = {x};
write(m);
}
/// Writes 16 bit little endian integer
void write_uint16(uint16_t x) {
byte_t m[2];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
write(m);
}
/// Writes 32 bit little endian integer
void write_uint32(uint32_t x) {
byte_t m[4];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
m[2] = byte_t(x >> 16);
m[3] = byte_t(x >> 24);
write(m);
}
void flush() { _out << std::flush; }
/// Prints formatted ASCII text
void print_line(const std::string &line) { _out << line; }
private:
std::ostream &_out;
};
/**
* Metafunction to detect input devices.
* Should be replaced by an external facility in the future.
*/
template <typename IODevice> struct is_input_device : std::false_type {};
template <typename FormatTag>
struct is_input_device<file_stream_device<FormatTag>> : std::true_type {};
template <typename FormatTag>
struct is_input_device<istream_device<FormatTag>> : std::true_type {};
template <typename FormatTag, typename T, typename D = void>
struct is_adaptable_input_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_adaptable_input_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<std::is_base_of<std::istream, T>,
std::is_same<std::istream, T>>::value>::type>
: std::true_type {
using device_type = istream_device<FormatTag>;
};
template <typename FormatTag>
struct is_adaptable_input_device<FormatTag, FILE *, void> : std::true_type {
using device_type = file_stream_device<FormatTag>;
};
///
/// Metafunction to decide if a given type is an acceptable read device type.
///
template <typename FormatTag, typename T, typename D = void>
struct is_read_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_read_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<is_input_device<FormatTag>,
is_adaptable_input_device<FormatTag, T>>::value>::type>
: std::true_type {};
/**
* Metafunction to detect output devices.
* Should be replaced by an external facility in the future.
*/
template <typename IODevice> struct is_output_device : std::false_type {};
template <typename FormatTag>
struct is_output_device<file_stream_device<FormatTag>> : std::true_type {};
template <typename FormatTag>
struct is_output_device<ostream_device<FormatTag>> : std::true_type {};
template <typename FormatTag, typename IODevice, typename D = void>
struct is_adaptable_output_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_adaptable_output_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<std::is_base_of<std::ostream, T>,
std::is_same<std::ostream, T>>::value>::type>
: std::true_type {
using device_type = ostream_device<FormatTag>;
};
template <typename FormatTag>
struct is_adaptable_output_device<FormatTag, FILE *, void> : std::true_type {
using device_type = file_stream_device<FormatTag>;
};
///
/// Metafunction to decide if a given type is an acceptable read device type.
///
template <typename FormatTag, typename T, typename D = void>
struct is_write_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_write_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<is_output_device<FormatTag>,
is_adaptable_output_device<FormatTag, T>>::value>::type>
: std::true_type {};
} // namespace detail
template <typename Device, typename FormatTag> class scanline_reader;
template <typename Device, typename FormatTag, typename ConversionPolicy>
class reader;
template <typename Device, typename FormatTag, typename Log = no_log>
class writer;
template <typename Device, typename FormatTag> class dynamic_image_reader;
template <typename Device, typename FormatTag, typename Log = no_log>
class dynamic_image_writer;
namespace detail {
template <typename T> struct is_reader : std::false_type {};
template <typename Device, typename FormatTag, typename ConversionPolicy>
struct is_reader<reader<Device, FormatTag, ConversionPolicy>> : std::true_type {
};
template <typename T> struct is_dynamic_image_reader : std::false_type {};
template <typename Device, typename FormatTag>
struct is_dynamic_image_reader<dynamic_image_reader<Device, FormatTag>>
: std::true_type {};
template <typename T> struct is_writer : std::false_type {};
template <typename Device, typename FormatTag>
struct is_writer<writer<Device, FormatTag>> : std::true_type {};
template <typename T> struct is_dynamic_image_writer : std::false_type {};
template <typename Device, typename FormatTag>
struct is_dynamic_image_writer<dynamic_image_writer<Device, FormatTag>>
: std::true_type {};
} // namespace detail
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(pop)
#endif
} // namespace gil
} // namespace boost
#endif
| 25.531373
| 80
| 0.651179
|
sdebionne
|
270e8b3df3b7bd8b52e67cb3eea40f08be838f4c
| 1,135
|
hpp
|
C++
|
e-Paper/src/WiFiHandler.hpp
|
PDA-UR/Dumb-e-Paper
|
99aecce5fbcb64d32b7e47809df393e0e2e7fab4
|
[
"MIT"
] | 2
|
2019-01-30T13:48:14.000Z
|
2021-10-30T16:11:03.000Z
|
e-Paper/src/WiFiHandler.hpp
|
PDA-UR/Dumb-e-Paper
|
99aecce5fbcb64d32b7e47809df393e0e2e7fab4
|
[
"MIT"
] | null | null | null |
e-Paper/src/WiFiHandler.hpp
|
PDA-UR/Dumb-e-Paper
|
99aecce5fbcb64d32b7e47809df393e0e2e7fab4
|
[
"MIT"
] | 2
|
2018-02-14T12:45:59.000Z
|
2021-12-17T20:57:02.000Z
|
#ifndef __WIFIHANDLER_H_INCLUDED__
#define __WIFIHANDLER_H_INCLUDED__
/**
* @defgroup WiFi Handler
*/
/** @addtogroup WiFi Handler */
/*@{*/
#include "main.hpp"
#include <WiFi.h>
#include <WiFiMulti.h>
/**
* @brief Could be anything but must also be changed in python script
*/
const int PORT = 1516;
enum class WiFiStatus
{
WIFI_SUCCESS,
WIFI_ERROR,
WIFI_WAIT,
SHOW_PICTURE_01,
SHOW_PICTURE_02,
CLEAR_SCREEN
};
class WiFiHandler
{
public:
/**
* @brief Start WiFi connection
*
* @param id ssid to connect
* @param password for network
* @return true if WiFi could connect
*/
static bool init(String id, String password);
/**
* @brief Receive data from WiFi and write to buffer
*
* @param buffer gets WiFi data
* @param le buffer length
* @return WiFiStatus
*/
static WiFiStatus handle(byte *buffer, int le);
/**
* @brief Sends "OK" to server, to receive new data
*/
static void requestDataChunk();
private:
static const byte O;
static const byte K;
static char *ip;
};
/*@}*/
#endif
| 17.461538
| 69
| 0.629956
|
PDA-UR
|
2716f46542abf6879e15307467bf50c0275d7865
| 1,125
|
cpp
|
C++
|
t_rex.cpp
|
alexycruz1/proyecto2
|
e4817969d610473d02f2b4c68c69d629ef93bef4
|
[
"MIT"
] | null | null | null |
t_rex.cpp
|
alexycruz1/proyecto2
|
e4817969d610473d02f2b4c68c69d629ef93bef4
|
[
"MIT"
] | null | null | null |
t_rex.cpp
|
alexycruz1/proyecto2
|
e4817969d610473d02f2b4c68c69d629ef93bef4
|
[
"MIT"
] | null | null | null |
#include "dinosaurio.h"
#include "t_rex.h"
#include <string>
#include <sstream>
using std::string;
using std::stringstream;
t_rex::t_rex(string nombre, char genero, int peso, int altura, int esperanza_vida, string era, string territorio, int hambre, int edad):dinosaurio(nombre,genero,peso,altura,esperanza_vida,era,territorio, hambre, edad){}
string t_rex::toString()const{
stringstream temp;
temp<<genero;
temp<<" ";
temp<<peso;
temp<<" ";
temp<<altura;
temp<<" ";
temp<<esperanza_vida;
temp<<" ";
temp<<era;
temp<<" ";
temp<<territorio;
temp<<" ";
temp<<hambre;
temp<<" ";
temp<<edad;
temp<<" ";
temp<<nombre;
temp;
return temp.str();
}
void t_rex::comer(int& comidon){
if(hambre<20){
comidon-=3;
hambre+=3;
}
}
void t_rex::hambrita(){
hambre-=7;
}
bool t_rex::morir(){
if(esperanza_vida==edad || hambre<=0){
return true;
}else{
return false;
}
}
void t_rex::cumple(){
edad+=1;
}
void t_rex::paga(int& dinero,int& semana){
if(semana % 4 == 0){
dinero += 3000;
}
}
| 18.75
| 219
| 0.587556
|
alexycruz1
|
271977f61e3e2b952a3d340389cb5a28802382f2
| 2,378
|
cpp
|
C++
|
src/graphics/backend/depth_pass.cpp
|
NotAPenguin0/Andromeda
|
69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4
|
[
"MIT"
] | 7
|
2020-04-28T11:01:55.000Z
|
2022-02-22T09:59:33.000Z
|
src/graphics/backend/depth_pass.cpp
|
NotAPenguin0/Andromeda
|
69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4
|
[
"MIT"
] | 2
|
2021-09-03T12:58:06.000Z
|
2021-09-20T20:07:33.000Z
|
src/graphics/backend/depth_pass.cpp
|
NotAPenguin0/Andromeda
|
69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4
|
[
"MIT"
] | 1
|
2021-09-03T12:56:25.000Z
|
2021-09-03T12:56:25.000Z
|
#include <andromeda/graphics/backend/depth_pass.hpp>
#include <andromeda/graphics/backend/mesh_draw.hpp>
namespace andromeda::gfx::backend {
void create_depth_only_pipeline(gfx::Context& ctx, VkSampleCountFlagBits samples, float sample_ratio) {
ph::PipelineCreateInfo pci = ph::PipelineBuilder::create(ctx, "depth_only")
.add_shader("data/shaders/depth.vert.spv", "main", ph::ShaderStage::Vertex)
.add_vertex_input(0)
// Note that not all these attributes will be used, but they are specified because the vertex size is deduced from them
.add_vertex_attribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT) // iPos
.add_vertex_attribute(0, 1, VK_FORMAT_R32G32B32_SFLOAT) // iNormal
.add_vertex_attribute(0, 2, VK_FORMAT_R32G32B32_SFLOAT) // iTangent
.add_vertex_attribute(0, 3, VK_FORMAT_R32G32_SFLOAT) // iUV
.add_dynamic_state(VK_DYNAMIC_STATE_SCISSOR)
.add_dynamic_state(VK_DYNAMIC_STATE_VIEWPORT)
.set_depth_test(true)
.set_depth_write(true)
.set_cull_mode(VK_CULL_MODE_BACK_BIT)
.set_samples(samples)
.set_sample_shading(sample_ratio)
.reflect()
.get();
ctx.create_named_pipeline(std::move(pci));
}
ph::Pass build_depth_pass(gfx::Context& ctx, ph::InFlightContext& ifc, std::string_view target, gfx::SceneDescription const& scene, ph::BufferSlice camera, ph::BufferSlice transforms) {
ph::Pass pass = ph::PassBuilder::create("fwd_plus_depth")
.add_depth_attachment(target, ph::LoadOp::Clear, {.depth_stencil = {.depth = 1.0f, .stencil = 0}})
.execute([&ctx, &ifc, &scene, camera, transforms](ph::CommandBuffer& cmd) {
cmd.bind_pipeline("depth_only");
cmd.auto_viewport_scissor();
VkDescriptorSet set = ph::DescriptorBuilder::create(ctx, cmd.get_bound_pipeline())
.add_uniform_buffer("camera", camera)
.add_storage_buffer("transforms", transforms)
.get();
cmd.bind_descriptor_set(set);
for_each_ready_mesh(scene, [&cmd](auto const& _, gfx::Mesh const& mesh, uint32_t index) {
cmd.push_constants(ph::ShaderStage::Vertex, 0, sizeof(uint32_t), &index); // mesh index is also the transform index
bind_and_draw(cmd, mesh);
});
})
.get();
return pass;
}
}
| 48.530612
| 185
| 0.671152
|
NotAPenguin0
|
271a387131255dd1d036ea05cd4a62a2a4d84380
| 11,061
|
cpp
|
C++
|
src/hostif/snmpAdapter/snmpAdapter.cpp
|
rdkcmf/rdk-tr69hostif
|
5d9042b968eca933481e111e352828402732ec26
|
[
"Apache-2.0"
] | 3
|
2018-11-23T05:08:54.000Z
|
2019-10-18T12:52:38.000Z
|
src/hostif/snmpAdapter/snmpAdapter.cpp
|
rdkcmf/rdk-tr69hostif
|
5d9042b968eca933481e111e352828402732ec26
|
[
"Apache-2.0"
] | null | null | null |
src/hostif/snmpAdapter/snmpAdapter.cpp
|
rdkcmf/rdk-tr69hostif
|
5d9042b968eca933481e111e352828402732ec26
|
[
"Apache-2.0"
] | 1
|
2018-08-16T19:15:22.000Z
|
2018-08-16T19:15:22.000Z
|
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2017 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file snmpAdapter.cpp
* @brief This source file contains the APIs for getting device information.
*/
/**
* @file snmpAdapter.cpp
*
* @brief SNMP RDKCENTRAL API Implementation.
*
* This is the implementation of the DeviceInfo API.
*
* @par Document
* TBD Relevant design or API documentation.
*
*/
/*****************************************************************************
* STANDARD INCLUDE FILES
*****************************************************************************/
/**
* @defgroup tr69hostif
* @{
* @defgroup hostif
* @{
**/
#include "snmpAdapter.h"
#include <fstream>
#include "safec_lib.h"
#ifdef YOCTO_BUILD
#include "secure_wrapper.h"
#endif
#define TR181_SNMPOID_FILE "/etc/tr181_snmpOID.conf"
#define SNMP_AGENT_IP_ADDRESS "192.168.100.1" //"127.0.0.1"
#define SNMP_COMMUNITY "hDaFHJG7"
GHashTable* hostIf_snmpAdapter::ifHash = NULL;
GHashTable* hostIf_snmpAdapter::m_notifyHash = NULL;
GMutex* hostIf_snmpAdapter::m_mutex = NULL;
map<string, string> hostIf_snmpAdapter::tr181SNMPMap;
/****************************************************************************************************************************************************/
// Device.X_RDKCENTRAL Profile. Getters:
/****************************************************************************************************************************************************/
/**
* @brief Class Constructor of the class hostIf_snmpAdapter.
*
*/
hostIf_snmpAdapter::hostIf_snmpAdapter(int dev_id):
dev_id(dev_id)
{
}
/**
* @brief Class Destructor of the class hostIf_snmpAdapter.
*
*/
hostIf_snmpAdapter::~hostIf_snmpAdapter()
{
if(m_notifyHash)
{
g_hash_table_destroy(m_notifyHash);
}
}
/**
* @brief This function opens the RF_DocsIf_tr181_snmp map file,
* parse the TR181 parameter and its correspoinding OID, fill it in map container.
*
*/
void hostIf_snmpAdapter::init(void)
{
string line;
ifstream fileStream (TR181_SNMPOID_FILE);
char delimeter[] = " \t\n\r\f\v";
tr181SNMPMap.clear();
if (fileStream.is_open())
{
while(getline(fileStream, line))
{
int pos = line.find('=');
if(pos != string::npos)
{
string key = line.substr(0, pos);
string value = line.substr(pos + 1);
key.erase(0, key.find_first_not_of(delimeter));
key.erase(key.find_last_not_of(delimeter) + 1);
value.erase(0, value.find_first_not_of(delimeter));
value.erase(value.find_last_not_of(delimeter) + 1);
tr181SNMPMap[key] = value;
}
}
}
else
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] Error opening %s fileStream.", __FUNCTION__, __LINE__, TR181_SNMPOID_FILE );
if (!tr181SNMPMap.empty())
{
RDK_LOG(RDK_LOG_DEBUG,LOG_TR69HOSTIF,"[%s] %s count %d\n", __FUNCTION__, TR181_SNMPOID_FILE, tr181SNMPMap.size());
for(map<string, string>::iterator it = tr181SNMPMap.begin(); it != tr181SNMPMap.end(); it++)
RDK_LOG(RDK_LOG_DEBUG,LOG_TR69HOSTIF,"[%s] %s : %s\n", __FUNCTION__, it->first.c_str(), it->second.c_str());
}
}
/**
* @brief This function clear the TR181 OID map container.
*
*/
void hostIf_snmpAdapter::unInit(void)
{
tr181SNMPMap.clear();
}
hostIf_snmpAdapter* hostIf_snmpAdapter::getInstance(int dev_id)
{
hostIf_snmpAdapter* pRet = NULL;
if(ifHash)
pRet = (hostIf_snmpAdapter *)g_hash_table_lookup(ifHash,(gpointer) dev_id);
else
ifHash = g_hash_table_new(NULL,NULL);
if(!pRet)
{
try {
pRet = new hostIf_snmpAdapter(dev_id);
} catch(int e)
{
RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"Caught exception, not able create SNMP Device RDK Central instance..\n");
}
g_hash_table_insert(ifHash, (gpointer)dev_id, pRet);
}
return pRet;
}
GList* hostIf_snmpAdapter::getAllInstances()
{
if(ifHash)
return g_hash_table_get_keys(ifHash);
return NULL;
}
void hostIf_snmpAdapter::closeInstance(hostIf_snmpAdapter *pDev)
{
if(pDev)
{
g_hash_table_remove(ifHash, (gconstpointer)pDev->dev_id);
delete pDev;
}
}
void hostIf_snmpAdapter::closeAllInstances()
{
if(ifHash)
{
GList* tmp_list = g_hash_table_get_values (ifHash);
while(tmp_list)
{
hostIf_snmpAdapter* pDev = (hostIf_snmpAdapter *)tmp_list->data;
tmp_list = tmp_list->next;
closeInstance(pDev);
}
}
}
void hostIf_snmpAdapter::getLock()
{
if(!m_mutex)
{
m_mutex = g_mutex_new();
}
g_mutex_lock(m_mutex);
}
void hostIf_snmpAdapter::releaseLock()
{
g_mutex_unlock(m_mutex);
}
GHashTable* hostIf_snmpAdapter::getNotifyHash()
{
if(m_notifyHash)
return m_notifyHash;
else
return m_notifyHash = g_hash_table_new(g_str_hash, g_str_equal);
}
/**
* @brief This function fetch the SNMP OID for the corresponding TR181 param,
* and run the snmpget command with the OID. The result will be return back as string.
*
*/
int hostIf_snmpAdapter::get_ValueFromSNMPAdapter(HOSTIF_MsgData_t *stMsgData)
{
int ret = NOT_HANDLED;
char cmd[BUFF_LENGTH_256] = { 0 };
char resultBuff[BUFF_LENGTH_256] = { 0 };
char delimeter[] = " \t\n\r\f\v";
map<string,string>::iterator it;
string consoleString("");
errno_t rc = -1;
if(stMsgData)
{
it = tr181SNMPMap.find(stMsgData->paramName);
if (it != tr181SNMPMap.end())
{
snprintf (cmd, BUFF_LENGTH_256, "snmpget -OQ -Ir -v 2c -c %s %s %s",
SNMP_COMMUNITY,
SNMP_AGENT_IP_ADDRESS,
it->second.c_str());
RDK_LOG(RDK_LOG_TRACE1,LOG_TR69HOSTIF,"[%s] %s\n", __FUNCTION__, cmd);
ret = GetStdoutFromCommand( cmd, consoleString);
if (ret == OK)
{
int pos = consoleString.find('=');
if(pos != string::npos)
{
string subStr = consoleString.substr(pos + 1);
subStr.erase(0, subStr.find_first_not_of(delimeter));
subStr.erase(subStr.find_last_not_of(delimeter) + 1);
rc=strcpy_s(stMsgData->paramValue,sizeof(stMsgData->paramValue), subStr.c_str());
if(rc!=EOK)
{
ERR_CHK(rc);
}
}
else
{
rc=strcpy_s(stMsgData->paramValue,sizeof(stMsgData->paramValue), resultBuff);
if(rc!=EOK)
{
ERR_CHK(rc);
}
}
stMsgData->paramtype = hostIf_StringType;
RDK_LOG(RDK_LOG_TRACE1,LOG_TR69HOSTIF,"[%s] %s %s\n", __FUNCTION__, stMsgData->paramName, stMsgData->paramValue);
ret = OK;
}
}
else
{
ret = NOK;
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] %s NOT found in the map.\n", __FUNCTION__, __LINE__, stMsgData->paramName );
}
}
return ret;
}
/**
* @brief This function fetch the SNMP OID for the corresponding TR181 param,
* and run the snmpset command with the OID.
*
*/
int hostIf_snmpAdapter::set_ValueToSNMPAdapter(HOSTIF_MsgData_t *stMsgData)
{
int ret = NOT_HANDLED;
char cmd[BUFF_LENGTH_256] = { 0 };
char resultBuff[BUFF_LENGTH_256] = { 0 };
map<string,string>::iterator it;
#ifdef YOCTO_BUILD
FILE *fp;
#define CMD(cmd, length, args...) ({ snprintf(cmd, length, args); fp = (v_secure_popen("r", args); )})
#else
#define CMD(cmd, length, args...) ({ snprintf(cmd, length, args); })
#endif
if(stMsgData)
{
it = tr181SNMPMap.find(stMsgData->paramName);
if (it != tr181SNMPMap.end())
{
switch(stMsgData->paramtype)
{
case hostIf_StringType:
CMD(cmd, BUFF_LENGTH_256, "snmpset -v 2c -c %s %s %s s %s",
SNMP_COMMUNITY, SNMP_AGENT_IP_ADDRESS,
it->second.c_str(),
stMsgData->paramValue);
break;
case hostIf_IntegerType:
CMD(cmd, BUFF_LENGTH_256, "snmpset -v 2c -c %s %s %s i %d",
SNMP_COMMUNITY, SNMP_AGENT_IP_ADDRESS,
it->second.c_str(),
stMsgData->paramValue);
break;
case hostIf_UnsignedIntType:
CMD(cmd, BUFF_LENGTH_256, "snmpset -v 2c -c %s %s %s u %d",
SNMP_COMMUNITY,
SNMP_AGENT_IP_ADDRESS,
it->second.c_str(),
stMsgData->paramValue);
break;
case hostIf_BooleanType:
case hostIf_DateTimeType:
case hostIf_UnsignedLongType:
default:
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] %s not supported type %d\n", __FUNCTION__, __LINE__, stMsgData->paramName, stMsgData->paramtype);
return NOK;
}
RDK_LOG(RDK_LOG_TRACE1,LOG_TR69HOSTIF,"[%s] %s\n", __FUNCTION__, cmd);
#ifdef YOCTO_BUILD
if (fp == NULL) {
RDK_LOG (RDK_LOG_ERROR, LOG_TR69HOSTIF, "[%s]: cannot run command [%s]\n", __FUNCTION__, cmd);
ret = NOK;
} else if (fgets (resultBuff, BUFF_LENGTH_256, fp) == NULL) {
RDK_LOG (RDK_LOG_ERROR, LOG_TR69HOSTIF, "[%s]: cannot read output from command [%s]\n", __FUNCTION__, cmd);
v_secure_pclose (fp);
ret = NOK;
} else {
ret = v_secure_pclose(fp);
}
RDK_LOG (RDK_LOG_DEBUG, LOG_TR69HOSTIF, "[%s]: command [%s] returned [%s]\n", __FUNCTION__, cmd, resultBuff);
#else
ret = read_command_output (cmd, resultBuff, BUFF_LENGTH_256);
#endif
stMsgData->faultCode = (OK == ret)?fcNoFault:fcRequestDenied;
}
else
{
ret = NOK;
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] %s NOT found in the map.\n", __FUNCTION__,__LINE__, stMsgData->paramName );
}
}
#undef CMD
return ret;
}
/* End of doxygen group */
/**
* @}
*/
/* End of file xxx_api.c. */
/** @} */
/** @} */
| 29.339523
| 163
| 0.574541
|
rdkcmf
|
271a6bb390cdea7444ec97670599d0ec5b539f6f
| 344
|
cpp
|
C++
|
hilbert_mapper/src/hilbert_mapper_node.cpp
|
Jaeyoung-Lim/mav_hilbertmap_planning
|
96df718a04953df3b39f080a7e33565407ad6be1
|
[
"BSD-3-Clause"
] | 4
|
2019-01-16T16:18:16.000Z
|
2019-06-06T14:30:56.000Z
|
hilbert_mapper/src/hilbert_mapper_node.cpp
|
Wayne-xixi/mav_hilbertmap_planning
|
96df718a04953df3b39f080a7e33565407ad6be1
|
[
"BSD-3-Clause"
] | 16
|
2019-01-24T12:44:28.000Z
|
2021-01-08T01:44:41.000Z
|
hilbert_mapper/src/hilbert_mapper_node.cpp
|
Wayne-xixi/mav_hilbertmap_planning
|
96df718a04953df3b39f080a7e33565407ad6be1
|
[
"BSD-3-Clause"
] | 2
|
2020-01-10T09:31:49.000Z
|
2021-01-02T23:25:53.000Z
|
// July/2018, ETHZ, Jaeyoung Lim, jalim@student.ethz.ch
#include "hilbert_mapper/hilbert_mapper.h"
//using namespace RAI;
int main(int argc, char** argv) {
ros::init(argc,argv,"geometric_controller");
ros::NodeHandle nh("");
ros::NodeHandle nh_private("~");
HilbertMapper Hilbertmapper(nh, nh_private);
ros::spin();
return 0;
}
| 22.933333
| 56
| 0.700581
|
Jaeyoung-Lim
|
271cba3e5d38e9e79acafa3f44fabf815445a617
| 422
|
hpp
|
C++
|
src/as3/as3_function_call.hpp
|
sweetkristas/swiftly
|
0b5c2badc88637b8bdaa841a45d1babd8f12a703
|
[
"BSL-1.0",
"Zlib",
"BSD-3-Clause"
] | null | null | null |
src/as3/as3_function_call.hpp
|
sweetkristas/swiftly
|
0b5c2badc88637b8bdaa841a45d1babd8f12a703
|
[
"BSL-1.0",
"Zlib",
"BSD-3-Clause"
] | null | null | null |
src/as3/as3_function_call.hpp
|
sweetkristas/swiftly
|
0b5c2badc88637b8bdaa841a45d1babd8f12a703
|
[
"BSL-1.0",
"Zlib",
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include "as3_object.hpp"
#include "as3_value.hpp"
#include "../swf_environment.hpp"
namespace avm2
{
class function_call
{
public:
function_call();
~function_call();
size_t arg_count() const { return arg_count_; }
as3_value_ptr arg(size_t n) const;
private:
as3_object_ptr this_;
as3_value_ptr result_;
//swf::environment env_;
size_t arg_count_;
swf::stack_iterator arg_iter_;
};
}
| 17.583333
| 49
| 0.727488
|
sweetkristas
|
271f8d927109f5c645a03e80ac2afa4111899984
| 4,779
|
cpp
|
C++
|
test/tbmv.cpp
|
Idein/qmkl6
|
ac3e631ca89293c562db24b78576eef66426ab65
|
[
"BSD-3-Clause"
] | 38
|
2020-09-24T08:46:33.000Z
|
2022-03-23T01:40:03.000Z
|
test/tbmv.cpp
|
Idein/qmkl6
|
ac3e631ca89293c562db24b78576eef66426ab65
|
[
"BSD-3-Clause"
] | 3
|
2021-02-03T08:33:55.000Z
|
2021-08-24T00:04:05.000Z
|
test/tbmv.cpp
|
Idein/qmkl6
|
ac3e631ca89293c562db24b78576eef66426ab65
|
[
"BSD-3-Clause"
] | 6
|
2020-09-24T13:40:19.000Z
|
2021-06-08T19:35:43.000Z
|
#include <algorithm>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <random>
#include <type_traits>
#include "cblasdefs.h"
#include "cxxutils.hpp"
template <typename T>
static void naive_tbmv([[maybe_unused]] const CBLAS_LAYOUT layout,
[[maybe_unused]] const CBLAS_UPLO uplo,
[[maybe_unused]] const CBLAS_TRANSPOSE trans,
[[maybe_unused]] const CBLAS_DIAG diag, const int n,
const int k, const T *const a, const int lda, T *const x,
const int incx) {
if (k != 0) {
std::cerr << "error: We only support diagonal matrices for now"
<< std::endl;
std::exit(EXIT_FAILURE);
}
#pragma omp parallel for default(none) firstprivate(n, a, lda, x, incx) \
schedule(guided)
for (int i = 0; i < n; ++i) x[incx * i] *= a[lda * i];
}
template <typename T,
typename std::enable_if_t<std::is_same<T, float>{}, bool> = true>
static void cblas_tbmv(const CBLAS_LAYOUT layout, const CBLAS_UPLO uplo,
const CBLAS_TRANSPOSE trans, const CBLAS_DIAG diag,
const int n, const int k, const T *const a,
const int lda, T *const x, const int incx) {
cblas_stbmv(layout, uplo, trans, diag, n, k, a, lda, x, incx);
}
template <typename T, typename std::enable_if_t<
std::is_same<T, std::complex<float>>{}, bool> = true>
static void cblas_tbmv(const CBLAS_LAYOUT layout, const CBLAS_UPLO uplo,
const CBLAS_TRANSPOSE trans, const CBLAS_DIAG diag,
const int n, const int k, const T *const a,
const int lda, T *const x, const int incx) {
cblas_ctbmv(layout, uplo, trans, diag, n, k, a, lda, x, incx);
}
template <typename T, class Generator>
static int test_tbmv_diag_single(const int n, const int lda, const int incx,
Generator &gen) {
T *a, *x0, *x1;
uniform_distribution<T> dist;
printf("%stbmv: n = %5d, lda = %5d, incx = %d: ", blas_prefix<T>(), n, lda,
incx);
a = (T *)mkl_malloc(n * lda * sizeof(T), 64);
std::generate(a, a + n * lda, std::bind(dist, gen));
x0 = (T *)malloc((1 + (n - 1) * incx) * sizeof(T));
x1 = (T *)mkl_malloc((1 + (n - 1) * incx) * sizeof(T), 64);
std::generate(x0, x0 + (1 + (n - 1) * incx), std::bind(dist, gen));
memcpy(x1, x0, (1 + (n - 1) * incx) * sizeof(T));
const double start0 = dsecnd();
naive_tbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, n, 0, a,
lda, x0, incx);
const double t0 = dsecnd() - start0;
const double start1 = dsecnd();
cblas_tbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, n, 0, a,
lda, x1, incx);
const double t1 = dsecnd() - start1;
using error_type = decltype(std::abs(T()));
error_type err_abs_min = std::numeric_limits<error_type>::infinity(),
err_abs_max = -std::numeric_limits<error_type>::infinity(),
err_rel_min = std::numeric_limits<error_type>::infinity(),
err_rel_max = -std::numeric_limits<error_type>::infinity();
for (int i = 0; i < n; ++i) {
const T err = x0[incx * i] - x1[incx * i];
const error_type err_abs = std::abs(err),
err_rel = std::abs(err / x0[incx * i]);
err_abs_min = std::min(err_abs_min, err_abs);
err_abs_max = std::max(err_abs_max, err_abs);
err_rel_min = std::min(err_rel_min, err_rel);
err_rel_max = std::max(err_rel_max, err_rel);
}
printf(
"err_abs = [%f, %f], "
"err_rel = [%f, %f], "
"%f sec -> %f sec, "
"%f Mflop/s -> %f Mflop/s\n",
err_abs_min, err_abs_max, err_rel_min, err_rel_max, t0, t1, n / t0 * 1e-6,
n / t1 * 1e-6);
if (err_rel_max > 1e-3) {
std::cerr << "error: Absolute error is too large" << std::endl;
return 1;
}
mkl_free(a);
free(x0);
mkl_free(x1);
return 0;
}
template <typename T, class Generator>
static int test_tbmv_diag_random(Generator &gen) {
std::uniform_int_distribution<int> dist_int;
dist_int.param(decltype(dist_int)::param_type(1, 1 << 16));
const int n = dist_int(gen);
dist_int.param(decltype(dist_int)::param_type(1, 8));
const int incx = dist_int(gen), lda = dist_int(gen);
return test_tbmv_diag_single<T>(n, lda, incx, gen);
}
int main(void) {
setbuf(stdout, NULL);
std::default_random_engine gen;
int ret;
for (int i = 0; i < 10; ++i) {
ret = test_tbmv_diag_random<float>(gen);
if (ret) return ret;
}
for (int i = 0; i < 10; ++i) {
ret = test_tbmv_diag_random<std::complex<float>>(gen);
if (ret) return ret;
}
return 0;
}
| 33.1875
| 80
| 0.596359
|
Idein
|
2726f408337596cb11dd98ed1f186d3fb3fbc84c
| 659
|
cpp
|
C++
|
pointers_class_memory/class7.cpp
|
Sinchiguano/Algorithmic-Toolbox
|
7e9dda588a72356fc43fa276016fc3486be47556
|
[
"BSD-2-Clause"
] | null | null | null |
pointers_class_memory/class7.cpp
|
Sinchiguano/Algorithmic-Toolbox
|
7e9dda588a72356fc43fa276016fc3486be47556
|
[
"BSD-2-Clause"
] | null | null | null |
pointers_class_memory/class7.cpp
|
Sinchiguano/Algorithmic-Toolbox
|
7e9dda588a72356fc43fa276016fc3486be47556
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* class7.cpp
* Copyright (C) 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es>
*
* Distributed under terms of the BSD license.
*/
#include <iostream>
#include <string>
//g++ -std=c++14 -o temp sort.cpp
using namespace std;
class Example4
{
string* ptr;
public:
// constructors:
Example4() : ptr(new string) {}
Example4 (const string& str) : ptr(new string(str)) {}
// destructor:
~Example4 () {delete ptr;}
// access content:
const string& content() const {return *ptr;}
};
int main ()
{
//Example4 myObject1;
Example4 myObject2("CESAR");
std::cout << myObject2.content() << '\n';
return 0;
}
| 15.325581
| 69
| 0.622155
|
Sinchiguano
|
272c01ee9f86a8fc7dad48ccdd942e8495d58c09
| 3,773
|
cpp
|
C++
|
sim/src/main.cpp
|
bentobox-dev/bento-box
|
3e10c62f586c1251529e059b6af515d4d03c60e9
|
[
"MIT"
] | 1
|
2021-01-02T02:50:15.000Z
|
2021-01-02T02:50:15.000Z
|
sim/src/main.cpp
|
joeltio/bento-box
|
3e10c62f586c1251529e059b6af515d4d03c60e9
|
[
"MIT"
] | 48
|
2020-10-21T07:42:30.000Z
|
2021-02-15T19:34:55.000Z
|
sim/src/main.cpp
|
joeltio/bento-box
|
3e10c62f586c1251529e059b6af515d4d03c60e9
|
[
"MIT"
] | null | null | null |
/*
* bentobox-sim
* Main Entrypoint
*/
#include <component/textureComponent.h>
#include <core/graphicsContext.h>
#include <core/systemContext.h>
#include <core/windowContext.h>
#include <ics.h>
#include <system/render.h>
#include <network/grpcServer.h>
#include <service/engineService.h>
using grpc::Service;
using network::GRPCServer;
using service::EngineServiceImpl;
using std::invalid_argument;
using std::list;
using std::stoi;
using std::string;
using std::to_string;
/**
* Get the value of the environment variable with the given name.
*
* @param name The name of environment variable to get.
* @param defaultValue The value to return if no such environment variable is
* found.
*
* @returns The value of the environment variable or defaultValue
* if the variable cannot be found.
*/
string getEnv(const string name, const string defaultValue) {
auto envValue = std::getenv(name.c_str());
if (!envValue) {
return defaultValue;
}
return envValue;
}
/**
* Bentobox-sim engine main entrypoint
*
* Environment Variable parameters:
* - BENTOBOX_SIM_HOST - the host/ip that bentobox-sim listens on.
* - BENTOBOX_SIM_PORT - the port that bentobox-sim listens on.
*/
int main(int argc, char *argv[]) {
// setup graphics
WindowContext windowContext = WindowContext(800, 600, "Bento Box");
GraphicsContext graphics = GraphicsContext(windowContext);
// setup ICS
ics::ComponentStore componentStore = ics::ComponentStore();
ics::index::IndexStore indexStore = ics::index::IndexStore();
SystemContext systemContext = SystemContext<ics::index::IndexStore>();
auto tex1 = ics::component::Texture2DComponent();
auto value = bento::protos::Value();
value.mutable_primitive()->set_int_64(1);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex1.setValue("texture", value);
auto tex2 = ics::component::Texture2DComponent();
value = bento::protos::Value();
value.mutable_primitive()->set_int_64(2);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex2.setValue("texture", value);
auto tex3 = ics::component::Texture2DComponent();
value = bento::protos::Value();
value.mutable_primitive()->set_int_64(3);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex3.setValue("texture", value);
auto tex4 = ics::component::Texture2DComponent();
value = bento::protos::Value();
value.mutable_primitive()->set_int_64(4);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex4.setValue("texture", value);
ics::addComponent(indexStore, componentStore, tex1);
ics::addComponent(indexStore, componentStore, tex2);
ics::addComponent(indexStore, componentStore, tex3);
ics::addComponent(indexStore, componentStore, tex4);
// register ICS systems
const SystemFn<ics::index::IndexStore> a(&ics::system::render);
systemContext.systems.push_front(a);
// start gRPC server using host and port obtained via env vars
string host = getEnv("BENTOBOX_SIM_HOST", "localhost");
int port = std::stoi(getEnv("BENTOBOX_SIM_PORT", "54242"));
EngineServiceImpl engineService;
list<Service *> services = {&engineService};
GRPCServer server(host, port, services);
std::cout << "bentobox-sim listening on " << server.address() << std::endl;
// run engine main loop
while (!windowContext.shouldClose()) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
systemContext.run(graphics, componentStore, indexStore);
windowContext.swapBuffers();
windowContext.updateEvents();
}
}
| 32.808696
| 79
| 0.702624
|
bentobox-dev
|
272cc7f0fb1519b31760bc68b706d7eab0933a6a
| 1,128
|
cpp
|
C++
|
tag_hierarchy/utils/filters.cpp
|
equinor/ioc-hierarchy-service
|
e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9
|
[
"MIT"
] | 3
|
2021-12-22T07:36:26.000Z
|
2022-03-29T07:24:28.000Z
|
tag_hierarchy/utils/filters.cpp
|
equinor/ioc-hierarchy-service
|
e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9
|
[
"MIT"
] | 10
|
2020-08-03T13:00:30.000Z
|
2021-12-27T10:08:54.000Z
|
tag_hierarchy/utils/filters.cpp
|
equinor/ioc-hierarchy-service
|
e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9
|
[
"MIT"
] | null | null | null |
#include "tag_hierarchy/utils/filters.h"
std::tuple<std::vector<std::string>, std::vector<std::string>, std::vector<std::string>>
TagHierarchyUtils::Filters::GetFilterSettings(NodeType& command_map) {
auto l1filter = std::vector<std::string>();
if (command_map.count("l1filter") &&
command_map["l1filter"].type() == typeid(std::vector<std::string>))
{
l1filter = boost::get<std::vector<std::string>>(command_map.at("l1filter"));
}
auto modelownerfilter = std::vector<std::string>();
if (command_map.count("modelownerfilter") &&
command_map["modelownerfilter"].type() == typeid(std::vector<std::string>))
{
modelownerfilter = boost::get<std::vector<std::string>>(command_map.at("modelownerfilter"));
}
auto modelclassfilter = std::vector<std::string>();
if (command_map.count("modelclassfilter") &&
command_map["modelclassfilter"].type() == typeid(std::vector<std::string>))
{
modelclassfilter = boost::get<std::vector<std::string>>(command_map.at("modelclassfilter"));
}
return {l1filter, modelownerfilter, modelclassfilter};
}
| 47
| 100
| 0.669326
|
equinor
|
272df97d7c2eeeb96e5bdcd9f8ff41d0e7495246
| 2,719
|
cc
|
C++
|
mace/ops/reduce_mean_benchmark.cc
|
nihui/mace
|
e13c3f66d3543a46248849294f6606eba769964d
|
[
"Apache-2.0"
] | 5
|
2018-06-28T02:39:33.000Z
|
2021-05-14T08:12:12.000Z
|
mace/ops/reduce_mean_benchmark.cc
|
fly-jelly/mace
|
e13c3f66d3543a46248849294f6606eba769964d
|
[
"Apache-2.0"
] | null | null | null |
mace/ops/reduce_mean_benchmark.cc
|
fly-jelly/mace
|
e13c3f66d3543a46248849294f6606eba769964d
|
[
"Apache-2.0"
] | null | null | null |
//
// Copyright (c) 2017 XiaoMi All rights reserved.
//
#include "mace/core/operator.h"
#include "mace/core/runtime/opencl/opencl_runtime.h"
#include "mace/core/testing/test_benchmark.h"
#include "mace/ops/ops_test_util.h"
namespace mace {
namespace ops {
namespace test {
namespace {
template <DeviceType D, typename T>
void ReduceMean(int iters, int batch, int channels,
int height, int width) {
mace::testing::StopTiming();
OpsTestNet net;
// Add input data
net.AddRandomInput<D, T>("Input", {batch, height, width, channels});
if (D == DeviceType::GPU) {
BufferToImage<D, T>(&net, "Input", "InputImage",
kernels::BufferType::IN_OUT_CHANNEL);
OpDefBuilder("ReduceMean", "ReduceMeanBM")
.Input("InputImage")
.AddIntsArg("axis", {1, 2})
.Output("OutputImage")
.Finalize(net.NewOperatorDef());
} else {
net.TransformDataFormat<DeviceType::CPU, float>("Input", NHWC, "InputNCHW",
NCHW);
OpDefBuilder("ReduceMean", "ReduceMeanBM")
.Input("InputNCHW")
.AddIntsArg("axis", {2, 3})
.Output("Output")
.Finalize(net.NewOperatorDef());
}
// Warm-up
for (int i = 0; i < 5; ++i) {
net.RunOp(D);
}
net.Sync();
mace::testing::StartTiming();
while (iters--) {
net.RunOp(D);
}
net.Sync();
}
} // namespace
#define MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, TYPE, DEVICE) \
static void \
MACE_BM_REDUCE_MEAN_##N##_##C##_##H##_##W##_##TYPE##_##DEVICE(\
int iters) { \
const int64_t tot = static_cast<int64_t>(iters) * N * C * H * W; \
mace::testing::MaccProcessed(tot); \
mace::testing::BytesProcessed(tot *(sizeof(TYPE))); \
ReduceMean<DEVICE, TYPE>(iters, N, C, H, W); \
} \
MACE_BENCHMARK( \
MACE_BM_REDUCE_MEAN_##N##_##C##_##H##_##W##_##TYPE##_##DEVICE)
#define MACE_BM_REDUCE_MEAN(N, C, H, W) \
MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, float, GPU); \
MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, half, GPU); \
MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, float, CPU);
MACE_BM_REDUCE_MEAN(1, 1, 512, 512);
MACE_BM_REDUCE_MEAN(4, 3, 128, 128);
MACE_BM_REDUCE_MEAN(4, 3, 512, 512);
MACE_BM_REDUCE_MEAN(16, 32, 112, 112);
MACE_BM_REDUCE_MEAN(8, 32, 112, 112);
MACE_BM_REDUCE_MEAN(8, 64, 256, 256);
MACE_BM_REDUCE_MEAN(1, 32, 480, 640);
} // namespace test
} // namespace ops
} // namespace mace
| 31.616279
| 79
| 0.552409
|
nihui
|
272ef38e2bdd26b398d8e764eadb4f729ee15768
| 3,715
|
cpp
|
C++
|
Src/Vessel/Atlantis/Common.cpp
|
Ybalrid/orbiter
|
7bed82f845ea8347f238011367e07007b0a24099
|
[
"MIT"
] | 1,040
|
2021-07-27T12:12:06.000Z
|
2021-08-02T14:24:49.000Z
|
Src/Vessel/Atlantis/Common.cpp
|
Ybalrid/orbiter
|
7bed82f845ea8347f238011367e07007b0a24099
|
[
"MIT"
] | 20
|
2021-07-27T12:25:22.000Z
|
2021-08-02T12:22:19.000Z
|
Src/Vessel/Atlantis/Common.cpp
|
Ybalrid/orbiter
|
7bed82f845ea8347f238011367e07007b0a24099
|
[
"MIT"
] | 71
|
2021-07-27T14:19:49.000Z
|
2021-08-02T05:51:52.000Z
|
// ==============================================================
// ORBITER MODULE: Atlantis
// Part of the ORBITER SDK
// Copyright (C) 2001-2003 Martin Schweiger
// All rights reserved
//
// Common.cpp
// Utility functions common to multiple Atlantis-related modules
// ==============================================================
#include "Atlantis.h"
#ifdef _DEBUG
// D. Beachy: GROW THE STACK HERE SO WE CAN USE BOUNDSCHECKER FOR DEBUGGING
// We need this is because BoundsChecker (for this object) grows the stack more than 1 full page (4K) at once
// and then touches data beyond the initial 4K, skipping over the guard page that Windows places below the stack to grow it automatically.
// Therefore we will grow the stack manually in one-page increments here.
// This is only necessary for BoundsChecker debugging.
int GrowStack()
{
#ifdef UNDEF // This function causes a crash (LoadLibrary fails with code 1001 (stack overflow) on compiling with VS2019, so I am disabling it for now
// NOTE: this requires that orbiter.exe has its 'Size of Stack Reserve' PE header parameter set to 4 MB
int pageCount = 256; // 256 4K pages = reserve 1 MB of stack
DWORD dwStackDelta = 0; // total # of stack bytes used
for (int i=0; i < pageCount; i++)
{
dwStackDelta += 4096;
__asm
{
sub esp, 4092; // 1 page - 4 bytes
push 0xFEEDFEED // touch the page
}
}
// now pop the stack we touched
__asm
{
mov eax, [dwStackDelta] // size in bytes
add esp, eax
}
#endif
return 0;
}
// invoke GrowStack early before the next lines are called (otherwise BoundsChecker will crash)
int growStack=GrowStack();
#endif
int SRB_nt = 6;
double SRB_Seq[6] = {-SRB_STABILISATION_TIME, -1, 103, 115, SRB_SEPARATION_TIME, SRB_CUTOUT_TIME};
double SRB_Thrust[6] = { 0, 1, 1, 0.85, 0.05, 0 };
double SRB_Prop[6] = { 1, 0.98768, 0.13365, 0.04250, 0.001848, 0 };
double SRB_ThrSCL[5] = {(SRB_Thrust[1]-SRB_Thrust[0])/(SRB_Seq[1]-SRB_Seq[0]),
(SRB_Thrust[2]-SRB_Thrust[1])/(SRB_Seq[2]-SRB_Seq[1]),
(SRB_Thrust[3]-SRB_Thrust[2])/(SRB_Seq[3]-SRB_Seq[2]),
(SRB_Thrust[4]-SRB_Thrust[3])/(SRB_Seq[4]-SRB_Seq[3]),
(SRB_Thrust[5]-SRB_Thrust[4])/(SRB_Seq[5]-SRB_Seq[4])};
double SRB_PrpSCL[5] = {(SRB_Prop[1]-SRB_Prop[0])/(SRB_Seq[1]-SRB_Seq[0]),
(SRB_Prop[2]-SRB_Prop[1])/(SRB_Seq[2]-SRB_Seq[1]),
(SRB_Prop[3]-SRB_Prop[2])/(SRB_Seq[3]-SRB_Seq[2]),
(SRB_Prop[4]-SRB_Prop[3])/(SRB_Seq[4]-SRB_Seq[3]),
(SRB_Prop[5]-SRB_Prop[4])/(SRB_Seq[5]-SRB_Seq[4])};
//PARTICLESTREAMSPEC srb_contrail = {
// 0, 12.0, 3, 150.0, 0.4, 8.0, 4, 3.0, PARTICLESTREAMSPEC::DIFFUSE,
// PARTICLESTREAMSPEC::LVL_PSQRT, 0, 0.5,
// PARTICLESTREAMSPEC::ATM_PLOG, 1e-6, 0.1
//};
PARTICLESTREAMSPEC srb_contrail = {
0, 12.0, 3, 200.0, 0.25, 12.0, 11, 10.0, PARTICLESTREAMSPEC::DIFFUSE,
PARTICLESTREAMSPEC::LVL_PSQRT, 0, 0.7,
PARTICLESTREAMSPEC::ATM_PLOG, 1e-6, 0.1
};
PARTICLESTREAMSPEC srb_exhaust = {
0, 6.0, 40, 250.0, 0.04, 0.4, 20, 6.0, PARTICLESTREAMSPEC::EMISSIVE,
PARTICLESTREAMSPEC::LVL_SQRT, 1, 1,
PARTICLESTREAMSPEC::ATM_FLAT, 1, 1
};
// time-dependent calculation of SRB thrust and remaining propellant
void GetSRB_State (double met, double &thrust_level, double &prop_level)
{
int i;
for (i = SRB_nt-2; i >= 0; i--)
if (met > SRB_Seq[i]) break;
thrust_level = SRB_ThrSCL[i] * (met-SRB_Seq[i]) + SRB_Thrust[i];
prop_level = SRB_PrpSCL[i] * (met-SRB_Seq[i]) + SRB_Prop[i];
}
| 40.380435
| 150
| 0.61319
|
Ybalrid
|
27305309e16b21f4b91241bdb63de3e3ea06e5ee
| 6,215
|
cxx
|
C++
|
EVE/EveDet/AliEveEMCALSModuleData.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
EVE/EveDet/AliEveEMCALSModuleData.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
EVE/EveDet/AliEveEMCALSModuleData.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TGeoBBox.h>
#include "AliEMCALGeometry.h"
#include "AliEveEMCALSModuleData.h"
class TClonesArray;
class TGeoNode;
//class TGeoMatrix;
class TVector2;
class AliEveEventManager;
/// \cond CLASSIMP
ClassImp(AliEveEMCALSModuleData) ;
/// \endcond
Float_t AliEveEMCALSModuleData::fgSModuleBigBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox2 = 0.;
//
// Constructor
//
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(Int_t sm,AliEMCALGeometry* geom, TGeoNode* node): //, TGeoHMatrix* m) :
TObject(),
fGeom(geom),
fNode(node),
fSmId(sm),
fNsm(0),
fNDigits(0),
fNClusters(0),
fNHits(0),
fPhiTileSize(0), fEtaTileSize(0),
fHitArray(0),
fDigitArray(0),
fClusterArray(0)
// fMatrix(0),
// fHMatrix(m)
{
Init(sm);
}
///
/// Copy constructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(const AliEveEMCALSModuleData &esmdata) :
TObject(),
fGeom(esmdata.fGeom),
fNode(esmdata.fNode),
fSmId(esmdata.fSmId),
fNsm(esmdata.fNsm),
fNDigits(esmdata.fNDigits),
fNClusters(esmdata.fNClusters),
fNHits(esmdata.fNHits),
fPhiTileSize(esmdata.fPhiTileSize), fEtaTileSize(esmdata.fEtaTileSize),
fHitArray(esmdata.fHitArray),
fDigitArray(esmdata.fDigitArray),
fClusterArray(esmdata.fClusterArray)
// fMatrix(esmdata.fMatrix),
// fHMatrix(esmdata.fHMatrix)
{
Init(esmdata.fNsm);
}
///
/// Destructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::~AliEveEMCALSModuleData()
{
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
}
///
/// Release the SM data.
///
//______________________________________________________________________________
void AliEveEMCALSModuleData::DropData()
{
fNDigits = 0;
fNClusters = 0;
fNHits = 0;
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
return;
}
///
/// Initialize parameters
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::Init(Int_t sm)
{
fNsm = fGeom->GetNumberOfSuperModules();
fPhiTileSize = fGeom->GetPhiTileSize();
fEtaTileSize = fGeom->GetPhiTileSize();
//fMatrix = (TGeoMatrix*) fNode->GetDaughter(sm)->GetMatrix();
TGeoBBox * bbox = (TGeoBBox*) fNode->GetDaughter(sm)->GetVolume()->GetShape();
if(sm < 10)
{
fgSModuleBigBox0 = bbox->GetDX();
fgSModuleBigBox1 = bbox->GetDY();
fgSModuleBigBox2 = bbox->GetDZ();
}
else if(sm < 12)
{
fgSModuleSmallBox0 = bbox->GetDX();
fgSModuleSmallBox1 = bbox->GetDY();
fgSModuleSmallBox2 = bbox->GetDZ();
}
else if(sm < 18)
{
fgSModuleDCalBox0 = bbox->GetDX();
fgSModuleDCalBox1 = bbox->GetDY();
fgSModuleDCalBox2 = bbox->GetDZ();
}
else if(sm < 20)
{
fgSModuleSmallDBox0 = bbox->GetDX();
fgSModuleSmallDBox1 = bbox->GetDY();
fgSModuleSmallDBox2 = bbox->GetDZ();
}
}
///
/// Add a digit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterDigit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufDig(6);
bufDig[0] = AbsId;
bufDig[1] = isupMod;
bufDig[2] = iamp;
bufDig[3] = ix;
bufDig[4] = iy;
bufDig[5] = iz;
fDigitArray.push_back(bufDig);
fNDigits++;
}
///
/// Add a hit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterHit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Float_t> bufHit(6);
bufHit[0] = AbsId;
bufHit[1] = isupMod;
bufHit[2] = iamp;
bufHit[3] = ix;
bufHit[4] = iy;
bufHit[5] = iz;
fHitArray.push_back(bufHit);
fNHits++;
}
///
/// Add a cluster to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterCluster(Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufClu(5);
bufClu[0] = isupMod;
bufClu[1] = iamp;
bufClu[2] = ix;
bufClu[3] = iy;
bufClu[4] = iz;
fClusterArray.push_back(bufClu);
fNClusters++;
}
| 27.258772
| 124
| 0.684312
|
AllaMaevskaya
|
27307444b2da9e8959408ee53db2556cc14f1982
| 578
|
cpp
|
C++
|
codes/HDU/hdu5510.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/HDU/hdu5510.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/HDU/hdu5510.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 505;
const int maxm = 2005;
int N, F[maxn];
char str[maxn][maxm];
int main () {
int cas;
scanf("%d", &cas);
for (int kcas = 1; kcas <= cas; kcas++) {
scanf("%d", &N);
for (int i = 0; i < N; i++) scanf("%s", str[i]);
int p = N-1;
while (p && strstr(str[p], str[p-1]) != NULL) p--;
p++;
for (int i = p-2; i >= 0 && p < N; i--) {
while (p < N && strstr(str[p], str[i]) == NULL) p++;
}
if (p == 1) p = -1;
printf("Case #%d: %d\n", kcas, p);
}
return 0;
}
| 18.645161
| 55
| 0.50346
|
JeraKrs
|
27326fc91fe01e24ab157440f0a5b456c35c17f4
| 5,121
|
cpp
|
C++
|
EsteganografiaC++/src/codificar.cpp
|
nen155/Metodolog-a-de-Programaci-n
|
587d9a231d1c6ef1fa59f895fdf69d30eb4c598a
|
[
"MIT"
] | null | null | null |
EsteganografiaC++/src/codificar.cpp
|
nen155/Metodolog-a-de-Programaci-n
|
587d9a231d1c6ef1fa59f895fdf69d30eb4c598a
|
[
"MIT"
] | null | null | null |
EsteganografiaC++/src/codificar.cpp
|
nen155/Metodolog-a-de-Programaci-n
|
587d9a231d1c6ef1fa59f895fdf69d30eb4c598a
|
[
"MIT"
] | null | null | null |
/**
* @file codificar.cpp
* @brief Fichero que contiene las funciones para codificar un mensaje en una imagen, tanto para introducirlo como para leerlo.
*
* Permite la E/S de archivos de tipo PGM,PPM
*
*/
#include "imagenES.h"
#include "codificar.h"
#include <iostream>
#include <cstring>
using namespace std;
//Para mostrarle mensajes al usuario por teclado
void lecturaTeclado(char nombre[],const int max,char mensaje[]){
cout<<mensaje;
cin.getline(nombre,max,'\n');
}
// _____________________________________________________________________________
bool compruebaLectura(char nombre[]){
if(strlen(nombre)>100){
cout<<"El mensaje tiene que ser de menos de 100 caracteres";
return true;
}
else return false;
}
//Introduce en la variable bncolor el tipo de imagen leido.
// _____________________________________________________________________________
void lecturaTipoIMG(const char nombre[],TipoImagen &bncolor,int &filas,int &columnas){
bncolor= LeerTipoImagen(nombre,filas,columnas);
}
//Dependiendo del tipo de imagen leido hace una lectura u otra y devuelve si la lectura ha tenido exito.
// _____________________________________________________________________________
bool lecturaIMG(const char nombre[],const TipoImagen bncolor,int &filas,int &columnas,unsigned char buffer[]){
bool flag=false;
switch(bncolor){
case IMG_PGM:
if(LeerImagenPGM(nombre,filas,columnas,buffer))
flag=true;
else
flag=false;
break;
case IMG_PPM:
if(LeerImagenPPM(nombre,filas,columnas,buffer))
flag=true;
else
flag=false;
break;
case IMG_DESCONOCIDO:
flag=false;
break;
return flag;
}
}
// _____________________________________________________________________________
void ocultar(unsigned char imagen[],char mensaje[]){
for(int i=0;i<strlen(mensaje);i++){
for(int k=0;k<8;k++){
//DESPLAZA A LA DERECHA EL รLTIMO BIT DE IMAGEN
if(((imagen[k]<<7)&(mensaje[i]<<k))!=0){
imagen[k]=imagen[k]|1; //HACE UN OR CON EL NUMERO 00000001 CON EL MENSAJE
}else{
imagen[k]=imagen[k]&~1; //HACE UN AND EL NUMERO 11111110
}
}
}
}
// _____________________________________________________________________________
void revelar(unsigned char imagen[],char mensajeRevelado[]){
int i=0;
do{
mensajeRevelado[i]=0;//Pongo a 0 el caracter con el que voy a operar para que no haya basura
//Recorro los 8 bytes primeros de la imagen
for(int k=0;k<8;k++){
mensajeRevelado[i]=((mensajeRevelado[i]>>k)|(imagen[k]<<7));//Desplazo el mensaje tantas posiciones como bytes haya recorrido y el byte de la imagen tambiรฉn lo desplazo para sรณlo tener algo de la forma 10000000
}
i++;
}while(mensajeRevelado[i]!='\0');//Voy metiendo caracteres hasta llegar al caracter \0
}
// _____________________________________________________________________________
int main(){
//Declaraciรณn de variables para utilizar durante la ejecuciรณn
const int MAXBUFFER= 1000000;
const int MAXNOMBRE= 100;
char nombre_imagen[MAXNOMBRE];
char nombreIMGSalida[MAXNOMBRE];//Nombre de la imagen de salida
unsigned char buffer[MAXBUFFER];
int filas,columnas;//Las filas y columnas de la imagen
TipoImagen bncolor;//El tipo de imagen que es
char mensaje[MAXNOMBRE];//EL mensaje que se ocultarรก o revelarรก de la imagen
bool flag=true;//Para saber si falla la ocultaciรณn o revelaciรณn
int n=0;
do{
cout<<"Introduce una opciรณn:\n(1) Ocultar\n(2) Revelar\n(0) Exit\n";
cin>>n;
cin.ignore();
switch(n){
case 1:
lecturaTeclado(nombre_imagen,MAXNOMBRE,(char *)"Introduce el nombre de la imagen para codificar el mensaje:");//Pido la imagen a usar
lecturaTipoIMG(nombre_imagen,bncolor,filas,columnas);//Compruebo el tipo de imagen
lecturaIMG(nombre_imagen,bncolor,filas,columnas,buffer);//Pido la imagen a usar
lecturaTeclado(nombreIMGSalida,MAXNOMBRE,(char *)"Introduce el nombre de la imagen de salida:");//Pido el nombre de la imagen a la salida
do{
lecturaTeclado(mensaje,MAXNOMBRE,(char *)"Introduce el mensaje a ocultar:");//Pido el mensaje al usuario
}while(compruebaLectura(mensaje)); //Compruebo que tenga menos de 100 caracteres
cout<<"Ocultando...\n";
ocultar(buffer,mensaje);
if(bncolor==IMG_PGM){
flag=EscribirImagenPGM(strcat(nombreIMGSalida,".pgm"),buffer,filas,columnas);
}
else if(bncolor==IMG_PPM){
flag=EscribirImagenPPM(strcat(nombreIMGSalida,".ppm"),buffer,filas,columnas);
}else flag=false;
if(flag)
cout<<"Ocultaciรณn con รฉxito!\n ยฟQue mรกs desea hacer?\n";
else
cout<<"Upps..El mensaje no se ha podido ocultar\n ยฟQue mรกs desea hacer?\n";
break;
case 2:
lecturaTeclado(nombre_imagen,MAXNOMBRE,(char *)"Introduce el nombre de la imagen con el mensaje codificado:");//Pido la imagen a usar
lecturaTipoIMG(nombre_imagen,bncolor,filas,columnas);//Compruebo el tipo de Imagen a descodificar
lecturaIMG(nombre_imagen,bncolor,filas,columnas,buffer);//Pido la imagen a usar
cout<<"Revelanado el mensaje...\n";
revelar(buffer,mensaje);
cout<<"El mensaje es: "<<mensaje <<"\nยฟQue mรกs desea hacer?\n";
break;
case 0:
break;
}
}while(n!=0);
}
| 34.369128
| 213
| 0.737161
|
nen155
|
27328566237e55700f7895bf93f686526d64ee99
| 3,341
|
cpp
|
C++
|
tests/src/QtSettingsUtilsTests.cpp
|
oclero/qtutils
|
477d65211a15bffabe11d9f0b526c917893ae8ee
|
[
"MIT"
] | null | null | null |
tests/src/QtSettingsUtilsTests.cpp
|
oclero/qtutils
|
477d65211a15bffabe11d9f0b526c917893ae8ee
|
[
"MIT"
] | null | null | null |
tests/src/QtSettingsUtilsTests.cpp
|
oclero/qtutils
|
477d65211a15bffabe11d9f0b526c917893ae8ee
|
[
"MIT"
] | null | null | null |
#include "QtSettingsUtilsTests.hpp"
#include <QTest>
#include <oclero/QtSettingsUtils.hpp>
constexpr auto SETTINGS_KEY = "Toto";
using namespace oclero;
void QtSettingsUtilsTests::init() {
{
QSettings qSettings;
qSettings.remove(SETTINGS_KEY);
}
}
void QtSettingsUtilsTests::cleanup() {
{
QSettings qSettings;
qSettings.remove(SETTINGS_KEY);
}
}
void QtSettingsUtilsTests::test_tryLoadInexistentSetting_enum() const {
QSettings settings;
auto const optionalValue = tryLoadSetting<DummyEnum>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadInvalidSetting_enum() const {
{ QSettings{}.setValue(SETTINGS_KEY, "1"); }
QSettings settings;
auto const optionalValue = tryLoadSetting<DummyEnum>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadValidSetting_enum() const {
{ QSettings{}.setValue(SETTINGS_KEY, "DummyValue2"); }
QSettings settings;
auto const optionalValue = tryLoadSetting<DummyEnum>(settings, SETTINGS_KEY);
QVERIFY(optionalValue.has_value() && optionalValue.value() == DummyEnum::DummyValue2);
}
void QtSettingsUtilsTests::test_tryLoadInexistentSetting_int() const {
QSettings settings;
auto const optionalValue = tryLoadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadInvalidSetting_int() const {
{ QSettings{}.setValue(SETTINGS_KEY, "abc"); }
QSettings settings;
auto const optionalValue = tryLoadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadValidSetting_int() const {
{ QSettings{}.setValue(SETTINGS_KEY, 42); }
QSettings settings;
auto const optionalValue = tryLoadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(optionalValue.has_value() && optionalValue.value() == 42);
}
void QtSettingsUtilsTests::test_loadValidSetting() const {
{ QSettings{}.setValue(SETTINGS_KEY, 42); }
QSettings settings;
auto const value = loadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(value == 42);
}
void QtSettingsUtilsTests::test_loadInvalidSetting() const {
QSettings settings;
auto const value = loadSetting<int>(settings, SETTINGS_KEY, 12);
QVERIFY(value == 12);
}
void QtSettingsUtilsTests::test_saveSetting_int() const {
{
QSettings settings;
saveSetting<int>(settings, SETTINGS_KEY, 42);
}
auto const value = QSettings{}.value(SETTINGS_KEY).toInt();
QVERIFY(value == 42);
}
void QtSettingsUtilsTests::test_saveSetting_enum() const {
{
QSettings settings;
saveSetting<DummyEnum>(settings, SETTINGS_KEY, DummyEnum::DummyValue2);
}
// Enum are saved as strings and parsed.
auto const value = QSettings{}.value(SETTINGS_KEY).toString();
QVERIFY(value == "DummyValue2");
}
void QtSettingsUtilsTests::test_useQStringAsKey() const {
auto qStringKey = QString{ SETTINGS_KEY };
{
QSettings settings;
saveSetting<int>(settings, qStringKey, 42);
}
auto const value = QSettings{}.value(SETTINGS_KEY).toInt();
QVERIFY(value == 42);
QSettings{}.setValue(qStringKey, "DummyValue");
{
QSettings settings;
auto const valueInSettings = loadSetting<QString>(settings, qStringKey, QString{});
QVERIFY(valueInSettings == "DummyValue");
}
}
| 29.052174
| 88
| 0.747082
|
oclero
|
2734ad912439e8edf65e2870e1d3906a68a2fbd6
| 13,656
|
hpp
|
C++
|
src/Memory/AffixAllocator.hpp
|
epicbrownie/Epic
|
c54159616b899bb24c6d59325d582e73f2803ab6
|
[
"MIT"
] | null | null | null |
src/Memory/AffixAllocator.hpp
|
epicbrownie/Epic
|
c54159616b899bb24c6d59325d582e73f2803ab6
|
[
"MIT"
] | 29
|
2016-08-01T14:50:12.000Z
|
2017-12-17T20:28:27.000Z
|
src/Memory/AffixAllocator.hpp
|
epicbrownie/Epic
|
c54159616b899bb24c6d59325d582e73f2803ab6
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016 Ronnie Brohn (EpicBrownie)
//
// Distributed under The MIT License (MIT).
// (See accompanying file License.txt or copy at
// https://opensource.org/licenses/MIT)
//
// Please report any bugs, typos, or suggestions to
// https://github.com/epicbrownie/Epic/issues
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Epic/Memory/MemoryBlock.hpp>
#include <Epic/Memory/detail/AllocatorTraits.hpp>
#include <Epic/Memory/detail/AllocatorHelpers.hpp>
#include <Epic/Memory/detail/AffixHelpers.hpp>
#include <cassert>
#include <cstdint>
#include <algorithm>
#include <type_traits>
//////////////////////////////////////////////////////////////////////////////
namespace Epic
{
template<class Allocator, class Prefix, class Suffix = void>
class AffixAllocator;
}
//////////////////////////////////////////////////////////////////////////////
/// AffixAllocator<A, Prefix, Suffix>
template<class A, class Prefix, class Suffix>
class Epic::AffixAllocator
{
static_assert(std::is_default_constructible<A>::value, "The affix allocator must be default-constructible.");
public:
using Type = Epic::AffixAllocator<A, Prefix, Suffix>;
using AllocatorType = A;
using PrefixType = Prefix;
using SuffixType = Suffix;
public:
static constexpr size_t Alignment = A::Alignment;
private:
static constexpr bool HasPrefix = !std::is_same<Prefix, void>::value;
static constexpr bool HasSuffix = !std::is_same<Suffix, void>::value;
static constexpr size_t UnalignedPrefixSize = detail::AffixSize<Prefix>::value;
static constexpr size_t PrefixSize = detail::RoundToAligned(UnalignedPrefixSize, Alignment);
static constexpr size_t SuffixSize = detail::AffixSize<Suffix>::value;
using AlignmentMemento = uint16_t;
private:
static constexpr size_t NonAllocSize = (PrefixSize + SuffixSize + sizeof(AlignmentMemento));
public:
static constexpr size_t MinAllocSize = A::MinAllocSize;
static constexpr size_t MaxAllocSize = A::MaxAllocSize - NonAllocSize;
static constexpr bool IsShareable = A::IsShareable;
static_assert(!HasPrefix || std::is_default_constructible<Prefix>::value, "The Prefix Type must be default-constructible.");
static_assert(!HasSuffix || std::is_default_constructible<Suffix>::value, "The Suffix Type must be default-constructible.");
static_assert(A::MaxAllocSize > NonAllocSize && MaxAllocSize > MinAllocSize,
"The affix sizes are too large for the backing Allocator.");
private:
AllocatorType m_Allocator;
public:
constexpr AffixAllocator()
noexcept(std::is_nothrow_default_constructible<A>::value) = default;
template<typename = std::enable_if_t<std::is_copy_constructible<A>::value>>
constexpr AffixAllocator(const Type& obj)
noexcept(std::is_nothrow_copy_constructible<A>::value)
: m_Allocator{ obj.m_Allocator }
{ }
template<typename = std::enable_if_t<std::is_move_constructible<A>::value>>
constexpr AffixAllocator(Type&& obj)
noexcept(std::is_nothrow_move_constructible<A>::value)
: m_Allocator{ std::move(obj.m_Allocator) }
{ }
template<typename = std::enable_if_t<std::is_copy_assignable<A>::value>>
AffixAllocator& operator = (const Type& obj)
noexcept(std::is_nothrow_copy_assignable<A>::value)
{
m_Allocator = obj.m_Allocator;
return *this;
}
template<typename = std::enable_if_t<std::is_move_assignable<A>::value>>
AffixAllocator& operator = (Type&& obj)
noexcept(std::is_nothrow_move_assignable<A>::value)
{
m_Allocator = std::move(obj.m_Allocator);
return *this;
}
private:
static constexpr Blk ClientToAffixedBlock(const Blk& blk, const AlignmentMemento& alignment) noexcept
{
return Blk
{
reinterpret_cast<unsigned char*>(blk.Ptr) - detail::RoundToAligned(UnalignedPrefixSize, alignment),
blk.Size + (detail::RoundToAligned(UnalignedPrefixSize, alignment) + SuffixSize + sizeof(AlignmentMemento))
};
}
static constexpr Blk AffixedToClientBlock(const Blk& blk, const AlignmentMemento& alignment) noexcept
{
return Blk
{
reinterpret_cast<unsigned char*>(blk.Ptr) + detail::RoundToAligned(UnalignedPrefixSize, alignment),
blk.Size - (detail::RoundToAligned(UnalignedPrefixSize, alignment) + SuffixSize + sizeof(AlignmentMemento))
};
}
static constexpr void* AffixedToPrefixPtr(const Blk& blk) noexcept
{
return blk.Ptr;
}
static constexpr void* AffixedToSuffixPtr(const Blk& blk) noexcept
{
return static_cast<void*>(reinterpret_cast<unsigned char*>(blk.Ptr) + blk.Size - SuffixSize);
}
static constexpr AlignmentMemento* AffixedToAlignmentMementoPtr(const Blk& blk)
{
return reinterpret_cast<AlignmentMemento*>(reinterpret_cast<unsigned char*>(AffixedToSuffixPtr(blk)) - sizeof(AlignmentMemento));
}
static constexpr void* ClientToPrefixPtr(const Blk& blk, const AlignmentMemento& alignment) noexcept
{
return static_cast<void*>(reinterpret_cast<unsigned char*>(blk.Ptr) - detail::RoundToAligned(UnalignedPrefixSize, alignment));
}
static constexpr void* ClientToSuffixPtr(const Blk& blk) noexcept
{
return static_cast<void*>(reinterpret_cast<unsigned char*>(blk.Ptr) + blk.Size + sizeof(AlignmentMemento));
}
static constexpr AlignmentMemento* ClientToAlignmentMementoPtr(const Blk& blk)
{
return reinterpret_cast<AlignmentMemento*>(reinterpret_cast<unsigned char*>(blk.Ptr) + blk.Size);
}
public:
/* Returns whether or not this allocator is responsible for the block Blk. */
inline bool Owns(const Blk& blk) const noexcept
{
return blk ? m_Allocator.Owns(ClientToAffixedBlock(blk, *ClientToAlignmentMementoPtr(blk))) : false;
}
public:
/* Returns a block of uninitialized memory.
The memory will be surrounded by constructed Affix objects. */
template<typename = std::enable_if_t<detail::CanAllocate<A>::value>>
Blk Allocate(size_t sz) noexcept
{
// Verify that the requested size isn't zero.
if (sz == 0) return{ nullptr, 0 };
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return{ nullptr, 0 };
// Allocate the block
auto blk = m_Allocator.Allocate(sz + NonAllocSize);
if (!blk) return{ nullptr, 0 };
// Construct the Prefix and Suffix objects
if constexpr (HasPrefix)
::new (AffixedToPrefixPtr(blk)) Prefix();
if constexpr (HasSuffix)
::new (AffixedToSuffixPtr(blk)) Suffix();
// Store alignment memento
const auto memento = static_cast<AlignmentMemento>(Alignment);
*AffixedToAlignmentMementoPtr(blk) = memento;
return AffixedToClientBlock(blk, memento);
}
/* Returns a block of uninitialized memory (aligned to 'alignment').
The memory will be surrounded by constructed Affix objects. */
template<typename = std::enable_if_t<detail::CanAllocateAligned<A>::value>>
Blk AllocateAligned(size_t sz, size_t alignment = Alignment) noexcept
{
// Verify that the alignment is acceptable
if (!detail::IsGoodAlignment(alignment))
return{ nullptr, 0 };
assert(alignment <= std::numeric_limits<AlignmentMemento>::max() &&
"AffixAllocator::AllocateAligned - Unsupported alignment value");
// Verify that the requested size isn't zero.
if (sz == 0) return{ nullptr, 0 };
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return{ nullptr, 0 };
// Allocate the block
const size_t szNew = sz + detail::RoundToAligned(UnalignedPrefixSize, alignment) + sizeof(AlignmentMemento) + SuffixSize;
auto blk = m_Allocator.AllocateAligned(szNew, alignment);
if (!blk) return{ nullptr, 0 };
// Construct the Prefix and Suffix objects
if constexpr (HasPrefix)
::new (AffixedToPrefixPtr(blk)) Prefix();
if constexpr (HasSuffix)
::new (AffixedToSuffixPtr(blk)) Suffix();
// Store alignment memento
const auto memento = static_cast<AlignmentMemento>(alignment);
*AffixedToAlignmentMementoPtr(blk) = memento;
return AffixedToClientBlock(blk, memento);
}
/* Attempts to reallocate the memory of blk to the new size sz.
The Affix objects will be moved as necessary. */
template<typename = std::enable_if_t<detail::CanReallocate<A>::value && detail::AffixBuffer<Suffix>::CanStore>>
bool Reallocate(Blk& blk, size_t sz)
{
// If the block isn't valid, delegate to Allocate
if (!blk)
{
if constexpr (detail::CanAllocate<Type>::value)
return (bool)(blk = Allocate(sz));
}
// If the requested size is zero, delegate to Deallocate
if (sz == 0)
{
if constexpr (detail::CanDeallocate<Type>::value)
Deallocate(blk);
blk = { nullptr, 0 };
return true;
}
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return false;
// Move the Suffix object to the stack
auto pSuffix = GetSuffixObject(blk);
detail::AffixBuffer<Suffix> suffix{ pSuffix };
// Reallocate the block
Blk affixedBlk = ClientToAffixedBlock(blk, Alignment);
if (!m_Allocator.Reallocate(affixedBlk, sz + NonAllocSize))
{
suffix.Restore(pSuffix);
return false;
}
// Place the Suffix object and the alignment memento
suffix.Restore(AffixedToSuffixPtr(affixedBlk));
*AffixedToAlignmentMementoPtr(affixedBlk) = Alignment;
blk = AffixedToClientBlock(affixedBlk, Alignment);
return true;
}
/* Attempts to reallocate the memory of blk to the new size 'sz' (aligned to 'alignment').
It must have been allocated through AllocateAligned().
The Affix objects will be moved as necessary. */
template<typename = std::enable_if_t<detail::CanReallocateAligned<A>::value && detail::AffixBuffer<Suffix>::CanStore>>
bool ReallocateAligned(Blk& blk, size_t sz, size_t alignment = Alignment)
{
// Verify that the alignment is acceptable
if (!detail::IsGoodAlignment(alignment))
return false;
assert(alignment <= std::numeric_limits<AlignmentMemento>::max() &&
"AffixAllocator::ReallocateAligned - Unsupported alignment value");
// If the block isn't valid, delegate to AllocateAligned
if (!blk)
{
if constexpr (detail::CanAllocateAligned<Type>::value)
return (bool)(blk = AllocateAligned(sz, alignment));
}
// If the requested size is zero, delegate to DeallocateAligned
if (sz == 0)
{
if constexpr (detail::CanDeallocateAligned<Type>::value)
DeallocateAligned(blk);
blk = { nullptr, 0 };
return true;
}
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return false;
// Verify alignment memento
const AlignmentMemento memento = *ClientToAlignmentMementoPtr(blk);
assert(detail::IsGoodAlignment(memento) &&
"AffixAllocator::ReallocateAligned - Either this block was not allocated aligned or the heap has been corrupted");
assert(alignment == memento &&
"AffixAllocator::ReallocateAligned - Once allocated, the alignment of an allocated block cannot be changed");
// Move the Suffix object to the stack
auto pSuffix = GetSuffixObject(blk);
detail::AffixBuffer<Suffix> suffix{ pSuffix };
// Reallocate the block
Blk affixedBlk = ClientToAffixedBlock(blk, memento);
size_t szNew = sz + detail::RoundToAligned(UnalignedPrefixSize, alignment) + sizeof(AlignmentMemento) + SuffixSize;
if (!m_Allocator.ReallocateAligned(affixedBlk, szNew))
{
suffix.Restore(pSuffix);
return false;
}
// Place the Suffix object and the alignment memento
suffix.Restore(AffixedToSuffixPtr(affixedBlk));
*AffixedToAlignmentMementoPtr(affixedBlk) = memento;
blk = AffixedToClientBlock(affixedBlk, memento);
return true;
}
public:
/* Frees the memory for blk.
The surrounding Affix objects will also be destroyed. */
template<typename = std::enable_if_t<detail::CanDeallocate<A>::value>>
void Deallocate(const Blk& blk)
{
if (!blk) return;
assert(Owns(blk) &&
"AffixAllocator::Deallocate - "
"Attempted to free a block that was not allocated by this allocator");
// Deconstruct the affix objects
if (HasPrefix) GetPrefixObject(blk)->~Prefix();
if (HasSuffix) GetSuffixObject(blk)->~Suffix();
// Deallocate the affixed block
m_Allocator.Deallocate(ClientToAffixedBlock(blk, static_cast<AlignmentMemento>(Alignment)));
}
/* Frees the memory for blk. It must have been allocated through AllocateAligned().
The surrounding Affix objects will also be destroyed. */
template<typename = std::enable_if_t<detail::CanDeallocateAligned<A>::value>>
void DeallocateAligned(const Blk& blk)
{
if (!blk) return;
assert(Owns(blk) &&
"AffixAllocator::DeallocateAligned - "
"Attempted to free a block that was not allocated by this allocator");
// Verify alignment memento
assert(detail::IsGoodAlignment(*ClientToAlignmentMementoPtr(blk)) &&
"AffixAllocator::DeallocateAligned - "
"Either this block was not allocated aligned or the heap has been corrupted");
// Deconstruct the affix objects
if (HasPrefix) GetPrefixObject(blk)->~Prefix();
if (HasSuffix) GetSuffixObject(blk)->~Suffix();
// Deallocate the affixed block
m_Allocator.DeallocateAligned(ClientToAffixedBlock(blk, *ClientToAlignmentMementoPtr(blk)));
}
public:
static constexpr Prefix* GetPrefixObject(const Blk& blk, size_t alignment = Alignment) noexcept
{
return HasPrefix ?
reinterpret_cast<Prefix*>(ClientToPrefixPtr(blk, static_cast<AlignmentMemento>(alignment))) :
nullptr;
}
static constexpr Suffix* GetSuffixObject(const Blk& blk) noexcept
{
return HasSuffix ? reinterpret_cast<Suffix*>(ClientToSuffixPtr(blk)) : nullptr;
}
};
| 33.80198
| 131
| 0.719098
|
epicbrownie
|
2738cad2ad0f4fd1993a2d3118846cbfdce350c9
| 6,275
|
cpp
|
C++
|
src/morda/widgets/label/NinePatch.cpp
|
Mactor2018/morda
|
7194f973783b4472b8671fbb52e8c96e8c972b90
|
[
"MIT"
] | 1
|
2018-10-27T05:07:05.000Z
|
2018-10-27T05:07:05.000Z
|
src/morda/widgets/label/NinePatch.cpp
|
Mactor2018/morda
|
7194f973783b4472b8671fbb52e8c96e8c972b90
|
[
"MIT"
] | null | null | null |
src/morda/widgets/label/NinePatch.cpp
|
Mactor2018/morda
|
7194f973783b4472b8671fbb52e8c96e8c972b90
|
[
"MIT"
] | null | null | null |
#include <utki/util.hpp>
#include <utki/types.hpp>
#include "../../Morda.hpp"
#include "../../util/util.hpp"
#include "../proxy/ResizeProxy.hpp"
#include "NinePatch.hpp"
using namespace morda;
namespace{
const char* ninePatchLayout_c = R"qwertyuiop(
Row{
layout{dx{fill}}
Image{
name{morda_lt}
}
Image{
layout{dx{0}weight{1}}
name{morda_t}
}
Image{
name{morda_rt}
}
}
Row{
layout{
dx{max}
weight{1}
}
Image{
name{morda_l}
layout{dy{fill}}
}
Pile{
name{morda_content}
layout{
weight{1}
dy{max}
}
Image{
name{morda_m}
layout{dx{fill}dy{fill}}
}
}
Image{
name{morda_r}
layout{dy{fill}}
}
}
Row{
layout{dx{fill}}
Image{
name{morda_lb}
}
Image{
layout{dx{0}weight{1}}
name{morda_b}
}
Image{
name{morda_rb}
}
}
)qwertyuiop";
}
NinePatch::NinePatch(const stob::Node* chain) :
Widget(chain),
BlendingWidget(chain),
Column(stob::parse(ninePatchLayout_c).get())
{
this->imageMatrix_v[0][0] = this->findByNameAs<Image>("morda_lt");
this->imageMatrix_v[0][1] = this->findByNameAs<Image>("morda_t");
this->imageMatrix_v[0][2] = this->findByNameAs<Image>("morda_rt");
this->imageMatrix_v[1][0] = this->findByNameAs<Image>("morda_l");
this->imageMatrix_v[1][1] = this->findByNameAs<Image>("morda_m");
this->imageMatrix_v[1][2] = this->findByNameAs<Image>("morda_r");
this->imageMatrix_v[2][0] = this->findByNameAs<Image>("morda_lb");
this->imageMatrix_v[2][1] = this->findByNameAs<Image>("morda_b");
this->imageMatrix_v[2][2] = this->findByNameAs<Image>("morda_rb");
this->onBlendingChanged();
this->content_v = this->findByNameAs<Pile>("morda_content");
if(auto n = getProperty(chain, "left")){
this->borders.left() = dimValueFromSTOB(*n);//'min' is by default, but not allowed to specify explicitly, as well as 'max' and 'fill'
}else{
this->borders.left() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "right")){
this->borders.right() = dimValueFromSTOB(*n);
}else{
this->borders.right() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "top")){
this->borders.top() = dimValueFromSTOB(*n);
}else{
this->borders.top() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "bottom")){
this->borders.bottom() = dimValueFromSTOB(*n);
}else{
this->borders.bottom() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "centerVisible")){
this->setCenterVisible(n->asBool());
}
//this should go after setting up border widgets
if(const stob::Node* n = getProperty(chain, "image")){
this->setNinePatch(morda::Morda::inst().resMan.load<ResNinePatch>(n->value()));
}
if(chain){
this->content_v->add(*chain);
}
}
void NinePatch::render(const morda::Matr4r& matrix) const {
this->Column::render(matrix);
}
void NinePatch::setNinePatch(std::shared_ptr<const ResNinePatch> np){
this->image = std::move(np);
this->scaledImage.reset();
this->applyImages();
this->clearCache();
}
Sidesr NinePatch::getActualBorders() const noexcept{
Sidesr ret;
for(auto i = 0; i != ret.size(); ++i){
if(this->borders[i] >= 0){
ret[i] = this->borders[i];
}else if(!this->image){
ret[i] = 0;
}else{
ret[i] = this->image->borders()[i];
}
}
return ret;
}
void NinePatch::applyImages(){
if(!this->image){
for(auto& i : this->imageMatrix_v){
for(auto& j : i){
j->setImage(nullptr);
}
}
return;
}
auto& minBorders = this->image->borders();
// TRACE(<< "minBorders = " << minBorders << std::endl)
{
//non-const call to getLayoutParams requests relayout which is not necessarily needed, so try to avoid it if possible
auto& layoutParams = utki::makePtrToConst(this->imageMatrix_v[0][0].get())->getLayoutParams();
if(this->borders.left() == LayoutParams::min_c){
if(layoutParams.dim.x != minBorders.left()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.x = minBorders.left();
}
}else{
if(layoutParams.dim.x != this->borders.left()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.x = this->borders.left();
}
}
if(this->borders.top() == LayoutParams::min_c){
if(layoutParams.dim.y != minBorders.top()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.y = minBorders.top();
}
}else{
if(layoutParams.dim.y != this->borders.top()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.y = this->borders.top();
}
}
// TRACE(<< "layoutParams.dim = " << layoutParams.dim << std::endl)
}
{
//non-const call to getLayoutParams requests relayout which is not necessarily needed, so try to avoid it if possible
auto& layoutParams = utki::makePtrToConst(this->imageMatrix_v[2][2].get())->getLayoutParams();
if(this->borders.right() == LayoutParams::min_c){
if(layoutParams.dim.x != minBorders.right()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.x = minBorders.right();
}
}else{
if(layoutParams.dim.x != this->borders.right()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.x = this->borders.right();
}
}
if(this->borders.bottom() == LayoutParams::min_c){
if(layoutParams.dim.y != minBorders.bottom()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.y = minBorders.bottom();
}
}else{
if(layoutParams.dim.y != this->borders.bottom()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.y = this->borders.bottom();
}
}
// TRACE(<< "lp.dim = " << lp.dim << std::endl)
}
// TRACE(<< "this->borders = " << this->borders << std::endl)
this->scaledImage = this->image->get(this->borders);
for(unsigned i = 0; i != 3; ++i){
for(unsigned j = 0; j != 3; ++j){
this->imageMatrix_v[i][j]->setImage(this->scaledImage->images()[i][j]);
}
}
}
void NinePatch::setCenterVisible(bool visible){
ASSERT(this->imageMatrix_v[1][1])
this->imageMatrix_v[1][1]->setVisible(visible);
}
void NinePatch::onBlendingChanged(){
for(unsigned i = 0; i != 3; ++i){
for(unsigned j = 0; j != 3; ++j){
this->imageMatrix_v[i][j]->setBlendingParams(this->blendingParams());
}
}
}
| 23.501873
| 135
| 0.631076
|
Mactor2018
|
27398d4050dfe38b74e7be92aaa139b91bd37c3e
| 988
|
cpp
|
C++
|
src/input/InputConfiguration.cpp
|
jaspervdj/JVGS
|
59be35ed61b355b445b82bf32796c0f229e21b60
|
[
"WTFPL"
] | 31
|
2015-02-02T04:51:10.000Z
|
2021-02-20T10:04:41.000Z
|
src/input/InputConfiguration.cpp
|
jaspervdj/JVGS
|
59be35ed61b355b445b82bf32796c0f229e21b60
|
[
"WTFPL"
] | 2
|
2016-08-30T09:26:31.000Z
|
2016-09-14T20:01:20.000Z
|
src/input/InputConfiguration.cpp
|
jaspervdj/JVGS
|
59be35ed61b355b445b82bf32796c0f229e21b60
|
[
"WTFPL"
] | 7
|
2015-02-02T05:02:09.000Z
|
2021-12-24T06:53:01.000Z
|
#include "InputConfiguration.h"
#include "../core/LogManager.h"
using namespace jvgs::core;
using namespace std;
namespace jvgs
{
namespace input
{
InputConfiguration::InputConfiguration()
{
}
InputConfiguration::~InputConfiguration()
{
}
InputConfiguration *InputConfiguration::getConfiguration()
{
static InputConfiguration configuration;
return &configuration;
}
const Key &InputConfiguration::getKey(const string &action)
{
map<string, Key>::iterator result = keys.find(action);
if(result != keys.end())
return result->second;
else
LogManager::getInstance()->error(
"No key defined for action '%s'", action.c_str());
}
void InputConfiguration::setKey(const string &action, const Key &key)
{
keys[action] = key;
}
}
}
| 23.52381
| 77
| 0.554656
|
jaspervdj
|
273cc8c66a8ab4bb13e42655a91d801541d9d465
| 1,609
|
hpp
|
C++
|
src/Core/Window.hpp
|
llGuy/Ondine
|
325c2d3ea5bd5ef5456b0181c53ad227571fada3
|
[
"MIT"
] | 1
|
2022-01-24T18:15:56.000Z
|
2022-01-24T18:15:56.000Z
|
src/Core/Window.hpp
|
llGuy/Ondine
|
325c2d3ea5bd5ef5456b0181c53ad227571fada3
|
[
"MIT"
] | null | null | null |
src/Core/Window.hpp
|
llGuy/Ondine
|
325c2d3ea5bd5ef5456b0181c53ad227571fada3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "IO.hpp"
#include <string_view>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Event.hpp"
#include "Time.hpp"
#include "Utils.hpp"
namespace Ondine::Core {
enum class WindowMode {
Fullscreen,
Windowed
};
using SurfaceCreationProc = void(*)(
struct VkInstance_T *instance,
struct VkSurfaceKHR_T **surface,
void *windowHandle);
/* To pass to graphics context */
struct WindowContextInfo {
void *handle;
Resolution resolution;
SurfaceCreationProc surfaceCreateProc;
};
class Window {
public:
Window(
WindowMode mode,
const std::string_view &title,
const Resolution &resolution = {});
WindowContextInfo init(OnEventProc callback);
void pollInput();
void toggleFullscreen();
void changeCursorDisplay(bool show);
static void initWindowAPI();
private:
void keyCallback(int key, int scancode, int action, int mods) const;
void mouseButtonCallback(int button, int action, int mods) const;
void charCallback(unsigned int codePoint) const;
void cursorMoveCallback(float x, float y) const;
void resizeCallback(unsigned width, unsigned height);
void scrollCallback(float x, float y) const;
void closeCallback() const;
static void createVulkanSurface(
struct VkInstance_T *instance,
struct VkSurfaceKHR_T **surface,
void *windowHandle);
private:
GLFWwindow *mHandle;
Resolution mResolution;
Resolution mPreviousWindowedResolution;
OnEventProc mEventCallback;
WindowMode mWindowMode;
bool mIsFullscreen;
bool mResized;
glm::ivec2 mPreviousWindowedPosition;
const std::string_view mTitle;
};
}
| 22.347222
| 70
| 0.747669
|
llGuy
|
2744efcee9ee1238eb1db6f9df77044fae3d1a37
| 156
|
hpp
|
C++
|
game_server/src/server_ui.hpp
|
CellWarsOfficial/CellWars
|
40b1e956c871ee686062eba1251a9f9a43d86c2c
|
[
"Apache-2.0"
] | 5
|
2017-07-20T10:36:23.000Z
|
2018-01-30T16:18:31.000Z
|
game_server/src/server_ui.hpp
|
CellWarsOfficial/CellWars
|
40b1e956c871ee686062eba1251a9f9a43d86c2c
|
[
"Apache-2.0"
] | null | null | null |
game_server/src/server_ui.hpp
|
CellWarsOfficial/CellWars
|
40b1e956c871ee686062eba1251a9f9a43d86c2c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef SERVER_UI_H
#define SERVER_UI_H
#include <log.hpp>
extern Game *game;
void signal_interpreter(int s);
void init_server_ui(Logger *log);
#endif
| 12
| 33
| 0.762821
|
CellWarsOfficial
|
2746c88ef909c7345bcb0470a83a4b4fe1616962
| 69,161
|
cpp
|
C++
|
cdl/CDL_interface.cpp
|
disi33/libRetroReversing
|
1c825a1971820dbb73fcc96aa444408f6b65803d
|
[
"MIT"
] | null | null | null |
cdl/CDL_interface.cpp
|
disi33/libRetroReversing
|
1c825a1971820dbb73fcc96aa444408f6b65803d
|
[
"MIT"
] | null | null | null |
cdl/CDL_interface.cpp
|
disi33/libRetroReversing
|
1c825a1971820dbb73fcc96aa444408f6b65803d
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include <stdio.h>
#include <map>
#include <fstream>
#include <iostream>
#include <sstream>
#include "../cdl/CDL_FileWriting.hpp"
#include "nlohmann/json.hpp"
using json = nlohmann::json;
using namespace std;
#include "CDL.hpp"
extern json fileConfig;
extern json reConfig;
extern json playthough_function_usage;
extern json libRR_console_constants;
json libultra_signatures;
json linker_map_file;
#define USE_CDL 1;
extern std::map<uint32_t,string> memory_to_log;
extern std::map<uint32_t,char> jumps;
extern std::map<uint32_t,string> audio_address;
extern std::map<uint32_t,uint8_t> cached_jumps;
std::map<uint32_t, uint8_t*> jump_data;
extern std::map<uint32_t,uint32_t> rsp_reads;
extern std::map<uint32_t,uint32_t> rdram_reads;
std::map<uint32_t,bool> offsetHasAssembly;
extern "C" {
// TODO: move the following includes, they are for N64
// #include "../main/rom.h"
// #include "../device/r4300/tlb.h"
// #include "../device/r4300/r4300_core.h"
// #include "../device/memory/memory.h"
// TODO: need to log input and then call input.keyDown(keymod, keysym);
//
// # Variables
//
string rom_name = "UNKNOWN_ROM"; // ROM_PARAMS.headername
int corrupt_start = 0xb2b77c;
int corrupt_end = 0xb2b77c;
int difference = corrupt_end-corrupt_start;
void find_most_similar_function(uint32_t function_offset, string bytes);
bool libRR_finished_boot_rom = false;
string last_reversed_address = "";
bool should_reverse_jumps = false;
bool should_change_jumps = false;
int frame_last_reversed = 0;
int time_last_reversed = 0;
string libRR_game_name = "";
string ucode_crc = "";
// string next_dma_type = "";
// uint32_t previous_function = 0;
std::vector<uint32_t> function_stack = std::vector<uint32_t>();
std::vector<uint32_t> previous_ra; // previous return address
std::map<uint32_t, std::map<string, string> > addresses;
uint32_t rspboot = 0;
#define NUMBER_OF_MANY_READS 40
#define NUMBER_OF_MANY_WRITES 40
//
// # Toggles
//
bool support_n64_prints = false;
bool cdl_log_memory = false;
bool tag_functions = false;
bool log_notes = false;
bool log_function_calls = false;
bool log_ostasks = false;
bool log_rsp = false;
void cdl_keyevents(int keysym, int keymod) {
#ifndef USE_CDL
return;
#endif
printf("event_sdl_keydown frame:%d key:%d modifier:%d \n", l_CurFrame, keysym, keymod);
should_reverse_jumps = false;
// S key
if (keysym == 115) {
printf("Lets save! \n");
main_state_save(0, NULL);
}
// L Key
if (keysym == 108) {
printf("Lets load! \n");
main_state_load(NULL);
}
// Z Key
if (keysym == 122) {
write_rom_mapping();
cdl_log_memory = !cdl_log_memory;
tag_functions = !tag_functions;
// should_change_jumps = true;
//should_reverse_jumps = true;
// show_interface();
}
}
bool createdCartBackup = false;
void backupCart() {
// libRR_game_name = alphabetic_only_name((char*)rom_name.c_str(), 21);
std::cout << "TODO: backup";
createdCartBackup = true;
}
void resetCart() {
std::cout << "TODO: reset";
}
void readLibUltraSignatures() {
std::ifstream i("libultra.json");
if (i.good()) {
i >> libultra_signatures;
}
if (libultra_signatures.find("function_signatures") == libultra_signatures.end()) {
libultra_signatures["function_signatures"] = R"([])"_json;
}
}
void saveLibUltraSignatures() {
std::ofstream o("libultra.json");
o << libultra_signatures.dump(1) << std::endl;
}
void setTogglesBasedOnConfig() {
cdl_log_memory = reConfig["shouldLogMemory"];
tag_functions = reConfig["shouldTagFunctions"];
log_notes = reConfig["shouldLogNotes"];
log_function_calls = reConfig["shouldLogFunctionCalls"];
support_n64_prints = reConfig["shouldSupportN64Prints"];
log_ostasks = reConfig["shouldLogOsTasks"];
log_rsp = reConfig["shouldLogRsp"];
}
void readJsonFromFile() {
readLibUltraSignatures();
readJsonToObject("symbols.json", linker_map_file);
readJsonToObject("./reconfig.json", reConfig);
setTogglesBasedOnConfig();
string filename = "./configs/";
filename+=rom_name;
filename += ".json";
// read a JSON file
if (!reConfig["startFreshEveryTime"]) {
cout << "Reading previous game config file \n";
readJsonToObject(filename, fileConfig);
}
if (fileConfig.find("jumps") == fileConfig.end()) {
fileConfig["jumps"] = R"([])"_json;
}
if (fileConfig.find("tlbs") == fileConfig.end()) {
fileConfig["tlbs"] = R"([])"_json;
}
if (fileConfig.find("dmas") == fileConfig.end()) {
fileConfig["dmas"] = R"([])"_json;
}
if (fileConfig.find("rsp_reads") == fileConfig.end()) {
fileConfig["rsp_reads"] = R"([])"_json;
}
if (fileConfig.find("rdram_reads") == fileConfig.end())
fileConfig["rdram_reads"] = R"([])"_json;
if (fileConfig.find("reversed_jumps") == fileConfig.end())
fileConfig["reversed_jumps"] = R"({})"_json;
if (fileConfig.find("labels") == fileConfig.end())
fileConfig["labels"] = R"([])"_json;
if (fileConfig.find("jump_returns") == fileConfig.end())
fileConfig["jump_returns"] = R"([])"_json;
if (fileConfig.find("memory_to_log") == fileConfig.end())
fileConfig["memory_to_log"] = R"([])"_json;
memory_to_log = fileConfig["memory_to_log"].get< std::map<uint32_t,string> >();
memory_to_log[0x0E5320] = "rsp.boot";
jumps = fileConfig["jumps"].get< std::map<uint32_t,char> >();
tlbs = fileConfig["tlbs"].get< std::map<uint32_t,cdl_tlb> >();
dmas = fileConfig["dmas"].get< std::map<uint32_t,cdl_dma> >();
rsp_reads = fileConfig["rsp_reads"].get< std::map<uint32_t,uint32_t> >();
rdram_reads = fileConfig["rdram_reads"].get< std::map<uint32_t,uint32_t> >();
labels = fileConfig["labels"].get< std::map<uint32_t,cdl_labels> >();
jump_returns = fileConfig["jump_returns"].get< std::map<uint32_t,cdl_jump_return> >();
}
void saveJsonToFile() {
string filename = "./configs/";
filename += rom_name;
filename += ".json";
std::ofstream o(filename);
o << fileConfig.dump(1) << std::endl;
}
void show_interface() {
int answer;
std::cout << "1) Reset ROM 2) Change corrupt number ";
std::cin >> std::hex >> answer;
if (answer == 1) {
std::cout << "Resetting ROM";
resetCart();
}
else {
std::cout << "Unknown command";
}
printf("Answer: %d \n", answer);
}
void corrupt_if_in_range(uint8_t* mem, uint32_t proper_cart_address) {
// if (proper_cart_address >= corrupt_start && proper_cart_address <= corrupt_end) { //l_CurFrame == 0x478 && length == 0x04) { //} proper_cart_address == 0xb4015c) {
// printf("save_state_before\n");
// main_state_save(0, "before_corruption");
// printBytes(mem, proper_cart_address);
// printf("MODIFIED IT!! %#08x\n\n\n", mem[proper_cart_address+1]);
// corruptBytes(mem, proper_cart_address, 10);
// printBytes(mem, proper_cart_address);
// }
}
void corruptBytes(uint8_t* mem, uint32_t cartAddr, int times) {
#ifndef USE_CDL
return;
#endif
if (times>difference) {
times=difference/4;
}
// srand(time(NULL)); //doesn't work on windows
printf("Corrupt Start: %d End: %d Difference: %d \n", corrupt_start, corrupt_end, difference);
int randomNewValue = rand() % 0xFF;
for (int i=0; i<=times; i++) {
int randomOffset = rand() % difference;
int currentOffset = randomOffset;
printf("Offset: %d OldValue: %#08x NewValue: %#08x \n", currentOffset, mem[cartAddr+currentOffset], randomNewValue);
mem[cartAddr+currentOffset] = randomNewValue;
}
}
void cdl_log_opcode(uint32_t program_counter, uint8_t* op_address) {
// only called in pure_interp mode
// jump_data[program_counter] = op_address;
// if (!labels[function_stack.back()].generatedSignature) {
// printf("Not generated sig yet: %#08x \n", *op_address);
// }
}
int note_count = 0;
void add_note(uint32_t pc, uint32_t target, string problem) {
if (!log_notes) return;
if (labels[function_stack.back()].doNotLog) return;
std::stringstream sstream;
sstream << std::hex << "pc:0x" << pc << "-> 0x" << target;
sstream << problem << " noteNumber:"<<note_count;
// cout << sstream.str();
labels[function_stack.back()].notes[pc] = sstream.str();
note_count++;
}
uint32_t map_assembly_offset_to_rom_offset(uint32_t assembly_offset, uint32_t tlb_mapped_addr) {
// or if its in KSEG0/1
if (assembly_offset >= 0x80000000) {
uint32_t mapped_offset = assembly_offset & UINT32_C(0x1ffffffc);
// std::cout << "todo:" << std::hex << assembly_offset << "\n";
return map_assembly_offset_to_rom_offset(mapped_offset, assembly_offset);
}
for(auto it = tlbs.begin(); it != tlbs.end(); ++it) {
auto t = it->second;
if (assembly_offset>=t.start && assembly_offset <=t.end) {
uint32_t mapped_offset = t.rom_offset + (assembly_offset-t.start);
return map_assembly_offset_to_rom_offset(mapped_offset, assembly_offset);
}
}
for(auto it = dmas.begin(); it != dmas.end(); ++it) {
auto& t = it->second;
if (assembly_offset>=t.dram_start && assembly_offset <=t.dram_end) {
uint32_t mapped_offset = t.rom_start + (assembly_offset-t.dram_start);
t.is_assembly = true;
t.tbl_mapped_addr = tlb_mapped_addr;
// DMA is likely the actual value in rom
return mapped_offset;
}
}
// std::cout << "Not in dmas:" << std::hex << assembly_offset << "\n";
// std::cout << "Unmapped: " << std::hex << assembly_offset << "\n";
return assembly_offset;
}
uint32_t current_function = 0;
void log_dma_write(uint8_t* mem, uint32_t proper_cart_address, uint32_t cart_addr, uint32_t length, uint32_t dram_addr) {
if (dmas.find(proper_cart_address) != dmas.end() )
return;
auto t = cdl_dma();
t.dram_start=dram_addr;
t.dram_end = dram_addr+length;
t.rom_start = proper_cart_address;
t.rom_end = proper_cart_address+length;
t.length = length;
t.ascii_header = get_header_ascii(mem, proper_cart_address);
t.header = mem[proper_cart_address+3];
t.frame = l_CurFrame;
// if (function_stack.size() > 0 && labels.find(current_function) != labels.end()) {
t.func_addr = print_function_stack_trace(); // labels[current_function].func_name;
// }
dmas[proper_cart_address] = t;
// std::cout << "DMA: Dram:0x" << std::hex << t.dram_start << "->0x" << t.dram_end << " Length:0x" << t.length << " " << t.ascii_header << " Stack:" << function_stack.size() << " " << t.func_addr << " last:"<< function_stack.back() << "\n";
}
void cdl_finish_pi_dma(uint32_t a) {
// cout <<std::hex<< "Finish PI DMA:" << a << "\n";
}
void cdl_finish_si_dma(uint32_t a) {
cout <<std::hex<< "Finish SI DMA:" << a << "\n";
}
void cdl_finish_ai_dma(uint32_t a) {
// cout <<std::hex<< "Finish AI DMA:" << (a & 0xffffff) << "\n";
}
void cdl_clear_dma_log() {
// next_dma_type = "cleared";
}
void cdl_clear_dma_log2() {
// next_dma_type = "interesting";
}
void cdl_log_cart_reg_access() {
// next_dma_type = "bin";
add_tag_to_function("_cartRegAccess", function_stack.back());
}
void cdl_log_dma_si_read() {
add_tag_to_function("_dmaSiRead", function_stack.back());
}
void cdl_log_copy_pif_rdram() {
add_tag_to_function("_copyPifRdram", function_stack.back());
}
void cdl_log_si_reg_access() {
// COntrollers, rumble paks etc
add_tag_to_function("_serialInterfaceRegAccess", function_stack.back());
}
void cdl_log_mi_reg_access() {
// The MI performs the read, modify, and write operations for the individual pixels at either one pixel per clock or one pixel for every two clocks. The MI also has special modes for loading the TMEM, filling rectangles (fast clears), and copying multiple pixels from the TMEM into the framebuffer (sprites).
add_tag_to_function("_miRegRead", function_stack.back());
}
void cdl_log_mi_reg_write() {
// The MI performs the read, modify, and write operations for the individual pixels at either one pixel per clock or one pixel for every two clocks. The MI also has special modes for loading the TMEM, filling rectangles (fast clears), and copying multiple pixels from the TMEM into the framebuffer (sprites).
add_tag_to_function("_miRegWrite", function_stack.back());
}
void cdl_log_pi_reg_read() {
if (function_stack.size() > 0)
add_tag_to_function("_piRegRead", function_stack.back());
}
void cdl_log_pi_reg_write() {
if (function_stack.size() > 0)
add_tag_to_function("_piRegWrite", function_stack.back());
}
void cdl_log_read_rsp_regs2() {
add_tag_to_function("_rspReg2Read", function_stack.back());
}
void cdl_log_write_rsp_regs2() {
add_tag_to_function("_rspReg2Write", function_stack.back());
}
void cdl_log_read_rsp_regs() {
if (function_stack.size() > 0)
add_tag_to_function("_rspRegRead", function_stack.back());
}
void cdl_log_write_rsp_regs() {
if (function_stack.size() > 0)
add_tag_to_function("_rspRegWrite", function_stack.back());
}
void cdl_log_update_sp_status() {
if (function_stack.size() > 0)
add_tag_to_function("_updatesSPStatus", function_stack.back());
}
void cdl_common_log_tag(const char* tag) {
if (function_stack.size() > 0)
add_tag_to_function(tag, function_stack.back());
}
void cdl_log_audio_reg_access() {
// TODO speed this up with a check first
add_tag_to_function("_audioRegAccess", function_stack.back());
}
string print_function_stack_trace() {
if (function_stack.size() ==0 || functions.size() ==0 /*|| labels.size() ==0*/ || function_stack.size() > 0xF) {
return "";
}
std::stringstream sstream;
int current_stack_number = 0;
for (auto& it : function_stack) {
if (strcmp(functions[it].func_name.c_str(),"") == 0) {
sstream << "0x" << std::hex << it<< "->";
continue;
}
if (current_stack_number>0) {
sstream << "->";
}
sstream << functions[it].func_name;
current_stack_number++;
}
// cout << "Stack:"<< sstream.str() << "\n";
return sstream.str();
}
void resetReversing() {
// time_last_reversed = time(0); // doesn;t work on windows
last_reversed_address="";
}
void save_cdl_files() {
resetReversing();
find_asm_sections();
find_audio_sections();
find_audio_functions();
save_dram_rw_to_json();
saveJsonToFile();
saveLibUltraSignatures();
}
uint32_t cdl_get_alternative_jump(uint32_t current_jump) {
if (!should_change_jumps) {
return current_jump;
}
for (auto& it : linker_map_file.items()) {
uint32_t new_jump = hex_to_int(it.key());
cout << "it:" << it.value() << " = " << it.key() << " old:" << current_jump << " new:"<< new_jump << "\n";
linker_map_file.erase(it.key());
should_change_jumps = false;
return new_jump;
}
return current_jump;
}
int reverse_jump(int take_jump, uint32_t jump_target) {
// this function doesn't work on windows
// time_t now = time(0);
// string key = n2hexstr(jump_target);
// printf("Reversing jump %#08x %d \n", jump_target, jumps[jump_target]);
// take_jump = !take_jump;
// time_last_reversed = now;
// frame_last_reversed=l_CurFrame;
// last_reversed_address = key;
// fileConfig["reversed_jumps"][key] = jumps[jump_target];
// write_rom_mapping();
return take_jump;
}
void cdl_log_jump_cached(int take_jump, uint32_t jump_target, uint8_t* jump_target_memory) {
if (cached_jumps.find(jump_target) != cached_jumps.end() )
return;
cached_jumps[jump_target] = 1;
cout << "Cached:" << std::hex << jump_target << "\n";
}
int number_of_functions = 0;
bool libRR_full_function_log = false;
bool libRR_full_trace_log = true;
int last_return_address = 0;
uint32_t libRR_call_depth = 0; // Tracks how big our stack trace is in terms of number of function calls
// We store the stackpointers in backtrace_stackpointers everytime a function gets called
uint16_t libRR_backtrace_stackpointers[0x200]; // 0x200 should be tons of function calls
uint32_t libRR_backtrace_size = 0; // Used with backtrace_stackpointers - Tracks how big our stack trace is in terms of number of function calls
extern uint32_t libRR_pc_lookahead;
string current_trace_log = "";
const int trace_messages_until_flush = 40;
int current_trace_count = 0;
bool first_trace_write = true;
void libRR_log_trace_str(string message) {
if (!libRR_full_trace_log) {
return;
}
current_trace_log += message + "\n";
current_trace_count++;
if (current_trace_count >= trace_messages_until_flush) {
libRR_log_trace_flush();
current_trace_count = 0;
current_trace_log="";
}
}
void libRR_log_trace(const char* message) {
libRR_log_trace_str(message);
}
void libRR_log_trace_flush() {
if (!libRR_full_trace_log) {
return;
}
string output_file_path = libRR_export_directory + "trace_log.txt";
if (first_trace_write) {
codeDataLogger::writeStringToFile(output_file_path, current_trace_log);
first_trace_write = false;
} else {
codeDataLogger::appendStringToFile(output_file_path, current_trace_log);
}
}
// libRR_log_return_statement
// stack_pointer is used to make sure our function stack doesn't exceed the actual stack pointer
void libRR_log_return_statement(uint32_t current_pc, uint32_t return_target, uint32_t stack_pointer) {
if (libRR_full_trace_log) {
libRR_log_trace_str("Return:"+n2hexstr(current_pc)+"->"+n2hexstr(return_target));
}
// printf("libRR_log_return_statement pc:%d return:%d stack:%d\n", current_pc, return_target, 65534-stack_pointer);
// check the integrety of the call stack
if (libRR_call_depth < 0) {
printf("Function seems to have returned without changing the stack, PC: %d \n", current_pc);
}
auto function_returning_from = function_stack.back();
auto presumed_return_address = previous_ra.back();
if (return_target != presumed_return_address) {
// printf("ERROR: Presumed return: %d actual return: %d current_pc: %d\n", presumed_return_address, return_target, current_pc);
// sometimes code manually pushes the ret value to the stack and returns
// if so we don't want to log as a function return
// but in the future we might want to consider making the previous jump a function call
return;
} else {
libRR_call_depth--;
// Remove from stacks
function_stack.pop_back();
previous_ra.pop_back();
}
if (!libRR_full_function_log) {
return;
}
current_pc -= libRR_pc_lookahead;
string current_function = n2hexstr(function_returning_from);
string current_pc_str = n2hexstr(current_pc);
// printf("Returning from function: %s current_pc:%s \n", current_function.c_str(), current_pc_str.c_str());
// string function_key = current_function;
playthough_function_usage[current_function]["returns"][current_pc_str] = return_target;
// Add max return to functions
if (functions.find(function_returning_from) != functions.end() ) {
uint32_t relative_return_pc = current_pc - function_returning_from;
if (relative_return_pc > functions[function_returning_from].return_offset_from_start) {
functions[function_returning_from].return_offset_from_start = relative_return_pc;
}
}
// TODO: Calculate Function Signature so we can check for its name
int length = current_pc - function_returning_from;
string length_str = n2hexstr(length);
playthough_function_usage[current_function]["lengths"][length_str] = length;
if (length > 0 && length < 200) {
if (playthough_function_usage[current_function]["signatures"].contains(length_str)) {
} else {
printf("Function Signature: About to get length: %d \n", length);
playthough_function_usage[current_function]["signatures"][n2hexstr(length)] = libRR_get_data_for_function(function_returning_from, length+1, true, true);
}
}
// string bytes_with_branch_delay = printBytesToStr(jump_data[previous_function_backup], byte_len+4)+"_"+n2hexstr(length+4);
// string word_pattern = printWordsToStr(jump_data[previous_function_backup], byte_len+4)+" L"+n2hexstr(length+4,4);
// TODO: need to get the moment where the bytes for the function are located
// printf("Logged inst: %s \n", name.c_str());
}
// libRR_log_full_function_call is expensive as it does extensive logging
void libRR_log_full_function_call(uint32_t current_pc, uint32_t jump_target) {
// Instead of using function name, we just use the location
string function_name = /*game_name + "_func_" +*/ n2hexstr(jump_target);
// printf("libRR_log_full_function_call Full function logging on %s \n", print_function_stack_trace().c_str());
// This is playthough specific
if (!playthough_function_usage.contains(function_name)) {
// printf("Adding new function %s \n", function_name.c_str());
playthough_function_usage[function_name] = json::parse("{}");
playthough_function_usage[function_name]["first_frame_access"] = RRCurrentFrame;
playthough_function_usage[function_name]["number_of_frames"]=0;
playthough_function_usage[function_name]["last_frame_access"] = 0;
playthough_function_usage[function_name]["number_of_calls_per_frame"] = 1;
}
else if (RRCurrentFrame < playthough_function_usage[function_name]["last_frame_access"]) {
// we have already ran this frame before, probably replaying, no need to add more logging
return;
}
if (RRCurrentFrame > playthough_function_usage[function_name]["last_frame_access"]) {
playthough_function_usage[function_name]["last_frame_access"] = RRCurrentFrame;
playthough_function_usage[function_name]["number_of_frames"]= (int)playthough_function_usage[function_name]["number_of_frames"]+1;
playthough_function_usage[function_name]["number_of_calls_per_frame"]=0;
}
else if (RRCurrentFrame == playthough_function_usage[function_name]["last_frame_access"]) {
// we are in the same frame so its called more than once per frame
playthough_function_usage[function_name]["number_of_calls_per_frame"]=(int)playthough_function_usage[function_name]["number_of_calls_per_frame"]+1;
}
// TODO: log read/writes to memory
// TODO: calculate return and paramerters
// TODO: find out how long the function is
}
const char* libRR_log_long_jump(uint32_t current_pc, uint32_t jump_target, const char* type) {
// cout << "Long Jump from:" << n2hexstr(current_pc) << " to:" << n2hexstr(jump_target) << "\n";
if (libRR_full_trace_log) {
libRR_log_trace_str("Long Jump:"+n2hexstr(current_pc)+"->"+n2hexstr(jump_target)+" type:"+type);
}
string target_bank_number = "0000";
string pc_bank_number = "0000";
target_bank_number = n2hexstr(get_current_bank_number_for_address(jump_target), 4);
// now we need the bank number of the function we are calling
pc_bank_number = n2hexstr(get_current_bank_number_for_address(current_pc), 4);
libRR_long_jumps[target_bank_number][n2hexstr(jump_target)][pc_bank_number+"::"+n2hexstr(current_pc)]=type;
return libRR_log_jump_label(jump_target, current_pc);
}
void libRR_log_interrupt_call(uint32_t current_pc, uint32_t jump_target) {
string pc_bank_number = "0000";
pc_bank_number = n2hexstr(get_current_bank_number_for_address(current_pc), 4);
// printf("Interrupt call at: %s::%s target:%s \n", pc_bank_number.c_str(), n2hexstr(current_pc).c_str(), n2hexstr(jump_target).c_str());
libRR_long_jumps["0000"][n2hexstr(jump_target)][pc_bank_number+"::"+n2hexstr(current_pc)]=true;
}
// Restarts are very similar to calls but can only jump to specific targets and only take up 1 byte
void libRR_log_rst(uint32_t current_pc, uint32_t jump_target) {
// for now just log it as a standard function call
libRR_log_function_call(current_pc, jump_target, 0x00);
}
string function_name = ""; // last function name called
const char* libRR_log_function_call(uint32_t current_pc, uint32_t jump_target, uint32_t stack_pointer) {
// TODO: find out why uncommeting the following causes a segfault
// if (!libRR_full_function_log || !libRR_finished_boot_rom) {
// return;
// }
string bank_number = "0000";
uint32_t calculated_jump_target = jump_target;
if (libRR_bank_switching_available) {
int bank = get_current_bank_number_for_address(jump_target);
bank_number = n2hexstr(bank, 4);
// TODO: the following might be gameboy specific
if (jump_target >= libRR_bank_size) {
// printf("TODO: remove this in gameboy!\n");
calculated_jump_target = jump_target + ((bank-1) * libRR_bank_size);
}
// END TODO
}
string jump_target_str = n2hexstr(jump_target);
function_name = "_"+bank_number+"_func_"+jump_target_str;
libRR_called_functions[bank_number][n2hexstr(jump_target)] = function_name;
libRR_log_trace_str("Function call: 0x"+jump_target_str);
// Start Stacktrace handling
libRR_call_depth++;
// End Stacktrace handling
last_return_address = current_pc;
function_stack.push_back(jump_target);
previous_ra.push_back(current_pc);
if (libRR_full_function_log) {
libRR_log_full_function_call(current_pc, jump_target);
}
if (functions.find(jump_target) != functions.end() ) {
// We have already logged this function, so ignore for now
return function_name.c_str();
}
// We have never logged this function so lets create it
auto t = cdl_labels();
t.func_offset = n2hexstr(calculated_jump_target);
// if (functions.find(previous_function_backup) != functions.end()) {
// t.caller_offset = functions[previous_function_backup].func_name+" (ra:"+n2hexstr(ra)+")";
// } else {
// t.caller_offset = n2hexstr(previous_function_backup);
// }
t.func_name = function_name; // /*libRR_game_name+*/"_"+bank_number+"_func_"+jump_target_str;
//t.func_stack = function_stack.size();
//t.export_path = "";
//t.bank_number = bank_number;
//t.bank_offset = jump_target;
// t.stack_trace = print_function_stack_trace();
t.doNotLog = false;
t.many_memory_reads = false;
t.many_memory_writes = false;
// t.additional["callers"][print_function_stack_trace()] = RRCurrentFrame;
printf("Logged new function: %s target:%d number_of_functions:%d \n", t.func_name.c_str(), jump_target, number_of_functions);
functions[jump_target] = t;
number_of_functions++;
return function_name.c_str();
}
// This will be replace be libRR_log_function_call
void log_function_call(uint32_t function_that_is_being_called) {
if (!log_function_calls) return;
uint32_t function_that_is_calling = function_stack.back();
if (labels.find(function_that_is_calling) == labels.end()) return;
if (labels[function_that_is_calling].isRenamed || labels[function_that_is_calling].doNotLog) return;
labels[function_that_is_calling].function_calls[function_that_is_being_called] = labels[function_that_is_being_called].func_name;
}
void cdl_log_jump_always(int take_jump, uint32_t jump_target, uint8_t* jump_target_memory, uint32_t ra, uint32_t pc) {
add_note(ra-8, pc, "Call (jal)");
previous_ra.push_back(ra);
uint32_t previous_function_backup = function_stack.back();
function_stack.push_back(jump_target);
current_function = jump_target;
if (jumps[jump_target] >3) return;
jumps[jump_target] = 0x04;
if (labels.find(jump_target) != labels.end() )
return;
log_function_call(jump_target);
auto t = cdl_labels();
string jump_target_str = n2hexstr(jump_target);
t.func_offset = jump_target_str;
if (labels.find(previous_function_backup) != labels.end()) {
t.caller_offset = labels[previous_function_backup].func_name+" (ra:"+n2hexstr(ra)+")";
} else {
t.caller_offset = n2hexstr(previous_function_backup);
}
t.func_name = libRR_game_name+"_func_"+jump_target_str;
t.func_stack = function_stack.size();
t.stack_trace = print_function_stack_trace();
t.doNotLog = false;
t.many_memory_reads = false;
t.many_memory_writes = false;
labels[jump_target] = t;
jump_data[jump_target] = jump_target_memory;
}
void cdl_log_jump_return(int take_jump, uint32_t jump_target, uint32_t pc, uint32_t ra, int64_t* registers, struct r4300_core* r4300) {
uint32_t previous_function_backup = -1;
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
// if (previous_function_backup > ra) {
// // cout << std::hex << " Odd the prev function start should never be before return address ra:" << ra << " previous_function_backup:" << previous_function_backup << "\n";
// return;
// }
if (function_stack.size()>0) {
previous_function_backup = function_stack.back();
}
else {
add_note(pc, jump_target, "function_stack <0");
// probably jumping from exception?
// cout << "Missed push back?" << std::hex << jump_target << " ra" << ra << " pc:"<< pc<< "\n";
// return;
}
if (jump_target == previous_ra.back()) {
add_note(pc, jump_target, "successful return");
} else {
string problem = "Expected $ra to be 0x";
problem += n2hexstr(previous_ra.back());
problem += " but was:";
problem += n2hexstr(jump_target);
add_note(pc, jump_target, problem);
// return;
}
function_stack.pop_back();
current_function = function_stack.back();
previous_ra.pop_back();
console_log_jump_return(take_jump, jump_target, pc, ra, registers, r4300);
if (jumps[jump_target] >3) return;
jumps[jump_target] = 0x04;
if (jump_returns.find(previous_function_backup) != jump_returns.end())
{
return;
}
auto t = cdl_jump_return();
string jump_target_str = n2hexstr(jump_target);
t.return_offset = pc;
t.func_offset = previous_function_backup;
t.caller_offset = jump_target;
jump_returns[previous_function_backup] = t;
uint64_t length = pc-previous_function_backup;
// labels[previous_function_backup].return_offset_from_start = length;
if (length<2) {
return;
}
if (jump_data.find(previous_function_backup) != jump_data.end()) {
uint64_t byte_len = length;
if (byte_len > 0xFFFF) {
byte_len = 0xFFFF;
}
// string bytes = printBytesToStr(jump_data[previous_function_backup], byte_len)+"_"+n2hexstr(length);
string bytes_with_branch_delay = printBytesToStr(jump_data[previous_function_backup], byte_len+4)+"_"+n2hexstr(length+4);
string word_pattern = printWordsToStr(jump_data[previous_function_backup], byte_len+4)+" L"+n2hexstr(length+4,4);
labels[previous_function_backup].function_bytes = bytes_with_branch_delay;
labels[previous_function_backup].doNotLog = true;
labels[previous_function_backup].generatedSignature = true;
// labels[previous_function_backup].function_bytes_endian = Swap4Bytes(bytes);
// now check to see if its in the mario map
// if (/*strcmp(game_name.c_str(),"SUPERMARIO") == 0 &&*/ linker_map_file.find( n2hexstr(previous_function_backup) ) != linker_map_file.end()) {
// string offset = n2hexstr(previous_function_backup);
// string func_name = linker_map_file[offset];
// cout << game_name << "It is in the map file!" << n2hexstr(previous_function_backup) << " as:" << linker_map_file[n2hexstr(previous_function_backup)] << "\n";
// function_signatures[bytes] = func_name;
// if (strcmp(func_name.c_str(),"gcc2_compiled.")==0) return; // we don't want gcc2_compiled labels
// libultra_signatures["function_signatures"][bytes_with_branch_delay] = func_name;
// labels[previous_function_backup].func_name = libultra_signatures["function_signatures"][bytes_with_branch_delay];
// return;
// }
// if it is a libultra function then lets name it
if (libultra_signatures["library_signatures"].find(word_pattern) != libultra_signatures["library_signatures"].end()) {
std::cout << "In library_signatures:" << word_pattern << " name:"<< libultra_signatures["library_signatures"][word_pattern] << "\n";
labels[previous_function_backup].func_name = libultra_signatures["library_signatures"][word_pattern];
labels[previous_function_backup].isRenamed = true;
// return since we have already named this functions, don't need its signature to be saved
return;
}
if (libultra_signatures["game_signatures"].find(word_pattern) != libultra_signatures["game_signatures"].end()) {
// std::cout << "In game_signatures:" << word_pattern << " name:"<< libultra_signatures["game_signatures"][word_pattern] << "\n";
labels[previous_function_backup].func_name = libultra_signatures["game_signatures"][word_pattern];
// return since we have already named this functions, don't need its signature to be saved
return;
}
// if it is a libultra function then lets name it
if (libultra_signatures["function_signatures"].find(bytes_with_branch_delay) != libultra_signatures["function_signatures"].end()) {
std::cout << "In old libultra:" << bytes_with_branch_delay << " name:"<< libultra_signatures["function_signatures"][bytes_with_branch_delay] << "\n";
labels[previous_function_backup].func_name = libultra_signatures["function_signatures"][bytes_with_branch_delay];
if (labels[previous_function_backup].func_name.find("_func_") != std::string::npos) {
// this is a non renamed function as it was auto generated
find_most_similar_function(previous_function_backup, word_pattern);
libultra_signatures["game_signatures"][word_pattern] = labels[previous_function_backup].func_name;
}
else {
libultra_signatures["library_signatures"][word_pattern] = labels[previous_function_backup].func_name;
labels[previous_function_backup].isRenamed = true;
}
libultra_signatures["function_signatures"].erase(bytes_with_branch_delay);
// return since we have already named this functions, don't need its signature to be saved
return;
}
// if it is an OLD libultra function then lets name it (without branch delay)
// if (libultra_signatures["function_signatures"].find(bytes) != libultra_signatures["function_signatures"].end()) {
// std::cout << "In OLDEST libultra:" << bytes << " name:"<< libultra_signatures["function_signatures"][bytes] << "\n";
// labels[previous_function_backup].func_name = libultra_signatures["function_signatures"][bytes];
// labels[previous_function_backup].isRenamed = true;
// libultra_signatures["function_signatures"][bytes_with_branch_delay] = labels[previous_function_backup].func_name;
// // delete the old non-branch delay version
// libultra_signatures["function_signatures"].erase(bytes);
// // return since we have already named this functions, don't need its signature to be saved
// return;
// }
find_most_similar_function(previous_function_backup, word_pattern);
// cout << "word_pattern:" << word_pattern << "\n";
if (function_signatures.find(word_pattern) == function_signatures.end()) {
// save this new function to both libultra and trace json
function_signatures[word_pattern] = labels[previous_function_backup].func_name;
libultra_signatures["game_signatures"][word_pattern] = labels[previous_function_backup].func_name;
} else {
//function_signatures.erase(bytes);
// function_signatures[word_pattern] = "Multiple functions";
std::cout << "Multiple Functions for :" << *jump_data[previous_function_backup] << " len:" << length << " pc:0x"<< pc << " - 0x" << previous_function_backup << "\n";
}
}
}
void find_most_similar_function(uint32_t function_offset, string bytes) {
string named_function_with_highest_distance = "";
// string auto_generated_function_with_highest_distance = "";
double highest_distance = 0;
// double highest_auto_distance = 0;
for(auto it = libultra_signatures["library_signatures"].begin(); it != libultra_signatures["library_signatures"].end(); ++it) {
double distance = jaro_winkler_distance(bytes.c_str(), it.key().c_str());
if (distance >= highest_distance) {
string function_name = it.value();
// if (!is_auto_generated_function_name(function_name)) {
if (distance == highest_distance) {
named_function_with_highest_distance += "_or_";
named_function_with_highest_distance += function_name;
} else {
highest_distance = distance;
named_function_with_highest_distance = function_name;
}
// } else {
// highest_auto_distance = distance;
// auto_generated_function_with_highest_distance=function_name;
// }
}
// cout << "IT:" << it.value() << " distance:" << jaro_winkler_distance(bytes_with_branch_delay.c_str(), it.key().c_str()) << "\n";
}
uint32_t highest_distance_percent = highest_distance*100;
// cout << "generated function_with_highest_distance to "<< std::hex << function_offset << " is:"<<auto_generated_function_with_highest_distance<<" with "<< std::dec << highest_auto_distance <<"%\n";
if (highest_distance_percent>=95) {
cout << "function will be renamed "<< std::hex << function_offset << " is:"<<named_function_with_highest_distance<<" with "<< std::dec << highest_distance_percent <<"%\n";
labels[function_offset].func_name = named_function_with_highest_distance;
labels[function_offset].isRenamed = true;
} else if (highest_distance_percent>=90) {
cout << "function_with_highest_distance to "<< std::hex << function_offset << " is:"<<named_function_with_highest_distance<<" with "<< std::dec << highest_distance_percent <<"%\n";
labels[function_offset].func_name += "_predict_"+named_function_with_highest_distance+"_";
labels[function_offset].func_name += (to_string(highest_distance_percent));
labels[function_offset].func_name += "percent";
}
}
// loop through and erse multiple functions
void erase_multiple_func_signatures() {
// function_signatures
// Multiple functions
}
bool is_auto_generated_function_name(string func_name) {
if (func_name.find("_func_") != std::string::npos) {
// this is a non renamed function as it was auto generated
return true;
}
return false;
}
unsigned int find_first_non_executed_jump() {
for(map<unsigned int, char>::iterator it = jumps.begin(); it != jumps.end(); ++it) {
if ((it->second+0) <3) {
return it->first;
}
}
return -1;
}
int cdl_log_jump(int take_jump, uint32_t jump_target, uint8_t* jump_target_memory, uint32_t pc, uint32_t ra) {
add_note(pc, jump_target, "jump");
// if (previous_ra.size() > 0 && ra != previous_ra.back()) {
// cdl_log_jump_always(take_jump, jump_target, jump_target_memory, ra, pc);
// //previous_ra.push_back(ra);
// return take_jump;
// }
// if (should_reverse_jumps)
// {
// time_t now = time(0);
// if (jumps[jump_target] < 3) {
// // should_reverse_jumps=false;
// if ( now-time_last_reversed > 2) { // l_CurFrame-frame_last_reversed >(10*5) ||
// take_jump = reverse_jump(take_jump, jump_target);
// }
// } else if (now-time_last_reversed > 15) {
// printf("Stuck fixing %d\n", find_first_non_executed_jump());
// take_jump=!take_jump;
// main_state_load(NULL);
// // we are stuck so lets load
// }
// }
if (take_jump) {
jumps[jump_target] |= 1UL << 0;
}
else {
jumps[jump_target] |= 1UL << 1;
}
return take_jump;
}
void save_table_mapping(int entry, uint32_t phys, uint32_t start,uint32_t end, bool isOdd) {
//printf("tlb_map:%d ODD Start:%#08x End:%#08x Phys:%#08x \n",entry, e->start_odd, e->end_odd, e->phys_odd);
uint32_t length = end-start;
auto t = cdl_tlb();
t.start=start;
t.end = end;
t.rom_offset = phys;
tlbs[phys]=t;
string key = "";
key+="[0x";
key+=n2hexstr(phys);
key+=", 0x";
key+=n2hexstr(phys+length);
key+="] Virtual: 0x";
key+=n2hexstr(start);
key+=" to 0x";
key+=n2hexstr(end);
if (isOdd)
key+=" Odd";
else
key+=" Even";
string value = "Entry:";
value += to_string(entry);
// value += " Frame:0x";
value += n2hexstr(l_CurFrame);
bool isInJson = fileConfig["tlb"].find(key) != fileConfig["tlb"].end();
if (isInJson) {
string original = fileConfig["tlb"][key];
bool isSameValue = (strcmp(original.c_str(), value.c_str()) == 0);
if (isSameValue) return;
// printf("isSameValue:%d \noriginal:%s \nnew:%s\n", isSameValue, original.c_str(), value.c_str());
return; // don't replace the original value as it is useful to match frame numbers to the mappings
}
fileConfig["tlb"][key] = value;
printf("TLB %s\n", value.c_str());
}
void cdl_log_dram_read(uint32_t address) {
}
void cdl_log_dram_write(uint32_t address, uint32_t value, uint32_t mask) {
}
void cdl_log_rsp_mem(uint32_t address, uint32_t* mem,int isBootRom) {
if (isBootRom) return;
rsp_reads[address] = (uint32_t)*mem;
}
void cdl_log_rdram(uint32_t address, uint32_t* mem,int isBootRom) {
//printf("RDRAM %#08x \n", address);
if (isBootRom) return;
rdram_reads[address] = (uint32_t)*mem;
}
void cdl_log_mm_cart_rom(uint32_t address,int isBootRom) {
printf("Cart ROM %#08x \n", address);
}
void cdl_log_mm_cart_rom_pif(uint32_t address,int isBootRom) {
printf("PIF? %#08x \n", address);
}
void cdl_log_pif_ram(uint32_t address, uint32_t* value) {
#ifndef USE_CDL
return;
#endif
printf("Game was reset? \n");
if (!createdCartBackup) {
backupCart();
readJsonFromFile();
function_stack.push_back(0);
}
if (should_reverse_jumps) {
// should_reverse_jumps = false;
fileConfig["bad_jumps"][last_reversed_address] = "reset";
main_state_load(NULL);
write_rom_mapping();
}
}
void cdl_log_opcode_error() {
printf("Very bad opcode, caused crash! \n");
fileConfig["bad_jumps"][last_reversed_address] = "crash";
main_state_load(NULL);
}
void find_asm_sections() {
printf("finding asm in sections \n");
for(map<unsigned int, char>::iterator it = jumps.begin(); it != jumps.end(); ++it) {
string jump_target_str = n2hexstr(it->first);
fileConfig["jumps_rom"][jump_target_str] = n2hexstr(map_assembly_offset_to_rom_offset(it->first,0));
}
}
void find_audio_sections() {
printf("finding audio sections \n");
for(map<uint32_t, cdl_dma>::iterator it = dmas.begin(); it != dmas.end(); ++it) {
uint32_t address = it->second.dram_start;
if (audio_address.find(address) == audio_address.end() )
continue;
dmas[address].guess_type = "audio";
it->second.guess_type="audio";
}
}
void add_tag_to_function(string tag, uint32_t labelAddr) {
if (!tag_functions || labels[labelAddr].isRenamed) return;
if (labels[labelAddr].func_name.find(tag) != std::string::npos) return;
labels[labelAddr].func_name += tag;
}
void find_audio_functions() {
printf("finding audio functions \n");
for(map<uint32_t, cdl_labels>::iterator it = labels.begin(); it != labels.end(); ++it) {
cdl_labels label = it->second;
if (label.isRenamed) {
continue; // only do it for new functions
}
if (label.many_memory_reads) {
add_tag_to_function("_manyMemoryReads", it->first);
}
if (label.many_memory_writes) {
add_tag_to_function("_manyMemoryWrites", it->first);
}
for(map<string, string>::iterator it2 = label.read_addresses.begin(); it2 != label.read_addresses.end(); ++it2) {
uint32_t address = hex_to_int(it2->first);
if (audio_address.find(address) != audio_address.end() )
{
cout << "Function IS audio:"<< label.func_name << "\n";
}
if (address>0x10000000 && address <= 0x107fffff) {
cout << "Function accesses cart rom:"<< label.func_name << "\n";
}
}
for(map<string, string>::iterator it2 = label.write_addresses.begin(); it2 != label.write_addresses.end(); ++it2) {
uint32_t address = hex_to_int(it2->first);
if (audio_address.find(address) != audio_address.end() )
{
cout << "Function IS audio:"<< label.func_name << "\n";
}
if (address>0x10000000 && address <= 0x107fffff) {
cout << "Function IS cart rom:"<< label.func_name << "\n";
}
}
}
}
bool isAddressCartROM(uint32_t address) {
return (address>0x10000000 && address <= 0x107fffff);
}
void cdl_log_audio_sample(uint32_t saved_ai_dram, uint32_t saved_ai_length) {
if (audio_samples.find(saved_ai_dram) != audio_samples.end() )
return;
auto t = cdl_dram_cart_map();
t.dram_offset = n2hexstr(saved_ai_dram);
t.rom_offset = n2hexstr(saved_ai_length);
audio_samples[saved_ai_dram] = t;
// printf("audio_plugin_push_samples AI_DRAM_ADDR_REG:%#08x length:%#08x\n", saved_ai_dram, saved_ai_length);
}
void cdl_log_cart_rom_dma_write(uint32_t dram_addr, uint32_t cart_addr, uint32_t length) {
if (cart_rom_dma_writes.find(cart_addr) != cart_rom_dma_writes.end() )
return;
auto t = cdl_dram_cart_map();
t.dram_offset = n2hexstr(dram_addr);
t.rom_offset = n2hexstr(cart_addr);
cart_rom_dma_writes[cart_addr] = t;
printf("cart_rom_dma_write: dram_addr:%#008x cart_addr:%#008x length:%#008x\n", dram_addr, cart_addr, length);
}
void cdl_log_dma_sp_write(uint32_t spmemaddr, uint32_t dramaddr, uint32_t length, unsigned char *dram) {
if (dma_sp_writes.find(dramaddr) != dma_sp_writes.end() )
return;
auto t = cdl_dram_cart_map();
t.dram_offset = n2hexstr(dramaddr);
t.rom_offset = n2hexstr(spmemaddr);
dma_sp_writes[dramaddr] = t;
// FrameBuffer RSP info
printWords(dram, dramaddr, length);
printf("FB: dma_sp_write SPMemAddr:%#08x Dramaddr:%#08x length:%#08x \n", spmemaddr, dramaddr, length);
}
inline void cdl_log_memory_common(const uint32_t lsaddr, uint32_t pc) {
// if (addresses.find(lsaddr) != addresses.end() )
// return;
// addresses[lsaddr] = currentMap;
}
void cdl_log_mem_read(const uint32_t lsaddr, uint32_t pc) {
if (!cdl_log_memory) return;
if (memory_to_log.find(lsaddr) != memory_to_log.end() )
{
cout << "Logging Mem Read for 0x"<< std::hex << lsaddr << " At PC:" << pc <<"\n";
}
if (labels[current_function].isRenamed || labels[current_function].doNotLog) {
// only do it for new functions
return;
}
if (labels[current_function].read_addresses.size() > NUMBER_OF_MANY_READS) {
labels[current_function].many_memory_reads = true;
return;
}
// auto currentMap = addresses[lsaddr];
// currentMap[n2hexstr(lsaddr)]=labels[current_function].func_name+"("+n2hexstr(current_function)+"+"+n2hexstr(pc-current_function)+")";
auto offset = pc-current_function;
labels[current_function].read_addresses[n2hexstr(lsaddr)] = "func+0x"+n2hexstr(offset)+" pc=0x"+n2hexstr(pc);
}
void cdl_log_mem_write(const uint32_t lsaddr, uint32_t pc) {
if (!cdl_log_memory) return;
if (memory_to_log.find(lsaddr) != memory_to_log.end() )
{
cout << "Logging Mem Write to 0x"<< std::hex << lsaddr << " At PC:" << pc <<"\n";
}
if (labels[current_function].isRenamed || labels[current_function].doNotLog) {
// only do it for new functions
return;
}
if (labels[current_function].write_addresses.size() > NUMBER_OF_MANY_WRITES) {
labels[current_function].many_memory_writes = true;
return;
}
// auto currentMap = addresses[lsaddr];
// currentMap[n2hexstr(lsaddr)]=labels[current_function].func_name+"("+n2hexstr(current_function)+"+"+n2hexstr(pc-current_function)+")";
auto offset = pc-current_function;
labels[current_function].write_addresses[n2hexstr(lsaddr)] = "+0x"+n2hexstr(offset)+" pc=0x"+n2hexstr(pc);
}
void cdl_hit_memory_log_point(uint32_t address) {
if (address>0x10000000 && address <= 0x107fffff) {
cout << "Cart Memory access!" << std::hex << address << " in:" << labels[current_function].func_name << "\n";
}
}
void cdl_log_masked_write(uint32_t* address, uint32_t dst2) {
if (!cdl_log_memory) return;
// cout << "masked write:"<<std::hex<<dst<<" : "<<dst2<<"\n";
// if (memory_to_log.find(address) != memory_to_log.end() )
// {
// cout << "Logging Mem Write to 0x"<< std::hex << address << " At PC:" <<"\n";
// }
}
void cdl_log_get_mem_handler(uint32_t address) {
if (!cdl_log_memory) return;
cdl_hit_memory_log_point(address);
if (memory_to_log.find(address) != memory_to_log.end() )
{
cout << "Logging Mem cdl_log_get_mem_handler access 0x"<< std::hex << address <<"\n";
cdl_hit_memory_log_point(address);
}
}
void cdl_log_mem_read32(uint32_t address) {
if (!cdl_log_memory) return;
cdl_hit_memory_log_point(address);
if (memory_to_log.find(address) != memory_to_log.end() )
{
cout << "Logging Mem cdl_log_mem_read32 access 0x"<< std::hex << address <<"\n";
cdl_hit_memory_log_point(address);
}
}
void cdl_log_mem_write32(uint32_t address) {
if (!cdl_log_memory) return;
cdl_hit_memory_log_point(address);
if (memory_to_log.find(address) != memory_to_log.end() )
{
cout << "Logging Mem cdl_log_mem_write32 access 0x"<< std::hex << address <<"\n";
cdl_hit_memory_log_point(address);
}
}
string mapping_names[] = {
"M64P_MEM_NOTHING",
"M64P_MEM_NOTHING",
"M64P_MEM_RDRAM",
"M64P_MEM_RDRAMREG",
"M64P_MEM_RSPMEM",
"M64P_MEM_RSPREG",
"M64P_MEM_RSP",
"M64P_MEM_DP",
"M64P_MEM_DPS",
"M64P_MEM_VI",
"M64P_MEM_AI",
"M64P_MEM_PI",
"M64P_MEM_RI",
"M64P_MEM_SI",
"M64P_MEM_FLASHRAMSTAT",
"M64P_MEM_ROM",
"M64P_MEM_PIF",
"M64P_MEM_MI"
};
#define OSTASK_GFX 1
#define OSTASK_AUDIO 2
void cdl_log_ostask(uint32_t type, uint32_t flags, uint32_t bootcode, uint32_t bootSize, uint32_t ucode, uint32_t ucodeSize, uint32_t ucodeData, uint32_t ucodeDataSize) {
if (!log_ostasks) return;
if (rspboot == 0) {
rspboot = map_assembly_offset_to_rom_offset(bootcode,0);
auto bootDma = cdl_dma();
bootDma.dram_start=rspboot;
bootDma.dram_end = rspboot+bootSize;
bootDma.rom_start = rspboot;
bootDma.rom_end = rspboot+bootSize;
bootDma.length = bootSize;
bootDma.frame = l_CurFrame;
bootDma.func_addr = print_function_stack_trace();
bootDma.known_name = "rsp.boot";
dmas[rspboot] = bootDma;
}
uint32_t ucodeRom = map_assembly_offset_to_rom_offset(ucode,0);
if (dmas.find(ucodeRom) != dmas.end() )
return;
printf("OSTask type:%#08x flags:%#08x bootcode:%#08x ucode:%#08x ucodeSize:%#08x ucodeData:%#08x ucodeDataSize:%#08x \n", type, flags, bootcode, ucode, ucodeSize, ucodeData, ucodeDataSize);
uint32_t ucodeDataRom = map_assembly_offset_to_rom_offset(ucodeData,0);
auto data = cdl_dma();
data.dram_start=ucodeData;
data.dram_end = ucodeData+ucodeDataSize;
data.rom_start = ucodeDataRom;
data.rom_end = ucodeDataRom+ucodeDataSize;
data.length = ucodeDataSize;
data.frame = l_CurFrame;
data.func_addr = print_function_stack_trace();
data.is_assembly = false;
auto t = cdl_dma();
t.dram_start=ucode;
t.dram_end = ucode+ucodeSize;
t.rom_start = ucodeRom;
t.rom_end = ucodeRom+ucodeSize;
t.length = ucodeSize;
t.frame = l_CurFrame;
t.func_addr = print_function_stack_trace();
t.is_assembly = false;
if (type == OSTASK_AUDIO) {
t.guess_type = "rsp.audio";
t.ascii_header = "rsp.audio";
t.known_name = "rsp.audio";
data.ascii_header = "rsp.audio.data";
data.known_name = "rsp.audio.data";
} else if (type == OSTASK_GFX) {
t.guess_type = "rsp.graphics";
t.ascii_header = "rsp.graphics";
t.known_name = "rsp.graphics";
data.ascii_header = "rsp.graphics.data";
data.known_name = "rsp.graphics.data";
} else {
printf("other type:%#08x ucode:%#08x \n",type, ucodeRom);
}
dmas[ucodeRom] = t;
dmas[ucodeDataRom] = data;
}
#define CDL_ALIST 0
#define CDL_UCODE_CRC 2
void cdl_log_rsp(uint32_t log_type, uint32_t address, const char * extra_data) {
if (!log_rsp) return;
if (log_type == CDL_ALIST) {
if (audio_address.find(address) != audio_address.end() )
return;
audio_address[address] = n2hexstr(address)+extra_data;
// cout << "Alist address:" << std::hex << address << " " << extra_data << "\n";
return;
}
if (log_type == CDL_UCODE_CRC) {
ucode_crc = n2hexstr(address);
return;
}
cout << "Log rsp\n";
}
void cdl_log_dpc_reg_write(uint32_t address, uint32_t value, uint32_t mask) {
cdl_common_log_tag("writeDPCRegs");
}
} // end extern C
// C++
uint32_t libRR_offset_to_look_for = 0x8149;
bool libRR_enable_look = false;
json libRR_disassembly = {};
json libRR_memory_reads = {};
json libRR_consecutive_rom_reads = {};
json libRR_called_functions = {};
json libRR_long_jumps = {};
int32_t previous_consecutive_rom_read = 0; // previous read address to check if this read is part of the chain
int16_t previous_consecutive_rom_bank = 0; // previous read address to check if this read is part of the chain
int32_t current_consecutive_rom_start = 0; // start address of the current chain
bool replace(std::string& str, const std::string from, const std::string to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
extern "C" void libRR_log_dma(int32_t offset) {
if (offset> 0x7fff) {
return;
}
cout << "DMA: " << n2hexstr(offset) << "\n";
}
static string label_name = "";
extern "C" const char* libRR_log_jump_label_with_name(uint32_t offset, uint32_t current_pc, const char* label_name) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return "";
}
string offset_str = n2hexstr(offset);
int bank = get_current_bank_number_for_address(offset);
string current_bank_str = n2hexstr(bank, 4);
if (offset >libRR_slot_2_max_addr) {
// if its greater than the max bank value then its probably in ram
return "";
}
// debugging code start
if (libRR_enable_look && (offset == libRR_offset_to_look_for || current_pc == libRR_offset_to_look_for)) {
printf("Found long jump label with name offset: %d\n", libRR_offset_to_look_for);
}
// debugging code end
// string label_name = "LAB_" + current_bank_str + "_" + n2hexstr(offset);
if (!libRR_disassembly[current_bank_str][offset_str].contains("label_name")) {
libRR_disassembly[current_bank_str][offset_str]["label_name"] = label_name;
}
libRR_disassembly[current_bank_str][offset_str]["meta"]["label_callers"][current_bank_str + "_" + n2hexstr(current_pc)] = true;
return label_name;
}
extern "C" const char* libRR_log_jump_label(uint32_t offset, uint32_t current_pc) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return "_not_logging";
}
string offset_str = n2hexstr(offset);
int bank = get_current_bank_number_for_address(offset);
string current_bank_str = n2hexstr(bank, 4);
if (offset >libRR_slot_2_max_addr) {
// if its greater than the max bank value then its probably in ram
return "max_bank_value";
}
// debugging code start
if (libRR_enable_look && (offset == libRR_offset_to_look_for || current_pc == libRR_offset_to_look_for)) {
printf("Found long jump label offset: %d\n", libRR_offset_to_look_for);
}
// debugging code end
label_name = "LAB_" + current_bank_str + "_" + n2hexstr(offset);
// return libRR_log_jump_label_with_name(offset, current_pc, label_name.c_str());
if (!libRR_disassembly[current_bank_str][offset_str].contains("label_name")) {
libRR_disassembly[current_bank_str][offset_str]["label_name"] = label_name;
}
libRR_disassembly[current_bank_str][offset_str]["meta"]["label_callers"][current_bank_str + "_" + n2hexstr(current_pc)] = true;
return label_name.c_str();
}
extern "C" void libRR_log_memory_read(int8_t bank, int32_t offset, const char* type, uint8_t byte_size, char* bytes) {
libRR_log_rom_read(bank, offset, type, byte_size, bytes);
}
extern "C" void libRR_log_rom_read(int16_t bank, int32_t offset, const char* type, uint8_t byte_size, char* bytes) {
string bank_str = n2hexstr(bank, 4);
string previous_bank_str = n2hexstr(previous_consecutive_rom_bank, 4);
string offset_str = n2hexstr(offset);
string current_consecutive_rom_start_str = n2hexstr(current_consecutive_rom_start);
if (libRR_full_trace_log) {
libRR_log_trace_str("Rom Read bank:"+bank_str+":"+n2hexstr(offset)+" = "+n2hexstr(bytes[0], 2));
}
// Check to see if the last read address is the same or 1 away
// Check for the same is because sometimes data is checked by reading the first byte
if (previous_consecutive_rom_bank == bank && previous_consecutive_rom_read == offset) {
// do nothing if its the same byte read twice
previous_consecutive_rom_bank = bank;
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] = 1;
return;
}
if (previous_consecutive_rom_bank == bank && previous_consecutive_rom_read == (offset-1)) {
if (libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str].is_null()) {
// check to see if the current read is null and if so create it
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] = 1+ byte_size;
} else {
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] = ((uint32_t) libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"]) +byte_size;
}
for (int i=0; i<byte_size; i++) {
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["value"][n2hexstr(offset+i)] = n2hexstr(bytes[i]);
}
}
else {
// cout << "previous consecutive length from:" << (int)previous_consecutive_rom_bank << "::" << n2hexstr(current_consecutive_rom_start) << " -> " << n2hexstr(previous_consecutive_rom_read) << " len:" << libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] << "\n";
current_consecutive_rom_start = offset;
current_consecutive_rom_start_str = n2hexstr(current_consecutive_rom_start);
// initialise new consecutive run
libRR_consecutive_rom_reads[bank_str][current_consecutive_rom_start_str]["length"] = 1;
for (int i=0; i<byte_size; i++) {
libRR_consecutive_rom_reads[bank_str][current_consecutive_rom_start_str]["value"][n2hexstr(offset+i)] = n2hexstr(bytes[i]);
}
}
previous_consecutive_rom_read = offset+(byte_size-1); // add byte_size to take into account 2 byte reads
previous_consecutive_rom_bank = bank;
string value_str = "";
if (byte_size == 2) {
value_str = n2hexstr(two_bytes_to_16bit_value(bytes[1], bytes[0]));
} else {
value_str = n2hexstr(bytes[0]);
}
// printf("Access data: %d::%s type: %s size: %d value: %s\n", bank, n2hexstr(offset).c_str(), type, byte_size, value_str.c_str());
}
extern "C" void libRR_log_instruction_2int(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, uint32_t operand, uint32_t operand2) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
replace(name, "%int%", libRR_constant_replace(operand));
replace(name, "%int2%", libRR_constant_replace(operand2));
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes);
}
// Takes a single int argument and replaces it in the string
extern "C" void libRR_log_instruction_1int(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, uint32_t operand) {
return libRR_log_instruction_2int(current_pc, c_name, instruction_bytes, number_of_bytes, operand, 0);
}
extern "C" void libRR_log_instruction_1string(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, const char* c_register_name) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
std::string register_name(c_register_name);
replace(name, "%str%",register_name);
libRR_log_instruction_1int(current_pc, name.c_str(), instruction_bytes, number_of_bytes, 0x00);
}
extern "C" void libRR_log_instruction_1int_registername(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, uint32_t operand, const char* c_register_name) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
std::string register_name(c_register_name);
replace(name, "%r%",register_name);
libRR_log_instruction_1int(current_pc, name.c_str(), instruction_bytes, number_of_bytes, operand);
}
extern "C" void libRR_log_instruction_z80_s_d(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, const char* source, const char* destination) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
replace(name, "%s%", source);
replace(name, "%d%", destination);
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes);
}
//
// Z80 End
//
// current_pc - current program counter
// instruction bytes as integer used for hex
// arguments - number of arguments - currently not really used for anything
// m - used for register number, replaces Rm with R1/R2 etc
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes, unsigned m, unsigned n, unsigned imm, unsigned d, unsigned ea) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
replace(name, "%EA", "0x"+n2hexstr(ea));
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes, m, n, imm, d);
}
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes, unsigned m, unsigned n, unsigned imm, unsigned d) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
replace(name, "#imm", "#"+to_string(imm));
replace(name, "disp", ""+to_string(d));
if (name.find("SysRegs") != std::string::npos) {
replace(name, "SysRegs[#0]", "MACH");
replace(name, "SysRegs[#1]", "MACL");
replace(name, "SysRegs[#2]", "PR");
}
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes, m, n);
}
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes, unsigned m, unsigned n) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
replace(name, "Rm", "R"+to_string(m));
replace(name, "Rn", "R"+to_string(n));
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes);
}
extern "C" void libRR_log_instruction(uint32_t current_pc, const char* name, uint32_t instruction_bytes, int number_of_bytes)
{
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
// printf("libRR_log_instruction pc:%d name: %s bytes: %d\n", current_pc, name, instruction_bytes);
std::string str(name);
libRR_log_instruction(current_pc, str, instruction_bytes, number_of_bytes);
}
// C version of the c++ template
extern "C" const char* n2hexstr_c(int number, size_t hex_len) {
return n2hexstr(number, hex_len).c_str();
}
string libRR_constant_replace(uint32_t da8) {
string addr_str = n2hexstr(da8);
if (libRR_console_constants["addresses"].contains(addr_str)) {
return libRR_console_constants["addresses"][addr_str];
}
return "$"+n2hexstr(da8);
}
int32_t previous_pc = 0; // used for debugging
bool has_read_first_ever_instruction = false;
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
if (!has_read_first_ever_instruction) {
// special handling for the entry point, we wanr to force a label here to it gets written to output
libRR_log_jump_label_with_name(current_pc, current_pc, "entry");
has_read_first_ever_instruction = true;
libRR_isDelaySlot = false;
}
int bank = get_current_bank_number_for_address(current_pc);
string current_bank_str = n2hexstr(bank, 4);
// trace log each instruction
if (libRR_full_trace_log) {
libRR_log_trace_str(name + "; pc:"+current_bank_str+":"+n2hexstr(current_pc));
}
// Code used for debugging why an address was reached
if (libRR_enable_look && current_pc == libRR_offset_to_look_for) {
printf("Reached %s: previous addr: %s name:%s bank:%d \n ", n2hexstr(libRR_offset_to_look_for).c_str(), n2hexstr(previous_pc).c_str(), name.c_str(), bank);
}
// end debugging code
if (strcmp(libRR_console,"Saturn")==0) {
printf("isSaturn\n");
// For saturn we remove 2 from the program counter, but this will vary per console
current_pc -= 4; // was -2
}
// string current_function = n2hexstr(function_stack.back());
string current_pc_str = n2hexstr(current_pc);
// printf("libRR_log_instruction %s \n", current_function.c_str());
if (strcmp(libRR_console,"Saturn")==0) {
if (libRR_isDelaySlot) {
current_pc_str = n2hexstr(libRR_delay_slot_pc - 2); //subtract 2 as pc is ahead
// printf("Delay Slot %s \n", current_pc_str.c_str());
libRR_isDelaySlot = false;
}
}
// TODO: Hex bytes should change based on number_of_bytes
string hexBytes = n2hexstr((uint32_t)instruction_bytes, number_of_bytes*2);
// if we are below the max addr of bank 0 (e.g 0x4000 for GB) then we are always in bank 0
// if (current_pc <libRR_slot_0_max_addr) {
// current_bank_str="0000";
// }
// libRR_disassembly[current_bank_str][current_pc_str][name]["frame"]=RRCurrentFrame;
libRR_disassembly[current_bank_str][current_pc_str][name]["bytes"]=hexBytes;
libRR_disassembly[current_bank_str][current_pc_str][name]["bytes_length"]=number_of_bytes;
previous_pc = current_pc;
}
| 40.186519
| 312
| 0.672836
|
disi33
|
274859fcc3c14d6621bb5912b64e71495ce6c751
| 518
|
cpp
|
C++
|
C++/402.remove-k-digits.cpp
|
WilliamZhaoz/github
|
2aa0eb17e272249fc225cf2e9861c4c44bd0e265
|
[
"MIT"
] | 1
|
2018-03-06T05:07:22.000Z
|
2018-03-06T05:07:22.000Z
|
C++/402.remove-k-digits.cpp
|
WilliamZhaoz/github
|
2aa0eb17e272249fc225cf2e9861c4c44bd0e265
|
[
"MIT"
] | 1
|
2021-12-24T16:41:02.000Z
|
2021-12-24T16:41:02.000Z
|
C++/402.remove-k-digits.cpp
|
WilliamZhaoz/github
|
2aa0eb17e272249fc225cf2e9861c4c44bd0e265
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.size();
int leave = n - k;
string res = "";
for (int i = 0; i < num.size(); i++) {
while (k && res.back() > num[i]) {
k--;
res.pop_back();
}
res += num[i];
}
res.resize(leave);
while (!res.empty() && res[0] == '0') {
res.erase(res.begin());
}
return res.empty() ? "0" : res;
}
};
| 25.9
| 47
| 0.3861
|
WilliamZhaoz
|
27491f61d7399b5fc86b9abe57f70c2615370f62
| 1,688
|
cpp
|
C++
|
vs2017/ui/mainwindow/workbench/AppStoreList.cpp
|
cheechang/cppcc
|
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
|
[
"MIT"
] | null | null | null |
vs2017/ui/mainwindow/workbench/AppStoreList.cpp
|
cheechang/cppcc
|
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
|
[
"MIT"
] | null | null | null |
vs2017/ui/mainwindow/workbench/AppStoreList.cpp
|
cheechang/cppcc
|
0292e9a9b27e0579970c83b4f6a75dcdae1558bf
|
[
"MIT"
] | null | null | null |
#include "AppStoreList.h"
#include <QListWidgetItem>
#include "AppStoreListItem.h"
namespace ui{
AppStoreList::AppStoreList(QWidget *parent)
: QListWidget(parent)
{
m_pAppMgr = APPMGRCONTROL;
CONNECT_SERVICE(GetApplication(std::vector<data::AppInfo>));
if (m_pAppMgr != CNull)
{
m_pAppMgr->getAllApplication(CBind
(&AppStoreList::signalSerGetApplication, this,
CPlaceholders _1));
}
this->setSelectionMode(SelectionMode::NoSelection);
this->setObjectName("appStoreList");
}
AppStoreList::~AppStoreList()
{
}
void AppStoreList::onSerGetApplication(std::vector<data::AppInfo> vec)
{
for (int i = 0; i < vec.size(); i++)
{
QListWidgetItem* pItem = new QListWidgetItem(this);
AppStoreListItem* pListItem = new AppStoreListItem(this);
connect(pListItem, SIGNAL(installApp(int64, QString, QString, QString)),
this, SLOT(onInstallApp(int64, QString, QString, QString)));
connect(pListItem, SIGNAL(uninstallApp(int64)),
this, SLOT(onUninstallApp(int64)));
pListItem->setAppID(vec[i].appID);
pListItem->setName(QString::fromUtf8(vec[i].name.data()));
pListItem->setAvatar(QString::fromUtf8(vec[i].icon.data()));
pListItem->setIntroduce(QString::fromUtf8(vec[i].introduction.data()));
pListItem->setUrl(QString::fromUtf8(vec[i].url.data()));
pListItem->setButtonStatus(vec[i].isInstalled);
this->setItemWidget(pItem, pListItem);
}
//this->update();
}
void AppStoreList::onInstallApp(int64 iAppID, QString strName,
QString strIcon, QString strUrl)
{
emit installApp(iAppID, strName, strIcon, strUrl);
}
void AppStoreList::onUninstallApp(int64 iAppID)
{
emit uninstallApp(iAppID);
}
}
| 25.969231
| 75
| 0.716232
|
cheechang
|
2749c9f90bf8cb43cd61b4ac13cdec61c38d4d45
| 407
|
cpp
|
C++
|
Course 201809/homework/11/C1.cpp
|
Seizzzz/DailyCodes
|
9a617fb64ee27b9f254be161850e9c9a61747cb1
|
[
"MIT"
] | null | null | null |
Course 201809/homework/11/C1.cpp
|
Seizzzz/DailyCodes
|
9a617fb64ee27b9f254be161850e9c9a61747cb1
|
[
"MIT"
] | null | null | null |
Course 201809/homework/11/C1.cpp
|
Seizzzz/DailyCodes
|
9a617fb64ee27b9f254be161850e9c9a61747cb1
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a,n ,m;
scanf("%d%d",&n,&m);
a=(int **)malloc(sizeof(int *)*n);
int i=0,j=0;
for(;i<n;i++)
{
a[i]=(int *)malloc(sizeof(int *)*m);
for(int j=0;j<m;j++) scanf("%d",&a[i][j]);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++) printf("%d ",a[i][j] * (-10));
printf("\n");
}
for(i=0;i<n;i++) free(a[i]);
free(a);
return 0;
}
| 14.034483
| 53
| 0.46683
|
Seizzzz
|
274b82dafccc64c402de9bd66315b1e8e8c56fd1
| 16,654
|
cpp
|
C++
|
regex_to_min_dfa.cpp
|
avinal/C_ode
|
f056da37c8c56a4a62a06351c2ea3773d16d1b11
|
[
"MIT"
] | 1
|
2020-08-23T20:21:35.000Z
|
2020-08-23T20:21:35.000Z
|
regex_to_min_dfa.cpp
|
avinal/C_ode
|
f056da37c8c56a4a62a06351c2ea3773d16d1b11
|
[
"MIT"
] | null | null | null |
regex_to_min_dfa.cpp
|
avinal/C_ode
|
f056da37c8c56a4a62a06351c2ea3773d16d1b11
|
[
"MIT"
] | 2
|
2019-03-18T10:22:13.000Z
|
2021-01-03T10:12:28.000Z
|
#include <iostream>
#include <vector>
#include <stack>
#include <set>
#include <queue>
#include <map>
#include<string>
using namespace std;
struct nst
{
vector<int> a[2], e;
bool f = 0;
};
vector<nst> nfa;
struct dst
{
int a[2] = {-1, -1};
bool f = 0;
};
vector<dst> dfa;
stack<int> st;
int nfa_size, dfa_size;
string dispregex;
struct nst init_nfa_state;
struct dst init_dfa_state;
void custom_clear()
{
for (int i = 0; i < 100; i++)
cout << endl;
}
/***************************** regex to nfa ****************************/
string insert_concat(string regexp)
{
string ret = "";
char c, c2;
for (unsigned int i = 0; i < regexp.size(); i++)
{
c = regexp[i];
if (i + 1 < regexp.size())
{
c2 = regexp[i + 1];
ret += c;
if (c != '(' && c2 != ')' && c != '+' && c2 != '+' && c2 != '*')
{
ret += '.';
}
}
}
ret += regexp[regexp.size() - 1];
return ret;
}
void character(int i)
{
nfa.push_back(init_nfa_state);
nfa.push_back(init_nfa_state);
nfa[nfa_size].a[i].push_back(nfa_size + 1);
st.push(nfa_size);
nfa_size++;
st.push(nfa_size);
nfa_size++;
}
void union_()
{
nfa.push_back(init_nfa_state);
nfa.push_back(init_nfa_state);
int d = st.top();
st.pop();
int c = st.top();
st.pop();
int b = st.top();
st.pop();
int a = st.top();
st.pop();
nfa[nfa_size].e.push_back(a);
nfa[nfa_size].e.push_back(c);
nfa[b].e.push_back(nfa_size + 1);
nfa[d].e.push_back(nfa_size + 1);
st.push(nfa_size);
nfa_size++;
st.push(nfa_size);
nfa_size++;
}
void concatenation()
{
int d = st.top();
st.pop();
int c = st.top();
st.pop();
int b = st.top();
st.pop();
int a = st.top();
st.pop();
nfa[b].e.push_back(c);
st.push(a);
st.push(d);
}
void kleene_star()
{
nfa.push_back(init_nfa_state);
nfa.push_back(init_nfa_state);
int b = st.top();
st.pop();
int a = st.top();
st.pop();
nfa[nfa_size].e.push_back(a);
nfa[nfa_size].e.push_back(nfa_size + 1);
nfa[b].e.push_back(a);
nfa[b].e.push_back(nfa_size + 1);
st.push(nfa_size);
nfa_size++;
st.push(nfa_size);
nfa_size++;
}
void postfix_to_nfa(string postfix)
{
for (unsigned int i = 0; i < postfix.size(); i++)
{
switch (postfix[i])
{
case 'a':
case 'b':
character(postfix[i] - 'a');
break;
case '*':
kleene_star();
break;
case '.':
concatenation();
break;
case '+':
union_();
}
}
}
void display_nfa()
{
cout << endl
<< endl;
cout << "Phase 1: regex to nfa conversion using thompson's construction algorithm\n";
cout << "------------------------------------------------------------------------\n";
cout << "State\t|\ta\t|\tb\t|\teps\t|accepting state|" << endl;
cout << "------------------------------------------------------------------------\n";
for (unsigned int i = 0; i < nfa.size(); i++)
{
cout << i << "\t|\t";
for (unsigned int j = 0; j < nfa[i].a[0].size(); j++)
cout << nfa[i].a[0][j] << ' ';
cout << "\t|\t";
for (unsigned int j = 0; j < nfa[i].a[1].size(); j++)
cout << nfa[i].a[1][j] << ' ';
cout << "\t|\t";
for (unsigned int j = 0; j < nfa[i].e.size(); j++)
cout << nfa[i].e[j] << ' ';
cout << "\t|\t";
if (nfa[i].f)
cout << "Yes";
else
cout << "No";
cout << "\t|\n";
}
cout << "------------------------------------------------------------------------\n";
}
int priority(char c)
{
switch (c)
{
case '*':
return 3;
case '.':
return 2;
case '+':
return 1;
default:
return 0;
}
}
string regexp_to_postfix(string regexp)
{
string postfix = "";
stack<char> op;
char c;
for (unsigned int i = 0; i < regexp.size(); i++)
{
switch (regexp[i])
{
case 'a':
case 'b':
postfix += regexp[i];
break;
case '(':
op.push(regexp[i]);
break;
case ')':
while (op.top() != '(')
{
postfix += op.top();
op.pop();
}
op.pop();
break;
default:
while (!op.empty())
{
c = op.top();
if (priority(c) >= priority(regexp[i]))
{
postfix += op.top();
op.pop();
}
else
break;
}
op.push(regexp[i]);
}
//cout<<regexp[i]<<' '<<postfix<<endl;
}
while (!op.empty())
{
postfix += op.top();
op.pop();
}
return postfix;
}
/***************************** nfa to dfa ****************************/
void print_dfa()
{
cout << endl;
cout << "NFA TO DFA CONVERSION" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "STATE\t|\t"
<< "a"
<< "\t|\t"
<< "b"
<< "\t|\t"
<< "FINAL"
<< "\t|" << endl;
cout << "---------------------------------------------------------" << endl;
for (int i = 0; i < dfa.size(); i++)
{
cout << i << "\t|\t" << dfa[i].a[0] << "\t|\t" << dfa[i].a[1] << "\t|\t" << dfa[i].f << "\t|" << endl;
}
cout << "---------------------------------------------------------" << endl;
}
void epsilon_closure(int state, set<int> &si)
{
for (unsigned int i = 0; i < nfa[state].e.size(); i++)
{
if (si.count(nfa[state].e[i]) == 0)
{
si.insert(nfa[state].e[i]);
epsilon_closure(nfa[state].e[i], si);
}
}
}
set<int> state_change(int c, set<int> &si)
{
set<int> temp;
if (c == 1)
{
for (std::set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
for (unsigned int j = 0; j < nfa[*it].a[0].size(); j++)
{
temp.insert(nfa[*it].a[0][j]);
}
}
}
else
{
for (std::set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
for (unsigned int j = 0; j < nfa[*it].a[1].size(); j++)
{
temp.insert(nfa[*it].a[1][j]);
}
}
}
return temp;
}
void nfa_to_dfa(set<int> &si, queue<set<int>> &que, int start_state)
{
map<set<int>, int> mp;
mp[si] = -1;
set<int> temp1;
set<int> temp2;
int ct = 0;
si.clear();
si.insert(0);
epsilon_closure(start_state, si);
if (mp.count(si) == 0)
{
mp[si] = ct++;
que.push(si);
}
int p = 0;
bool f1 = false;
while (que.size() != 0)
{
dfa.push_back(init_dfa_state);
si.empty();
si = que.front();
f1 = false;
for (set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
if (nfa[*it].f == true)
f1 = true;
}
dfa[p].f = f1;
temp1 = state_change(1, si);
si = temp1;
for (set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
epsilon_closure(*it, si);
}
if (mp.count(si) == 0)
{
mp[si] = ct++;
que.push(si);
dfa[p].a[0] = ct - 1;
}
else
{
dfa[p].a[0] = mp.find(si)->second;
}
temp1.clear();
si = que.front();
temp2 = state_change(2, si);
si = temp2;
for (set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
epsilon_closure(*it, si);
}
if (mp.count(si) == 0)
{
mp[si] = ct++;
que.push(si);
dfa[p].a[1] = ct - 1;
}
else
{
dfa[p].a[1] = mp.find(si)->second;
}
temp2.clear();
que.pop();
p++;
}
for (int i = 0; i < p; i++)
{
if (dfa[i].a[0] == -1)
dfa[i].a[0] = p;
if (dfa[i].a[1] == -1)
dfa[i].a[1] = p;
}
dfa.push_back(init_dfa_state);
dfa[p].a[0] = p;
dfa[p].a[1] = p;
//cout<<p<<endl;
}
/***************************** min dfa ****************************/
/// Function to minimize DFA
pair<int, vector<tuple<int, int, bool>>> minimize_dfa(vector<dst> dfa)
{
//cout<<dfa.size()<<endl;
vector<int> grp(dfa.size()); /// Group number for states
vector<vector<int>> part(2, vector<int>()); /// Partition for groups
/// Initializing the groups
part[0].push_back(0);
for (int i = 1; i < (int)grp.size(); i++)
{
if (dfa[i].f == dfa[0].f)
{
grp[i] = 0;
part[0].push_back(i);
}
else
{
grp[i] = 1;
part[1].push_back(i);
}
}
if (!part[1].size())
part.erase(part.end());
/// Loop until no new partition is created
bool chk = true; /// Check if any new partition is created
int strt = 0; /// Starting State
while (chk)
{
chk = false;
/*for(int i=0; i<part.size(); i++) {
cout<<i<<":";
for(int j=0; j<part[i].size(); j++) {
cout<<part[i][j]<<" ";
} cout<<endl;
} cout<<endl;*/
/// Iterate over partitions and alphabets
for (int i = 0; i < part.size(); i++)
{
for (int j = 0; j < 2; j++)
{
vector<pair<int, int>> trans(part[i].size()); /// Transitions for the states of partitions
/// Iterate over states of partitions and find transition groups
for (int k = 0; k < part[i].size(); k++)
{
if (dfa[part[i][k]].a[j] >= 0)
trans[k] = make_pair(grp[dfa[part[i][k]].a[j]], part[i][k]);
else
trans[k] = make_pair(-1, part[i][k]);
}
sort(trans.begin(), trans.end());
/// Break partition in case of different transitions
if (trans[0].first != trans[trans.size() - 1].first)
{
chk = true;
int k, m = part.size() - 1;
part[i].clear();
part[i].push_back(trans[0].second);
for (k = 1; k < trans.size() && (trans[k].first == trans[k - 1].first); k++)
{
part[i].push_back(trans[k].second);
}
while (k < trans.size())
{
if (trans[k].first != trans[k - 1].first)
{
part.push_back(vector<int>());
m++;
}
grp[trans[k].second] = m;
part[m].push_back(trans[k].second);
k++;
}
}
}
}
}
for (int i = 0; i < part.size(); i++)
{
for (int j = 0; j < part[i].size(); j++)
{
if (part[i][j] == 0)
strt = i;
}
}
vector<tuple<int, int, bool>> ret(part.size());
//cout<<part.size()<<endl;
//sort(part.begin(), part.end());
for (int i = 0; i < (int)part.size(); i++)
{
//cout<<grp[part[i][0]]<<endl;
get<0>(ret[i]) = (dfa[part[i][0]].a[0] >= 0) ? grp[dfa[part[i][0]].a[0]] : -1;
get<1>(ret[i]) = (dfa[part[i][0]].a[1] >= 0) ? grp[dfa[part[i][0]].a[1]] : -1;
get<2>(ret[i]) = dfa[part[i][0]].f;
}
return make_pair(strt, ret);
}
void print_menu()
{
cout << "\n---------------------------------------\n";
cout << "Input Regex: " << dispregex << endl
<< endl;
cout << "1. NFA\n";
cout << "2. Intermediate DFA\n";
cout << "3. Minimized DFA\n";
cout << "4. Simulation\n";
cout << "Press any other key to exit...\n\n";
}
void print(vector<tuple<int, int, bool>> min_dfa)
{
cout << "---------------------------------------------------------" << endl;
cout << "State\t|\tA\t|\tB\t|\tFinal\t|" << endl;
cout << "---------------------------------------------------------" << endl;
for (int i = 0; i < (int)min_dfa.size(); i++)
{
cout << i << "\t|\t";
cout << get<0>(min_dfa[i]) << "\t|\t";
cout << get<1>(min_dfa[i]) << "\t|\t";
if (get<2>(min_dfa[i]))
cout << "Yes\t|";
else
cout << "No\t|";
cout << endl;
}
cout << "---------------------------------------------------------" << endl;
}
void simulate(int start_st, vector<tuple<int, int, bool>> min_dfa)
{
print_menu();
cout << "Enter string : ";
string input;
cin.ignore();
getline(cin, input);
int curr_state, next_state;
curr_state = start_st;
custom_clear();
cout << "-----------------------------------------" << endl;
cout << "Input\t|\tCurrent\t|\tNext\t|" << endl;
cout << "-----------------------------------------" << endl;
for (unsigned i = 0; i < input.size(); i++)
{
if (input[i] == 'a')
next_state = get<0>(min_dfa[curr_state]);
else
next_state = get<1>(min_dfa[curr_state]);
cout << input[i] << "\t|\t" << curr_state << "\t|\t" << next_state << "\t|\n";
curr_state = next_state;
}
cout << "-----------------------------------------" << endl;
cout << endl
<< "Verdict: ";
if (curr_state >= 0 && get<2>(min_dfa[curr_state]))
cout << "Accepted";
else
cout << "Rejected";
cout << endl;
}
int main()
{
custom_clear();
string regexp, postfix;
cout << "Enter Regular Expression: ";
cin >> regexp;
dispregex = regexp;
regexp = insert_concat(regexp);
postfix = regexp_to_postfix(regexp);
cout << "Postfix Expression: " << postfix << endl;
postfix_to_nfa(postfix);
int final_state = st.top();
st.pop();
int start_state = st.top();
st.pop();
//cout<<start_state<<' '<<final_state<<endl;
nfa[final_state].f = 1;
set<int> si;
queue<set<int>> que;
nfa_to_dfa(si, que, start_state);
cout << endl
<< endl;
pair<int, vector<tuple<int, int, bool>>> min_dfa_tmp = minimize_dfa(dfa);
vector<tuple<int, int, bool>> min_dfa = min_dfa_tmp.second;
int start_st = min_dfa_tmp.first;
getchar();
custom_clear();
while (1)
{
print_menu();
char choice;
choice = getchar();
custom_clear();
switch (choice)
{
case '1':
display_nfa();
getchar();
break;
case '2':
print_dfa();
getchar();
break;
case '3':
print(min_dfa);
getchar();
break;
case '4':
simulate(start_st, min_dfa);
break;
default:
exit(EXIT_SUCCESS);
}
}
cout << endl
<< endl;
cout << "Enter string : ";
string input;
cin.ignore();
getline(cin, input);
int curr_state, next_state;
while (input != "")
{
//cout<<input<<endl;
curr_state = start_st;
for (unsigned i = 0; i < input.size(); i++)
{
if (curr_state >= 0)
{
if (input[i] == 'a')
next_state = get<0>(min_dfa[curr_state]);
else
next_state = get<1>(min_dfa[curr_state]);
if (next_state >= 0)
{
cout << input[i] << " : State " << curr_state << " -> State " << next_state << endl;
}
else
cout << input[i] << " : State " << curr_state << " -> Trap State" << endl;
}
else
cout << input[i] << " : Trapped" << endl;
curr_state = next_state;
}
if (curr_state >= 0 && get<2>(min_dfa[curr_state]))
cout << "accepted";
else
cout << "rejected";
cout << endl
<< endl;
cout << "Enter string : ";
getline(cin, input);
}
return 0;
}
| 25.119155
| 110
| 0.402066
|
avinal
|
274cbc7004d0d77513d27a2b76ca6151e5f7e538
| 2,942
|
cc
|
C++
|
cc/ipc/render_pass_struct_traits.cc
|
Wzzzx/chromium-crosswalk
|
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2019-01-28T08:09:58.000Z
|
2021-11-15T15:32:10.000Z
|
cc/ipc/render_pass_struct_traits.cc
|
Wzzzx/chromium-crosswalk
|
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
cc/ipc/render_pass_struct_traits.cc
|
Wzzzx/chromium-crosswalk
|
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6
|
2020-09-23T08:56:12.000Z
|
2021-11-18T03:40:49.000Z
|
// Copyright 2016 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 "cc/ipc/render_pass_struct_traits.h"
#include "base/numerics/safe_conversions.h"
#include "cc/ipc/shared_quad_state_struct_traits.h"
namespace mojo {
// static
void* StructTraits<cc::mojom::RenderPass, std::unique_ptr<cc::RenderPass>>::
SetUpContext(const std::unique_ptr<cc::RenderPass>& input) {
DCHECK_GT(input->quad_list.size(), 0u);
std::unique_ptr<mojo::Array<uint32_t>> sqs_references(
new mojo::Array<uint32_t>(input->quad_list.size()));
cc::SharedQuadStateList::ConstIterator sqs_iter =
input->shared_quad_state_list.begin();
for (auto it = input->quad_list.begin(); it != input->quad_list.end(); ++it) {
if ((*it)->shared_quad_state != *sqs_iter)
++sqs_iter;
(*sqs_references)[it.index()] =
base::checked_cast<uint32_t>(sqs_iter.index());
DCHECK_NE(nullptr, (*it)->shared_quad_state);
DCHECK_EQ(*sqs_iter, (*it)->shared_quad_state);
}
DCHECK_EQ(input->shared_quad_state_list.size() - 1, sqs_iter.index());
return sqs_references.release();
}
// static
void StructTraits<cc::mojom::RenderPass, std::unique_ptr<cc::RenderPass>>::
TearDownContext(const std::unique_ptr<cc::RenderPass>& input,
void* context) {
// static_cast to ensure the destructor is called.
delete static_cast<mojo::Array<uint32_t>*>(context);
}
// static
bool StructTraits<cc::mojom::RenderPass, std::unique_ptr<cc::RenderPass>>::Read(
cc::mojom::RenderPassDataView data,
std::unique_ptr<cc::RenderPass>* out) {
*out = cc::RenderPass::Create();
if (!data.ReadId(&(*out)->id) || !data.ReadOutputRect(&(*out)->output_rect) ||
!data.ReadDamageRect(&(*out)->damage_rect) ||
!data.ReadTransformToRootTarget(&(*out)->transform_to_root_target)) {
return false;
}
(*out)->has_transparent_background = data.has_transparent_background();
if (!data.ReadQuadList(&(*out)->quad_list) ||
!data.ReadSharedQuadStateList(&(*out)->shared_quad_state_list))
return false;
mojo::Array<uint32_t> shared_quad_state_references;
if (!data.ReadSharedQuadStateReferences(&shared_quad_state_references))
return false;
if ((*out)->quad_list.size() != shared_quad_state_references.size())
return false;
cc::SharedQuadStateList::ConstIterator sqs_iter =
(*out)->shared_quad_state_list.begin();
for (auto it = (*out)->quad_list.begin(); it != (*out)->quad_list.end();
++it) {
if (sqs_iter.index() != shared_quad_state_references[it.index()])
++sqs_iter;
if (shared_quad_state_references[it.index()] != sqs_iter.index())
return false;
(*it)->shared_quad_state = *sqs_iter;
if (!(*it)->shared_quad_state)
return false;
}
return sqs_iter.index() == (*out)->shared_quad_state_list.size() - 1;
}
} // namespace mojo
| 37.717949
| 80
| 0.692386
|
Wzzzx
|
274ce82c885e09cfd9385abc9b22a029ac0417a1
| 1,731
|
cc
|
C++
|
netlibcc/base/Socket.cc
|
kohakus/tiny-netlib
|
da9998ee06f4e2eb5ebcaf0e383196269dea1f33
|
[
"MIT"
] | 1
|
2021-03-05T10:14:27.000Z
|
2021-03-05T10:14:27.000Z
|
netlibcc/base/Socket.cc
|
kohakus/tiny-netlib
|
da9998ee06f4e2eb5ebcaf0e383196269dea1f33
|
[
"MIT"
] | null | null | null |
netlibcc/base/Socket.cc
|
kohakus/tiny-netlib
|
da9998ee06f4e2eb5ebcaf0e383196269dea1f33
|
[
"MIT"
] | null | null | null |
#include "netlibcc/base/Socket.h"
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <cstdio>
#include "netlibcc/base/InetAddr.h"
#include "netlibcc/base/SockOps.h"
#include "netlibcc/core/Logger.h"
namespace netlibcc {
namespace net {
Socket::~Socket() {
sockets::close(sockfd_);
}
void Socket::listen() {
sockets::listen(sockfd_);
}
void Socket::bind(const InetAddr& local_addr) {
sockets::bind(sockfd_, local_addr.getSockAddr());
}
int Socket::accept(InetAddr* peer_addr) {
// address that return from accept
struct sockaddr_in addr;
::memset(&addr, 0, sizeof addr);
int connfd = sockets::accept(sockfd_, &addr);
if (connfd >= 0) {
peer_addr->setSockAddrInet(addr);
}
return connfd;
}
void Socket::shutdownWrite() {
sockets::shutdownWR(sockfd_);
}
// Socket option setting
bool Socket::setTcpNoDelay(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
bool Socket::setReuseAddr(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
bool Socket::setReusePort(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
bool Socket::setKeepAlive(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
} // namespace net
} // namespace netlibcc
| 25.835821
| 79
| 0.638937
|
kohakus
|
27525b161306b860b02f28e342178932470bbecf
| 21,657
|
cpp
|
C++
|
source/add-ons/Quantize/Quantize.cpp
|
thaflo/Becasso
|
9a1411913ee46f4dfa5116def50ebc41495dad28
|
[
"MIT"
] | 2
|
2020-10-05T14:18:09.000Z
|
2021-08-05T02:56:43.000Z
|
source/add-ons/Quantize/Quantize.cpp
|
thaflo/Becasso
|
9a1411913ee46f4dfa5116def50ebc41495dad28
|
[
"MIT"
] | 26
|
2017-01-10T19:54:10.000Z
|
2020-12-17T07:28:57.000Z
|
source/add-ons/Quantize/Quantize.cpp
|
thaflo/Becasso
|
9a1411913ee46f4dfa5116def50ebc41495dad28
|
[
"MIT"
] | 5
|
2017-12-14T18:46:08.000Z
|
2020-12-13T18:22:34.000Z
|
// ยฉ 2000-2001 Sum Software
#define BUILDING_ADDON
#include "BecassoAddOn.h"
#include "AddOnSupport.h"
#include "Slider.h"
#include <string.h>
#include <CheckBox.h>
#include <RadioButton.h>
#include <Box.h>
#define bzero(p,n) memset (p, 0, n)
int16 *gLut = 0;
#define FOREGROUND 0
#define BACKGROUND 1
#define R_BITS 5
#define G_BITS 6
#define B_BITS 5
#define R_PREC (1<<R_BITS)
#define G_PREC (1<<G_BITS)
#define B_PREC (1<<B_BITS)
#define ELEM(array,r,g,b) (array[b*R_PREC*G_PREC+r*G_PREC+g])
// This is because on MWCC, the huge array needed for the lut can't be
// created on the stack. Hence this workaround.
//#define FLOAT_WEIGHTS 1
// Strangely, the new weights give worst results.
// With the integer weights, results are almost identical with the old floats,
// and probably a lot faster.
#if defined (FLOAT_WEIGHTS)
# define R_WEIGHT 0.2125
# define G_WEIGHT 0.7154
# define B_WEIGHT 0.0721
#elif defined (OLD_WEIGHTS)
# define R_WEIGHT 0.299
# define G_WEIGHT 0.587
# define B_WEIGHT 0.114
#else
# define R_WEIGHT 2
# define G_WEIGHT 3
# define B_WEIGHT 1
#endif
#define R_SHIFT 3
#define G_SHIFT 2
#define B_SHIFT 3
/* log2(histogram cells in update box) for each axis; this can be adjusted */
#define BOX_R_LOG (R_BITS - 3)
#define BOX_G_LOG (G_BITS - 3)
#define BOX_B_LOG (B_BITS - 3)
#define BOX_R_ELEMS (1 << BOX_R_LOG) /* # of hist cells in update box */
#define BOX_G_ELEMS (1 << BOX_G_LOG)
#define BOX_B_ELEMS (1 << BOX_B_LOG)
#define BOX_R_SHIFT (R_SHIFT + BOX_R_LOG)
#define BOX_G_SHIFT (G_SHIFT + BOX_G_LOG)
#define BOX_B_SHIFT (B_SHIFT + BOX_B_LOG)
class QView : public BView
{
public:
QView (BRect rect) : BView (rect, "Quantize_view", B_FOLLOW_ALL, B_WILL_DRAW)
{
fNumColors = 256;
fDitherCB = NULL;
fPalette = FOREGROUND;
ResizeTo (188, 118);
Slider *nSlid = new Slider (BRect (8, 8, 180, 24), 50, "# Colors", 1, 256, 1, new BMessage ('numC'));
AddChild (nSlid);
nSlid->SetValue (256);
fDitherCB = new BCheckBox (BRect (8, 30, 180, 46), "dither", "Floyd-Steinberg Dithering", new BMessage ('fsDt'));
fDitherCB->SetValue (false);
AddChild (fDitherCB);
BBox *palB = new BBox (BRect (8, 54, 180, 110), "palette");
palB->SetLabel ("Use Colors From");
AddChild (palB);
BRadioButton *fgF = new BRadioButton (BRect (4, 14, 170, 30), "fg", "Foreground Palette", new BMessage ('palF'));
BRadioButton *fgB = new BRadioButton (BRect (4, 32, 170, 48), "bg", "Background Palette", new BMessage ('palB'));
palB->AddChild (fgF);
palB->AddChild (fgB);
fgF->SetValue (true);
}
virtual ~QView () {}
virtual void MessageReceived (BMessage *msg);
int numColors () { return fNumColors; }
bool dither () { return (fDitherCB ? fDitherCB->Value() : false); }
int palette () { return fPalette; }
BCheckBox *fDitherCB;
private:
int fNumColors;
int fPalette;
};
QView *view = NULL;
void QView::MessageReceived (BMessage *msg)
{
switch (msg->what)
{
case 'numC':
fNumColors = int (msg->FindFloat ("value"));
break;
case 'fsDt':
// We query the button itself...
break;
case 'palF':
fPalette = FOREGROUND;
break;
case 'palB':
fPalette = BACKGROUND;
break;
default:
BView::MessageReceived (msg);
return;
}
for (int32 i = 0; i < R_PREC; i++)
for (int32 j = 0; j < G_PREC; j++)
for (int32 k = 0; k < B_PREC; k++)
ELEM (gLut, i, j, k) = -1; // We build the LUT on the fly
addon_preview();
}
status_t addon_init (uint32 index, becasso_addon_info *info)
{
strcpy (info->name, "Quantize");
strcpy (info->author, "Sander Stoks");
strcpy (info->copyright, "ยฉ 2000-2001 โ Sum Software");
strcpy (info->description, "Quantizes the colors to a given palette");
info->type = BECASSO_FILTER;
info->index = index;
info->version = 0;
info->release = 7;
info->becasso_version = 2;
info->becasso_release = 0;
info->does_preview = PREVIEW_FULLSCALE;
info->flags = LAYER_ONLY;
return B_OK;
}
status_t addon_close (void)
{
delete [] gLut;
gLut = 0;
return B_OK;
}
status_t addon_exit (void)
{
return B_OK;
}
void fill_lut (int16 *lut, rgb_color palette[], int max_colors, int r, int g, int b);
int find_nearby_colors (rgb_color palette[], int numcolors, uint8 color_list[], int min_r, int min_g, int min_b);
void find_best_colors (rgb_color palette[], int numcolors, int minr, int ming, int minb, uint8 colorlist[], uint8 bestcolors[]);
int find_nearby_colors (rgb_color palette[], int numcolors, uint8 color_list[], int minr, int ming, int minb)
{
int maxr, maxg, maxb;
int cr, cg, cb;
int i, x, ncolors;
float minmaxdist, min_dist, max_dist, tdist;
float mindist[256]; // 256 = the maximum palette size, actually.
maxr = minr + ((1 << BOX_R_SHIFT) - (1 << R_SHIFT));
cr = (minr + maxr)/2;
maxg = ming + ((1 << BOX_G_SHIFT) - (1 << G_SHIFT));
cg = (ming + maxg)/2;
maxb = minb + ((1 << BOX_B_SHIFT) - (1 << B_SHIFT));
cb = (minb + maxb)/2;
/* For each color in colormap, find:
* 1. its minimum squared-distance to any point in the update box
* (zero if color is within update box);
* 2. its maximum squared-distance to any point in the update box.
* Both of these can be found by considering only the corners of the box.
* We save the minimum distance for each color in mindist[];
* only the smallest maximum distance is of interest.
*/
minmaxdist = 0x7FFFFFFFL;
for (i = 0; i < numcolors; i++)
{
/* We compute the squared-r-distance term, then add in the other two. */
x = palette[i].red;
if (x < minr)
{
tdist = (x - minr)*R_WEIGHT;
min_dist = tdist*tdist;
tdist = (x - maxr)*R_WEIGHT;
max_dist = tdist*tdist;
}
else if (x > maxr)
{
tdist = (x - maxr)*R_WEIGHT;
min_dist = tdist*tdist;
tdist = (x - minr)*R_WEIGHT;
max_dist = tdist*tdist;
}
else // within cell range so no contribution to min_dist
{
min_dist = 0;
if (x <= cr)
{
tdist = (x - maxr)*R_WEIGHT;
max_dist = tdist*tdist;
}
else
{
tdist = (x - minr)*R_WEIGHT;
max_dist = tdist*tdist;
}
}
x = palette[i].green;
if (x < ming)
{
tdist = (x - ming)*G_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - maxg)*G_WEIGHT;
max_dist += tdist*tdist;
}
else if (x > maxg)
{
tdist = (x - maxg)*G_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - ming)*G_WEIGHT;
max_dist += tdist*tdist;
}
else
{
if (x <= cg)
{
tdist = (x - maxg)*G_WEIGHT;
max_dist += tdist*tdist;
}
else
{
tdist = (x - ming)*G_WEIGHT;
max_dist += tdist*tdist;
}
}
x = palette[i].blue;
if (x < minb)
{
tdist = (x - minb)*B_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - maxb)*B_WEIGHT;
max_dist += tdist*tdist;
}
else if (x > maxb)
{
tdist = (x - maxb)*B_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - minb)*B_WEIGHT;
max_dist += tdist*tdist;
}
else
{
if (x <= cb)
{
tdist = (x - maxb)*B_WEIGHT;
max_dist += tdist*tdist;
}
else
{
tdist = (x - minb)*B_WEIGHT;
max_dist += tdist*tdist;
}
}
mindist[i] = min_dist; /* save away the results */
if (max_dist < minmaxdist)
minmaxdist = max_dist;
}
/* Now we know that no cell in the update box is more than minmaxdist
* away from some colormap entry. Therefore, only colors that are
* within minmaxdist of some part of the box need be considered.
*/
ncolors = 0;
for (i = 0; i < numcolors; i++)
{
if (mindist[i] <= minmaxdist)
color_list[ncolors++] = i;
}
return ncolors;
}
void find_best_colors (rgb_color palette[], int numcolors, int minr, int ming, int minb, uint8 colorlist[], uint8 bestcolors[])
{
int ir, ig, ib;
int i, icolor;
register float *bptr; // pointer into bestdist[] array
uint8 *cptr; // pointer into bestcolor[] array
float dist0, dist1; // initial distance values
register float dist2; // current distance in inner loop
float xx0, xx1; // distance increments
register float xx2;
float inc0, inc1, inc2; // initial values for increments
// This array holds the distance to the nearest-so-far color for each cell
float bestdist[BOX_R_ELEMS*BOX_G_ELEMS*BOX_B_ELEMS];
/* Initialize best-distance for each cell of the update box */
bptr = bestdist - 1;
for (i = BOX_R_ELEMS*BOX_G_ELEMS*BOX_B_ELEMS - 1; i >= 0; i--)
*(++bptr) = 0x7FFFFFFFL;
/* For each color selected by find_nearby_colors,
* compute its distance to the center of each cell in the box.
* If that's less than best-so-far, update best distance and color number.
*/
/* Nominal steps between cell centers ("x" in Thomas article) */
#define STEP_R ((1 << R_SHIFT)*R_WEIGHT)
#define STEP_G ((1 << G_SHIFT)*G_WEIGHT)
#define STEP_B ((1 << B_SHIFT)*B_WEIGHT)
for (i = 0; i < numcolors; i++)
{
icolor = colorlist[i];
/* Compute (square of) distance from minr/g/b to this color */
inc0 = (minr - palette[icolor].red)*R_WEIGHT;
dist0 = inc0*inc0;
inc1 = (ming - palette[icolor].green)*G_WEIGHT;
dist0 += inc1*inc1;
inc2 = (minb - palette[icolor].blue)*B_WEIGHT;
dist0 += inc2*inc2;
/* Form the initial difference increments */
inc0 = inc0*(2*STEP_R) + STEP_R*STEP_R;
inc1 = inc1*(2*STEP_G) + STEP_G*STEP_G;
inc2 = inc2*(2*STEP_B) + STEP_B*STEP_B;
/* Now loop over all cells in box, updating distance per Thomas method */
bptr = bestdist;
cptr = bestcolors;
xx0 = inc0;
for (ir = BOX_R_ELEMS - 1; ir >= 0; ir--)
{
dist1 = dist0;
xx1 = inc1;
for (ig = BOX_G_ELEMS - 1; ig >= 0; ig--)
{
dist2 = dist1;
xx2 = inc2;
for (ib = BOX_B_ELEMS - 1; ib >= 0; ib--)
{
if (dist2 < *bptr)
{
*bptr = dist2;
*cptr = icolor;
}
dist2 += xx2;
xx2 += 2*STEP_B*STEP_B;
bptr++;
cptr++;
}
dist1 += xx1;
xx1 += 2*STEP_G*STEP_G;
}
dist0 += xx0;
xx0 += 2*STEP_R*STEP_R;
}
}
}
void fill_lut (int16 *lut, rgb_color palette[], int max_colors, int r, int g, int b)
{
int minr, ming, minb; /* lower left corner of update box */
int ir, ig, ib;
register uint8 *cptr; /* pointer into bestcolor[] array */
/* This array lists the candidate colormap indexes. */
uint8 colorlist[256];
int numcolors; /* number of candidate colors */
/* This array holds the actually closest colormap index for each cell. */
uint8 bestcolor[BOX_R_ELEMS*BOX_G_ELEMS*BOX_B_ELEMS];
/* Convert cell coordinates to update box ID */
r >>= BOX_R_LOG;
g >>= BOX_G_LOG;
b >>= BOX_B_LOG;
/* Compute true coordinates of update box's origin corner.
* Actually we compute the coordinates of the center of the corner
* histogram cell, which are the lower bounds of the volume we care about.
*/
minr = (r << BOX_R_SHIFT) + ((1 << R_SHIFT) >> 1);
ming = (g << BOX_G_SHIFT) + ((1 << G_SHIFT) >> 1);
minb = (b << BOX_B_SHIFT) + ((1 << B_SHIFT) >> 1);
/* Determine which colormap entries are close enough to be candidates
* for the nearest entry to some cell in the update box.
*/
numcolors = find_nearby_colors (palette, max_colors, colorlist, minr, ming, minb);
/* Determine the actually nearest colors. */
find_best_colors (palette, numcolors, minr, ming, minb, colorlist, bestcolor);
/* Save the best color numbers (plus 1) in the main cache array */
r <<= BOX_R_LOG; /* convert ID back to base cell indexes */
g <<= BOX_G_LOG;
b <<= BOX_B_LOG;
cptr = bestcolor - 1;
for (ir = 0; ir < BOX_R_ELEMS; ir++)
for (ig = 0; ig < BOX_G_ELEMS; ig++)
for (ib = 0; ib < BOX_B_ELEMS; ib++)
ELEM (lut, (r + ir), (g + ig), (b + ib)) = *(++cptr);
}
status_t addon_make_config (BView **vw, BRect rect)
{
view = new QView (rect);
*vw = view;
gLut = new int16 [R_PREC*G_PREC*B_PREC];
for (int32 i = 0; i < R_PREC; i++)
for (int32 j = 0; j < G_PREC; j++)
for (int32 k = 0; k < B_PREC; k++)
ELEM (gLut, i, j, k) = -1; // We build the LUT on the fly
return B_OK;
}
status_t process (Layer *inLayer, Selection *inSelection,
Layer **outLayer, Selection **outSelection, int32 mode,
BRect * /* frame */, bool final, BPoint /* point */, uint32 /* buttons */)
{
int error = ADDON_OK;
BRect bounds = inLayer->Bounds();
// printf ("Bounds: ");
// bounds.PrintToStream();
// printf ("Frame: ");
// frame->PrintToStream();
if (*outLayer == NULL && mode== M_DRAW)
*outLayer = new Layer (*inLayer);
if (mode == M_SELECT)
{
if (inSelection)
*outSelection = new Selection (*inSelection);
else // No Selection to Quantize
return (0);
}
if (*outLayer)
(*outLayer)->Lock();
if (*outSelection)
(*outSelection)->Lock();
uint32 h = bounds.IntegerHeight() + 1;
uint32 w = bounds.IntegerWidth() + 1;
grey_pixel *mapbits = NULL;
uint32 mbpr = 0;
uint32 mdiff = 0;
if (inSelection)
{
mapbits = (grey_pixel *) inSelection->Bits() - 1;
mbpr = inSelection->BytesPerRow();
mdiff = mbpr - w;
}
if (final)
addon_start();
float delta = 100.0/h; // For the Status Bar.
switch (mode)
{
case M_DRAW:
{
bgra_pixel *sbits = (bgra_pixel *) inLayer->Bits() - 1;
bgra_pixel *dbits = (bgra_pixel *) (*outLayer)->Bits() - 1;
rgb_color *palette;
if (view->palette() == BACKGROUND)
palette = lowpalette();
else
palette = highpalette();
int numcolors = view->numColors();
if (!view->dither()) // Simple quantizer
{
for (uint32 y = 0; y < h; y++)
{
if (final)
{
addon_update_statusbar (delta);
if (addon_stop())
{
error = ADDON_ABORT;
break;
}
}
for (uint32 x = 0; x < w; x++)
{
bgra_pixel pixel = *(++sbits);
if (!inSelection || *(++mapbits))
{
uint8 r = RED (pixel);
uint8 g = GREEN (pixel);
uint8 b = BLUE (pixel);
// uint16 appr = ((r << 8) & 0xF700)|((g << 3) & 0x07E0)|((b >> 3) & 0x001F);
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
{
fill_lut (gLut, palette, numcolors, r >> R_SHIFT, g >> G_SHIFT, b >> B_SHIFT);
}
*(++dbits) = rgb2bgra (palette[ELEM (gLut, rs, gs, bs)]);
}
else
*(++dbits) = *(++sbits);
}
mapbits += mdiff;
}
}
else // FS Dither
{
// Foley & Van Dam, pp 572.
// Own note: Probably the errors in the different color channels should be weighted
// according to visual sensibility. But this version is primarily meant to
// be quick.
uint32 width = bounds.IntegerWidth() + 1;
uint32 slpr = inLayer->BytesPerRow()/4;
bgra_pixel *src = sbits; //(bgra_pixel *) inLayer->Bits() + int (bounds.top)*slpr + int (bounds.left) - 1;
int32 sdif = slpr - width;
uint32 dbpr = (*outLayer)->BytesPerRow()/4;
bgra_pixel *dest = dbits; //(bgra_pixel *) (*outLayer)->Bits() + int (bounds.top)*dbpr + int (bounds.left) - 1;
int32 ddif = dbpr - width;
int *nera = new int[width];
int *nega = new int[width];
int *neba = new int[width];
int *cera = new int[width];
int *cega = new int[width];
int *ceba = new int[width];
bzero (nera, width*sizeof(int));
bzero (nega, width*sizeof(int));
bzero (neba, width*sizeof(int));
bzero (cera, width*sizeof(int));
bzero (cega, width*sizeof(int));
bzero (ceba, width*sizeof(int));
int r, g, b, er, eg, eb, per, peg, peb;
uint8 apix;
uint32 x, y;
rgb_color a;
for (y = uint32 (bounds.top); y < uint32 (bounds.bottom); y++)
{
// printf ("%ld", y); fflush (stdout);
if (final)
{
addon_update_statusbar (delta);
if (addon_stop())
{
error = ADDON_ABORT;
break;
}
}
x = 0;
// Special case: First pixel in a row
bgra_pixel s = *(++src);
r = clip8 (RED (s) + cera[0]);
g = clip8 (GREEN (s) + cega[0]);
b = clip8 (BLUE (s) + ceba[0]);
cera[0] = 0;
cega[0] = 0;
ceba[0] = 0;
// Find the nearest match in the palette and write it out
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// And the corresponding RGB color
a = palette[apix];
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
per = 7*er/16;
peg = 7*eg/16;
peb = 7*eb/16;
// Put all the remaining error in the pixels down and down-right
// (since there is no pixel down-left...)
nera[x] += er/2;
nega[x] += eg/2;
neba[x] += eb/2;
nera[x + 1] += er/16;
nega[x + 1] += eg/16;
neba[x + 1] += eb/16;
for (x = 1; x < width - 1; x++)
{
// printf (","); fflush (stdout);
// Get one source pixel
s = *(++src);
// Get color components and add errors from previous pixel
r = clip8 (RED (s) + per + cera[x]);
g = clip8 (GREEN (s) + peg + cega[x]);
b = clip8 (BLUE (s) + peb + ceba[x]);
cera[x] = 0;
cega[x] = 0;
ceba[x] = 0;
// Find the nearest match in the palette and write it out
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// And the corresponding RGB color
a = palette[apix];
// printf ("%c.", 8); fflush (stdout);
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// printf ("%c:", 8); fflush (stdout);
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
per = 7*er/16;
peg = 7*eg/16;
peb = 7*eb/16;
nera[x - 1] += 3*er/16;
nega[x - 1] += 3*eg/16;
neba[x - 1] += 3*eb/16;
nera[x] += 5*er/16;
nega[x] += 5*eg/16;
neba[x] += 5*eb/16;
nera[x + 1] += er/16;
nega[x + 1] += eg/16;
neba[x + 1] += eb/16;
}
// Special case: Last pixel
// printf ("Writing last pixel - "); fflush (stdout);
s = *(++src);
// printf ("1"); fflush (stdout);
// Get color components and add errors from previous pixel
r = clip8 (RED (s) + per + cera[x]);
g = clip8 (GREEN (s) + peg + cega[x]);
b = clip8 (BLUE (s) + peb + ceba[x]);
cera[x] = 0;
cega[x] = 0;
ceba[x] = 0;
// Find the nearest match in the palette and write it out
rs = r >> R_SHIFT;
gs = g >> G_SHIFT;
bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// printf ("@"); fflush (stdout);
// And the corresponding RGB color
a = palette[apix];
// printf ("2"); fflush (stdout);
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// printf ("Still alive.\n");
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
// Put all the error in the pixels down and down-left
nera[x - 1] += er/2;
nega[x - 1] += eg/2;
neba[x - 1] += eb/2;
nera[x] += er/2;
nega[x] += eg/2;
neba[x] += eb/2;
// Switch the scratch data
int *tmp;
tmp = cera; cera = nera; nera = tmp;
tmp = cega; cega = nega; nega = tmp;
tmp = ceba; ceba = neba; neba = tmp;
dest += ddif;
src += sdif;
mapbits += mdiff;
}
// Special case: Last line
// All the error goes into the right pixel.
er = 0;
eg = 0;
eb = 0;
// printf ("Entering last line...\n");
for (x = 0; x < width - 1; x++)
{
// Get one source pixel
bgra_pixel s = *(++src);
// Get color components and add errors from previous pixel
r = clip8 (RED (s) + er + cera[x]);
g = clip8 (GREEN (s) + eg + cega[x]);
b = clip8 (BLUE (s) + eb + ceba[x]);
// Find the nearest match in the palette and write it out
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// And the corresponding RGB color
a = palette[apix];
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
}
// Last but not least, the bottom right pixel.
bgra_pixel s = *(++src);
r = clip8 (RED (s) + er + cera[x]);
g = clip8 (GREEN (s) + eg + cega[x]);
b = clip8 (BLUE (s) + eb + ceba[x]);
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (palette[apix]);
else
*(++dest) = s;
delete [] nera;
delete [] nega;
delete [] neba;
delete [] cera;
delete [] cega;
delete [] ceba;
}
delete [] palette;
break;
}
case M_SELECT:
{
break;
}
default:
fprintf (stderr, "Quantize: Unknown mode\n");
error = ADDON_UNKNOWN;
}
if (*outSelection)
(*outSelection)->Unlock();
if (*outLayer)
(*outLayer)->Unlock();
if (final)
addon_done();
return (error);
}
| 26.540441
| 128
| 0.586323
|
thaflo
|
27529bcb836fad9ead65325abb59bf5376582755
| 5,373
|
cpp
|
C++
|
55479c656d65636fdb050000/code/RobotAI.cpp
|
MechEmpire/Mechempire-meches
|
aa95b15f061f4179c9061595e73c7127587cc4df
|
[
"Apache-2.0"
] | 1
|
2020-07-29T05:50:16.000Z
|
2020-07-29T05:50:16.000Z
|
55479ffa6d65636fdb0d0000/code/RobotAI.cpp
|
MechEmpire/Mechempire-meches
|
aa95b15f061f4179c9061595e73c7127587cc4df
|
[
"Apache-2.0"
] | null | null | null |
55479ffa6d65636fdb0d0000/code/RobotAI.cpp
|
MechEmpire/Mechempire-meches
|
aa95b15f061f4179c9061595e73c7127587cc4df
|
[
"Apache-2.0"
] | null | null | null |
๏ปฟ#include "RobotAI.h"
#include<math.h>
#include<iostream>
using namespace std;
RobotAI::RobotAI()
{
}
RobotAI::~RobotAI()
{
}
//-----------------------------------------------------
//1.ๅฟ
้กปๅฎๆ็ๆๆๆ ธๅฟ
//-----------------------------------------------------
struct node
{
double x,y,dis;
};
double max_num(double a,double b)
{
return a>b?a:b;
}
void RobotAI::Update(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info,int myID)
{
int enery;
if(myID==1)
enery=0;
else
enery=1;
int x=info.robotInformation[myID].circle.x;
int y=info.robotInformation[myID].circle.y;
int x1=info.robotInformation[enery].circle.x;
int y1=info.robotInformation[enery].circle.y;
int x2=300;
int y2=250;
int x3=1066;
int y3=430;
int d=120;
int dis;
int ddx;
int ddy;
if(myID==1)
{
dis=(int)sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
ddx=(120*(x3-x1))/dis+x3;
ddy=(120*(y3-y1))/dis+y3;
}
else
{
dis=(int)sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
ddx=x2-dis*(x1-x2)/120;
ddy=y2-dis*(y1-y2)/120;
}
int dx=(x1-x);
int dy=(y1-y);
double k=Random0_1();
double kk,kk1;
if(myID==1)
{
kk=(y1-430)/max_num(0.01,(x1-1066));
kk1=(430-y)/(max_num(0.01,(1066-x)));
}
else
{
kk=(y1-250)/max_num(0.01,(x1-300));
kk1=(250-y)/(max_num(0.01,(300-x)));
}
//1234 ๅทฆๅณไธไธ
if(k<0.5)
{
if(ddx>x)
order.run=2;
else
order.run=1;
}
else
{
if(ddy>y)
order.run=4;
else
order.run=3;
}
if(myID==1)
{
if(info.robotInformation[myID].circle.x>1066+d)
order.run=1;
if(info.robotInformation[myID].circle.x<1066-d)
order.run=2;
if(info.robotInformation[myID].circle.y>430+d)
order.run=3;
if(info.robotInformation[myID].circle.y<430-d)
order.run=4;
}
if(myID==0)
{
if(info.robotInformation[myID].circle.x>300+d)
order.run=1;
if(info.robotInformation[myID].circle.x<300-d)
order.run=2;
if(info.robotInformation[myID].circle.y>250+d)
order.run=3;
if(info.robotInformation[myID].circle.y<250-d)
order.run=4;
}
double kiss=Random0_1();
if(info.robotInformation[myID].remainingAmmo==0)
{
for(int i=0;i<2;i++)
{
if(info.arsenal[i].respawning_time==0)
{
if(kiss<0.5)
{
if(info.arsenal[i].circle.x+30>info.robotInformation[myID].circle.x)
{
order.run=2;
break;
}
if(info.arsenal[i].circle.x+30<info.robotInformation[myID].circle.x)
{
order.run=1;
break;
}
}
else
{
if(info.arsenal[i].circle.y+30>info.robotInformation[myID].circle.y)
{
order.run=4;
break;
}
if(info.arsenal[i].circle.y+30<info.robotInformation[myID].circle.y)
{
order.run=3;
break;
}
}
}
}
}
double ck;
Beam shoot;
double ck1=info.robotInformation[myID].weaponRotation;
shoot.x=x;
shoot.y=y;
shoot.rotation=ck1;
Circle kis;
if(myID==1)
{
kis.x=1066;
kis.y=430;
kis.r=100;
if(HitTestBeamCircle(shoot,kis))
order.wturn=1;
}
else
{
kis.x=300;
kis.y=250;
kis.r=80;
if(HitTestBeamCircle(shoot,kis))
order.wturn=1;
}
if(myID==0)
order.fire=2;
else
order.fire=1;
}
void RobotAI::ChooseArmor(weapontypename& weapon,enginetypename& engine,bool a)
{
//ๆ้่ฃ
ๅคๅฝๆฐ
//ๅ่ฝ๏ผๅจๆๆๅผๅงๆถไธบไฝ ็ๆบ็ฒ้ๆฉๅ้็ๆญฆๅจ็ฎๅกๅๅผๆ่ฝฝๅ
ท
//ๅๆฐ๏ผweapon ... ไปฃ่กจไฝ ้ๆฉ็ๆญฆๅจ๏ผๅจๅฝๆฐไฝไธญ็ปๅฎ่ตๅผ
// engine ... ไปฃ่กจไฝ ้ๆฉ็ๅผๆ๏ผๅจๅฝๆฐไฝไธญ็ปๅฎ่ตๅผ
//tip: ๆฌๅท้็ๅๆฐๆฏๆไธพ็ฑปๅ weapontypename ๆ enginetypename
// ๅผๅๆๆกฃไธญๆ่ฏฆ็ป่ฏดๆ๏ผไฝ ไนๅฏไปฅๅจRobotAIstruct.hไธญ็ดๆฅๆพๅฐๅฎไปฌ็ไปฃ็
//tip: ๆๅไธไธชboolๆฏๆฒก็จ็ใใ้ฃๆฏไธไธช้ๅ็ๅจๅฎ
weapon = WT_MissileLauncher;
engine = ET_Spider;
}
//-----------------------------------------------------
//2.ไธชๆงไฟกๆฏ
//-----------------------------------------------------
string RobotAI::GetName()
{
//่ฟๅไฝ ็ๆบ็ฒ็ๅๅญ
return "bird_raincoatV0.19";
}
string RobotAI::GetAuthor()
{
//่ฟๅๆบ็ฒๅถไฝไบบๆๅข้็ๅๅญ
return "qscqesze";
}
//่ฟๅไธไธช(-255,255)ไน้ด็ๆบ็ฒๆญฆๅจ็ฎๅก็้ข่ฒๅ็งปๅผ๏ผ็บขใ็ปฟใ่๏ผ
//ไฝ ๅฏไปฅๅจflashๅฎขๆท็ซฏ็ๅๆฐ้ข่งไธญ้ข่ง้ข่ฒๆญ้
็ๆๆ
int RobotAI::GetWeaponRed()
{
//่ฟๅไธไธช-255-255ไน้ด็ๆดๆฐ,ไปฃ่กจๆญฆๅจ็บข่ฒ็ๅ็งปๅผ
return 255;
}
int RobotAI::GetWeaponGreen()
{
//่ฟๅไธไธช-255-255ไน้ด็ๆดๆฐ,ไปฃ่กจๆญฆๅจ็ปฟ่ฒ็ๅ็งปๅผ
return -69;
}
int RobotAI::GetWeaponBlue()
{
//่ฟๅไธไธช-255-255ไน้ด็ๆดๆฐ,ไปฃ่กจๆญฆๅจ่่ฒ็ๅ็งปๅผ
return 31;
}
//่ฟๅไธไธช(-255,255)ไน้ด็ๆบ็ฒๅผๆ่ฝฝๅ
ท็้ข่ฒๅ็งปๅผ๏ผ็บขใ็ปฟใ่๏ผ
//ไฝ ๅฏไปฅๅจflashๅฎขๆท็ซฏ็ๅๆฐ้ข่งไธญ้ข่ง้ข่ฒๆญ้
็ๆๆ
int RobotAI::GetEngineRed()
{
//่ฟๅไธไธช-255-255ไน้ด็ๆฐ,ไปฃ่กจ่ฝฝๅ
ท็บข่ฒ็ๅ็งปๅผ
return -255;
}
int RobotAI::GetEngineGreen()
{
//่ฟๅไธไธช-255-255ไน้ด็ๆดๆฐ,ไปฃ่กจ่ฝฝๅ
ท็ปฟ่ฒ็ๅ็งปๅผ
return -106;
}
int RobotAI::GetEngineBlue()
{
//่ฟๅไธไธช-255-255ไน้ด็ๆดๆฐ,ไปฃ่กจ่ฝฝๅ
ท่่ฒ็ๅ็งปๅผ
return -4;
}
//-----------------------------------------------------
//3.็จไธ็จ้ไฝ ็่งฆๅๅฝๆฐ
//-----------------------------------------------------
void RobotAI::onBattleStart(const RobotAI_BattlefieldInformation& info,int myID)
{
//ไธๅบๆๆๅผๅงๆถ่ขซ่ฐ็จ๏ผๅฏ่ฝๅฏไปฅ็จๆฅๅๅงๅ
//ๅๆฐ๏ผinfo ... ๆๅบไฟกๆฏ
// myID ... ่ชๅทฑๆบ็ฒๅจinfoไธญrobotๆฐ็ปๅฏนๅบ็ไธๆ
}
void RobotAI::onBattleEnd(const RobotAI_BattlefieldInformation& info,int myID)
{
//ไธๅบๆๆ็ปๆๆถ่ขซ่ฐ็จ๏ผๅฏ่ฝๅฏไปฅ็จๆฅๆๆไฝ ๅจๆๅ้
็ๅ
ๅญ็ฉบ้ด๏ผๅฆๆไฝ ็จไบ็่ฏ๏ผ
//ๅๆฐ๏ผinfo ... ๆๅบไฟกๆฏ
// myID ... ่ชๅทฑๆบ็ฒๅจinfoไธญrobotๆฐ็ปๅฏนๅบ็ไธๆ
}
void RobotAI::onSomeoneFire(int fireID)
{
//ๆๆบ็ฒๅผ็ซๆถ่ขซ่ฐ็จ
//ๅๆฐ๏ผfireID ... ๅผ็ซ็ๆบ็ฒไธๆ
}
void RobotAI::onHit(int launcherID,bullettypename btn)
{
//่ขซๅญๅผนๅปไธญๆถ่ขซ่ฐ็จ
//ๅๆฐ๏ผbtn ... ๅปไธญไฝ ็ๅญๅผน็ง็ฑป๏ผๆไธพ็ฑปๅ๏ผ
}
//TODO:่ฟ้ๅฏไปฅๅฎ็ฐไฝ ่ชๅทฑ็ๅฝๆฐ
| 17.166134
| 95
| 0.577703
|
MechEmpire
|
27535f079eb414837f11b815cca167a6b7fe7654
| 10,997
|
cpp
|
C++
|
webkit/WebCore/dom/Text.cpp
|
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
|
3dd05f035e0a5fc9723300623e9b9b359be64e11
|
[
"Unlicense"
] | 15
|
2016-01-05T12:43:41.000Z
|
2022-03-15T10:34:47.000Z
|
webkit/WebCore/dom/Text.cpp
|
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
|
3dd05f035e0a5fc9723300623e9b9b359be64e11
|
[
"Unlicense"
] | null | null | null |
webkit/WebCore/dom/Text.cpp
|
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
|
3dd05f035e0a5fc9723300623e9b9b359be64e11
|
[
"Unlicense"
] | 2
|
2020-11-30T18:36:01.000Z
|
2021-02-05T23:20:24.000Z
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "Text.h"
#include "CString.h"
#include "ExceptionCode.h"
#include "RenderText.h"
#include "TextBreakIterator.h"
#if ENABLE(SVG)
#include "RenderSVGInlineText.h"
#include "SVGNames.h"
#endif
#if ENABLE(WML)
#include "WMLDocument.h"
#include "WMLVariables.h"
#endif
using namespace std;
namespace WebCore {
Text::Text(Document* document, const String& data)
: CharacterData(document, data, CreateText)
{
}
PassRefPtr<Text> Text::create(Document* document, const String& data)
{
return adoptRef(new Text(document, data));
}
PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionCode& ec)
{
ec = 0;
// INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than
// the number of 16-bit units in data.
if (offset > length()) {
ec = INDEX_SIZE_ERR;
return 0;
}
RefPtr<StringImpl> oldStr = dataImpl();
RefPtr<Text> newText = virtualCreate(oldStr->substring(offset));
setDataImpl(oldStr->substring(0, offset));
dispatchModifiedEvent(oldStr.get());
if (parentNode())
parentNode()->insertBefore(newText.get(), nextSibling(), ec);
if (ec)
return 0;
if (parentNode())
document()->textNodeSplit(this);
if (renderer())
toRenderText(renderer())->setText(dataImpl());
return newText.release();
}
static const Text* earliestLogicallyAdjacentTextNode(const Text* t)
{
const Node* n = t;
while ((n = n->previousSibling())) {
Node::NodeType type = n->nodeType();
if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) {
t = static_cast<const Text*>(n);
continue;
}
// We would need to visit EntityReference child text nodes if they existed
ASSERT(type != Node::ENTITY_REFERENCE_NODE || !n->hasChildNodes());
break;
}
return t;
}
static const Text* latestLogicallyAdjacentTextNode(const Text* t)
{
const Node* n = t;
while ((n = n->nextSibling())) {
Node::NodeType type = n->nodeType();
if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) {
t = static_cast<const Text*>(n);
continue;
}
// We would need to visit EntityReference child text nodes if they existed
ASSERT(type != Node::ENTITY_REFERENCE_NODE || !n->hasChildNodes());
break;
}
return t;
}
String Text::wholeText() const
{
const Text* startText = earliestLogicallyAdjacentTextNode(this);
const Text* endText = latestLogicallyAdjacentTextNode(this);
Node* onePastEndText = endText->nextSibling();
unsigned resultLength = 0;
for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) {
if (!n->isTextNode())
continue;
const Text* t = static_cast<const Text*>(n);
const String& data = t->data();
#if 1
// added at webkit.org trunk r68705
if (std::numeric_limits<unsigned>::max() - data.length() < resultLength)
CRASH();
#endif
resultLength += data.length();
}
UChar* resultData;
String result = String::createUninitialized(resultLength, resultData);
UChar* p = resultData;
for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) {
if (!n->isTextNode())
continue;
const Text* t = static_cast<const Text*>(n);
const String& data = t->data();
unsigned dataLength = data.length();
memcpy(p, data.characters(), dataLength * sizeof(UChar));
p += dataLength;
}
ASSERT(p == resultData + resultLength);
return result;
}
PassRefPtr<Text> Text::replaceWholeText(const String& newText, ExceptionCode&)
{
// Remove all adjacent text nodes, and replace the contents of this one.
// Protect startText and endText against mutation event handlers removing the last ref
RefPtr<Text> startText = const_cast<Text*>(earliestLogicallyAdjacentTextNode(this));
RefPtr<Text> endText = const_cast<Text*>(latestLogicallyAdjacentTextNode(this));
RefPtr<Text> protectedThis(this); // Mutation event handlers could cause our last ref to go away
Node* parent = parentNode(); // Protect against mutation handlers moving this node during traversal
ExceptionCode ignored = 0;
for (RefPtr<Node> n = startText; n && n != this && n->isTextNode() && n->parentNode() == parent;) {
RefPtr<Node> nodeToRemove(n.release());
n = nodeToRemove->nextSibling();
parent->removeChild(nodeToRemove.get(), ignored);
}
if (this != endText) {
Node* onePastEndText = endText->nextSibling();
for (RefPtr<Node> n = nextSibling(); n && n != onePastEndText && n->isTextNode() && n->parentNode() == parent;) {
RefPtr<Node> nodeToRemove(n.release());
n = nodeToRemove->nextSibling();
parent->removeChild(nodeToRemove.get(), ignored);
}
}
if (newText.isEmpty()) {
if (parent && parentNode() == parent)
parent->removeChild(this, ignored);
return 0;
}
setData(newText, ignored);
return protectedThis.release();
}
String Text::nodeName() const
{
return textAtom.string();
}
Node::NodeType Text::nodeType() const
{
return TEXT_NODE;
}
PassRefPtr<Node> Text::cloneNode(bool /*deep*/)
{
return create(document(), data());
}
bool Text::rendererIsNeeded(RenderStyle *style)
{
if (!CharacterData::rendererIsNeeded(style))
return false;
bool onlyWS = containsOnlyWhitespace();
if (!onlyWS)
return true;
RenderObject *par = parentNode()->renderer();
if (par->isTable() || par->isTableRow() || par->isTableSection() || par->isTableCol() || par->isFrameSet())
return false;
if (style->preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
return true;
RenderObject *prev = previousRenderer();
if (prev && prev->isBR()) // <span><br/> <br/></span>
return false;
if (par->isRenderInline()) {
// <span><div/> <div/></span>
if (prev && !prev->isInline())
return false;
} else {
if (par->isRenderBlock() && !par->childrenInline() && (!prev || !prev->isInline()))
return false;
RenderObject *first = par->firstChild();
while (first && first->isFloatingOrPositioned())
first = first->nextSibling();
RenderObject *next = nextRenderer();
if (!first || next == first)
// Whitespace at the start of a block just goes away. Don't even
// make a render object for this text.
return false;
}
return true;
}
RenderObject* Text::createRenderer(RenderArena* arena, RenderStyle*)
{
#if ENABLE(SVG)
if (parentNode()->isSVGElement()
#if ENABLE(SVG_FOREIGN_OBJECT)
&& !parentNode()->hasTagName(SVGNames::foreignObjectTag)
#endif
)
return new (arena) RenderSVGInlineText(this, dataImpl());
#endif
return new (arena) RenderText(this, dataImpl());
}
void Text::attach()
{
#if ENABLE(WML)
if (document()->isWMLDocument() && !containsOnlyWhitespace()) {
String text = data();
ASSERT(!text.isEmpty());
text = substituteVariableReferences(text, document());
ExceptionCode code = 0;
setData(text, code);
ASSERT(!code);
}
#endif
createRendererIfNeeded();
CharacterData::attach();
}
void Text::recalcStyle(StyleChange change)
{
if (change != NoChange && parentNode()) {
if (renderer())
renderer()->setStyle(parentNode()->renderer()->style());
}
if (needsStyleRecalc()) {
if (renderer()) {
if (renderer()->isText())
toRenderText(renderer())->setText(dataImpl());
} else {
if (attached())
detach();
attach();
}
}
setNeedsStyleRecalc(NoStyleChange);
}
bool Text::childTypeAllowed(NodeType)
{
return false;
}
PassRefPtr<Text> Text::virtualCreate(const String& data)
{
return create(document(), data);
}
PassRefPtr<Text> Text::createWithLengthLimit(Document* document, const String& data, unsigned& charsLeft, unsigned maxChars)
{
unsigned dataLength = data.length();
if (charsLeft == dataLength && charsLeft <= maxChars) {
charsLeft = 0;
return create(document, data);
}
unsigned start = dataLength - charsLeft;
unsigned end = start + min(charsLeft, maxChars);
// Check we are not on an unbreakable boundary.
// Some text break iterator implementations work best if the passed buffer is as small as possible,
// see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
// We need at least two characters look-ahead to account for UTF-16 surrogates.
if (end < dataLength) {
TextBreakIterator* it = characterBreakIterator(data.characters() + start, (end + 2 > dataLength) ? dataLength - start : end - start + 2);
if (!isTextBreak(it, end - start))
end = textBreakPreceding(it, end - start) + start;
}
// If we have maxChars of unbreakable characters the above could lead to
// an infinite loop.
// FIXME: It would be better to just have the old value of end before calling
// textBreakPreceding rather than this, because this exceeds the length limit.
if (end <= start)
end = dataLength;
charsLeft = dataLength - end;
return create(document, data.substring(start, end - start));
}
#ifndef NDEBUG
void Text::formatForDebugger(char *buffer, unsigned length) const
{
String result;
String s;
s = nodeName();
if (s.length() > 0) {
result += s;
}
s = data();
if (s.length() > 0) {
if (result.length() > 0)
result += "; ";
result += "value=";
result += s;
}
strncpy(buffer, result.utf8().data(), length - 1);
}
#endif
} // namespace WebCore
| 29.964578
| 145
| 0.626807
|
s1rcheese
|
2753944f40611ce3b32bdff335d878da63ecb12b
| 2,770
|
cpp
|
C++
|
Source/Planet/Map/PlanetMapTile.cpp
|
unconed/NFSpace
|
bbd544afb32a10bc4ee497e1d58cefe4bbbe7953
|
[
"BSD-3-Clause"
] | 91
|
2015-01-19T11:03:56.000Z
|
2022-03-12T15:54:06.000Z
|
Source/Planet/Map/PlanetMapTile.cpp
|
unconed/NFSpace
|
bbd544afb32a10bc4ee497e1d58cefe4bbbe7953
|
[
"BSD-3-Clause"
] | null | null | null |
Source/Planet/Map/PlanetMapTile.cpp
|
unconed/NFSpace
|
bbd544afb32a10bc4ee497e1d58cefe4bbbe7953
|
[
"BSD-3-Clause"
] | 9
|
2015-03-16T03:36:50.000Z
|
2021-06-17T09:47:26.000Z
|
/*
* PlanetMapTile.cpp
* NFSpace
*
* Created by Steven Wittens on 26/11/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "PlanetMapTile.h"
#include "Utility.h"
namespace NFSpace {
PlanetMapTile::PlanetMapTile(QuadTreeNode* node, TexturePtr heightTexture, Image heightImage, TexturePtr normalTexture, int size) {
mNode = node;
mHeightTexture = heightTexture;
mHeightImage = heightImage;
mNormalTexture = normalTexture;
mSize = size;
mReferences = 0;
PlanetStats::totalTiles++;
prepareMaterial();
}
PlanetMapTile::~PlanetMapTile() {
OGRE_FREE(mHeightImage.getData(), MEMCATEGORY_GENERAL);
if (mMaterialCreated) {
MaterialManager::getSingleton().remove(mMaterial->getName());
}
TextureManager::getSingleton().remove(mHeightTexture->getName());
TextureManager::getSingleton().remove(mNormalTexture->getName());
PlanetStats::totalTiles--;
}
String PlanetMapTile::getMaterial() {
if (!mMaterialCreated) prepareMaterial();
return mMaterial->getName();//"Planet/Surface";//mMaterial->getName();
}
Image* PlanetMapTile::getHeightMap() {
return &mHeightImage;
}
void PlanetMapTile::prepareMaterial() {
mMaterialCreated = TRUE;
// Get original planet/surface material and clone it.
MaterialPtr planetSurface = MaterialManager::getSingleton().getByName("Planet/Surface");
mMaterial = planetSurface->clone("Planet/Surface/" + getUniqueId(""));
// Prepare texture substitution list.
AliasTextureNamePairList aliasList;
aliasList.insert(AliasTextureNamePairList::value_type("heightMap", mHeightTexture->getName()));
aliasList.insert(AliasTextureNamePairList::value_type("normalMap", mNormalTexture->getName()));
mMaterial->applyTextureAliases(aliasList);
// Clear out pass caches between scene managers.
updateSceneManagersAfterMaterialsChange();
}
const QuadTreeNode* PlanetMapTile::getNode() {
return mNode;
}
size_t PlanetMapTile::getGPUMemoryUsage() {
return 1.3125 * (
mHeightTexture->getWidth() * mHeightTexture->getHeight() * Ogre::PixelUtil::getNumElemBytes(mHeightTexture->getFormat()) +
mNormalTexture->getWidth() * mNormalTexture->getHeight() * Ogre::PixelUtil::getNumElemBytes(mNormalTexture->getFormat()));
}
void PlanetMapTile::addReference() {
mReferences++;
}
void PlanetMapTile::removeReference() {
mReferences--;
}
int PlanetMapTile::getReferences() {
return mReferences;
}
}
| 31.123596
| 135
| 0.651264
|
unconed
|
2755d2ac1baa5df3c2f5c744333f2853a896e547
| 1,579
|
cpp
|
C++
|
Graphs/dijkstra.cpp
|
adiletabs/Algos
|
fa2bb9edddb517f52b79fc712f70d6f8a0786e33
|
[
"MIT"
] | 3
|
2020-01-29T18:26:37.000Z
|
2021-01-19T06:26:34.000Z
|
Graphs/dijkstra.cpp
|
adiletabs/Algos
|
fa2bb9edddb517f52b79fc712f70d6f8a0786e33
|
[
"MIT"
] | null | null | null |
Graphs/dijkstra.cpp
|
adiletabs/Algos
|
fa2bb9edddb517f52b79fc712f70d6f8a0786e33
|
[
"MIT"
] | 2
|
2019-03-06T03:40:42.000Z
|
2019-09-23T03:48:21.000Z
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2020, inf = INT_MAX;
vector<pair<int, int> > g[N];
int dist[N], par[N], n, m;
bool used[N];
vector<int> path;
void init(int s) {
for (int i = 0; i < N; i++)
dist[i] = inf;
dist[s] = 0;
}
void dijkstra(int s) {
init(s);
for (int i = 0; i < n; i++) {
int v = -1;
for (int j = 0; j < n; j++)
if (!used[j] && (v == -1 || dist[j] < dist[v]))
v = j;
used[v] = true;
for (pair<int, int> p: g[v]) {
int to = p.first, len = p.second;
if (dist[v] + len < dist[to]) {
dist[to] = dist[v] + len;
par[to] = v;
}
}
}
}
void fast_dijkstra(int s) {
init(s);
set<pair<int, int> > best_vertices;
best_vertices.insert(make_pair(dist[s], s));
while (!best_vertices.empty()) {
int v = best_vertices.begin()->second;
best_vertices.erase(best_vertices.begin());
for (pair<int, int> p: g[v]) {
int to = p.first, len = p.second;
if (dist[v] + len < dist[to]) {
best_vertices.erase(make_pair(dist[to], to));
dist[to] = dist[v] + len;
par[to] = v;
best_vertices.insert(make_pair(dist[to], to));
}
}
}
}
void get_best_path(int start, int target) {
fast_dijkstra(start);
for (int v = target; v != start; v = par[v])
path.push_back(v);
path.push_back(start);
reverse(path.begin(), path.end());
}
int main() {
cin >> n >> m;
while (m--) {
int v, u, weight;
g[v].push_back(make_pair(u, weight));
g[u].push_back(make_pair(v, weight));
}
int start;
cin >> start;
fast_dijkstra(start);
for (int i = 1; i <= n; i++)
cout << dist[i] << ' ';
}
| 20.24359
| 50
| 0.559215
|
adiletabs
|
2756ebb0e82a9b58972a2a24859faf61057b140e
| 5,107
|
hpp
|
C++
|
src/threepp/renderers/gl/GLClipping.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
src/threepp/renderers/gl/GLClipping.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
src/threepp/renderers/gl/GLClipping.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
// https://github.com/mrdoob/three.js/blob/r129/src/renderers/webgl/WebGLClipping.js
#ifndef THREEPP_GLCLIPPING_HPP
#define THREEPP_GLCLIPPING_HPP
#include "GLProperties.hpp"
#include "threepp/cameras/Camera.hpp"
#include "threepp/math/Plane.hpp"
#include "threepp/core/Uniform.hpp"
namespace threepp::gl {
struct GLClipping {
std::optional<std::vector<float>> globalState;
int numGlobalPlanes = 0;
bool localClippingEnabled = false;
bool renderingShadows = false;
Plane plane;
Matrix3 viewNormalMatrix;
Uniform uniform;
int numPlanes = 0;
int numIntersection = 0;
explicit GLClipping(GLProperties &properties) : properties(properties) {
uniform.needsUpdate = false;
}
bool init(
const std::vector<Plane> &planes,
bool enableLocalClipping,
const std::shared_ptr<Camera> &camera) {
bool enabled =
!planes.empty() ||
enableLocalClipping ||
// enable state of previous frame - the clipping code has to
// run another frame in order to reset the state:
numGlobalPlanes != 0 || localClippingEnabled;
localClippingEnabled = enableLocalClipping;
globalState = projectPlanes(planes, camera, 0);
numGlobalPlanes = (int) planes.size();
return enabled;
}
void beginShadows() {
renderingShadows = true;
projectPlanes();
}
void endShadows() {
renderingShadows = false;
resetGlobalState();
}
void setState(const std::shared_ptr<Material> &material, const std::shared_ptr<Camera> &camera, bool useCache) {
auto &planes = material->clippingPlanes;
auto clipIntersection = material->clipIntersection;
auto clipShadows = material->clipShadows;
auto &materialProperties = properties.materialProperties.get(material->uuid);
if (!localClippingEnabled || planes.empty() || renderingShadows && !clipShadows) {
// there's no local clipping
if (renderingShadows) {
// there's no global clipping
projectPlanes();
} else {
resetGlobalState();
}
} else {
const auto nGlobal = renderingShadows ? 0 : numGlobalPlanes,
lGlobal = nGlobal * 4;
auto &dstArray = materialProperties.clippingState;
uniform.setValue(dstArray);// ensure unique state
dstArray = projectPlanes(planes, camera, lGlobal, useCache);
for (int i = 0; i != lGlobal; ++i) {
dstArray[i] = globalState.value()[i];
}
materialProperties.clippingState = dstArray;
this->numIntersection = clipIntersection ? this->numPlanes : 0;
this->numPlanes += nGlobal;
}
}
void resetGlobalState() {
if (!uniform.hasValue() || uniform.value<std::vector<float>>() != globalState) {
uniform.setValue(*globalState);
uniform.needsUpdate = numGlobalPlanes > 0;
}
numPlanes = numGlobalPlanes;
numIntersection = 0;
}
void projectPlanes() {
numPlanes = 0;
numIntersection = 0;
}
std::vector<float> projectPlanes(
const std::vector<Plane> &planes,
const std::shared_ptr<Camera> &camera,
int dstOffset, bool skipTransform = false) {
int nPlanes = (int) planes.size();
std::vector<float> dstArray;
if (nPlanes != 0) {
if (uniform.hasValue()) {
dstArray = uniform.value<std::vector<float>>();
}
if (!skipTransform || dstArray.empty()) {
const auto flatSize = dstOffset + nPlanes * 4;
const auto &viewMatrix = camera->matrixWorldInverse;
viewNormalMatrix.getNormalMatrix(viewMatrix);
if (dstArray.size() < flatSize) {
dstArray.resize(flatSize);
}
for (int i = 0, i4 = dstOffset; i != nPlanes; ++i, i4 += 4) {
plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
plane.normal.toArray(dstArray, i4);
dstArray[i4 + 3] = plane.constant;
}
}
uniform.setValue(dstArray);
uniform.needsUpdate = true;
}
numPlanes = nPlanes;
numIntersection = 0;
return dstArray;
}
private:
GLProperties &properties;
};
}// namespace threepp::gl
#endif//THREEPP_GLCLIPPING_HPP
| 27.907104
| 120
| 0.527511
|
maidamai0
|
2758945d92d2bba295767c04dccf123ca71c6a50
| 960
|
cpp
|
C++
|
src/console/commands/environment/terrain/environmentTerrainValleys.cpp
|
fantasiorona/LGen
|
bb670278b7faf82154d6256e6a283fa3e226c00b
|
[
"MIT"
] | 22
|
2019-08-01T22:04:43.000Z
|
2021-12-23T07:53:59.000Z
|
src/console/commands/environment/terrain/environmentTerrainValleys.cpp
|
fantasiorona/LGen
|
bb670278b7faf82154d6256e6a283fa3e226c00b
|
[
"MIT"
] | 15
|
2019-05-01T10:57:36.000Z
|
2019-05-27T11:23:42.000Z
|
src/console/commands/environment/terrain/environmentTerrainValleys.cpp
|
fantasiorona/LGen
|
bb670278b7faf82154d6256e6a283fa3e226c00b
|
[
"MIT"
] | 4
|
2019-08-02T08:07:45.000Z
|
2022-01-22T00:46:03.000Z
|
#include "environmentTerrainValleys.h"
#include "environment/terrain/terrainValleys.h"
using namespace LGen;
const std::string Command::Environment::Terrain::Valleys::KEYWORD = "valleys";
const std::string Command::Environment::Terrain::Valleys::FILE_HELP = "text/helpEnvironmentTerrainValleys.txt";
Command::Environment::Terrain::Valleys::Valleys() :
Command({ KEYWORD }, FILE_HELP, 3) {
}
void Command::Environment::Terrain::Valleys::application(
const std::vector<std::string> &arguments,
Console &console) {
if(!workspace.environment) {
console << MSG_NO_ENVIRONMENT << std::endl;
return;
}
try {
const auto width = std::stof(arguments[ARG_WIDTH]);
const auto height = std::stof(arguments[ARG_HEIGHT]);
const auto resolution = std::stof(arguments[ARG_RESOLUTION]);
workspace.environment->setTerrain(std::make_unique<TerrainValleys>(width, height, resolution));
}
catch(...) {
console << MSG_INVALID_INPUT << std::endl;
}
}
| 27.428571
| 111
| 0.734375
|
fantasiorona
|
275af587f3742e93eef69ddd318501c98c79f037
| 3,214
|
hpp
|
C++
|
Code/Engine/Renderer/Effects/Tonemapping.hpp
|
ntaylorbishop/Copycat
|
c02f2881f0700a33a2630fd18bc409177d80b8cd
|
[
"MIT"
] | 2
|
2017-10-02T03:18:55.000Z
|
2018-11-21T16:30:36.000Z
|
Code/Engine/Renderer/Effects/Tonemapping.hpp
|
ntaylorbishop/Copycat
|
c02f2881f0700a33a2630fd18bc409177d80b8cd
|
[
"MIT"
] | null | null | null |
Code/Engine/Renderer/Effects/Tonemapping.hpp
|
ntaylorbishop/Copycat
|
c02f2881f0700a33a2630fd18bc409177d80b8cd
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Engine/General/Core/EngineCommon.hpp"
#include "Engine/Renderer/General/RenderCommon.hpp"
#include "Engine/Math/Objects/AABB3.hpp"
class TextureBuffer;
class Material;
class Framebuffer;
const float MIN_EXPOSURE = 1.6f;
const float MAX_EXPOSURE = 6.f;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//EXPOSURE VOLUME
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------------------------------------------------------------
struct ExposureVolume {
ExposureVolume();
ExposureVolume(const AABB3& vol, float exposure)
: m_volume(vol)
, m_exposureVal(exposure)
{ }
AABB3 m_volume = AABB3();
float m_exposureVal = 0.f;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//TONEMAPPING PASS CLASS
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------------------------------------------------------------
class Tonemapping {
public:
//GET
static Tonemapping* Get();
//UPDATE RENDER
void Update(float deltaSeconds);
void RunPass();
//ADD VOLUMES
void AddExposureVolume(const AABB3& volume, float exposureVal);
void SetMinExposure(float minExposure) { m_minExposure = minExposure; }
void SetMaxExposure(float maxExposure) { m_maxExposure = maxExposure; }
void SetExposureChangeRate(float changeRate) { m_exposureChangeRate = changeRate; }
void SetDefaultExposure(float defExp) { m_defaultExposure = defExp; }
void EnableDebugVisualizer() { m_debugVisualizer = true; }
void DisableDebugVisualizer() { m_debugVisualizer = false; }
void ToggleExposureVolumes(bool enabled) { m_exposureVolumesEnabled = enabled; }
private:
//STRUCTORS
Tonemapping();
~Tonemapping();
static void Shutdown();
TextureBuffer* m_colorTarget = nullptr;
Material* m_tonemappingMat = nullptr;
Framebuffer* m_tonemapFBO = nullptr;
float m_minExposure = 0.f;
float m_maxExposure = 0.f;
float m_exposureChangeRate = 0.f;
float m_exposure = 0.f;
float m_targetExposure = 1.f;
float m_defaultExposure = 1.f;
MeshID m_fullScreenMesh = 0;
bool m_debugDraw = false;
bool m_debugVisualizer = false;
bool m_exposureVolumesEnabled = true;
std::vector<ExposureVolume> m_exposureVolumes;
static Tonemapping* s_HDR;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//INLINES
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------------------------------------------------------------
inline void Tonemapping::AddExposureVolume(const AABB3& volume, float exposureVal) {
m_exposureVolumes.push_back(ExposureVolume(volume, exposureVal));
}
| 33.479167
| 125
| 0.47822
|
ntaylorbishop
|
275e4de2d23f93672a8e3a261c6cb895b631b1a2
| 18,965
|
cpp
|
C++
|
CaptureManagerSource/SampleAccumulatorNode/SampleAccumulator.cpp
|
luoyingwen/CaptureManagerSDK
|
e96395a120175a45c56ff4e2b3283b807a42fd75
|
[
"MIT"
] | 64
|
2020-07-20T09:35:16.000Z
|
2022-03-27T19:13:08.000Z
|
CaptureManagerSource/SampleAccumulatorNode/SampleAccumulator.cpp
|
luoyingwen/CaptureManagerSDK
|
e96395a120175a45c56ff4e2b3283b807a42fd75
|
[
"MIT"
] | 8
|
2020-07-30T09:20:28.000Z
|
2022-03-03T22:37:10.000Z
|
CaptureManagerSource/SampleAccumulatorNode/SampleAccumulator.cpp
|
luoyingwen/CaptureManagerSDK
|
e96395a120175a45c56ff4e2b3283b807a42fd75
|
[
"MIT"
] | 28
|
2020-07-20T13:02:42.000Z
|
2022-03-18T07:36:05.000Z
|
/*
MIT License
Copyright(c) 2020 Evgeny Pereguda
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 "SampleAccumulator.h"
#include "../MediaFoundationManager/MediaFoundationManager.h"
#include "../Common/MFHeaders.h"
#include "../Common/Common.h"
#include "../LogPrintOut/LogPrintOut.h"
#include "../MemoryManager/MemoryManager.h"
#include "../Common/Singleton.h"
namespace CaptureManager
{
namespace Transform
{
namespace Accumulator
{
using namespace CaptureManager::Core;
SampleAccumulator::SampleAccumulator(
UINT32 aAccumulatorSize) :
mAccumulatorSize(aAccumulatorSize),
mPtrOutputSampleAccumulator(nullptr),
mEndOfStream(false),
mCurrentLength(0)
{
mPtrInputSampleAccumulator = &mFirstSampleAccumulator;
mPtrOutputSampleAccumulator = &mSecondSampleAccumulator;
Singleton<MemoryManager>::getInstance().initialize();
}
SampleAccumulator::~SampleAccumulator()
{
}
STDMETHODIMP SampleAccumulator::GetStreamLimits(DWORD* aPtrInputMinimum, DWORD* aPtrInputMaximum,
DWORD* aPtrOutputMinimum, DWORD* aPtrOutputMaximum)
{
HRESULT lresult = E_FAIL;
do
{
LOG_CHECK_STATE_DESCR(aPtrInputMinimum == NULL ||
aPtrInputMaximum == NULL ||
aPtrOutputMinimum == NULL ||
aPtrOutputMaximum == NULL, E_POINTER);
*aPtrInputMinimum = 1;
*aPtrInputMaximum = 1;
*aPtrOutputMinimum = 1;
*aPtrOutputMaximum = 1;
lresult = S_OK;
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetStreamIDs(DWORD aInputIDArraySize, DWORD* aPtrInputIDs,
DWORD aOutputIDArraySize, DWORD* aPtrOutputIDs)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::GetStreamCount(DWORD* aPtrInputStreams, DWORD* aPtrOutputStreams)
{
HRESULT lresult = E_FAIL;
do
{
LOG_CHECK_STATE_DESCR(aPtrInputStreams == NULL || aPtrOutputStreams == NULL, E_POINTER);
*aPtrInputStreams = 1;
*aPtrOutputStreams = 1;
lresult = S_OK;
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetInputStreamInfo(DWORD aInputStreamID,
MFT_INPUT_STREAM_INFO* aPtrStreamInfo)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrStreamInfo);
LOG_CHECK_STATE_DESCR(aInputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
aPtrStreamInfo->dwFlags = MFT_INPUT_STREAM_WHOLE_SAMPLES |
MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER;
aPtrStreamInfo->cbMaxLookahead = 0;
aPtrStreamInfo->cbAlignment = 0;
aPtrStreamInfo->hnsMaxLatency = 0;
aPtrStreamInfo->cbSize = 0;
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetOutputStreamInfo(DWORD aOutputStreamID,
MFT_OUTPUT_STREAM_INFO* aPtrStreamInfo)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrStreamInfo);
LOG_CHECK_STATE_DESCR(aOutputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
aPtrStreamInfo->dwFlags =
MFT_OUTPUT_STREAM_WHOLE_SAMPLES |
MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER |
MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE |
MFT_OUTPUT_STREAM_PROVIDES_SAMPLES;
aPtrStreamInfo->cbAlignment = 0;
aPtrStreamInfo->cbSize = 0;
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetInputStreamAttributes(DWORD aInputStreamID,
IMFAttributes** aPtrPtrAttributes)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::GetOutputStreamAttributes(DWORD aOutputStreamID,
IMFAttributes** aPtrPtrAttributes)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::DeleteInputStream(DWORD aStreamID)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::AddInputStreams(DWORD aStreams, DWORD* aPtrStreamIDs)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::GetInputAvailableType(DWORD aInputStreamID, DWORD aTypeIndex,
IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
CComPtrCustom<IMFMediaType> lMediaType;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_STATE_DESCR(aInputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
*aPtrPtrType = NULL;
if (!mInputMediaType)
{
*aPtrPtrType = lMediaType.Detach();
}
else if (aTypeIndex == 0)
{
*aPtrPtrType = mInputMediaType.get();
(*aPtrPtrType)->AddRef();
}
else
{
lresult = MF_E_NO_MORE_TYPES;
}
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetOutputAvailableType(DWORD aOutputStreamID, DWORD aTypeIndex,
IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
CComPtrCustom<IMFMediaType> lMediaType;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_STATE_DESCR(aOutputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
if (!mOutputMediaType)
{
*aPtrPtrType = lMediaType.get();
(*aPtrPtrType)->AddRef();
}
else
{
*aPtrPtrType = mOutputMediaType.get();
(*aPtrPtrType)->AddRef();
}
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::SetInputType(DWORD aInputStreamID, IMFMediaType* aPtrType,
DWORD aFlags)
{
HRESULT lresult = S_OK;
CComPtrCustom<IMFAttributes> lTypeAttributes;
do
{
lTypeAttributes = aPtrType;
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_STATE_DESCR(aInputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
LOG_CHECK_STATE_DESCR(!mFirstSampleAccumulator.empty() || !mSecondSampleAccumulator.empty(),
MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING);
if (aPtrType != nullptr && !(!mInputMediaType))
{
BOOL lBoolResult = FALSE;
LOG_INVOKE_MF_METHOD(Compare,
aPtrType,
lTypeAttributes,
MF_ATTRIBUTES_MATCH_INTERSECTION,
&lBoolResult);
if (lBoolResult == FALSE)
{
lresult = MF_E_INVALIDMEDIATYPE;
break;
}
}
if (aFlags != MFT_SET_TYPE_TEST_ONLY)
{
mInputMediaType = aPtrType;
PROPVARIANT lVarItem;
LOG_INVOKE_MF_METHOD(GetItem,
mInputMediaType,
MF_MT_FRAME_SIZE,
&lVarItem);
UINT32 lHigh = 0, lLow = 0;
DataParser::unpack2UINT32AsUINT64(lVarItem, lHigh, lLow);
LONG lstride = 0;
do
{
LOG_INVOKE_MF_METHOD(GetUINT32,
mInputMediaType,
MF_MT_DEFAULT_STRIDE,
((UINT32*)&lstride));
} while (false);
//if (FAILED(lresult))
//{
// GUID lSubType;
// LOG_INVOKE_MF_METHOD(GetGUID,
// mInputMediaType,
// MF_MT_SUBTYPE,
// &lSubType);
//
// lresult = LOG_INVOKE_MF_FUNCTION(MFGetStrideForBitmapInfoHeader,
// lSubType.Data1,
// lHigh,
// &lstride);
// LOG_CHECK_STATE(lstride == 0);
// LOG_INVOKE_MF_METHOD(SetUINT32,
// mInputMediaType,
// MF_MT_DEFAULT_STRIDE,
// *((UINT32*)&lstride));
//}
if (SUCCEEDED(lresult))
mCurrentLength = lLow * ::abs(lstride);
lresult = S_OK;
mOutputMediaType = aPtrType;
}
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::SetOutputType(DWORD aOutputStreamID, IMFMediaType* aPtrType,
DWORD aFlags)
{
HRESULT lresult = S_OK;
CComPtrCustom<IMFMediaType> lType;
do
{
lType = aPtrType;
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_STATE_DESCR(aOutputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
LOG_CHECK_STATE_DESCR(!mFirstSampleAccumulator.empty() || !mSecondSampleAccumulator.empty(),
MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING);
if (!(!lType) && !(!mInputMediaType))
{
DWORD flags = 0;
LOG_INVOKE_MF_METHOD(IsEqual,
lType,
mInputMediaType,
&flags);
}
if (aFlags != MFT_SET_TYPE_TEST_ONLY)
{
mOutputMediaType = lType.Detach();
}
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetInputCurrentType(DWORD aInputStreamID, IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_STATE_DESCR(aInputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
LOG_CHECK_STATE_DESCR(!mInputMediaType, MF_E_TRANSFORM_TYPE_NOT_SET);
*aPtrPtrType = mInputMediaType;
(*aPtrPtrType)->AddRef();
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetOutputCurrentType(DWORD aOutputStreamID, IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_STATE_DESCR(aOutputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
LOG_CHECK_STATE_DESCR(!mOutputMediaType, MF_E_TRANSFORM_TYPE_NOT_SET);
*aPtrPtrType = mOutputMediaType;
(*aPtrPtrType)->AddRef();
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetInputStatus(DWORD aInputStreamID, DWORD* aPtrFlags)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrFlags);
LOG_CHECK_STATE_DESCR(aInputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
*aPtrFlags = MFT_INPUT_STATUS_ACCEPT_DATA;
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::GetOutputStatus(DWORD* aPtrFlags)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::SetOutputBounds(LONGLONG aLowerBound, LONGLONG aUpperBound)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::ProcessEvent(DWORD aInputStreamID, IMFMediaEvent* aPtrEvent)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::GetAttributes(IMFAttributes** aPtrPtrAttributes)
{
return E_NOTIMPL;
}
STDMETHODIMP SampleAccumulator::ProcessMessage(MFT_MESSAGE_TYPE aMessage, ULONG_PTR aParam)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
if (aMessage == MFT_MESSAGE_COMMAND_FLUSH)
{
while (!mFirstSampleAccumulator.empty())
{
mFirstSampleAccumulator.pop();
}
while (!mSecondSampleAccumulator.empty())
{
mSecondSampleAccumulator.pop();
}
}
else if (aMessage == MFT_MESSAGE_COMMAND_DRAIN)
{
while (!mFirstSampleAccumulator.empty())
{
mFirstSampleAccumulator.pop();
}
while (!mSecondSampleAccumulator.empty())
{
mSecondSampleAccumulator.pop();
}
}
else if (aMessage == MFT_MESSAGE_NOTIFY_BEGIN_STREAMING)
{
}
else if (aMessage == MFT_MESSAGE_NOTIFY_END_STREAMING)
{
}
else if (aMessage == MFT_MESSAGE_NOTIFY_END_OF_STREAM)
{
mEndOfStream = true;
}
else if (aMessage == MFT_MESSAGE_NOTIFY_START_OF_STREAM)
{
}
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::ProcessInput(DWORD aInputStreamID, IMFSample* aPtrSample,
DWORD aFlags)
{
HRESULT lresult = S_OK;
DWORD dwBufferCount = 0;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrSample);
LOG_CHECK_STATE(aInputStreamID != 0 || aFlags != 0);
LOG_CHECK_STATE_DESCR(!mInputMediaType, MF_E_NOTACCEPTING);
LOG_CHECK_STATE_DESCR(!mOutputMediaType, MF_E_NOTACCEPTING);
CComPtrCustom<IMFSample> lUnk;
LOG_INVOKE_FUNCTION(copySample,
aPtrSample, &lUnk);
if (mPtrInputSampleAccumulator->size() >= mAccumulatorSize )
{
mPtrInputSampleAccumulator->front().Release();
mPtrInputSampleAccumulator->pop();
}
mPtrInputSampleAccumulator->push(lUnk);
lresult = S_FALSE;// MF_E_TRANSFORM_NEED_MORE_INPUT;
} while (false);
return lresult;
}
HRESULT SampleAccumulator::copySample(
IMFSample* aPtrOriginalSample,
IMFSample** aPtrPtrCopySample)
{
class MediaBufferLock
{
public:
MediaBufferLock(
IMFMediaBuffer* aPtrInputBuffer,
DWORD& aRefMaxLength,
DWORD& aRefCurrentLength,
BYTE** aPtrPtrInputBuffer,
HRESULT& aRefResult)
{
HRESULT lresult;
do
{
LOG_CHECK_PTR_MEMORY(aPtrInputBuffer);
LOG_CHECK_PTR_MEMORY(aPtrPtrInputBuffer);
LOG_INVOKE_POINTER_METHOD(aPtrInputBuffer, Lock,
aPtrPtrInputBuffer,
&aRefMaxLength,
&aRefCurrentLength);
LOG_CHECK_PTR_MEMORY(aPtrPtrInputBuffer);
mInputBuffer = aPtrInputBuffer;
} while (false);
aRefResult = lresult;
}
~MediaBufferLock()
{
if (mInputBuffer)
{
mInputBuffer->Unlock();
}
}
private:
CComPtrCustom<IMFMediaBuffer> mInputBuffer;
MediaBufferLock(
const MediaBufferLock&){}
MediaBufferLock& operator=(
const MediaBufferLock&){
return *this;
}
};
HRESULT lresult;
CComPtrCustom<IMFSample> lOutputSample;
CComPtrCustom<IMFMediaBuffer> lMediaBuffer;
CComPtrCustom<IMFMediaBuffer> lOriginalMediaBuffer;
do
{
LOG_CHECK_PTR_MEMORY(aPtrOriginalSample);
LOG_CHECK_PTR_MEMORY(aPtrPtrCopySample);
LOG_INVOKE_MF_METHOD(GetBufferByIndex, aPtrOriginalSample,
0,
&lOriginalMediaBuffer);
DWORD lCurrentLength;
LOG_INVOKE_MF_METHOD(GetCurrentLength, lOriginalMediaBuffer,
&lCurrentLength);
LOG_INVOKE_MF_FUNCTION(MFCreateSample,
&lOutputSample);
LOG_INVOKE_MF_FUNCTION(MFCreateMemoryBuffer,
lCurrentLength,
&lMediaBuffer);
LOG_INVOKE_MF_FUNCTION(SetCurrentLength, lMediaBuffer,
lCurrentLength);
LOG_INVOKE_MF_METHOD(AddBuffer,
lOutputSample,
lMediaBuffer);
LOG_INVOKE_MF_METHOD(CopyAllItems, aPtrOriginalSample,
lOutputSample);
MFTIME lTime;
LOG_INVOKE_MF_METHOD(GetSampleDuration, aPtrOriginalSample,
&lTime);
LOG_INVOKE_MF_METHOD(SetSampleDuration, lOutputSample, lTime);
LOG_INVOKE_MF_METHOD(GetSampleTime, aPtrOriginalSample, &lTime);
LOG_INVOKE_MF_METHOD(SetSampleTime, lOutputSample, lTime);
DWORD lMaxDestLength;
DWORD lCurrentDestLength;
BYTE* lPtrDestBuffer;
MediaBufferLock lMediaBufferLock(
lMediaBuffer,
lMaxDestLength,
lCurrentDestLength,
&lPtrDestBuffer,
lresult);
if (FAILED(lresult))
{
break;
}
DWORD lMaxScrLength;
DWORD lCurrentScrLength;
BYTE* lPtrScrBuffer;
MediaBufferLock lScrMediaBufferLock(
lOriginalMediaBuffer,
lMaxScrLength,
lCurrentScrLength,
&lPtrScrBuffer,
lresult);
if (FAILED(lresult))
{
break;
}
MemoryManager::memcpy(lPtrDestBuffer, lPtrScrBuffer, lCurrentLength > lCurrentScrLength ? lCurrentScrLength : lCurrentLength);
LOG_INVOKE_QUERY_INTERFACE_METHOD(lOutputSample, aPtrPtrCopySample);
} while (false);
return lresult;
}
STDMETHODIMP SampleAccumulator::ProcessOutput(DWORD aFlags, DWORD aOutputBufferCount,
MFT_OUTPUT_DATA_BUFFER* aPtrOutputSamples, DWORD* aPtrStatus)
{
HRESULT lresult = S_OK;
do
{
LOG_CHECK_PTR_MEMORY(aPtrOutputSamples);
LOG_CHECK_PTR_MEMORY(aPtrStatus);
LOG_CHECK_STATE_DESCR(aOutputBufferCount != 1 || aFlags != 0, E_INVALIDARG);
//LOG_CHECK_STATE_DESCR(!mSample, MF_E_TRANSFORM_NEED_MORE_INPUT);
CComPtrCustom<IMFSample> lOutputSample;
{
std::lock_guard<std::mutex> lock(mMutex);
if (mEndOfStream)
{
aPtrOutputSamples[0].pSample = lOutputSample.Detach();
aPtrOutputSamples[0].dwStatus = 0;
*aPtrStatus = 0;
lresult = MF_E_TRANSFORM_NEED_MORE_INPUT;
break;
}
if (mFirstSampleAccumulator.empty() && mSecondSampleAccumulator.empty())
{
CComPtrCustom<IMFMediaBuffer> lMediaBuffer;
LOG_INVOKE_MF_FUNCTION(MFCreateSample,
&lOutputSample);
LOG_INVOKE_MF_FUNCTION(MFCreateMemoryBuffer,
mCurrentLength,
&lMediaBuffer);
LOG_CHECK_PTR_MEMORY(lMediaBuffer);
LOG_INVOKE_MF_METHOD(SetCurrentLength,
lMediaBuffer,
mCurrentLength);
LOG_INVOKE_MF_METHOD(AddBuffer,
lOutputSample,
lMediaBuffer);
aPtrOutputSamples[0].pSample = lOutputSample.Detach();
aPtrOutputSamples[0].dwStatus = 0;
*aPtrStatus = 0;
break;
}
else if (mPtrOutputSampleAccumulator->empty())
{
auto ltempPtr = mPtrOutputSampleAccumulator;
mPtrOutputSampleAccumulator = mPtrInputSampleAccumulator;
mPtrInputSampleAccumulator = ltempPtr;
//CComPtrCustom<IMFMediaBuffer> lMediaBuffer;
//LOG_INVOKE_MF_FUNCTION(MFCreateSample,
// &lOutputSample);
//LOG_INVOKE_MF_FUNCTION(MFCreateMemoryBuffer,
// 1,
// &lMediaBuffer);
//LOG_INVOKE_MF_METHOD(AddBuffer,
// lOutputSample,
// lMediaBuffer);
//lMediaBuffer->SetCurrentLength(1);
//aPtrOutputSamples[0].pSample = lOutputSample.Detach();
//aPtrOutputSamples[0].dwStatus = 0;
//*aPtrStatus = 0;
//break;
}
}
aPtrOutputSamples[0].pSample = mPtrOutputSampleAccumulator->front().Detach();
mPtrOutputSampleAccumulator->pop();
aPtrOutputSamples[0].dwStatus = 0;
*aPtrStatus = 0;
} while (false);
return lresult;
}
}
}
}
| 22.443787
| 131
| 0.670393
|
luoyingwen
|
275e5f0f0c8ed2d36c61c7e308e3de6edd03bc34
| 11,634
|
cpp
|
C++
|
source/io/net/TlsServer.cpp
|
tarm-project/tarm-io
|
6aebd85573f65017decf81be073c8b13ce6ac12c
|
[
"MIT"
] | 4
|
2021-01-14T15:19:35.000Z
|
2022-01-09T09:22:18.000Z
|
source/io/net/TlsServer.cpp
|
ink-splatters/tarm-io
|
6aebd85573f65017decf81be073c8b13ce6ac12c
|
[
"MIT"
] | null | null | null |
source/io/net/TlsServer.cpp
|
ink-splatters/tarm-io
|
6aebd85573f65017decf81be073c8b13ce6ac12c
|
[
"MIT"
] | 1
|
2020-08-05T21:14:59.000Z
|
2020-08-05T21:14:59.000Z
|
/*----------------------------------------------------------------------------------------------
* Copyright (c) 2020 - present Alexander Voitenko
* Licensed under the MIT License. See License.txt in the project root for license information.
*----------------------------------------------------------------------------------------------*/
#include "net/TlsServer.h"
#include "Convert.h"
#include "net/TcpServer.h"
#include "detail/ConstexprString.h"
#include "detail/TlsContext.h"
#include "detail/OpenSslContext.h"
#include <openssl/pem.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <iostream>
#include <memory>
#include <cstdio>
namespace tarm {
namespace io {
namespace net {
class TlsServer::Impl {
public:
Impl(EventLoop& loop, const fs::Path& certificate_path, const fs::Path& private_key_path, TlsVersionRange version_range, TlsServer& parent);
~Impl();
Error listen(const Endpoint endpoint,
const NewConnectionCallback& new_connection_callback,
const DataReceivedCallback& data_receive_callback,
const CloseConnectionCallback& close_connection_callback,
int backlog_size);
void shutdown(const ShutdownServerCallback& shutdown_callback);
void close(const CloseServerCallback& close_callback);
std::size_t connected_clients_count() const;
bool certificate_and_key_match();
TlsVersionRange version_range() const;
bool schedule_removal();
protected:
const SSL_METHOD* ssl_method();
// callbacks
void on_new_connection(TcpConnectedClient& tcp_client, const Error& tcp_error);
void on_data_receive(TcpConnectedClient& tcp_client, const DataChunk&, const Error& tcp_error);
void on_connection_close(TcpConnectedClient& tcp_client, const Error& tcp_error);
private:
using X509Ptr = std::unique_ptr<::X509, decltype(&::X509_free)>;
using EvpPkeyPtr = std::unique_ptr<::EVP_PKEY, decltype(&::EVP_PKEY_free)>;
TlsServer* m_parent;
EventLoop* m_loop;
TcpServer* m_tcp_server;
fs::Path m_certificate_path;
fs::Path m_private_key_path;
X509Ptr m_certificate;
EvpPkeyPtr m_private_key;
TlsVersionRange m_version_range;
detail::OpenSslContext<TlsServer, TlsServer::Impl> m_openssl_context;
NewConnectionCallback m_new_connection_callback = nullptr;
DataReceivedCallback m_data_receive_callback = nullptr;
CloseConnectionCallback m_close_connection_callback = nullptr;
};
TlsServer::Impl::Impl(EventLoop& loop,
const fs::Path& certificate_path,
const fs::Path& private_key_path,
TlsVersionRange version_range,
TlsServer& parent) :
m_parent(&parent),
m_loop(&loop),
m_tcp_server(new TcpServer(loop)),
m_certificate_path(certificate_path),
m_private_key_path(private_key_path),
m_certificate(nullptr, ::X509_free),
m_private_key(nullptr, ::EVP_PKEY_free),
m_version_range(version_range),
m_openssl_context(loop, parent) {
}
TlsServer::Impl::~Impl() {
}
bool TlsServer::Impl::schedule_removal() {
LOG_TRACE(m_loop, m_parent, "");
if (m_parent->is_removal_scheduled()) {
LOG_TRACE(m_loop, m_parent, "is_removal_scheduled: true");
return true;
}
if (m_tcp_server->is_open()) {
m_tcp_server->close([this](TcpServer& server, const Error& error) {
if (error.code() != StatusCode::NOT_CONNECTED) {
LOG_ERROR(this->m_loop, error);
}
this->m_parent->schedule_removal();
server.schedule_removal();
});
m_parent->set_removal_scheduled();
return false;
} else {
m_tcp_server->schedule_removal();
return true;
}
}
const SSL_METHOD* TlsServer::Impl::ssl_method() {
return SSLv23_server_method(); // This call includes also TLS versions
}
TlsVersionRange TlsServer::Impl::version_range() const {
return m_version_range;
}
void TlsServer::Impl::on_new_connection(TcpConnectedClient& tcp_client, const Error& tcp_error) {
detail::TlsContext context {
m_certificate.get(),
m_private_key.get(),
m_openssl_context.ssl_ctx(),
m_version_range
};
// Can not use unique_ptr here because TlsConnectedClient has proteted destructor and
// TlsServer is a friend of TlsConnectedClient, but we can not transfer that friendhsip to unique_ptr.
auto tls_client = new TlsConnectedClient(*m_loop, *m_parent, m_new_connection_callback, tcp_client, &context);
if (tcp_error) {
if (m_new_connection_callback) {
m_new_connection_callback(*tls_client, tcp_error);
}
delete tls_client;
return;
}
Error tls_init_error = tls_client->init_ssl();
if (tls_init_error) {
if (m_new_connection_callback) {
m_new_connection_callback(*tls_client, tls_init_error);
}
tcp_client.set_user_data(nullptr); // to not process deletion in on_connection_close
tcp_client.close();
delete tls_client;
} else {
tls_client->set_data_receive_callback(m_data_receive_callback);
}
}
void TlsServer::Impl::on_data_receive(TcpConnectedClient& tcp_client, const DataChunk& chunk, const Error& tcp_error) {
auto& tls_client = *reinterpret_cast<TlsConnectedClient*>(tcp_client.user_data());
tls_client.on_data_receive(chunk.buf.get(), chunk.size, tcp_error);
}
void TlsServer::Impl::on_connection_close(TcpConnectedClient& tcp_client, const Error& tcp_error) {
LOG_TRACE(this->m_loop, "Removing TLS client");
if (tcp_client.user_data()) {
auto& tls_client = *reinterpret_cast<TlsConnectedClient*>(tcp_client.user_data());
if (m_close_connection_callback) {
m_close_connection_callback(tls_client, tcp_error);
}
delete &tls_client;
}
}
Error TlsServer::Impl::listen(const Endpoint endpoint,
const NewConnectionCallback& new_connection_callback,
const DataReceivedCallback& data_receive_callback,
const CloseConnectionCallback& close_connection_callback,
int backlog_size) {
m_new_connection_callback = new_connection_callback;
m_data_receive_callback = data_receive_callback;
m_close_connection_callback = close_connection_callback;
using FilePtr = std::unique_ptr<FILE, decltype(&std::fclose)>;
FilePtr certificate_file(std::fopen(m_certificate_path.string().c_str(), "r"), &std::fclose);
if (certificate_file == nullptr) {
return Error(StatusCode::TLS_CERTIFICATE_FILE_NOT_EXIST);
}
m_certificate.reset(PEM_read_X509(certificate_file.get(), nullptr, nullptr, nullptr));
if (m_certificate == nullptr) {
return Error(StatusCode::TLS_CERTIFICATE_INVALID);
}
FilePtr private_key_file(std::fopen(m_private_key_path.string().c_str(), "r"), &std::fclose);
if (private_key_file == nullptr) {
return Error(StatusCode::TLS_PRIVATE_KEY_FILE_NOT_EXIST);
}
m_private_key.reset(PEM_read_PrivateKey(private_key_file.get(), nullptr, nullptr, nullptr));
if (m_private_key == nullptr) {
return Error(StatusCode::TLS_PRIVATE_KEY_INVALID);
}
if (!certificate_and_key_match()) {
return Error(StatusCode::TLS_PRIVATE_KEY_AND_CERTIFICATE_NOT_MATCH);
}
const auto& context_init_error = m_openssl_context.init_ssl_context(ssl_method());
if (context_init_error) {
return context_init_error;
}
const auto& version_error = m_openssl_context.set_tls_version(std::get<0>(m_version_range), std::get<1>(m_version_range));
if (version_error) {
return version_error;
}
const auto& certificate_error = m_openssl_context.ssl_init_certificate_and_key(m_certificate.get(), m_private_key.get());
if (certificate_error) {
return certificate_error;
}
using namespace std::placeholders;
return m_tcp_server->listen(endpoint,
std::bind(&TlsServer::Impl::on_new_connection, this, _1, _2),
std::bind(&TlsServer::Impl::on_data_receive, this, _1, _2, _3),
std::bind(&TlsServer::Impl::on_connection_close, this, _1, _2));
}
void TlsServer::Impl::shutdown(const ShutdownServerCallback& shutdown_callback) {
if (shutdown_callback) {
m_tcp_server->shutdown([this, shutdown_callback](TcpServer&, const Error& error) {
shutdown_callback(*m_parent, error);
});
} else {
m_tcp_server->shutdown();
}
}
void TlsServer::Impl::close(const CloseServerCallback& close_callback) {
if (close_callback) {
m_tcp_server->shutdown([this, close_callback](TcpServer&, const Error& error) {
close_callback(*m_parent, error);
});
} else {
m_tcp_server->close();
}
}
std::size_t TlsServer::Impl::connected_clients_count() const {
return m_tcp_server->connected_clients_count();
}
namespace {
//int ssl_key_type(::EVP_PKEY* pkey) {
// assert(pkey);
// return pkey ? EVP_PKEY_type(pkey->type) : NID_undef;
//}
} // namespace
bool TlsServer::Impl::certificate_and_key_match() {
assert(m_certificate);
assert(m_private_key);
return X509_verify(m_certificate.get(), m_private_key.get()) != 0;
}
///////////////////////////////////////// implementation ///////////////////////////////////////////
TlsServer::TlsServer(EventLoop& loop, const fs::Path& certificate_path, const fs::Path& private_key_path, TlsVersionRange version_range) :
Removable(loop),
m_impl(new Impl(loop, certificate_path, private_key_path, version_range, *this)) {
}
TlsServer::~TlsServer() {
}
Error TlsServer::listen(const Endpoint endpoint,
const NewConnectionCallback& new_connection_callback,
const DataReceivedCallback& data_receive_callback,
const CloseConnectionCallback& close_connection_callback,
int backlog_size) {
return m_impl->listen(endpoint, new_connection_callback, data_receive_callback, close_connection_callback, backlog_size);
}
Error TlsServer::listen(const Endpoint endpoint,
const DataReceivedCallback& data_receive_callback,
int backlog_size) {
return m_impl->listen(endpoint, nullptr, data_receive_callback, nullptr, backlog_size);
}
Error TlsServer::listen(const Endpoint endpoint,
const NewConnectionCallback& new_connection_callback,
const DataReceivedCallback& data_receive_callback,
int backlog_size) {
return m_impl->listen(endpoint, new_connection_callback, data_receive_callback, nullptr, backlog_size);
}
void TlsServer::shutdown(const CloseServerCallback& shutdown_callback) {
return m_impl->shutdown(shutdown_callback);
}
void TlsServer::close(const CloseServerCallback& close_callback) {
return m_impl->close(close_callback);
}
std::size_t TlsServer::connected_clients_count() const {
return m_impl->connected_clients_count();
}
TlsVersionRange TlsServer::version_range() const {
return m_impl->version_range();
}
void TlsServer::schedule_removal() {
const bool ready_to_remove = m_impl->schedule_removal();
if (ready_to_remove) {
Removable::schedule_removal();
}
}
} // namespace net
} // namespace io
} // namespace tarm
| 34.318584
| 144
| 0.670191
|
tarm-project
|
2763e7da0af34195ab15cee538b3c4b789795527
| 1,840
|
cpp
|
C++
|
docs/melb-cpp-talk-feb-2017/24a-cpp17-auto-template-parameter.cpp
|
RossBencina/StaticMode
|
04eead233a6a03aa4f47c22f81c1d89b4e5cf5ca
|
[
"MIT"
] | 3
|
2017-02-15T22:49:40.000Z
|
2018-04-19T15:42:57.000Z
|
docs/melb-cpp-talk-feb-2017/24a-cpp17-auto-template-parameter.cpp
|
RossBencina/StaticMode
|
04eead233a6a03aa4f47c22f81c1d89b4e5cf5ca
|
[
"MIT"
] | 14
|
2017-02-19T14:25:30.000Z
|
2017-02-20T10:11:42.000Z
|
docs/melb-cpp-talk-feb-2017/24a-cpp17-auto-template-parameter.cpp
|
RossBencina/StaticMode
|
04eead233a6a03aa4f47c22f81c1d89b4e5cf5ca
|
[
"MIT"
] | null | null | null |
//!clang++ -std=c++1z -Weverything -Wno-c++98-compat 24a-cpp17-auto-template-parameter.cpp -o z24a.out && ./z24a.out
// WARNING: bleeding edge. tested in gcc 7, possibly clang 4
// This file is optional. It's a side note about C++17 auto template parameters.
// It requires clang 4 or GCC 7 to compile.
// When C++17 arrives, "auto template parameter" syntax will allow us to
// simplify the declaration of Mode instances as follows:
// C++11:
// template<typename T, T X>
// struct Mode : ModeType<T> { ... };
//
// constexpr Mode<LineStyle, LineStyle::dotted> dotted; // <-- notice that LineStyle appears twice
// C++17: (this file)
// template<auto X> // C++17: auto template parameter
// struct Mode { ... };
//
// constexpr Mode<LineStyle::dotted> dotted; // <-- simplified
//
// http://en.cppreference.com/w/cpp/language/auto
#include <iostream> // cout
// ............................................................................
// Library code
template<typename T>
struct ModeType {}; // aka mode category
template<auto X> // C++17: auto template parameter
struct Mode : ModeType<decltype(X)> {
constexpr Mode() {}
};
// ............................................................................
enum class LineStyle { dotted, dashed, solid };
constexpr Mode<LineStyle::dotted> dotted; // note simplified syntax
constexpr Mode<LineStyle::dashed> dashed;
constexpr Mode<LineStyle::solid> solid;
class AsciiPainter {
public:
void drawLine(decltype(dotted)) {
std::cout << "..........\n";
}
void drawLine(decltype(dashed)) {
std::cout << "----------\n";
}
void drawLine(decltype(solid)) {
std::cout << "__________\n";
}
};
int main()
{
AsciiPainter painter;
painter.drawLine(dotted);
painter.drawLine(dashed);
painter.drawLine(solid);
}
| 27.462687
| 116
| 0.59837
|
RossBencina
|
27645cc5b63715c2686976d8c80b04e1667d197e
| 330
|
cpp
|
C++
|
Black Horse C++/ex0027_encapsulation/main.cpp
|
Dragontalker/CPP-study-notes
|
d9ebd183d414d2de247ef37c03a24504dd3053d5
|
[
"MIT"
] | null | null | null |
Black Horse C++/ex0027_encapsulation/main.cpp
|
Dragontalker/CPP-study-notes
|
d9ebd183d414d2de247ef37c03a24504dd3053d5
|
[
"MIT"
] | null | null | null |
Black Horse C++/ex0027_encapsulation/main.cpp
|
Dragontalker/CPP-study-notes
|
d9ebd183d414d2de247ef37c03a24504dd3053d5
|
[
"MIT"
] | null | null | null |
#include <iostream>
class Circle
{
private:
const double PI = 3.1415926;
public:
double m_r;
double calculateZC()
{
return 2 * PI * m_r;
}
};
int main()
{
Circle c1;
c1.m_r = 10;
std::cout << "The raius of our circle = "
<< c1.calculateZC() << std::endl;
return 0;
}
| 12.692308
| 47
| 0.524242
|
Dragontalker
|
2764a0b63daefb8e607a670a6a3612e9adc2079a
| 2,885
|
cpp
|
C++
|
test/test_main.cpp
|
ChrizZhuang/3D_particle_simulator
|
cc2a0c75dc67ec7e4f89a270bca736d9425dbec0
|
[
"MIT"
] | null | null | null |
test/test_main.cpp
|
ChrizZhuang/3D_particle_simulator
|
cc2a0c75dc67ec7e4f89a270bca736d9425dbec0
|
[
"MIT"
] | null | null | null |
test/test_main.cpp
|
ChrizZhuang/3D_particle_simulator
|
cc2a0c75dc67ec7e4f89a270bca736d9425dbec0
|
[
"MIT"
] | null | null | null |
// File to test main functions
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <string>
#include "Vector3D.hpp"
#include "SimpleParticleList.hpp"
#include "Spring1DForce.hpp"
#include "LatticeParticleList.hpp"
#include "LatticeParticleForce.hpp"
#include "GravityForce.hpp"
#include "FrictionForce.hpp"
#include "verlet_integrator.hpp"
#include "test_main.hpp"
void test_func()
{
struct Args
{
int N = 64; // -n <N> (int), number of interior particles
int Nstep = 1e4; // -nstep <Nstep> (int), number of time steps
std::string test; // -test <test> (string), the type of test
double L = 2; // -l <L> (double), length of the cubic simulation box
double t_end = 2; // -time (double), end of simulation time.
};
Args args;
args.test = "equil";
// args.test = "shift";
// args.test = "moving";
/*
* Struct to hold constants needed for the particle calculation
* NOTE: we declare it here "static const" to avoid updating values
*/
struct ParticleConst
{
double gamma = 5;
double c=0.5; // spring constant N/m
double mass = 0.1; // mass per particle, kg
};
static const ParticleConst pc;
// Defensive programming: check that the input N is an integer to the third power
int index = 0; // initiate a index to mark when the input N is not an integer to the third power
for (int i=0; i<=args.N; i++)
{
if (args.N == pow(i, 3))
{
index = 1; // change the index if the input N is an integer to the third power
}
}
if (index == 0)
{
std::cout << "error: The input N is not an integer to the third power!" << std::endl; // print out message to indicate the possible mistakes
}
assert(index == 1);
// Convert the mass value to a vector
std::vector<double> mass_vec;
mass_vec.assign(args.N, pc.mass);
// Instantiate the LatticeParticleList
LatticeParticleList lpl(args.N, mass_vec);
// Instantiate verlet_integrator
verlet_integrator vi(args.N, args.Nstep, args.test, args.L, args.t_end, pc.gamma, pc.c, pc.mass, lpl);
// Initialize the particle positions, velocities and accelerations regarding the condition
vi.init_particles(lpl);
// Test init
test_main tm(args.N, args.Nstep, args.test, args.L, args.t_end, pc.gamma, pc.c, pc.mass);
tm.test_init(lpl);
// Instantiate some objects
double equil_distance = args.L/(std::cbrt(args.N)-1);
LatticeParticleForce lpf(args.N, pc.c, equil_distance);
double drag = 0.1;
FrictionForce ff(args.N, drag);
double g[3] = {0, 0, -9.8}; // gravity in z direction
GravityForce gf(args.N, g);
// Calculate the particle final position, velocity and acceleration
vi.do_time_integration(lpl, lpf, ff, gf);
// Test integration
tm.test_results(lpl);
std::cout << ".. Main tests passed!" << std::endl;
}
| 29.141414
| 144
| 0.67383
|
ChrizZhuang
|
276533790d14865853af0f89f47ee160125a3ee4
| 169
|
cpp
|
C++
|
Code full house/buoi20 nguyen dinh trung duc/implement/bai 16 1352A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
Code full house/buoi20 nguyen dinh trung duc/implement/bai 16 1352A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
Code full house/buoi20 nguyen dinh trung duc/implement/bai 16 1352A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
/*bai 16 1325A*/
#include<stdio.h>
int main(){
int T;
scanf("%d",&T);
while (T--)
{
int x;
scanf("%d",&x);
printf("1 %d\n",x-1);
}
}
| 12.071429
| 26
| 0.408284
|
ducyb2001
|
27657d88fd215d96f5e3585a5224aaf294f12e25
| 15,198
|
cc
|
C++
|
agent/src/agent_win.cc
|
chromium/content_analysis_sdk
|
1a6e24f9ced8a4cf180ee7eafbc5fa0beb1046eb
|
[
"BSD-3-Clause"
] | null | null | null |
agent/src/agent_win.cc
|
chromium/content_analysis_sdk
|
1a6e24f9ced8a4cf180ee7eafbc5fa0beb1046eb
|
[
"BSD-3-Clause"
] | 1
|
2022-03-30T21:06:11.000Z
|
2022-03-30T21:06:11.000Z
|
agent/src/agent_win.cc
|
chromium/content_analysis_sdk
|
1a6e24f9ced8a4cf180ee7eafbc5fa0beb1046eb
|
[
"BSD-3-Clause"
] | 1
|
2022-03-14T23:15:39.000Z
|
2022-03-14T23:15:39.000Z
|
// Copyright 2022 The Chromium Authors.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <ios>
#include <utility>
#include <vector>
#include <windows.h>
#include <sddl.h>
#include "common/utils_win.h"
#include "agent_utils_win.h"
#include "agent_win.h"
#include "event_win.h"
namespace content_analysis {
namespace sdk {
// The minimum number of pipe in listening mode. This is greater than one to
// handle the case of multiple instance of Google Chrome browser starting
// at the same time.
const DWORD kMinNumListeningPipeInstances = 2;
// The minimum number of handles to wait on. This is the minimum number
// of pipes in listening mode plus the stop event.
const DWORD kMinNumWaitHandles = kMinNumListeningPipeInstances + 1;
// static
std::unique_ptr<Agent> Agent::Create(
Config config,
std::unique_ptr<AgentEventHandler> handler,
ResultCode* rc) {
auto agent = std::make_unique<AgentWin>(std::move(config), std::move(handler), rc);
return *rc == ResultCode::OK ? std::move(agent) : nullptr;
}
AgentWin::Connection::Connection(const std::string& pipename,
AgentEventHandler* handler,
bool is_first_pipe,
ResultCode* rc)
: handler_(handler) {
*rc = ResultCode::OK;
memset(&overlapped_, 0, sizeof(overlapped_));
// Create a manual reset event as specified for overlapped IO.
// Use default security attriutes and no name since this event is not
// shared with other processes.
overlapped_.hEvent = CreateEvent(/*securityAttr=*/nullptr,
/*manualReset=*/TRUE,
/*initialState=*/FALSE,
/*name=*/nullptr);
if (!overlapped_.hEvent) {
*rc = ResultCode::ERR_CANNOT_CREATE_CHANNEL_IO_EVENT;
return;
}
*rc = ResetInternal(pipename, is_first_pipe);
}
AgentWin::Connection::~Connection() {
Cleanup();
if (handle_ != INVALID_HANDLE_VALUE) {
CloseHandle(handle_);
}
// Invalid event handles are represented as null.
if (overlapped_.hEvent) {
CloseHandle(overlapped_.hEvent);
}
}
ResultCode AgentWin::Connection::Reset(const std::string& pipename) {
return ResetInternal(pipename, false);
}
ResultCode AgentWin::Connection::HandleEvent(HANDLE handle) {
auto rc = ResultCode::OK;
DWORD count;
BOOL success = GetOverlappedResult(handle, &overlapped_, &count,
/*wait=*/FALSE);
if (!is_connected_) {
// This connection is currently listing for a new connection from a Google
// Chrome browser. If the result is a success, this means the browser has
// connected as expected. Otherwise an error occured so report it to the
// caller.
if (success) {
// A Google Chrome browser connected to the agent. Reset this
// connection object to handle communication with the browser and then
// tell the handler about it.
is_connected_ = true;
buffer_.resize(internal::kBufferSize);
rc = BuildBrowserInfo();
if (rc == ResultCode::OK) {
handler_->OnBrowserConnected(browser_info_);
}
} else {
rc = ErrorToResultCode(GetLastError());
}
} else {
// Some data has arrived from Google Chrome. This data is (part of) an
// instance of the proto message `ChromeToAgent`.
//
// If the message is small it is received in by one call to ReadFile().
// If the message is larger it is received in by multiple calls to
// ReadFile().
//
// `success` is true if the data just read is the last bytes for a message.
// Otherwise it is false.
rc = OnReadFile(success, count);
}
// If all data has been read, queue another read.
if (rc == ResultCode::OK || rc == ResultCode::ERR_MORE_DATA) {
rc = QueueReadFile(rc == ResultCode::OK);
}
if (rc != ResultCode::OK && rc != ResultCode::ERR_IO_PENDING &&
rc != ResultCode::ERR_MORE_DATA) {
Cleanup();
} else {
// Don't propagate all the "success" error codes to the called to keep
// this simpler.
rc = ResultCode::OK;
}
return rc;
}
void AgentWin::Connection::AppendDebugString(std::stringstream& state) const {
state << "{handle=" << handle_;
state << " connected=" << is_connected_;
state << " pid=" << browser_info_.pid;
state << " rsize=" << read_size_;
state << " fsize=" << final_size_;
state << "}";
}
ResultCode AgentWin::Connection::ConnectPipe() {
// In overlapped mode, connecting to a named pipe always returns false.
if (ConnectNamedPipe(handle_, &overlapped_)) {
return ErrorToResultCode(GetLastError());
}
DWORD err = GetLastError();
if (err == ERROR_IO_PENDING) {
// Waiting for a Google Chrome Browser to connect.
return ResultCode::OK;
} else if (err == ERROR_PIPE_CONNECTED) {
// A Google Chrome browser is already connected. Make sure event is in
// signaled state in order to process the connection.
if (SetEvent(overlapped_.hEvent)) {
err = ERROR_SUCCESS;
} else {
err = GetLastError();
}
}
return ErrorToResultCode(err);
}
ResultCode AgentWin::Connection::ResetInternal(const std::string& pipename,
bool is_first_pipe) {
auto rc = ResultCode::OK;
// If this is the not the first time, disconnect from any existing Google
// Chrome browser. Otherwise creater a new pipe.
if (handle_ != INVALID_HANDLE_VALUE) {
if (!DisconnectNamedPipe(handle_)) {
rc = ErrorToResultCode(GetLastError());
}
} else {
rc = ErrorToResultCode(
internal::CreatePipe(pipename, is_first_pipe, &handle_));
}
// Make sure event starts in reset state.
if (rc == ResultCode::OK && !ResetEvent(overlapped_.hEvent)) {
rc = ErrorToResultCode(GetLastError());
}
if (rc == ResultCode::OK) {
rc = ConnectPipe();
}
if (rc != ResultCode::OK) {
Cleanup();
handle_ = INVALID_HANDLE_VALUE;
}
return rc;
}
void AgentWin::Connection::Cleanup() {
if (is_connected_ && handler_) {
handler_->OnBrowserDisconnected(browser_info_);
}
is_connected_ = false;
browser_info_ = BrowserInfo();
buffer_.clear();
cursor_ = nullptr;
read_size_ = 0;
final_size_ = 0;
if (handle_ != INVALID_HANDLE_VALUE) {
// Cancel all outstanding IO requests on this pipe by using a null for
// overlapped.
CancelIoEx(handle_, /*overlapped=*/nullptr);
}
// This function does not close `handle_` or the event in `overlapped` so
// that the server can resuse the pipe with an new Google Chrome browser
// instance.
}
ResultCode AgentWin::Connection::QueueReadFile(bool reset_cursor) {
if (reset_cursor) {
cursor_ = buffer_.data();
read_size_ = buffer_.size();
final_size_ = 0;
}
// When this function is called there are the following possiblities:
//
// 1/ Data is already available and the buffer is filled in. ReadFile()
// return TRUE and the event is set.
// 2/ Data is not avaiable yet. ReadFile() returns FALSE and the last error
// is ERROR_IO_PENDING(997) and the event is reset.
// 3/ Some error occurred, like for example Google Chrome stops. ReadFile()
// returns FALSE and the last error is something other than
// ERROR_IO_PENDING, for example ERROR_BROKEN_PIPE(109). The event
// state is unchanged.
auto rc = ResultCode::OK;
DWORD count;
if (!ReadFile(handle_, cursor_, read_size_, &count, &overlapped_)) {
rc = ErrorToResultCode(GetLastError());
}
return rc;
}
ResultCode AgentWin::Connection::OnReadFile(BOOL done_reading, DWORD count) {
final_size_ += count;
// If `done_reading` is TRUE, this means the full message has been read.
// Call the appropriate handler method.
if (done_reading) {
return CallHandler();
}
// If success os false, there are two possibilities:
//
// 1/ The last error is ERROR_MORE_DATA(234). This means there are more
// bytes to read before the request message is complete. Resize the
// buffer and adjust the cursor. The caller will queue up another read
// and wait.
// 2/ Some error occured. In this case return the error.
DWORD err = GetLastError();
if (err == ERROR_MORE_DATA) {
read_size_ = internal::kBufferSize;
buffer_.resize(buffer_.size() + read_size_);
cursor_ = buffer_.data() + buffer_.size() - read_size_;
}
return ErrorToResultCode(err);
}
ResultCode AgentWin::Connection::CallHandler() {
ChromeToAgent message;
if (!message.ParseFromArray(buffer_.data(), final_size_)) {
// Malformed message.
return ResultCode::ERR_INVALID_REQUEST_FROM_BROWSER;
}
auto rc = ResultCode::OK;
if (message.has_request()) {
// This is a request from Google Chrome to perform a content analysis
// request.
//
// Move the request from `message` to the event to reduce the amount
// of memory allocation/copying and also because the the handler takes
// ownership of the event.
auto event = std::make_unique<ContentAnalysisEventWin>(
handle_, browser_info_, std::move(*message.mutable_request()));
rc = event->Init();
if (rc == ResultCode::OK) {
handler_->OnAnalysisRequested(std::move(event));
} else {
// Malformed message.
rc = ResultCode::ERR_INVALID_REQUEST_FROM_BROWSER;
}
} else if (message.has_ack()) {
// This is an ack from Google Chrome that it has received a content
// analysis response from the agent.
handler_->OnResponseAcknowledged(message.ack());
} else {
// Malformed message.
rc = ResultCode::ERR_INVALID_REQUEST_FROM_BROWSER;
}
return rc;
}
ResultCode AgentWin::Connection::BuildBrowserInfo() {
if (!GetNamedPipeClientProcessId(handle_, &browser_info_.pid)) {
return ResultCode::ERR_CANNOT_GET_BROWSER_PID;
}
HANDLE hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
browser_info_.pid);
if (hProc == nullptr) {
return ResultCode::ERR_CANNOT_OPEN_BROWSER_PROCESS;
}
auto rc = ResultCode::OK;
char path[MAX_PATH];
DWORD size = sizeof(path);
DWORD length = QueryFullProcessImageNameA(hProc, /*flags=*/0, path, &size);
if (length == 0) {
rc = ResultCode::ERR_CANNOT_GET_BROWSER_BINARY_PATH;
}
CloseHandle(hProc);
browser_info_.binary_path = path;
return rc;
}
AgentWin::AgentWin(
Config config,
std::unique_ptr<AgentEventHandler> event_handler,
ResultCode* rc)
: AgentBase(std::move(config), std::move(event_handler)) {
*rc = ResultCode::OK;
if (handler() == nullptr) {
*rc = ResultCode::ERR_AGENT_EVENT_HANDLER_NOT_SPECIFIED;
return;
}
stop_event_ = CreateEvent(/*securityAttr=*/nullptr,
/*manualReset=*/TRUE,
/*initialState=*/FALSE,
/*name=*/nullptr);
if (stop_event_ == nullptr) {
*rc = ResultCode::ERR_CANNOT_CREATE_AGENT_STOP_EVENT;
return;
}
std::string pipename =
internal::GetPipeName(configuration().name,
configuration().user_specific);
if (pipename.empty()) {
*rc = ResultCode::ERR_INVALID_CHANNEL_NAME;
return;
}
pipename_ = pipename;
connections_.reserve(kMinNumListeningPipeInstances);
for (int i = 0; i < kMinNumListeningPipeInstances; ++i) {
connections_.emplace_back(
std::make_unique<Connection>(pipename_, handler(), i == 0, rc));
if (*rc != ResultCode::OK || !connections_.back()->IsValid()) {
Shutdown();
break;
}
}
}
AgentWin::~AgentWin() {
Shutdown();
}
ResultCode AgentWin::HandleEvents() {
std::vector<HANDLE> wait_handles;
auto rc = ResultCode::OK;
bool stopped = false;
while (!stopped && rc == ResultCode::OK) {
rc = HandleOneEvent(wait_handles, &stopped);
}
return rc;
}
ResultCode AgentWin::Stop() {
SetEvent(stop_event_);
return AgentBase::Stop();
}
std::string AgentWin::DebugString() const {
std::stringstream state;
state.setf(std::ios::boolalpha);
state << "AgentWin{pipe=\"" << pipename_;
state << "\" stop=" << stop_event_;
for (size_t i = 0; i < connections_.size(); ++i) {
state << " conn@" << i;
connections_[i]->AppendDebugString(state);
}
state << "}" << std::ends;
return state.str();
}
void AgentWin::GetHandles(std::vector<HANDLE>& wait_handles) const {
// Reserve enough space in the handles vector to include the stop event plus
// all connections.
wait_handles.clear();
wait_handles.reserve(1 + connections_.size());
for (auto& state : connections_) {
HANDLE wait_handle = state->GetWaitHandle();
if (!wait_handle) {
wait_handles.clear();
break;
}
wait_handles.push_back(wait_handle);
}
// Push the stop event last so that connections_ index calculations in
// HandleOneEvent() don't have to account for this handle.
wait_handles.push_back(stop_event_);
}
ResultCode AgentWin::HandleOneEventForTesting() {
std::vector<HANDLE> wait_handles;
bool stopped;
return HandleOneEvent(wait_handles, &stopped);
}
bool AgentWin::IsAClientConnectedForTesting() {
for (const auto& state : connections_) {
if (state->IsConnected()) {
return true;
}
}
return false;
}
ResultCode AgentWin::HandleOneEvent(std::vector<HANDLE>& wait_handles, bool* stopped) {
*stopped = false;
// Wait on the specified handles for an event to occur.
GetHandles(wait_handles);
if (wait_handles.size() < kMinNumWaitHandles) {
return ResultCode::ERR_AGENT_NOT_INITIALIZED;
}
DWORD index = WaitForMultipleObjects(
wait_handles.size(), wait_handles.data(),
/*waitAll=*/FALSE, /*timeoutMs=*/INFINITE);
if (index == WAIT_FAILED) {
return ErrorToResultCode(GetLastError());
}
// If the index of signaled handle is the last one in wait_handles, then the
// stop event was signaled.
index -= WAIT_OBJECT_0;
if (index == wait_handles.size() - 1) {
*stopped = true;
return ResultCode::OK;
}
auto& connection = connections_[index];
bool was_listening = !connection->IsConnected();
auto rc = connection->HandleEvent(wait_handles[index]);
if (rc != ResultCode::OK) {
// If `connection` was not listening and there are more than
// kNumPipeInstances pipes, delete this connection. Otherwise
// reset it so that it becomes a listener.
if (!was_listening &&
connections_.size() > kMinNumListeningPipeInstances) {
connections_.erase(connections_.begin() + index);
} else {
rc = connection->Reset(pipename_);
}
}
// If `connection` was listening and is now connected, create a new
// one so that there are always kNumPipeInstances listening.
if (rc == ResultCode::OK && was_listening && connection->IsConnected()) {
connections_.emplace_back(
std::make_unique<Connection>(pipename_, handler(), false, &rc));
}
return ResultCode::OK;
}
void AgentWin::Shutdown() {
connections_.clear();
pipename_.clear();
if (stop_event_ != nullptr) {
CloseHandle(stop_event_);
stop_event_ = nullptr;
}
}
} // namespace sdk
} // namespace content_analysis
| 30.035573
| 87
| 0.665745
|
chromium
|
2776b138321d36f835b798181a8f27dbae2206f0
| 1,119
|
cpp
|
C++
|
tools/disktool/src/AssistantPage.cpp
|
DarkMaguz/CodingPiratesOS
|
7750224b87646ad376664bd1f826aae5112ea41c
|
[
"MIT"
] | 1
|
2020-03-09T14:14:02.000Z
|
2020-03-09T14:14:02.000Z
|
tools/disktool/src/AssistantPage.cpp
|
DarkMaguz/CodingPiratesOS
|
7750224b87646ad376664bd1f826aae5112ea41c
|
[
"MIT"
] | null | null | null |
tools/disktool/src/AssistantPage.cpp
|
DarkMaguz/CodingPiratesOS
|
7750224b87646ad376664bd1f826aae5112ea41c
|
[
"MIT"
] | 2
|
2020-03-11T21:29:20.000Z
|
2020-07-06T20:20:18.000Z
|
/*
* AssistantPage.cpp
*
* Created on: Mar 20, 2022
* Author: magnus
*/
#include "AssistantPage.h"
#include <iostream>
AssistantPage::AssistantPage(const Glib::ustring &resourcePath) :
m_assistantPage(nullptr),
m_refBuilder(Gtk::Builder::create())
{
try
{
m_refBuilder->add_from_resource(resourcePath);
}
catch(const Gio::ResourceError& ex)
{
std::cerr << "ResourceError: " << ex.what() << std::endl;
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
}
catch(const Glib::MarkupError& ex)
{
std::cerr << "MarkupError: " << ex.what() << std::endl;
}
catch(const Gtk::BuilderError& ex)
{
std::cerr << "BuilderError: " << ex.what() << std::endl;
}
}
AssistantPage::~AssistantPage()
{
for (auto garbage : m_gc)
if (garbage)
delete garbage;
}
Gtk::Box *AssistantPage::GetPage(void)
{
return m_assistantPage;
}
AssistantPage::type_signalPageComplete AssistantPage::SignalPageComplete(void)
{
return m_signalPageComplete;
}
void AssistantPage::EvaluatePageCompleteness(void)
{
m_signalPageComplete.emit(true);
}
| 18.966102
| 78
| 0.669348
|
DarkMaguz
|
2776b3077b548c5674269fbc460f15f64720a1c2
| 16,734
|
cpp
|
C++
|
src/parse_symbol_set.cpp
|
DavideConficconi/hscompile
|
819e35c50ffb2a767cbf4634bc05cd2c9e4d21a7
|
[
"BSD-3-Clause"
] | 4
|
2017-06-22T19:30:05.000Z
|
2021-11-17T07:45:24.000Z
|
src/parse_symbol_set.cpp
|
DavideConficconi/hscompile
|
819e35c50ffb2a767cbf4634bc05cd2c9e4d21a7
|
[
"BSD-3-Clause"
] | 2
|
2018-03-19T15:29:22.000Z
|
2021-03-14T13:16:59.000Z
|
src/parse_symbol_set.cpp
|
DavideConficconi/hscompile
|
819e35c50ffb2a767cbf4634bc05cd2c9e4d21a7
|
[
"BSD-3-Clause"
] | 4
|
2018-03-13T17:23:12.000Z
|
2021-04-18T16:17:18.000Z
|
/*
* Copyright (c) 2016, University of Virginia
* All rights reserved.
*
* 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 the University of Virginia 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 UNIVERSITY OF VIRGINIA 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.
*
* This software was originally developed by Jack Wadden (jackwadden@gmail.com).
* A list of all contributors is maintained at https://github.com/jackwadden/VASim.
*
* If you use VASim in your project, please use the following citation:
* Wadden, J. and Skadron, K. "VASim: An Open Source Simulation and Analysis
* Platform for Finite Automata Applications and Architecture Research." GitHub
* repository, https://github.com/jackwadden/VASim. University of Virginia, 2016.
*/
/*
* Modified by Kevin Angstadt <angstadt@virginia.edu> for use with HyperScan
*/
#include "parse_symbol_set.h"
#include <string>
#include <iostream>
namespace ue2 {
void parseSymbolSet(CharReach &column, std::string symbol_set) {
if(symbol_set.compare("*") == 0){
column.setall();
return;
}
// KAA found that apcompile parses symbol-set="." to mean "^\x0a"
// hard-coding this here
if(symbol_set.compare(".") == 0) {
column.set('\n');
column.flip();
return;
}
bool in_charset = false;
bool escaped = false;
bool inverting = false;
bool range_set = false;
int bracket_sem = 0;
int brace_sem = 0;
const unsigned int value = 1;
unsigned char last_char = 0;
unsigned char range_start = 0;
// handle symbol sets that start and end with curly braces {###}
if((symbol_set[0] == '{') &&
(symbol_set[symbol_set.size() - 1] == '}')){
std::cout << "CURLY BRACES NOT IMPLEMENTED" << std::endl;
exit(1);
}
int index = 0;
while(index < symbol_set.size()) {
unsigned char c = symbol_set[index];
//std::cout << "PROCESSING CHAR: " << c << std::endl;
switch(c){
// Brackets
case '[' :
if(escaped){
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
escaped = false;
}else{
bracket_sem++;
}
break;
case ']' :
if(escaped){
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
escaped = false;
last_char = c;
}else{
bracket_sem--;
}
break;
// Braces
case '{' :
//if(escaped){
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
//escaped = false;
//}else{
//brace_sem++;
//}
break;
case '}' :
//if(escaped){
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
//escaped = false;
//}else{
//brace_sem--;
//}
break;
//escape
case '\\' :
if(escaped){
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
escaped = false;
}else{
escaped = true;
}
break;
// escaped chars
case 'n' :
if(escaped){
column.set('\n');
if(range_set){
column.setRange(range_start,'\n');
range_set = false;
}
last_char = '\n';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'r' :
if(escaped){
column.set('\r');
if(range_set){
column.setRange(range_start,'\r');
range_set = false;
}
last_char = '\r';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 't' :
if(escaped){
column.set('\t');
if(range_set){
column.setRange(range_start,'\t');
range_set = false;
}
last_char = '\t';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'a' :
if(escaped){
column.set('\a');
if(range_set){
column.setRange(range_start,'\a');
range_set = false;
}
last_char = '\a';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'b' :
if(escaped){
column.set('\b');
if(range_set){
column.setRange(range_start,'\b');
range_set = false;
}
last_char = '\b';
escaped = false;
}else{
column.set(c);
if(range_set){
//std::cout << "RANGE SET" << std::endl;
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'f' :
if(escaped){
column.set('\f');
if(range_set){
column.setRange(range_start,'\f');
range_set = false;
}
last_char = '\f';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'v' :
if(escaped){
column.set('\v');
if(range_set){
column.setRange(range_start,'\v');
range_set = false;
}
last_char = '\v';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case '\'' :
if(escaped){
column.set('\'');
if(range_set){
column.setRange(range_start,'\'');
range_set = false;
}
last_char = '\'';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case '\"' :
if(escaped){
column.set('\"');
if(range_set){
column.setRange(range_start,'\"');
range_set = false;
}
last_char = '\"';
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
/*
case '?' :
if(escaped){
column.set('?',value);
last_char = '?';
escaped = false;
}else{
column.set(c, value);
last_char = c;
}
break;
*/
// Range
case '-' :
if(escaped){
column.set('-');
if(range_set){
column.setRange(range_start,'-');
range_set = false;
}
last_char = '-';
escaped = false;
}else{
range_set = true;
range_start = last_char;
}
break;
// Special Classes
case 's' :
if(escaped){
column.set('\n');
column.set('\t');
column.set('\r');
column.set('\x0B'); //vertical tab
column.set('\x0C');
column.set('\x20');
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'd' :
if(escaped){
column.setRange(48,57);
//setRange(column,48,57, value);
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
case 'w' :
if(escaped){
column.set('_'); // '_'
column.setRange(48,57);
//setRange(column,48,57, value); // d
column.setRange(65,90);
//setRange(column,65,90, value); // A-Z
column.setRange(97,122);
// setRange(column,97,122, value); // a-z
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
// Inversion
case '^' :
if(escaped){
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
escaped = false;
}else{
inverting = true;
}
break;
// HEX
case 'x' :
if(escaped){
//process hex char
++index;
char hex[3];
hex[0] = (char)symbol_set.c_str()[index];
hex[1] = (char)symbol_set.c_str()[index+1];
hex[2] = '\0';
unsigned char number = (unsigned char)std::strtoul(hex, NULL, 16);
//
++index;
column.set(number);
if(range_set){
column.setRange(range_start,number);
range_set = false;
}
last_char = number;
escaped = false;
}else{
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
}
break;
// Other characters
default:
if(escaped){
// we escaped a char that is not valid so treat it normaly
escaped = false;
}
column.set(c);
if(range_set){
column.setRange(range_start,c);
range_set = false;
}
last_char = c;
};
index++;
} // char while loop
if(inverting)
column.flip();
if(bracket_sem != 0 ||
brace_sem != 0){
std::cout << "MALFORMED BRACKETS OR BRACES: " << symbol_set << std::endl;
std::cout << "brackets: " << bracket_sem << std::endl;
exit(1);
}
/*
std::cout << "***" << std::endl;
for(int i = 0; i < 256; i++){
if(column.test(i))
std::cout << i << " : 1" << std::endl;
else
std::cout << i << " : 0" << std::endl;
}
std::cout << "***" << std::endl;
*/
}
};
| 33.806061
| 86
| 0.369906
|
DavideConficconi
|
2777883fc452b8b0d7f2cfb50caebc5a9ae8dcaa
| 539
|
cpp
|
C++
|
leetcode/88/main.cpp
|
yukienomiya/competitive-programming
|
6f5e502ba66da2f62fb37aaa786a841f64bb192a
|
[
"MIT"
] | null | null | null |
leetcode/88/main.cpp
|
yukienomiya/competitive-programming
|
6f5e502ba66da2f62fb37aaa786a841f64bb192a
|
[
"MIT"
] | null | null | null |
leetcode/88/main.cpp
|
yukienomiya/competitive-programming
|
6f5e502ba66da2f62fb37aaa786a841f64bb192a
|
[
"MIT"
] | null | null | null |
#include <vector>
using namespace std;
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> nums3(m + n, 0);
int idx1 = 0, idx2 = 0, idx3 = 0;
while (idx1 < m && idx2 < n) {
if (nums1[idx1] <= nums2[idx2]) nums3[idx3++] = nums1[idx1++];
else nums3[idx3++] = nums2[idx2++];
}
while (idx1 < m) nums3[idx3++] = nums1[idx1++];
while (idx2 < n) nums3[idx3++] = nums2[idx2++];
for (int i = 0; i < m + n; i++) {
nums1[i] = nums3[i];
}
}
};
| 26.95
| 68
| 0.526902
|
yukienomiya
|
277797464e507b139fac06991ad4b81922a4e221
| 8,478
|
cpp
|
C++
|
projects/Phantom.Code/phantom/lang/Project.cpp
|
vlmillet/Phantom.Code
|
05ed65bc4a456e76da4b2d9da1fe3dabe64ba1b3
|
[
"MIT"
] | null | null | null |
projects/Phantom.Code/phantom/lang/Project.cpp
|
vlmillet/Phantom.Code
|
05ed65bc4a456e76da4b2d9da1fe3dabe64ba1b3
|
[
"MIT"
] | null | null | null |
projects/Phantom.Code/phantom/lang/Project.cpp
|
vlmillet/Phantom.Code
|
05ed65bc4a456e76da4b2d9da1fe3dabe64ba1b3
|
[
"MIT"
] | null | null | null |
// license [
// This file is part of the Phantom project. Copyright 2011-2020 Vivien Millet.
// Distributed under the MIT license. Text available here at
// https://github.com/vlmillet/phantom
// ]
#include "Project.h"
#include "CompiledSource.h"
#include "Compiler.h"
#include "Solution.h"
#include <fstream>
#include <phantom/lang/Application.h>
#include <phantom/lang/Module.h>
#include <phantom/lang/Package.h>
#include <phantom/lang/Plugin.h>
#include <phantom/lang/SourceFile.h>
#include <phantom/utils/Path.h>
#include <phantom/utils/StringUtil.h>
#include <system_error>
namespace phantom
{
namespace lang
{
Project::~Project()
{
if (m_pModule)
{
// Compiler::Get()->cleanupProject(this);
if (!m_pModule->isNative())
{
if (m_pModule->getOwner())
Application::Get()->removeModule(m_pModule);
Application::Get()->deleteModule(m_pModule);
m_pModule = nullptr;
}
}
}
Projects Project::getDependenciesProjects() const
{
Projects projs;
for (auto pMod : getDependencies())
{
if (Project* pDep = getSolution()->getProjectFromModule(pMod))
projs.push_back(pDep);
}
return projs;
}
phantom::String Project::getSourcePath() const
{
return Path(m_Path).parentPath().genericString();
}
Package* Project::getPackageForSourceStream(SourceStream* a_pStream) const
{
PHANTOM_ASSERT(std::find(m_SourceFiles.begin(), m_SourceFiles.end(), a_pStream) != m_SourceFiles.end());
Path p(Path(a_pStream->getPath()).relative(Path(getPath()).parentPath()));
if (p.size() == 1)
{
return m_pModule->getOrCreatePackage("default");
}
String packageName;
for (size_t i = 0; i < p.size() - 1; ++i)
{
if (packageName.empty())
packageName = p[i];
else
packageName += '.' + p[i];
}
return m_pModule->getOrCreatePackage(packageName);
}
SourceFile* Project::getSourceFileByPath(StringView a_Path) const
{
for (SourceFile* pSourceFile : m_SourceFiles)
if (Path::Equivalent(Path(pSourceFile->getPath()).relative(Path(getPath()).parentPath()),
Path(a_Path).relative(Path(getPath()).parentPath())))
return pSourceFile;
return nullptr;
}
void Project::addDependency(Module* a_pModule)
{
PHANTOM_ASSERT(std::find(m_Dependencies.begin(), m_Dependencies.end(), a_pModule) == m_Dependencies.end());
PHANTOM_ASSERT(m_pSolution->getProjectFromModule(a_pModule) || a_pModule->getPlugin(),
"the module is neither a project neither a plugin");
m_Dependencies.push_back(a_pModule);
m_pModule->addDependency(a_pModule);
}
bool Project::addDependency(StringView a_Name)
{
if (std::find_if(m_Dependencies.begin(), m_Dependencies.end(), [&](Module* m) { return m->getName() == a_Name; }) !=
m_Dependencies.end())
{
PHANTOM_LOG(Warning, "'%.*s' : dependency project '%.*s' already declared",
PHANTOM_STRING_AS_PRINTF_ARG(m_Path), PHANTOM_STRING_AS_PRINTF_ARG(a_Name));
return true;
}
if (Project* pProject = m_pSolution->getProjectFromName(a_Name))
{
if (pProject == this || pProject->hasProjectDependencyCascade(this))
return false;
addDependency(pProject->getModule());
return true;
}
if (Plugin* pPlugin = Application::Get()->getPlugin(a_Name))
{
pPlugin->load();
addDependency(pPlugin->getModule());
return true;
}
return false;
}
void Project::removeDependency(Module* a_pModule)
{
PHANTOM_ASSERT(m_pSolution->getProjectFromModule(a_pModule) || a_pModule->getPlugin());
auto found = std::find(m_Dependencies.begin(), m_Dependencies.end(), a_pModule);
PHANTOM_ASSERT(found != m_Dependencies.end());
m_pModule->removeDependency(a_pModule);
m_Dependencies.erase(found);
}
bool Project::hasDependency(Module* a_pModule) const
{
auto found = std::find(m_Dependencies.begin(), m_Dependencies.end(), a_pModule);
return found != m_Dependencies.end();
}
bool Project::addSourceFile(SourceFile* a_pSourceFile)
{
PHANTOM_ASSERT(getSourceFileByPath(a_pSourceFile->getPath()) == nullptr, "source file already added");
m_SourceFiles.push_back(a_pSourceFile);
return true;
}
SourceFile* Project::addSourceFile(StringView a_RelativePath, StringView a_Code /*= ""*/)
{
if (getSourceFileByPath(a_RelativePath))
return nullptr;
Path projectFullPath(getPath());
Path sourcePath = a_RelativePath;
if (!sourcePath.isAbsolute())
sourcePath = projectFullPath.parentPath().childPath(sourcePath);
if (!sourcePath.exists())
{
std::error_code errcode;
if (!Path::CreateDirectories(sourcePath.parentPath(), errcode))
return nullptr;
std::ofstream os(sourcePath.genericString().c_str());
if (!os.is_open())
return nullptr;
os.write(a_Code.data(), a_Code.size());
}
SourceFile* pSourceFile = new_<SourceFile>(sourcePath.genericString());
if (!addSourceFile(pSourceFile))
{
delete_<SourceFile>(pSourceFile);
return nullptr;
}
return pSourceFile;
}
void Project::removeSourceFile(SourceFile* a_pSourceFile)
{
auto found = std::find(m_SourceFiles.begin(), m_SourceFiles.end(), a_pSourceFile);
PHANTOM_ASSERT(found != m_SourceFiles.end());
m_SourceFiles.erase(found);
}
bool Project::isPathExisting() const
{
Path path = getPath();
return path.exists() && path.isDirectory();
}
bool Project::hasProjectDependencyCascade(Project* a_pOther) const
{
if (hasDependency(a_pOther->getModule()))
return true;
for (Module* pDep : m_Dependencies)
{
if (Project* pDepProj = m_pSolution->getProjectFromModule(pDep))
if (pDepProj->hasProjectDependencyCascade(a_pOther))
return true;
}
return false;
}
void Project::getCompiledSources(CompiledSources& _out) const
{
for (auto source : m_SourceFiles)
{
if (auto pCS = Compiler::Get()->getCompiledSource(source))
_out.push_back(pCS);
}
}
phantom::lang::CompiledSources Project::getCompiledSources() const
{
CompiledSources sources;
getCompiledSources(sources);
return sources;
}
phantom::String Project::getPath() const
{
if (Path::IsAbsolute(m_Path))
{
return m_Path;
}
return Path(m_pSolution->getPath()).parentPath().childPath(m_Path).genericString();
}
Project::Project(Solution* a_pSolution, StringView a_Path, Module* a_pModule)
: m_pSolution(a_pSolution), m_Path(a_Path), m_pModule(a_pModule)
{
}
ProjectData Project::getData() const
{
ProjectData data;
data.options = m_Options;
for (SourceFile* pSourceFile : m_SourceFiles)
{
data.files.push_back(Path(pSourceFile->getPath()).relative(Path(getPath()).parentPath()).genericString());
}
for (Module* pModule : m_Dependencies)
{
if (Project* pProject = m_pSolution->getProjectFromModule(pModule))
{
data.dependencies.push_back(pProject->getName());
}
else
{
PHANTOM_ASSERT(pModule->getPlugin());
data.dependencies.push_back(pModule->getPlugin()->getName());
}
}
return data;
}
int Project::getDependencyLevel() const
{
int maxLevel = 0;
for (auto dep : m_Dependencies)
{
if (Project* pProject = m_pSolution->getProjectFromModule(dep))
{
int level = pProject->getDependencyLevel() + 1;
if (level > maxLevel)
maxLevel = level;
}
}
return maxLevel;
}
bool Project::setData(ProjectData _data)
{
PHANTOM_ASSERT(m_pModule);
m_Options = _data.options;
for (auto& file : _data.files)
{
Path p(Path(getPath()).parentPath().childPath(file));
if (getSourceFileByPath(p.genericString()))
{
PHANTOM_LOG(Warning, "file '%.*s' already exists in this project, skipping doublon",
PHANTOM_STRING_AS_PRINTF_ARG(p.genericString()));
continue;
}
addSourceFile(new_<SourceFile>(p.genericString()));
}
for (auto& dep : _data.dependencies)
{
if (!addDependency(dep))
return false;
}
return true;
}
void Project::removeFromDisk()
{
Path::Remove(getPath());
}
} // namespace lang
} // namespace phantom
| 28.935154
| 120
| 0.651215
|
vlmillet
|
277a4ebe107b13457f249f8345419ed6ebef086f
| 19,986
|
hpp
|
C++
|
include/chobo/vector_view.hpp
|
mikke89/chobo-shl
|
7f888d1c97e0a69da99ab147c7f691ca0c64038f
|
[
"MIT"
] | 147
|
2016-09-23T19:33:11.000Z
|
2021-09-25T01:44:10.000Z
|
include/chobo/vector_view.hpp
|
mikke89/chobo-shl
|
7f888d1c97e0a69da99ab147c7f691ca0c64038f
|
[
"MIT"
] | 14
|
2016-09-27T10:54:35.000Z
|
2020-10-15T03:56:41.000Z
|
include/chobo/vector_view.hpp
|
mikke89/chobo-shl
|
7f888d1c97e0a69da99ab147c7f691ca0c64038f
|
[
"MIT"
] | 19
|
2016-09-25T15:49:26.000Z
|
2021-08-09T06:34:28.000Z
|
// chobo-vector-view v1.01
//
// A view of a std::vector which makes it look as a vector of another type
//
// MIT License:
// Copyright(c) 2016 Chobolabs Inc.
//
// 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.
//
//
// VERSION HISTORY
//
// 1.01 (2016-09-27) Added checks for unsupported resizes when
// sizeof(view type) is less than half of sizeof(vec type)
// 1.00 (2016-09-23) First public release
//
//
// DOCUMENTATION
//
// Simply include this file wherever you need.
// A vector view is a class which attaches to an existing std::vector
// and provides a view to its data as an alternative type, along
// with a working std::vector-like interface.
//
// THIS IS DANGEROUS, so you must know the risks ot doing so before
// using this library.
//
// The library includes two classes, for viewing const and non-const
// vectors: vector_view, and const_vector_view. To automatically generate
// the appropriate pointer, use `make_vector_view<NewType>(your_vector)`.
//
// Example:
//
// vector<vector2D> geometry;
// ... // fill geometry with data
// auto float_view = make_vector_view<float>(geometry);
// float_view[5] = 8; // equivalent to geometry[2].y = 8;
//
// auto view4d = make_vector_view<vector4D>(geometry);
//
// // add two elements to original array {1,2} and {3,4}
// view4d.push_back(make_vector4D(1, 2, 3, 4));
//
// Reference:
//
// vector_view has the most common std::vector methods and operators
// const_vector_view has the most common std::vector const methods and operators
//
// besides that both have a method vector& vec() for getting the underlying
// std::vector
//
//
// Configuration
//
// chobo::vector_view has two configurable settings:
//
// Config bounds checks:
//
// By default bounds checks are made in debug mode (via an assert) when accessing
// elements (with `at` or `[]`). Iterators are not checked (yet...)
//
// To disable them, you can define CHOBO_VECTOR_VIEW_NO_DEBUG_BOUNDS_CHECK
// before including the header.
//
// Config POD check:
//
// By default the library checks that both the source and the target type of
// the view are PODs. This is a good idea but sometimes a type is almost a POD
// (say constructors to geometry vectors) and is still fit for a view
//
// To disable the POD checks, define CHOBO_VECTOR_VIEW_NO_POD_CHECK
// before including the header.
//
// Using vector_view with non-POD types
//
// If you end up using the class with a non-pod type, you should take into
// account that when changing the size of the vector via its view ONLY the
// constructors and destructors of the source type (the one in the std::vector)
// will be called. The target type's constructors and destructors will NEVER be
// called. All assignments happen with its assignment operator (oprator=).
//
//
// TESTS
//
// The tests are included in the header file and use doctest (https://github.com/onqtam/doctest).
// To run them, define CHOBO_VECTOR_VIEW_TEST_WITH_DOCTEST before including
// the header in a file which has doctest.h already included.
//
#pragma once
#include <vector>
#if defined(CHOBO_VECTOR_VIEW_NO_DEBUG_BOUNDS_CHECK)
# define _CHOBO_VECTOR_VIEW_BOUNDS_CHECK(i)
#else
# include <cassert>
# define _CHOBO_VECTOR_VIEW_BOUNDS_CHECK(i) assert((i) < this->size())
#endif
#if defined(CHOBO_VECTOR_VIEW_NO_POD_CHECK)
#define _CHOBO_VECTOR_VIEW_POD_CHECK(T)
#else
#include <type_traits>
#define _CHOBO_VECTOR_VIEW_POD_CHECK(T) static_assert(std::is_pod<T>::value, #T " must be a pod");
#endif
namespace chobo
{
template <typename T, typename U, typename Alloc = std::allocator<T>>
class vector_view
{
_CHOBO_VECTOR_VIEW_POD_CHECK(T)
_CHOBO_VECTOR_VIEW_POD_CHECK(U)
public:
typedef std::vector<T, Alloc> vector;
typedef U value_type;
typedef T vec_value_type;
typedef Alloc allocator_type;
typedef typename vector::size_type size_type;
typedef typename vector::difference_type difference_type;
typedef U& reference;
typedef const U& const_reference;
typedef U* pointer;
typedef const U* const_pointer;
typedef pointer iterator;
typedef const_pointer const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
explicit vector_view(vector& vec)
: m_vector(vec)
{}
vector_view(const vector_view& other) = delete;
vector_view& operator=(const vector_view& other) = delete;
vector_view(vector_view&& other)
: m_vector(other.m_vector)
{} // intentionally don't inavlidate the other view
vector_view& operator=(vector_view&& other)
{
m_vector = std::move(other.m_vector);
}
vector& vec()
{
return m_vector;
}
const vector& vec() const
{
return m_vector;
}
template <typename UAlloc>
vector_view& operator=(const std::vector<U, UAlloc>& other)
{
size_type n = other.size();
resize(n);
for (size_type i = 0; i < n; ++i)
{
this->at(i) = other[i];
}
}
iterator begin() noexcept
{
return reinterpret_cast<iterator>(m_vector.data());
}
const_iterator begin() const noexcept
{
return reinterpret_cast<const_iterator>(m_vector.data());
}
const_iterator cbegin() const noexcept
{
return begin();
}
iterator end() noexcept
{
return begin() + size();
}
const_iterator end() const noexcept
{
return begin() + size();
}
const_iterator cend() const noexcept
{
return begin() + size();
}
reverse_iterator rbegin() noexcept
{
return reverse_iterator(end());
}
const_reverse_iterator rbegin() const noexcept
{
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const noexcept
{
return const_reverse_iterator(end());
}
reverse_iterator rend() noexcept
{
return reverse_iterator(begin());
}
const_reverse_iterator rend() const noexcept
{
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const noexcept
{
return const_reverse_iterator(begin());
}
size_type size() const noexcept
{
return (m_vector.size() * sizeof(vec_value_type)) / sizeof(value_type);
}
size_type capacity() const noexcept
{
return (m_vector.capacity() * sizeof(vec_value_type)) / sizeof(value_type);
}
size_type max_size() const noexcept
{
return (m_vector.max_size() * sizeof(vec_value_type)) / sizeof(value_type);
}
void resize(size_type n)
{
size_type s = (n * sizeof(value_type) + sizeof(vec_value_type) - 1) / sizeof(vec_value_type);
m_vector.resize(s);
#if !defined CHOBO_VECTOR_VIEW_NO_RESIZE_CHECK
// Is this assert fails, here's what has happened:
// The size of the type of the view is smaller than the half of the size of the vector.
// Since the vector's number of elements must be a whole number, we cannot resize it to
// hold cerrtain numbers of the type of the view (ie not multiples of the sizeof(vec_type)/sizeof(view_type))
//
// In theory this could be supported if we add a custom size variable for the view class
// However, besides the increase in complexity, this will cause us to lose a cruicial
// feature - having changes to the vector from outside be automatically reflected on the view
// because it's only a view, and has no state of its own.
// Adding such size will be a state for this class.
// Perhaps if there is need such a feature could be implemented but in a class
// with another name, where it's clear that persisting it would be hurtful.
//
// So to avoid potential bugs this assertion, as well as the static assertions in
// push_back and pop_back have been added.
assert(size() == n && "unsupported resize");
#endif
}
void resize(size_type n, const value_type& val)
{
size_type prev_size = size();
resize(n);
for (iterator i = begin() + prev_size; i != end(); ++i)
{
*i = val;
}
}
bool empty() const noexcept
{
return m_vector.size() * sizeof(vec_value_type) < sizeof(value_type);
}
void reserve(size_type n)
{
n = (n * sizeof(value_type) + sizeof(vec_value_type) - 1) / sizeof(vec_value_type);
m_vector.reserve(n);
}
void shrink_to_fit()
{
m_vector.shrink_to_fit();
}
const_reference at(size_type i) const
{
_CHOBO_VECTOR_VIEW_BOUNDS_CHECK(i);
return *(begin() + i);
}
reference at(size_type i)
{
_CHOBO_VECTOR_VIEW_BOUNDS_CHECK(i);
return *(begin() + i);
}
const_reference operator[](size_type i) const
{
return at(i);
}
reference operator[](size_type i)
{
return at(i);
}
const_reference front() const
{
return at(0);
}
reference front()
{
return at(0);
}
const_reference back() const
{
return *(end() - 1);
}
reference back()
{
return *(end() - 1);
}
const_pointer data() const noexcept
{
return begin();
}
pointer data() noexcept
{
return begin();
}
void push_back(const value_type& val)
{
// see comment in resize for an explanation
static_assert(sizeof(value_type) > sizeof(vec_value_type) / 2,
"vector_view::push_back is not supported for value_type with size smaller than half of the viewed type");
resize(size() + 1, val);
}
void push_back(value_type&& val)
{
// see comment in resize for an explanation
static_assert(sizeof(value_type) > sizeof(vec_value_type) / 2,
"vector_view::push_back is not supported for value_type with size smaller than half of the viewed type");
resize(size() + 1);
back() = std::move(val);
}
void pop_back()
{
// see comment in resize for an explanation
static_assert(sizeof(value_type) > sizeof(vec_value_type) / 2,
"vector_view::pop_back is not supported for value_type with size smaller than half of the viewed type");
resize(size() - 1);
}
void clear() noexcept
{
m_vector.clear();
}
private:
vector& m_vector;
};
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename U, typename Alloc = std::allocator<T>>
class const_vector_view
{
_CHOBO_VECTOR_VIEW_POD_CHECK(T)
_CHOBO_VECTOR_VIEW_POD_CHECK(U)
public:
typedef std::vector<T, Alloc> vector;
typedef U value_type;
typedef T vec_value_type;
typedef Alloc allocator_type;
typedef typename vector::size_type size_type;
typedef typename vector::difference_type difference_type;
typedef U& reference;
typedef const U& const_reference;
typedef U* pointer;
typedef const U* const_pointer;
typedef pointer iterator;
typedef const_pointer const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
explicit const_vector_view(const vector& vec)
: m_vector(vec)
{}
const_vector_view(const const_vector_view& other) = delete;
const_vector_view& operator=(const const_vector_view& other) = delete;
const_vector_view(const_vector_view&& other)
: m_vector(other.m_vector)
{} // intentionally don't inavlidate the other view
const_vector_view& operator=(const_vector_view&& other) = delete;
const vector& vec() const
{
return m_vector;
}
const_iterator begin() const noexcept
{
return reinterpret_cast<const_iterator>(m_vector.data());
}
const_iterator cbegin() const noexcept
{
return begin();
}
const_iterator end() const noexcept
{
return begin() + size();
}
const_iterator cend() const noexcept
{
return begin() + size();
}
const_reverse_iterator rbegin() const noexcept
{
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const noexcept
{
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const noexcept
{
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const noexcept
{
return const_reverse_iterator(begin());
}
size_type size() const noexcept
{
return (m_vector.size() * sizeof(vec_value_type)) / sizeof(value_type);
}
size_type capacity() const noexcept
{
return (m_vector.capacity() * sizeof(vec_value_type)) / sizeof(value_type);
}
size_type max_size() const noexcept
{
return (m_vector.max_size() * sizeof(vec_value_type)) / sizeof(value_type);
}
bool empty() const noexcept
{
return m_vector.size() * sizeof(vec_value_type) < sizeof(value_type);
}
const_reference at(size_type i) const
{
_CHOBO_VECTOR_VIEW_BOUNDS_CHECK(i);
return *(begin() + i);
}
const_reference operator[](size_type i) const
{
return at(i);
}
const_reference front() const
{
return at(0);
}
const_reference back() const
{
return *(end() - 1);
}
const_pointer data() const noexcept
{
return begin();
}
private:
const vector& m_vector;
};
///////////////////////////////////////////////////////////////////////////////
template <typename U, typename T, typename Alloc>
vector_view<T, U, Alloc> make_vector_view(std::vector<T, Alloc>& vec)
{
return vector_view<T, U, Alloc>(vec);
}
template <typename U, typename T, typename Alloc>
const_vector_view<T, U, Alloc> make_vector_view(const std::vector<T, Alloc>& vec)
{
return const_vector_view<T, U, Alloc>(vec);
}
}
#if defined(CHOBO_VECTOR_VIEW_TEST_WITH_DOCTEST)
namespace chobo_vector_view_test
{
struct vector3D
{
int x, y, z;
};
struct vector4D
{
int x, y, z, w;
};
struct chobo_vector3D
{
int a, b, c;
};
}
TEST_CASE("[vector_view] test")
{
using namespace chobo;
using namespace chobo_vector_view_test;
std::vector<int> vec;
auto v3dview = make_vector_view<vector3D>(vec);
CHECK(v3dview.empty());
CHECK(v3dview.size() == 0);
vec.push_back(5);
CHECK(v3dview.empty());
CHECK(v3dview.size() == 0);
vec.push_back(10);
CHECK(v3dview.empty());
CHECK(v3dview.size() == 0);
vec.push_back(15);
CHECK(!v3dview.empty());
CHECK(v3dview.size() == 1);
CHECK(v3dview.front().x == 5);
CHECK(v3dview.front().y == 10);
CHECK(v3dview.front().z == 15);
CHECK(v3dview.back().x == 5);
CHECK(v3dview.back().y == 10);
CHECK(v3dview.back().z == 15);
v3dview.resize(2);
CHECK(vec.size() == 6);
v3dview[1].x = 2;
v3dview.at(1).y = 4;
(v3dview.begin() + 1)->z = 6;
CHECK(vec[3] == 2);
CHECK(vec[4] == 4);
CHECK(vec[5] == 6);
CHECK((v3dview.rend() - 2)->z == 6);
vector3D foo = { 1,3,5 };
v3dview.resize(4, foo);
CHECK(vec.size() == 12);
CHECK(vec.back() == 5);
CHECK(vec[6] == 1);
CHECK(v3dview.rbegin()->y == 3);
v3dview.resize(3);
CHECK(vec.size() == 9);
CHECK(v3dview.crbegin()->z == 5);
v3dview.push_back(foo);
CHECK(vec.size() == 12);
CHECK(vec[9] == 1);
CHECK(vec[10] == 3);
CHECK(vec[11] == 5);
v3dview.pop_back();
CHECK(vec.size() == 9);
v3dview.clear();
CHECK(vec.empty());
vec.resize(5);
CHECK(v3dview.size() == 1);
v3dview.resize(2);
CHECK(vec.size() == 6);
void* data = vec.data();
CHECK(v3dview.data() == data);
// same
std::vector<chobo_vector3D> vec3d;
auto v3dview_chobo = make_vector_view<vector3D>(vec3d);
vec3d.resize(5);
CHECK(v3dview_chobo.size() == 5);
vec3d[2].a = 7;
vec3d[2].b = 8;
vec3d[2].c = 9;
CHECK(v3dview_chobo[2].x == 7);
CHECK(v3dview_chobo.at(2).y == 8);
CHECK((v3dview_chobo.begin() + 2)->z == 9);
// unequal
std::vector<vector4D> vec4d;
auto v3dview4d = make_vector_view<vector3D>(vec4d);
vec4d.resize(1);
CHECK(v3dview4d.size() == 1);
v3dview4d.resize(2);
CHECK(v3dview4d.size() == 2);
CHECK(vec4d.size() == 2);
// smaller
auto iview = make_vector_view<int>(vec4d);
CHECK(iview.size() == 8);
iview.resize(12);
CHECK(vec4d.size() == 3);
}
TEST_CASE("[const_vector_view] test")
{
using namespace chobo;
using namespace chobo_vector_view_test;
std::vector<int> vvec;
const auto& vec = vvec;
auto v3dview = make_vector_view<vector3D>(vec);
CHECK(v3dview.empty());
CHECK(v3dview.size() == 0);
vvec.push_back(5);
CHECK(v3dview.empty());
CHECK(v3dview.size() == 0);
vvec.push_back(10);
CHECK(v3dview.empty());
CHECK(v3dview.size() == 0);
vvec.push_back(15);
CHECK(!v3dview.empty());
CHECK(v3dview.size() == 1);
CHECK(v3dview.front().x == 5);
CHECK(v3dview.front().y == 10);
CHECK(v3dview.front().z == 15);
CHECK(v3dview.back().x == 5);
CHECK(v3dview.back().y == 10);
CHECK(v3dview.back().z == 15);
vvec.resize(6);
CHECK(v3dview.size() == 2);
vvec[3] = 2;
vvec[4] = 4;
vvec[5] = 6;
CHECK(v3dview[1].x == 2);
CHECK(v3dview.at(1).y == 4);
CHECK((v3dview.begin() + 1)->z == 6);
CHECK((v3dview.rend() - 2)->z == 6);
vvec.resize(12);
CHECK(v3dview.size() == 4);
vvec[10] = 3;
CHECK(v3dview.rbegin()->y == 3);
vvec.resize(9);
CHECK(v3dview.size() == 3);
vvec.clear();
CHECK(v3dview.empty());
vvec.resize(5);
CHECK(v3dview.size() == 1);
const void* data = vec.data();
CHECK(v3dview.data() == data);
// same
std::vector<chobo_vector3D> vvec3d;
const auto& vec3d = vvec3d;
auto v3dview_chobo = make_vector_view<vector3D>(vec3d);
vvec3d.resize(5);
CHECK(v3dview_chobo.size() == 5);
vvec3d[2].a = 7;
vvec3d[2].b = 8;
vvec3d[2].c = 9;
CHECK(v3dview_chobo[2].x == 7);
CHECK(v3dview_chobo.at(2).y == 8);
CHECK((v3dview_chobo.begin() + 2)->z == 9);
// unequal
std::vector<vector4D> vvec4d;
const auto& vec4d = vvec4d;
auto v3dview4d = make_vector_view<vector3D>(vec4d);
vvec4d.resize(1);
CHECK(v3dview4d.size() == 1);
vvec4d.resize(2);
CHECK(v3dview4d.size() == 2);
vvec4d.resize(3);
CHECK(v3dview4d.size() == 4);
// smaller
auto iview = make_vector_view<int>(vec4d);
CHECK(iview.size() == 12);
}
#endif
| 26.262812
| 117
| 0.631992
|
mikke89
|
277b93df3e0d432f978009c9bf64272146c36b1d
| 1,014
|
cpp
|
C++
|
Stacks/Longest-Valid-Parentheses-32.cpp
|
devangi2000/Data-Structures-Algorithms-Handbook
|
ce0f00de89af5da7f986e65089402dc6908a09b5
|
[
"MIT"
] | 38
|
2021-10-14T09:36:53.000Z
|
2022-01-27T02:36:19.000Z
|
Stacks/Longest-Valid-Parentheses-32.cpp
|
devangi2000/Data-Structures-Algorithms-Handbook
|
ce0f00de89af5da7f986e65089402dc6908a09b5
|
[
"MIT"
] | null | null | null |
Stacks/Longest-Valid-Parentheses-32.cpp
|
devangi2000/Data-Structures-Algorithms-Handbook
|
ce0f00de89af5da7f986e65089402dc6908a09b5
|
[
"MIT"
] | 4
|
2021-12-06T15:47:12.000Z
|
2022-02-04T04:25:00.000Z
|
// Given a string containing just the characters '(' and ')', find the
// length of the longest valid (well-formed) parentheses substring.
// Example 1:
// Input: s = "(()"
// Output: 2
// Explanation: The longest valid parentheses substring is "()".
// Example 2:
// Input: s = ")()())"
// Output: 4
// Explanation: The longest valid parentheses substring is "()()".
// Example 3:
// Input: s = ""
// Output: 0
// Constraints:
// 0 <= s.length <= 3 * 104
// s[i] is '(', or ')'.
class Solution {
public:
stack<int> st;
int ans = 0;
int longestValidParentheses(string s){
int n = s.size();
st.push(-1);
for(int i=0; i<n; ++i){
if(s[i] == '('){
st.push(i);
}
else{
st.pop();
if(st.empty()){
st.push(i);
}
ans = max(ans, i - st.top());
}
}
return ans;
}
};
| 22.533333
| 72
| 0.439842
|
devangi2000
|
277c302017dae8c7514180218fc0b1412a451c54
| 3,057
|
cpp
|
C++
|
array_inversion/main.cpp
|
8alery/algorithms
|
67cf12724f61cdae7eff1788062c1b7c26f98ca4
|
[
"Apache-2.0"
] | null | null | null |
array_inversion/main.cpp
|
8alery/algorithms
|
67cf12724f61cdae7eff1788062c1b7c26f98ca4
|
[
"Apache-2.0"
] | null | null | null |
array_inversion/main.cpp
|
8alery/algorithms
|
67cf12724f61cdae7eff1788062c1b7c26f98ca4
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include <queue>
#include <limits>
void printVector(std::vector<int> array){
for (auto v:array){
std::cout << v << " ";
}
std::cout << std::endl;
}
int next_power_of_two(int v){
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return v++;
}
long merge_sort_iterative(std::vector<int> array){
long inversions = 0;
int sizeModified = next_power_of_two(array.size());
std::queue<std::vector<int>> queue;
for (auto value:array){
queue.push(std::vector<int>{ value });
}
for (int i = array.size(); i <= sizeModified; i++){
queue.push(std::vector<int>{ std::numeric_limits<int>::max() });
}
while (queue.size() > 1){
auto first = queue.front();
queue.pop();
auto second = queue.front();
queue.pop();
std::cout << "first: ";
printVector(first);
std::cout << "second: ";
printVector(second);
int i = 0, j = 0, totalSize = first.size() + second.size();
std::vector<int> sorted;
int current;
long currentInversions = 0;
while (i < first.size() && j < second.size()){
if (first[i] <= second[j]){
current = first[i++];
} else {
current = second[j++];
currentInversions += (first.size() - i);
}
sorted.push_back(current);
}
while (i < first.size()) {
sorted.push_back(first[i++]);
}
while (j < second.size()) {
sorted.push_back(second[j++]);
}
queue.push(sorted);
std::cout << "inversions: " << currentInversions << std::endl;
std::cout << "sorted: ";
printVector(sorted);
inversions += currentInversions;
}
std::cout << "inversions: " << inversions << std::endl;
std::cout << "sorted: ";
printVector(queue.front());
return inversions;
}
int main() {
// std::vector<int> array = {7, 6, 5, 4, 3, 2, 1 };
// int n = array.size();
int n;
std::cin >> n;
std::vector<int> array;
for (int i = 0; i < n; i++){
int element = 0; //dis(gen);
std::cin >> element;
array.push_back(element);
}
long inversionsCount = merge_sort_iterative(array);
std::cout << inversionsCount << std::endl;
return 0;
// int n = 100000;
// std::vector<int> array;
// std::random_device rd; //Will be used to obtain a seed for the random number engine
// std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
// std::uniform_int_distribution<> dis(1, 1000000000);
// for (int i = 0; i < n; i++){
// int element = dis(gen);
// array.push_back(element);
// }
// long inversionsCount = merge_sort_iterative(array);
// std::cout << inversionsCount << std::endl;
// return 0;
}
| 26.815789
| 94
| 0.514884
|
8alery
|
277d16cc64a386e3bc92eb09a29e6fac42aec4ec
| 5,323
|
cpp
|
C++
|
compat/BSSynchronizedClipGenerator_1.cpp
|
BlazesRus/hkxcmd
|
e00a554225234e40e111e808b095156ac1d4b1fe
|
[
"Intel"
] | 38
|
2015-03-24T00:41:59.000Z
|
2022-03-23T09:18:29.000Z
|
compat/BSSynchronizedClipGenerator_1.cpp
|
BlazesRus/hkxcmd
|
e00a554225234e40e111e808b095156ac1d4b1fe
|
[
"Intel"
] | 2
|
2015-10-14T07:41:48.000Z
|
2015-12-14T02:19:05.000Z
|
compat/BSSynchronizedClipGenerator_1.cpp
|
BlazesRus/hkxcmd
|
e00a554225234e40e111e808b095156ac1d4b1fe
|
[
"Intel"
] | 24
|
2015-08-03T20:41:07.000Z
|
2022-03-27T03:58:37.000Z
|
#include "StdAfx.h"
#include "BSSynchronizedClipGenerator_1.h"
#include <Common/Serialize/hkSerialize.h>
#include <Common/Serialize/Util/hkSerializeUtil.h>
#include <Common/Serialize/Version/hkVersionPatchManager.h>
#include <Common/Serialize/Data/Dict/hkDataObjectDict.h>
#include <Common/Serialize/Data/Native/hkDataObjectNative.h>
#include <Common/Serialize/Data/Util/hkDataObjectUtil.h>
#include <Common/Base/Reflection/Registry/hkDynamicClassNameRegistry.h>
#include <Common/Base/Reflection/Registry/hkVtableClassRegistry.h>
#include <Common/Base/Reflection/hkClass.h>
#include <Common/Base/Reflection/hkInternalClassMember.h>
#include <Common/Serialize/Util/hkSerializationCheckingUtils.h>
#include <Common/Serialize/Util/hkVersionCheckingUtils.h>
static const hkInternalClassMember BSSynchronizedClipGeneratorClass_Members[] =
{
{ "pClipGenerator",&hkbGeneratorClass,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_STRUCT,0,hkClassMember::ALIGN_16,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_pClipGenerator) /*48*/,HK_NULL},
{ "SyncAnimPrefix",HK_NULL,HK_NULL,hkClassMember::TYPE_CSTRING,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_SyncAnimPrefix) /*52*/,HK_NULL},
{ "bSyncClipIgnoreMarkPlacement",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bSyncClipIgnoreMarkPlacement) /*56*/,HK_NULL},
{ "fGetToMarkTime",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_fGetToMarkTime) /*60*/,HK_NULL},
{ "fMarkErrorThreshold",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_fMarkErrorThreshold) /*64*/,HK_NULL},
{ "bLeadCharacter",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bLeadCharacter) /*68*/,HK_NULL},
{ "bReorientSupportChar",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bReorientSupportChar) /*69*/,HK_NULL},
{ "bApplyMotionFromRoot",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bApplyMotionFromRoot) /*70*/,HK_NULL},
{ "pSyncScene",HK_NULL,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_pSyncScene) /*72*/,HK_NULL},
{ "StartMarkWS",HK_NULL,HK_NULL,hkClassMember::TYPE_QSTRANSFORM,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_StartMarkWS) /*80*/,HK_NULL},
{ "EndMarkWS",HK_NULL,HK_NULL,hkClassMember::TYPE_QSTRANSFORM,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_EndMarkWS) /*128*/,HK_NULL},
{ "StartMarkMS",HK_NULL,HK_NULL,hkClassMember::TYPE_QSTRANSFORM,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_StartMarkMS) /*176*/,HK_NULL},
{ "fCurrentLerp",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_fCurrentLerp) /*224*/,HK_NULL},
{ "pLocalSyncBinding",HK_NULL,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_pLocalSyncBinding) /*228*/,HK_NULL},
{ "pEventMap",HK_NULL,HK_NULL,hkClassMember::TYPE_POINTER,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_pEventMap) /*232*/,HK_NULL},
{ "sAnimationBindingIndex",HK_NULL,HK_NULL,hkClassMember::TYPE_INT16,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_sAnimationBindingIndex) /*236*/,HK_NULL},
{ "bAtMark",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bAtMark) /*238*/,HK_NULL},
{ "bAllCharactersInScene",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bAllCharactersInScene) /*239*/,HK_NULL},
{ "bAllCharactersAtMarks",HK_NULL,HK_NULL,hkClassMember::TYPE_BOOL,hkClassMember::TYPE_VOID,0,hkClassMember::SERIALIZE_IGNORED,HK_OFFSET_OF(BSSynchronizedClipGenerator,m_bAllCharactersAtMarks) /*240*/,HK_NULL},
};
// Signature: d83bea64
extern const hkClass hkbGeneratorClass;
extern const hkClass BSSynchronizedClipGeneratorClass;
const hkClass BSSynchronizedClipGeneratorClass(
"BSSynchronizedClipGenerator",
&hkbGeneratorClass, // parent
sizeof(BSSynchronizedClipGenerator),
HK_NULL, 0, // interfaces
HK_NULL, 0, // enums
reinterpret_cast<const hkClassMember*>(BSSynchronizedClipGeneratorClass_Members), HK_COUNT_OF(BSSynchronizedClipGeneratorClass_Members),
HK_NULL, // defaults
HK_NULL, // attributes
0, // flags
1 // version
);
HK_REFLECTION_DEFINE_VIRTUAL(BSSynchronizedClipGenerator, BSSynchronizedClipGenerator);
| 91.775862
| 219
| 0.833177
|
BlazesRus
|
277d97de0c9342aa004f99d363161c6cd19d89b8
| 54
|
cpp
|
C++
|
App/FIFOServer/ClientB.cpp
|
Lw-Cui/Compression-server
|
3501d746f14145d3764700d40d3672a0da0b2eae
|
[
"MIT"
] | 3
|
2016-12-10T16:06:20.000Z
|
2017-06-25T12:47:06.000Z
|
App/FIFOServer/ClientB.cpp
|
Lw-Cui/Compression-server
|
3501d746f14145d3764700d40d3672a0da0b2eae
|
[
"MIT"
] | 2
|
2017-05-15T15:22:36.000Z
|
2017-05-20T15:01:25.000Z
|
App/FIFOServer/ClientB.cpp
|
Lw-Cui/Tiny-server
|
3501d746f14145d3764700d40d3672a0da0b2eae
|
[
"MIT"
] | null | null | null |
#define CLIENT "ClientB"
#include "ClientBody.cpp"
| 9
| 25
| 0.722222
|
Lw-Cui
|
277ec282bacc3d331bb049b9c28b4d96dc43d669
| 4,003
|
cpp
|
C++
|
src/Samples/Synthetic_TwoView/main.cpp
|
eivan/one-ac-pose
|
79451626238f47130578c18b65e37cabd7332de1
|
[
"MIT"
] | 4
|
2020-07-31T19:12:44.000Z
|
2022-02-22T14:34:48.000Z
|
src/Samples/Synthetic_TwoView/main.cpp
|
eivan/OneAC
|
79451626238f47130578c18b65e37cabd7332de1
|
[
"MIT"
] | null | null | null |
src/Samples/Synthetic_TwoView/main.cpp
|
eivan/OneAC
|
79451626238f47130578c18b65e37cabd7332de1
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <time.h>
#include <common/numeric.hpp>
#include <common/camera_radial.hpp>
#include <common/local_affine_frame.hpp>
#include <common/pose_estimation.hpp>
using namespace OneACPose;
void compute_synthetic_LAF(
const Mat34& P, const common::CameraPtr& cam,
const Vec3& X, const Mat32& dX_dx,
common::Feature_LAF_D& laf);
int main()
{
srand(time(0));
// ==========================================================================
// initialize two poses
// ==========================================================================
const Vec3 target{ Vec3::Random() };
const double distance_from_target = 5;
// init pose 0
const Vec3 C0{ Vec3::Random().normalized() * distance_from_target };
const Mat3 R0{ common::LookAt(target - C0) };
const Mat34 P0{ (Mat34() << R0, -R0 * C0).finished() };
// init pose 1
const Vec3 C1{ Vec3::Random().normalized() * distance_from_target };
const Mat3 R1{ common::LookAt(target - C1) };
const Mat34 P1{ (Mat34() << R1, -R1 * C1).finished() };
// ==========================================================================
// initialize two cameras
// ==========================================================================
common::CameraPtr cam0 = std::make_shared<common::Camera_Radial>();
cam0->set_params({ 1000.0, 1000.0, 500.0, 500.0, 0.0, 0.0, 0.0 });
common::CameraPtr cam1 = std::make_shared<common::Camera_Radial>();
cam1->set_params({ 1000.0, 1000.0, 500.0, 500.0, 0.0, 0.0, 0.0 });
// ==========================================================================
// initialize 3D structure
// ==========================================================================
// surface point
const Vec3 X{ Vec3::Random() };
// surface normal at X
const Vec3 N{ Vec3::Random().normalized() };
// local frame of surface around X (perpendicular to N)
const Mat32 dX_dx{ common::nullspace(N) };
// ==========================================================================
// compute synthetic LAFs with depths, by projecting X and dX_dx onto the image plane
// ==========================================================================
common::Feature_LAF_D laf0;
compute_synthetic_LAF(P0, cam0, X, dX_dx, laf0);
common::Feature_LAF_D laf1;
compute_synthetic_LAF(P1, cam1, X, dX_dx, laf1);
// ==========================================================================
// perform estimation
// ==========================================================================
double scale;
Mat3 R;
Vec3 t;
estimatePose_1ACD(
cam0, cam1, // calibrated cameras
laf0, // LAF 0: 2d location, 2D shape, depth and depth derivatives
laf1, // LAF 1, 2d location, 2D shape, depth and depth derivatives
scale, R, t);
// ==========================================================================
// measure errors wrt ground truth
// ==========================================================================
std::cout << "R_gt:\t" << (R1 * R0.transpose()) << std::endl;
std::cout << "R_est:\t" << R << std::endl;
std::cout << "t_est:\t" << (t).transpose() << std::endl;
std::cout << "t_gt:\t" << (R1 * (C0 - C1)).transpose() << std::endl;
std::cout << "scale:\t" << scale << std::endl;
}
void compute_synthetic_LAF(
const Mat34& P, const common::CameraPtr& cam,
const Vec3& X, const Mat32& dX_dx,
common::Feature_LAF_D& laf)
{
const Vec3 Y = P * X.homogeneous();
const Mat32 dY_dx = P.topLeftCorner<3, 3>() * dX_dx;
Mat23 dx_dY;
//std::tie(laf.x.noalias(), dx_dY.noalias()) = cam->p_gradient(Y); // g++8 error, msvc works
std::tie(laf.x, dx_dY) = cam->p_gradient(Y);
// affine shape around x, aka dx0_dx
laf.M.noalias() = dx_dY * dY_dx;
RowVec3 dlambda_dY;
//std::tie(laf.lambda, dlambda_dY.noalias()) = cam->depth_gradient(Y); // g++8 error, msvc works
std::tie(laf.lambda, dlambda_dY) = cam->depth_gradient(Y);
// aka dlambda_dx
laf.dlambda_dx.noalias() = dlambda_dY * dY_dx;
}
| 36.390909
| 98
| 0.501624
|
eivan
|