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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ac3125dafa9e64c2e8ea6a66b08374a304a43b93 | 2,492 | cpp | C++ | Main.cpp | dushyant-shukla/take-me-home | 4e7793dc253cf7be55fc6456276d8b17f4de3218 | [
"Apache-2.0"
] | null | null | null | Main.cpp | dushyant-shukla/take-me-home | 4e7793dc253cf7be55fc6456276d8b17f4de3218 | [
"Apache-2.0"
] | null | null | null | Main.cpp | dushyant-shukla/take-me-home | 4e7793dc253cf7be55fc6456276d8b17f4de3218 | [
"Apache-2.0"
] | null | null | null | /* Start Header -------------------------------------------------------
Copyright (C) 2017 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
File Name: Main.cpp
Purpose: Main game loop
Language: C/C++ using Visual Studio 2019
Platform: Visual Studio 2019,
Hardware Requirements: 1.6 GHz or faster processor
1 GB of RAM (1.5 GB if running on a virtual machine)
4 GB of available hard disk space 5400 RPM hard disk drive
DirectX 9-capable video card (1024 x 768 or higher resolution)
Operating Systems: Windows 10
Windows 7 SP 2
Project: CS529_dushyant.shukla_FinalProject_Milestone1
Author: Name: Dushyant Shukla ; Login: dushyant.shukla ; Student ID : 60000519
Creation date: October 16, 2019.
- End Header --------------------------------------------------------*/
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include "Core.h"
#include "GameStateManager.h"
#include "GameState.h"
void InitializeWindow();
void FrameBufferSizeCallBack(GLFWwindow* window, GLsizei width, GLsizei height);
GLFWwindow* window;
FILE _iob[] = { *stdin, *stdout, *stderr };
extern "C" FILE * __cdecl __iob_func(void)
{
return _iob;
}
#pragma comment(lib, "legacy_stdio_definitions.lib")
int main(int argc, char* args[])
{
InitializeWindow();
InitializeGameStateManager(GAME_STATE::GAME_INIT);
//InitializeGameStateManager(GAME_STATE::GAME_ACTIVE);
MainGameLoop();
glfwTerminate();
return 0;
}
void InitializeWindow() {
if (!glfwInit()) {
//std::cout << "Failed to initialize GLFW!!" << std::endl;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "2D PLATFORMER", NULL, NULL);
if (window == NULL) {
//std::cout << "Failed to create GLFW WINDOW!!" << std::endl;
glfwTerminate();
exit(-1);
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
//std::cout << "Failed to initialize GLAD!!" << std::endl;
glfwTerminate();
exit(-1);
}
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glfwSetFramebufferSizeCallback(window, FrameBufferSizeCallBack);
}
void FrameBufferSizeCallBack(GLFWwindow* window, GLsizei width, GLsizei height) {
glViewport(0, 0, width, height);
} | 28.976744 | 85 | 0.717496 | dushyant-shukla |
ac31d147c9ca399883791c3aa7cf2ca33c5664c5 | 1,544 | cpp | C++ | 2017.8.17/a.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | 2017.8.17/a.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | 2017.8.17/a.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | #include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define ll long long
#define read(a) scanf("%d",&a);
using namespace std;
const int maxn=1e5+5;
string s[maxn];
int Next[maxn];
void getNext(int num,int &j,int &k,int len){
while(j<len-1){
if(k==-1||s[num][j]==s[num][k]){
++k;
++j;
Next[j]=k;
}
else{
k=Next[k];
}
}
}
int kmp_search(int x,int j,int lenx,int y,int i,int leny){
while(i<leny&&j<lenx){
if(j==-1||s[y][i]==s[x][j]){
i++;
j++;
}
else{
j=Next[j];
}
}
if(j==lenx)
return i-j;
else
return -1;
}
int search(int x,int y){
int len=0;
Next[0]=-1;
int j=0;
int k=-1;
int i=0;
int maxnlen=0;
while(len<s[x].size()){
len++;
getNext(x,j,k,len);
i=kmp_search(x,0,len,y,i,s[y].size());
if(i==-1){
break;
}
else{
maxnlen=max(maxnlen,len);
}
}
return maxnlen;
}
int main(){
freopen("test.txt","r",stdin);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>s[i];
//cout<<s[i]<<endl;
}
int m;
cin>>m;
int ans=0;
while(m--){
int x,y;
cin>>x>>y;
if(x>y)
swap(x,y);
// ans=max(search(x,y),search(y,x));
// printf("%d\n",ans);
ans=0;
for(int i=1;i<=n;i++){
if(i!=x&&i!=y){
int num=min(search(i,x),search(i,y));
ans=max(num,ans);
}
}
ans=max(ans,search(x,y));
ans=max(ans,search(y,x));
printf("%d\n",ans);
}
}
return 0;
} | 15.44 | 58 | 0.542098 | 1980744819 |
ac32efebadd4b44baf21acc04ae2cd208dafc741 | 635 | cpp | C++ | solutions/beecrowd/1285/1285.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 18 | 2015-01-22T04:08:51.000Z | 2022-01-08T22:36:47.000Z | solutions/beecrowd/1285/1285.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 4 | 2016-04-25T12:32:46.000Z | 2021-06-15T18:01:30.000Z | solutions/beecrowd/1285/1285.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 25 | 2015-03-02T06:21:51.000Z | 2021-09-12T20:49:21.000Z | #include <cstdint>
#include <iostream>
#include <map>
bool has_repeated(int16_t n) {
int16_t cur;
std::map< int16_t, bool > previous;
while (n) {
cur = n % 10;
if (previous[cur]) {
return true;
}
previous[cur] = true;
n = static_cast< int16_t >(n / 10);
}
return false;
}
int main() {
int16_t n, m, count = 0;
while (std::cin >> n >> m) {
for (int16_t i = n; i <= m; i++) {
if (!has_repeated(i)) {
count++;
}
}
std::cout << count << std::endl;
count = 0;
}
return 0;
}
| 17.638889 | 43 | 0.445669 | deniscostadsc |
ac368927254d73d2cd53384474db706eb604681b | 1,879 | cpp | C++ | sdk/boost_1_30_0/libs/mpl/test/bind.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 2 | 2020-01-30T12:51:49.000Z | 2020-08-31T08:36:49.000Z | sdk/boost_1_30_0/libs/mpl/test/bind.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | sdk/boost_1_30_0/libs/mpl/test/bind.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | //-----------------------------------------------------------------------------
// boost mpl/test/bind.cpp source file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2001-02
// Peter Dimov, Aleksey Gurtovoy
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose 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
// supporting documentation. No representations are made about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
#include "boost/mpl/bind.hpp"
#include "boost/mpl/apply.hpp"
#include "boost/mpl/assert_is_same.hpp"
#include "boost/type_traits/is_same.hpp"
namespace mpl = boost::mpl;
namespace {
struct f1
{
template< typename T1 > struct apply
{
typedef T1 type;
};
};
struct f5
{
template< typename T1, typename T2, typename T3, typename T4, typename T5 >
struct apply
{
typedef T5 type;
};
};
} // namespace
int main()
{
using namespace mpl::placeholders;
typedef mpl::apply1< mpl::bind1<f1,_1>,int >::type r11;
typedef mpl::apply5< mpl::bind1<f1,_5>,void,void,void,void,int >::type r12;
BOOST_MPL_ASSERT_IS_SAME(r11,int);
BOOST_MPL_ASSERT_IS_SAME(r12,int);
typedef mpl::apply5< mpl::bind5<f5,_1,_2,_3,_4,_5>,void,void,void,void,int >::type r51;
typedef mpl::apply5< mpl::bind5<f5,_5,_4,_3,_2,_1>,int,void,void,void,void >::type r52;
BOOST_MPL_ASSERT_IS_SAME(r51,int);
BOOST_MPL_ASSERT_IS_SAME(r52,int);
return 0;
}
| 30.803279 | 92 | 0.61735 | acidicMercury8 |
ac3902e3a4f4960c4ea7542847291ca6dd6e151a | 533 | cpp | C++ | legacy/fpvlaptracker_bt/rssi.cpp | warhog/fpvlaptracker-firmware | f25afb3c88335acb9621f5b6dd7116bcf573c5ad | [
"MIT"
] | null | null | null | legacy/fpvlaptracker_bt/rssi.cpp | warhog/fpvlaptracker-firmware | f25afb3c88335acb9621f5b6dd7116bcf573c5ad | [
"MIT"
] | null | null | null | legacy/fpvlaptracker_bt/rssi.cpp | warhog/fpvlaptracker-firmware | f25afb3c88335acb9621f5b6dd7116bcf573c5ad | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "rssi.h"
Rssi::Rssi() {
pinMode(A0, INPUT);
}
void Rssi::process() {
this->currentRssiRawValue = this->measure();
this->filter();
}
unsigned int Rssi::scan() {
return this->measure();
}
void Rssi::filter() {
this->currentRssiValue = this->currentRssiValue * 0.75 + this->currentRssiRawValue * 0.25;
}
/**
* get current rssi strength
* @return
*/
unsigned int Rssi::measure() {
int rssi = analogRead(0) - this->getRssiOffset();
if (rssi < 0) {
rssi = 0;
}
return rssi;
}
| 16.65625 | 92 | 0.626642 | warhog |
ac3a57e78215357414f45e0fff0f3ca171d38dbc | 1,460 | hpp | C++ | src/single_thread_rlnc_benchmark/benchmark/write_result.hpp | AgileCloudLab/single-threaded-rlnc-benchmark | 914c18cf408d62f7294f796f386e98740d6fc83d | [
"MIT"
] | null | null | null | src/single_thread_rlnc_benchmark/benchmark/write_result.hpp | AgileCloudLab/single-threaded-rlnc-benchmark | 914c18cf408d62f7294f796f386e98740d6fc83d | [
"MIT"
] | null | null | null | src/single_thread_rlnc_benchmark/benchmark/write_result.hpp | AgileCloudLab/single-threaded-rlnc-benchmark | 914c18cf408d62f7294f796f386e98740d6fc83d | [
"MIT"
] | null | null | null | #pragma once
#include "result.hpp"
#include "../readers/config.hpp"
#include <string>
#include <sstream>
#include <ctime>
#include <iostream>
#include <fstream>
namespace standard_encoder
{
namespace benchmark
{
std::string generate_path(std::string result_path, std::string experiment_name, readers::config& config)
{
std::time_t t = std::time(nullptr);
auto timestamp = static_cast<uint64_t>(t);
std::stringstream ss;
ss << result_path << "/" << timestamp << "_" << experiment_name <<
"_" << config.threads() << "_" << config.generation_size() <<
"_" << config.symbol_size();
// Cast the content of ss to a string
return ss.str();
}
std::string convert_to_json_array(std::vector<result> results)
{
std::stringstream stream;
stream << "[" << std::endl;
for (uint32_t i = 0; i < results.size(); ++i)
{
stream << results.at(i).to_json_string();
if (i != results.size() - 1)
{
stream << ",";
}
stream << std::endl;
}
stream << "]";
return stream.str();
}
bool write_results(std::string file_path, std::vector<result> results)
{
std::ofstream result_file;
result_file.open(file_path);
result_file << convert_to_json_array(results);
result_file.close();
return true;
}
}
}
| 23.934426 | 108 | 0.557534 | AgileCloudLab |
ac3b15e8ee1531880f947fabf73ac11f76d28d6f | 1,204 | cpp | C++ | contests/leetcode-133/b.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | contests/leetcode-133/b.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | contests/leetcode-133/b.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
auto c = [r0, c0](pair<int, int> &pp1, pair<int, int> &pp2) -> bool{
int d1 = abs(pp1.first - r0) + abs(pp1.second - c0);
int d2 = abs(pp2.first - r0) + abs(pp2.second - c0);
return d1 < d2;
};
vector<pair<int, int> > vec;
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j)
vec.push_back(make_pair(i, j));
sort(vec.begin(), vec.end(), c);
vector<vector<int> > ans;
for (int i = 1; i < R * C; ++i){
vector<int> aa;
aa.push_back(vec[i].first);
aa.push_back(vec[i].second);
ans.push_back(aa);
}
return ans;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 25.617021 | 76 | 0.480897 | Nightwish-cn |
ac3cbec66042da19af26e2c3beb4897c0af24b74 | 34,855 | cpp | C++ | Core/burn/drv/galaxian/gal_gfx.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 17 | 2018-05-24T05:20:45.000Z | 2021-12-24T07:27:22.000Z | Core/burn/drv/galaxian/gal_gfx.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 6 | 2019-01-21T10:55:02.000Z | 2021-02-19T18:47:56.000Z | Core/burn/drv/galaxian/gal_gfx.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 5 | 2019-01-21T00:45:00.000Z | 2021-07-20T08:34:22.000Z | #include "gal.h"
GalRenderBackground GalRenderBackgroundFunction;
GalCalcPalette GalCalcPaletteFunction;
GalDrawBullet GalDrawBulletsFunction;
GalExtendTileInfo GalExtendTileInfoFunction;
GalExtendSpriteInfo GalExtendSpriteInfoFunction;
GalRenderFrame GalRenderFrameFunction;
UINT8 GalFlipScreenX;
UINT8 GalFlipScreenY;
UINT8 *GalGfxBank;
UINT8 GalPaletteBank;
UINT8 GalSpriteClipStart;
UINT8 GalSpriteClipEnd;
UINT8 FroggerAdjust;
UINT8 GalBackgroundRed;
UINT8 GalBackgroundGreen;
UINT8 GalBackgroundBlue;
UINT8 GalBackgroundEnable;
UINT8 SfxTilemap;
UINT8 GalOrientationFlipX;
UINT8 GalColourDepth;
UINT8 DarkplntBulletColour;
UINT8 DambustrBgColour1;
UINT8 DambustrBgColour2;
UINT8 DambustrBgPriority;
UINT8 DambustrBgSplitLine;
UINT8 *RockclimTiles;
UINT16 RockclimScrollX;
UINT16 RockclimScrollY;
// Graphics decode helpers
INT32 CharPlaneOffsets[2] = { 0, 0x4000 };
INT32 CharXOffsets[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
INT32 CharYOffsets[8] = { 0, 8, 16, 24, 32, 40, 48, 56 };
INT32 SpritePlaneOffsets[2] = { 0, 0x4000 };
INT32 SpriteXOffsets[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71 };
INT32 SpriteYOffsets[16] = { 0, 8, 16, 24, 32, 40, 48, 56, 128, 136, 144, 152, 160, 168, 176, 184 };
// Tile extend helpers
void UpperExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code += 0x100;
}
void PiscesExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code |= GalGfxBank[0] << 8;
}
void Batman2ExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
if (*Code & 0x80) *Code |= GalGfxBank[0] << 8;
}
void GmgalaxExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code |= GalGfxBank[0] << 9;
}
void MooncrstExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
if (GalGfxBank[2] && (*Code & 0xc0) == 0x80) *Code = (*Code & 0x3f) | (GalGfxBank[0] << 6) | (GalGfxBank[1] << 7) | 0x0100;
}
void MoonqsrExtendTileInfo(UINT16 *Code, INT32*, INT32 Attr, INT32)
{
*Code |= (Attr & 0x20) << 3;
}
void SkybaseExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code |= GalGfxBank[2] << 8;
}
void JumpbugExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
if ((*Code & 0xc0) == 0x80 && (GalGfxBank[2] & 0x01)) *Code += 128 + ((GalGfxBank[0] & 0x01) << 6) + ((GalGfxBank[1] & 0x01) << 7) + ((~GalGfxBank[4] & 0x01) << 8);
}
void FroggerExtendTileInfo(UINT16*, INT32 *Colour, INT32, INT32)
{
*Colour = ((*Colour >> 1) & 0x03) | ((*Colour << 2) & 0x04);
}
void MshuttleExtendTileInfo(UINT16 *Code, INT32*, INT32 Attr, INT32)
{
*Code |= (Attr & 0x30) << 4;
}
void Fourin1ExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code |= Fourin1Bank << 8;
}
void MarinerExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32 x)
{
UINT8 *Prom = GalProm + 0x120;
*Code |= (Prom[x] & 0x01) << 8;
}
void MimonkeyExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code |= (GalGfxBank[0] << 8) | (GalGfxBank[1] << 9);
}
void DambustrExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32 x)
{
if (GalGfxBank[0] == 0) {
*Code |= 0x300;
} else {
if (x == 28) {
*Code |= 0x300;
} else {
*Code &= 0xff;
}
}
}
void Ad2083ExtendTileInfo(UINT16 *Code, INT32 *Colour, INT32 Attr, INT32)
{
INT32 Bank = Attr & 0x30;
*Code |= (Bank << 4);
*Colour |= ((Attr & 0x40) >> 3);
}
void RacknrolExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32 x)
{
UINT8 Bank = GalGfxBank[x] & 7;
*Code |= Bank << 8;
}
void BagmanmcExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32)
{
*Code |= GalGfxBank[0] << 9;
}
// Sprite extend helpers
void UpperExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code += 0x40;
}
void PiscesExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= GalGfxBank[0] << 6;
}
void GmgalaxExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= (GalGfxBank[0] << 7) | 0x40;
}
void MooncrstExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
if (GalGfxBank[2] && (*Code & 0x30) == 0x20) *Code = (*Code & 0x0f) | (GalGfxBank[0] << 4) | (GalGfxBank[1] << 5) | 0x40;
}
void MoonqsrExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= (Base[2] & 0x20) << 1;
}
void SkybaseExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= GalGfxBank[2] << 6;
}
void RockclimExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
if (GalGfxBank[2]) *Code |= 0x40;
}
void JumpbugExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
if ((*Code & 0x30) == 0x20 && (GalGfxBank[2] & 0x01) != 0) *Code += 32 + ((GalGfxBank[0] & 0x01) << 4) + ((GalGfxBank[1] & 0x01) << 5) + ((~GalGfxBank[4] & 0x01) << 6);
}
void FroggerExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16*, UINT8 *Colour)
{
*Colour = ((*Colour >> 1) & 0x03) | ((*Colour << 2) & 0x04);
}
void CalipsoExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8 *xFlip, UINT8 *yFlip, UINT16 *Code, UINT8*)
{
*Code = Base[1];
*xFlip = 0;
*yFlip = 0;
}
void MshuttleExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= (Base[2] & 0x30) << 2;
}
void Fourin1ExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= Fourin1Bank << 6;
}
void DkongjrmExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8 *xFlip, UINT8*, UINT16 *Code, UINT8*)
{
*Code = (Base[1] & 0x7f) | 0x80;
*xFlip = 0;
}
void MimonkeyExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= (GalGfxBank[0] << 6) | (GalGfxBank[1] << 7);
}
void Ad2083ExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8 *xFlip, UINT8*, UINT16 *Code, UINT8*)
{
*Code = (Base[1] & 0x7f) | ((Base[2] & 0x30) << 2);
*xFlip = 0;
}
void BagmanmcExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*)
{
*Code |= (GalGfxBank[0] << 7) | 0x40;
}
// Hardcode a Galaxian PROM for any games that are missing a PROM dump
void HardCodeGalaxianPROM()
{
GalProm[0x00]= 0x00;
GalProm[0x01]= 0x00;
GalProm[0x02]= 0x00;
GalProm[0x03]= 0xf6;
GalProm[0x04]= 0x00;
GalProm[0x05]= 0x16;
GalProm[0x06]= 0xc0;
GalProm[0x07]= 0x3f;
GalProm[0x08]= 0x00;
GalProm[0x09]= 0xd8;
GalProm[0x0a]= 0x07;
GalProm[0x0b]= 0x3f;
GalProm[0x0c]= 0x00;
GalProm[0x0d]= 0xc0;
GalProm[0x0e]= 0xc4;
GalProm[0x0f]= 0x07;
GalProm[0x10]= 0x00;
GalProm[0x11]= 0xc0;
GalProm[0x12]= 0xa0;
GalProm[0x13]= 0x07;
GalProm[0x14]= 0x00;
GalProm[0x15]= 0x00;
GalProm[0x16]= 0x00;
GalProm[0x17]= 0x07;
GalProm[0x18]= 0x00;
GalProm[0x19]= 0xf6;
GalProm[0x1a]= 0x07;
GalProm[0x1b]= 0xf0;
GalProm[0x1c]= 0x00;
GalProm[0x1d]= 0x76;
GalProm[0x1e]= 0x07;
GalProm[0x1f]= 0xc6;
}
void HardCodeMooncrstPROM()
{
GalProm[0x00]= 0x00;
GalProm[0x01]= 0x7a;
GalProm[0x02]= 0x36;
GalProm[0x03]= 0x07;
GalProm[0x04]= 0x00;
GalProm[0x05]= 0xf0;
GalProm[0x06]= 0x38;
GalProm[0x07]= 0x1f;
GalProm[0x08]= 0x00;
GalProm[0x09]= 0xc7;
GalProm[0x0a]= 0xf0;
GalProm[0x0b]= 0x3f;
GalProm[0x0c]= 0x00;
GalProm[0x0d]= 0xdb;
GalProm[0x0e]= 0xc6;
GalProm[0x0f]= 0x38;
GalProm[0x10]= 0x00;
GalProm[0x11]= 0x36;
GalProm[0x12]= 0x07;
GalProm[0x13]= 0xf0;
GalProm[0x14]= 0x00;
GalProm[0x15]= 0x33;
GalProm[0x16]= 0x3f;
GalProm[0x17]= 0xdb;
GalProm[0x18]= 0x00;
GalProm[0x19]= 0x3f;
GalProm[0x1a]= 0x57;
GalProm[0x1b]= 0xc6;
GalProm[0x1c]= 0x00;
GalProm[0x1d]= 0xc6;
GalProm[0x1e]= 0x3f;
GalProm[0x1f]= 0xff;
}
// Pallet generation
#define RGB_MAXIMUM 224
#define MAX_NETS 3
#define MAX_RES_PER_NET 18
#define Combine2Weights(tab,w0,w1) ((INT32)(((tab)[0]*(w0) + (tab)[1]*(w1)) + 0.5))
#define Combine3Weights(tab,w0,w1,w2) ((INT32)(((tab)[0]*(w0) + (tab)[1]*(w1) + (tab)[2]*(w2)) + 0.5))
static double ComputeResistorWeights(INT32 MinVal, INT32 MaxVal, double Scaler, INT32 Count1, const INT32 *Resistances1, double *Weights1, INT32 PullDown1, INT32 PullUp1, INT32 Count2, const INT32 *Resistances2, double *Weights2, INT32 PullDown2, INT32 PullUp2, INT32 Count3, const INT32 *Resistances3, double *Weights3, INT32 PullDown3, INT32 PullUp3)
{
INT32 NetworksNum;
INT32 ResCount[MAX_NETS];
double r[MAX_NETS][MAX_RES_PER_NET];
double w[MAX_NETS][MAX_RES_PER_NET];
double ws[MAX_NETS][MAX_RES_PER_NET];
INT32 r_pd[MAX_NETS];
INT32 r_pu[MAX_NETS];
double MaxOut[MAX_NETS];
double *Out[MAX_NETS];
INT32 i, j, n;
double Scale;
double Max;
NetworksNum = 0;
for (n = 0; n < MAX_NETS; n++) {
INT32 Count, pd, pu;
const INT32 *Resistances;
double *Weights;
switch (n) {
case 0: {
Count = Count1;
Resistances = Resistances1;
Weights = Weights1;
pd = PullDown1;
pu = PullUp1;
break;
}
case 1: {
Count = Count2;
Resistances = Resistances2;
Weights = Weights2;
pd = PullDown2;
pu = PullUp2;
break;
}
case 2:
default: {
Count = Count3;
Resistances = Resistances3;
Weights = Weights3;
pd = PullDown3;
pu = PullUp3;
break;
}
}
if (Count > 0) {
ResCount[NetworksNum] = Count;
for (i = 0; i < Count; i++) {
r[NetworksNum][i] = 1.0 * Resistances[i];
}
Out[NetworksNum] = Weights;
r_pd[NetworksNum] = pd;
r_pu[NetworksNum] = pu;
NetworksNum++;
}
}
for (i = 0; i < NetworksNum; i++) {
double R0, R1, Vout, Dst;
for (n = 0; n < ResCount[i]; n++) {
R0 = (r_pd[i] == 0) ? 1.0 / 1e12 : 1.0 / r_pd[i];
R1 = (r_pu[i] == 0) ? 1.0 / 1e12 : 1.0 / r_pu[i];
for (j = 0; j < ResCount[i]; j++) {
if (j == n) {
if (r[i][j] != 0.0) R1 += 1.0 / r[i][j];
} else {
if (r[i][j] != 0.0) R0 += 1.0 / r[i][j];
}
}
R0 = 1.0/R0;
R1 = 1.0/R1;
Vout = (MaxVal - MinVal) * R0 / (R1 + R0) + MinVal;
Dst = (Vout < MinVal) ? MinVal : (Vout > MaxVal) ? MaxVal : Vout;
w[i][n] = Dst;
}
}
j = 0;
Max = 0.0;
for (i = 0; i < NetworksNum; i++) {
double Sum = 0.0;
for (n = 0; n < ResCount[i]; n++) Sum += w[i][n];
MaxOut[i] = Sum;
if (Max < Sum) {
Max = Sum;
j = i;
}
}
if (Scaler < 0.0) {
Scale = ((double)MaxVal) / MaxOut[j];
} else {
Scale = Scaler;
}
for (i = 0; i < NetworksNum; i++) {
for (n = 0; n < ResCount[i]; n++) {
ws[i][n] = w[i][n] * Scale;
(Out[i])[n] = ws[i][n];
}
}
return Scale;
}
void GalaxianCalcPalette()
{
static const INT32 RGBResistances[3] = {1000, 470, 220};
double rWeights[3], gWeights[3], bWeights[2];
ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0);
// Colour PROM
for (INT32 i = 0; i < 32; i++) {
UINT8 Bit0, Bit1, Bit2, r, g, b;
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2);
r = Combine3Weights(rWeights, Bit0, Bit1, Bit2);
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5);
g = Combine3Weights(gWeights, Bit0, Bit1, Bit2);
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],6);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],7);
b = Combine2Weights(bWeights, Bit0, Bit1);
GalPalette[i] = BurnHighCol(r, g, b, 0);
}
// Stars
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) {
INT32 Bits, r, g, b;
INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff};
Bits = (i >> 0) & 0x03;
r = Map[Bits];
Bits = (i >> 2) & 0x03;
g = Map[Bits];
Bits = (i >> 4) & 0x03;
b = Map[Bits];
GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0);
}
// Bullets
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_BULLETS - 1; i++) {
GalPalette[i + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0xff, 0);
}
GalPalette[GAL_PALETTE_NUM_COLOURS_BULLETS - 1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0x00, 0);
}
void RockclimCalcPalette()
{
static const INT32 RGBResistances[3] = {1000, 470, 220};
double rWeights[3], gWeights[3], bWeights[2];
ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0);
// Colour PROM
for (INT32 i = 0; i < 64; i++) {
UINT8 Bit0, Bit1, Bit2, r, g, b;
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2);
r = Combine3Weights(rWeights, Bit0, Bit1, Bit2);
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5);
g = Combine3Weights(gWeights, Bit0, Bit1, Bit2);
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],6);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],7);
b = Combine2Weights(bWeights, Bit0, Bit1);
GalPalette[i] = BurnHighCol(r, g, b, 0);
}
// Stars
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) {
INT32 Bits, r, g, b;
INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff};
Bits = (i >> 0) & 0x03;
r = Map[Bits];
Bits = (i >> 2) & 0x03;
g = Map[Bits];
Bits = (i >> 4) & 0x03;
b = Map[Bits];
GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0);
}
// Bullets
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_BULLETS - 1; i++) {
GalPalette[i + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0xff, 0);
}
GalPalette[GAL_PALETTE_NUM_COLOURS_BULLETS - 1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0x00, 0);
}
void MarinerCalcPalette()
{
GalaxianCalcPalette();
for (INT32 i = 0; i < 16; i++) {
INT32 b = 0x0e * BIT(i, 0) + 0x1f * BIT(i, 1) + 0x43 * BIT(i, 2) + 0x8f * BIT(i, 3);
GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, b, 0);
}
}
void StratgyxCalcPalette()
{
GalaxianCalcPalette();
for (INT32 i = 0; i < 8; i++) {
INT32 r = BIT(i, 0) * 0x7c;
INT32 g = BIT(i, 1) * 0x3c;
INT32 b = BIT(i, 2) * 0x47;
GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(r, g, b, 0);
}
}
void RescueCalcPalette()
{
GalaxianCalcPalette();
for (INT32 i = 0; i < 128; i++) {
INT32 b = i * 2;
GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, b, 0);
}
}
void MinefldCalcPalette()
{
RescueCalcPalette();
for (INT32 i = 0; i < 128; i++) {
INT32 r = (INT32)(i * 1.5);
INT32 g = (INT32)(i * 0.75);
INT32 b = i / 2;
GalPalette[i + 128 + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(r, g, b, 0);
}
}
void DarkplntCalcPalette()
{
static const INT32 RGBResistances[3] = {1000, 470, 220};
double rWeights[3], gWeights[3], bWeights[2];
ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0);
// Colour PROM
for (INT32 i = 0; i < 32; i++) {
UINT8 Bit0, Bit1, Bit2, r, g, b;
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2);
r = Combine3Weights(rWeights, Bit0, Bit1, Bit2);
g = 0;
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5);
b = Combine2Weights(bWeights, Bit0, Bit1);
GalPalette[i] = BurnHighCol(r, g, b, 0);
}
// Stars
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) {
INT32 Bits, r, g, b;
INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff};
Bits = (i >> 0) & 0x03;
r = Map[Bits];
Bits = (i >> 2) & 0x03;
g = Map[Bits];
Bits = (i >> 4) & 0x03;
b = Map[Bits];
GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0);
}
// Bullets
GalPalette[0 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xef, 0x00, 0x00, 0);
GalPalette[1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0x00, 0x00, 0xef, 0);
}
void DambustrCalcPalette()
{
static const INT32 RGBResistances[3] = {1000, 470, 220};
double rWeights[3], gWeights[3], bWeights[2];
ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0);
// Colour PROM
for (INT32 i = 0; i < 32; i++) {
UINT8 Bit0, Bit1, Bit2, r, g, b;
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2);
b = Combine3Weights(rWeights, Bit0, Bit1, Bit2);
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4);
Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5);
r = Combine3Weights(gWeights, Bit0, Bit1, Bit2);
Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],6);
Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],7);
g = Combine2Weights(bWeights, Bit0, Bit1);
GalPalette[i] = BurnHighCol(r, g, b, 0);
}
// Stars
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) {
INT32 Bits, r, g, b;
INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff};
Bits = (i >> 0) & 0x03;
r = Map[Bits];
Bits = (i >> 2) & 0x03;
g = Map[Bits];
Bits = (i >> 4) & 0x03;
b = Map[Bits];
GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0);
}
// Bullets
for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_BULLETS - 1; i++) {
GalPalette[i + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0xff, 0);
}
GalPalette[GAL_PALETTE_NUM_COLOURS_BULLETS - 1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0x00, 0);
for (INT32 i = 0; i < 8; i++) {
INT32 r = BIT(i, 0) * 0x47;
INT32 g = BIT(i, 1) * 0x47;
INT32 b = BIT(i, 2) * 0x4f;
GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(r, g, b, 0);
}
}
#undef RGB_MAXIMUM
#undef MAX_NETS
#undef MAX_RES_PER_NET
#undef Combine_2Weights
#undef Combine_3Weights
// Background and Stars rendering
void GalaxianDrawBackground()
{
if (GalStarsEnable) GalaxianRenderStarLayer();
}
void RockclimDrawBackground()
{
INT32 mx, my, Code, Colour, x, y, TileIndex = 0;
for (my = 0; my < 32; my++) {
for (mx = 0; mx < 64; mx++) {
Code = GalVideoRam2[TileIndex];
Colour = 0;
x = 8 * mx;
y = 8 * my;
x -= RockclimScrollX & 0x1ff;
y -= RockclimScrollY & 0xff;
if (x < -8) x += 512;
if (y < -8) y += 256;
y -= 16;
if (x > 8 && x < (nScreenWidth - 8) && y > 8 && y < (nScreenHeight - 8)) {
Render8x8Tile(pTransDraw, Code, x, y, Colour, 4, 32, RockclimTiles);
} else {
Render8x8Tile_Clip(pTransDraw, Code, x, y, Colour, 4, 32, RockclimTiles);
}
TileIndex++;
}
}
}
void JumpbugDrawBackground()
{
if (GalStarsEnable) JumpbugRenderStarLayer();
}
void FroggerDrawBackground()
{
GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, 0x47, 0);
if (GalFlipScreenX) {
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = nScreenWidth - 1; x > 128 - 8; x--) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
} else {
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = 0; x < 128 + 8; x++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
}
}
void TurtlesDrawBackground()
{
GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(GalBackgroundRed * 0x55, GalBackgroundGreen * 0x47, GalBackgroundBlue * 0x55, 0);
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = 0; x < nScreenWidth; x++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
}
void ScrambleDrawBackground()
{
GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, 0x56, 0);
if (GalBackgroundEnable) {
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = 0; x < nScreenWidth; x++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
}
if (GalStarsEnable) ScrambleRenderStarLayer();
}
void AnteaterDrawBackground()
{
GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, 0x56, 0);
if (GalBackgroundEnable) {
if (GalFlipScreenX) {
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = nScreenWidth - 1; x > 256 - 56; x--) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
} else {
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = 0; x < 56; x++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
}
}
}
void MarinerDrawBackground()
{
UINT8 *BgColourProm = GalProm + 0x20;
INT32 x;
if (GalFlipScreenX) {
for (x = 0; x < 32; x++) {
INT32 Colour;
if (x == 0) {
Colour = 0;
} else {
Colour = BgColourProm[0x20 + x - 1];
}
INT32 xStart = 8 * (31 - x);
for (INT32 sy = 0; sy < nScreenHeight; sy++) {
for (INT32 sx = xStart; sx < xStart + 8; sx++) {
pTransDraw[(sy * nScreenWidth) + sx] = GAL_PALETTE_BACKGROUND_OFFSET + Colour;
}
}
}
} else {
for (x = 0; x < 32; x++) {
INT32 Colour;
if (x == 31) {
Colour = 0;
} else {
Colour = BgColourProm[x + 1];
}
INT32 xStart = x * 8;
for (INT32 sy = 0; sy < nScreenHeight; sy++) {
for (INT32 sx = xStart; sx < xStart + 8; sx++) {
pTransDraw[(sy * nScreenWidth) + sx] = GAL_PALETTE_BACKGROUND_OFFSET + Colour;
}
}
}
}
if (GalStarsEnable) MarinerRenderStarLayer();
}
void StratgyxDrawBackground()
{
UINT8 *BgColourProm = GalProm + 0x20;
for (INT32 x = 0; x < 32; x++) {
INT32 xStart, Colour = 0;
if ((~BgColourProm[x] & 0x02) && GalBackgroundRed) Colour |= 0x01;
if ((~BgColourProm[x] & 0x02) && GalBackgroundGreen) Colour |= 0x02;
if ((~BgColourProm[x] & 0x01) && GalBackgroundBlue) Colour |= 0x04;
if (GalFlipScreenX) {
xStart = 8 * (31 - x);
} else {
xStart = 8 * x;
}
for (INT32 sy = 0; sy < nScreenHeight; sy++) {
for (INT32 sx = xStart; sx < xStart + 8; sx++) {
pTransDraw[(sy * nScreenWidth) + sx] = GAL_PALETTE_BACKGROUND_OFFSET + Colour;
}
}
}
}
void RescueDrawBackground()
{
if (GalBackgroundEnable) {
INT32 x;
for (x = 0; x < 128; x++) {
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + x;
}
}
for (x = 0; x < 120; x++) {
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + (x + 128)] = GAL_PALETTE_BACKGROUND_OFFSET + x + 8;
}
}
for (x = 0; x < 8; x++) {
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + (x + 248)] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
}
if (GalStarsEnable) RescueRenderStarLayer();
}
void MinefldDrawBackground()
{
if (GalBackgroundEnable) {
INT32 x;
for (x = 0; x < 128; x++) {
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + x;
}
}
for (x = 0; x < 120; x++) {
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + (x + 128)] = GAL_PALETTE_BACKGROUND_OFFSET + x + 128;
}
}
for (x = 0; x < 8; x++) {
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + (x + 248)] = GAL_PALETTE_BACKGROUND_OFFSET;
}
}
}
if (GalStarsEnable) RescueRenderStarLayer();
}
void DambustrDrawBackground()
{
INT32 xClipStart = GalFlipScreenX ? 254 - DambustrBgSplitLine : 0;
INT32 xClipEnd = GalFlipScreenX ? 0 : 254 - DambustrBgSplitLine;
for (INT32 x = 0; x < 256 - DambustrBgSplitLine; x++) {
if (DambustrBgPriority && (x < xClipStart || x > xClipEnd)) continue;
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + ((GalFlipScreenX) ? DambustrBgColour2 : DambustrBgColour1);
}
}
for (INT32 x = 255; x > 256 - DambustrBgSplitLine; x--) {
if (DambustrBgPriority && (x < xClipStart || x > xClipEnd)) continue;
for (INT32 y = 0; y < nScreenHeight; y++) {
pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + ((GalFlipScreenX) ? DambustrBgColour1 : DambustrBgColour2);
}
}
if (GalStarsEnable && !DambustrBgPriority) GalaxianRenderStarLayer();
}
// Char Layer rendering
static void GalRenderBgLayer(UINT8 *pVideoRam)
{
INT32 mx, my, Attr, Colour, x, y, TileIndex = 0, RamPos;
UINT16 Code;
for (my = 0; my < 32; my++) {
for (mx = 0; mx < 32; mx++) {
RamPos = TileIndex & 0x1f;
Code = pVideoRam[TileIndex];
Attr = GalSpriteRam[(RamPos * 2) + 1];
Colour = Attr & ((GalColourDepth == 3) ? 0x03 : 0x07);
if (GalExtendTileInfoFunction) GalExtendTileInfoFunction(&Code, &Colour, Attr, RamPos);
if (SfxTilemap) {
x = 8 * my;
y = 8 * mx;
} else {
x = 8 * mx;
y = 8 * my;
}
y -= 16;
if (GalFlipScreenX) x = nScreenWidth - 8 - x;
if (GalFlipScreenY) y = nScreenHeight - 8 - y;
INT32 px, py;
UINT32 nPalette = Colour << GalColourDepth;
for (py = 0; py < 8; py++) {
for (px = 0; px < 8; px++) {
UINT8 c = GalChars[(Code * 64) + (py * 8) + px];
if (GalFlipScreenX) c = GalChars[(Code * 64) + (py * 8) + (7 - px)];
if (GalFlipScreenY) c = GalChars[(Code * 64) + ((7 - py) * 8) + px];
if (GalFlipScreenX && GalFlipScreenY) c = GalChars[(Code * 64) + ((7 - py) * 8) + (7 - px)];
if (c) {
INT32 xPos = x + px;
INT32 yPos = y + py;
if (SfxTilemap) {
if (GalFlipScreenX) {
xPos += GalScrollVals[mx];
} else {
xPos -= GalScrollVals[mx];
}
if (xPos < 0) xPos += 256;
if (xPos > 255) xPos -= 256;
} else {
if (GalFlipScreenY) {
yPos += GalScrollVals[mx];
} else {
yPos -= GalScrollVals[mx];
}
if (yPos < 0) yPos += 256;
if (yPos > 255) yPos -= 256;
}
if (GalOrientationFlipX) {
xPos = nScreenWidth - 1 - xPos;
}
if (yPos >= 0 && yPos < nScreenHeight) {
UINT16* pPixel = pTransDraw + (yPos * nScreenWidth);
if (xPos >= 0 && xPos < nScreenWidth) {
pPixel[xPos] = c | nPalette;
}
}
}
}
}
TileIndex++;
}
}
}
// Sprite Rendering
static void GalRenderSprites(const UINT8 *SpriteBase)
{
INT32 SprNum;
INT32 ClipOfs = GalFlipScreenX ? 16 : 0;
INT32 xMin = GalSpriteClipStart - ClipOfs;
INT32 xMax = GalSpriteClipEnd - ClipOfs + 1;
for (SprNum = 7; SprNum >= 0; SprNum--) {
const UINT8 *Base = &SpriteBase[SprNum * 4];
UINT8 Base0 = FroggerAdjust ? ((Base[0] >> 4) | (Base[0] << 4)) : Base[0];
INT32 sy = 240 - (Base0 - (SprNum < 3));
UINT16 Code = Base[1] & 0x3f;
UINT8 xFlip = Base[1] & 0x40;
UINT8 yFlip = Base[1] & 0x80;
UINT8 Colour = Base[2] & ((GalColourDepth == 3) ? 0x03 : 0x07);
INT32 sx = Base[3];
if (GalExtendSpriteInfoFunction) GalExtendSpriteInfoFunction(Base, &sx, &sy, &xFlip, &yFlip, &Code, &Colour);
if (GalFlipScreenX) {
sx = 242 - sx;
xFlip = !xFlip;
}
if (sx < xMin || sx > xMax) continue;
if (GalFlipScreenY) {
sy = 240 - sy;
yFlip = !yFlip;
}
sy -= 16;
if (GalOrientationFlipX) {
sx = 242 - 1 - sx;
xFlip = !xFlip;
}
if (sx > 16 && sx < (nScreenWidth - 16) && sy > 16 && sy < (nScreenHeight - 16)) {
if (xFlip) {
if (yFlip) {
Render16x16Tile_Mask_FlipXY(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
} else {
Render16x16Tile_Mask_FlipX(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
}
} else {
if (yFlip) {
Render16x16Tile_Mask_FlipY(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
} else {
Render16x16Tile_Mask(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
}
}
} else {
if (xFlip) {
if (yFlip) {
Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
} else {
Render16x16Tile_Mask_FlipX_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
}
} else {
if (yFlip) {
Render16x16Tile_Mask_FlipY_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
} else {
Render16x16Tile_Mask_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites);
}
}
}
}
}
// Bullet rendering
static inline void GalDrawPixel(INT32 x, INT32 y, INT32 Colour)
{
if (y >= 0 && y < nScreenHeight && x >= 0 && x < nScreenWidth) {
pTransDraw[(y * nScreenWidth) + x] = Colour;
}
}
void GalaxianDrawBullets(INT32 Offs, INT32 x, INT32 y)
{
x -= 4;
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
}
void TheendDrawBullets(INT32 Offs, INT32 x, INT32 y)
{
x -= 4;
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 7] = BurnHighCol(0xff, 0x00, 0xff, 0);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs);
}
void ScrambleDrawBullets(INT32, INT32 x, INT32 y)
{
x -= 6;
GalDrawPixel(x, y, GAL_PALETTE_BULLETS_OFFSET + 7);
}
void MoonwarDrawBullets(INT32, INT32 x, INT32 y)
{
x -= 6;
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 7] = BurnHighCol(0xef, 0xef, 0x97, 0);
GalDrawPixel(x, y, GAL_PALETTE_BULLETS_OFFSET + 7);
}
void MshuttleDrawBullets(INT32, INT32 x, INT32 y)
{
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 0] = BurnHighCol(0xff, 0xff, 0xff, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 1] = BurnHighCol(0xff, 0xff, 0x00, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 2] = BurnHighCol(0x00, 0xff, 0xff, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 3] = BurnHighCol(0x00, 0xff, 0x00, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 4] = BurnHighCol(0xff, 0x00, 0xff, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 5] = BurnHighCol(0xff, 0x00, 0x00, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 6] = BurnHighCol(0x00, 0x00, 0xff, 0);
GalPalette[GAL_PALETTE_BULLETS_OFFSET + 7] = BurnHighCol(0x00, 0x00, 0x00, 0);
--x;
GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4);
--x;
GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4);
--x;
GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4);
--x;
GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4);
}
void DarkplntDrawBullets(INT32, INT32 x, INT32 y)
{
if (GalFlipScreenX) x++;
x -= 6;
GalDrawPixel(x, y, GAL_PALETTE_BULLETS_OFFSET + DarkplntBulletColour);
}
void DambustrDrawBullets(INT32 Offs, INT32 x, INT32 y)
{
INT32 Colour;
if (GalFlipScreenX) x++;
x -= 6;
for (INT32 i = 0; i < 2; i++) {
if (Offs < 16) {
Colour = GAL_PALETTE_BULLETS_OFFSET + 7;
y--;
} else {
Colour = GAL_PALETTE_BULLETS_OFFSET;
x--;
}
}
GalDrawPixel(x, y, Colour);
}
static void GalDrawBullets(const UINT8 *Base)
{
for (INT32 y = 0; y < nScreenHeight; y++) {
UINT8 Shell = 0xff;
UINT8 Missile = 0xff;
UINT8 yEff;
INT32 Which;
yEff = (GalFlipScreenY) ? (y + 16 - 1) ^ 255 : y + 16 - 1;
for (Which = 0; Which < 3; Which++) {
if ((UINT8)(Base[Which * 4 + 1] + yEff) == 0xff) Shell = Which;
}
yEff = (GalFlipScreenY) ? (y + 16) ^ 255 : y + 16;
for (Which = 3; Which < 8; Which++) {
if ((UINT8)(Base[Which * 4 + 1] + yEff) == 0xff) {
if (Which != 7) {
Shell = Which;
} else {
Missile = Which;
}
}
}
if (Shell != 0xff) GalDrawBulletsFunction(Shell, (GalOrientationFlipX) ? Base[Shell * 4 + 3] : 255 - Base[Shell * 4 + 3], y);
if (Missile != 0xff) GalDrawBulletsFunction(Missile, (GalOrientationFlipX) ? Base[Missile * 4 + 3] : 255 - Base[Missile * 4 + 3], y);
}
}
// Render a frame
void GalDraw()
{
if (GalRenderFrameFunction) {
GalRenderFrameFunction();
} else {
BurnTransferClear();
GalCalcPaletteFunction();
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
GalRenderBgLayer(GalVideoRam);
GalRenderSprites(&GalSpriteRam[0x40]);
if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0x60]);
BurnTransferCopy(GalPalette);
}
}
void DkongjrmRenderFrame()
{
BurnTransferClear();
GalCalcPaletteFunction();
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
GalRenderBgLayer(GalVideoRam);
GalRenderSprites(&GalSpriteRam[0x40]);
GalRenderSprites(&GalSpriteRam[0x60]);
GalRenderSprites(&GalSpriteRam[0xc0]);
GalRenderSprites(&GalSpriteRam[0xe0]);
if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0x60]);
BurnTransferCopy(GalPalette);
}
void DambustrRenderFrame()
{
BurnTransferClear();
GalCalcPaletteFunction();
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
GalRenderBgLayer(GalVideoRam);
GalRenderSprites(&GalSpriteRam[0x40]);
if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0x60]);
if (DambustrBgPriority) {
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
memset(GalVideoRam2, 0x20, 0x400);
for (INT32 i = 0; i < 32; i++) {
INT32 Colour = GalSpriteRam[(i << 1) | 1] & 7;
if (Colour > 3) {
for (INT32 j = 0; j < 32; j++) GalVideoRam2[(32 * j) + i] = GalVideoRam[(32 * j) + i];
}
}
GalRenderBgLayer(GalVideoRam2);
}
BurnTransferCopy(GalPalette);
}
void FantastcRenderFrame()
{
BurnTransferClear();
GalCalcPaletteFunction();
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
GalRenderBgLayer(GalVideoRam);
GalRenderSprites(&GalSpriteRam[0x40]);
if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0xc0]);
BurnTransferCopy(GalPalette);
}
void TimefgtrRenderFrame()
{
BurnTransferClear();
GalCalcPaletteFunction();
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
GalRenderBgLayer(GalVideoRam);
GalRenderSprites(&GalSpriteRam[0x040]); // MAME renders different sprite ram areas depending on screen-area - necessary?
GalRenderSprites(&GalSpriteRam[0x140]);
GalRenderSprites(&GalSpriteRam[0x240]);
GalRenderSprites(&GalSpriteRam[0x340]);
if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0xc0]);
BurnTransferCopy(GalPalette);
}
void ScramblerRenderFrame()
{
BurnTransferClear();
GalCalcPaletteFunction();
if (GalRenderBackgroundFunction) GalRenderBackgroundFunction();
GalRenderBgLayer(GalVideoRam);
GalRenderSprites(&GalSpriteRam[0xc0]);
if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0xe0]);
BurnTransferCopy(GalPalette);
}
| 26.770353 | 352 | 0.634887 | atship |
ac3daf335b0abcbfae8f308c03102d18ca19722a | 8,174 | cpp | C++ | src/componentLib/websocketServer/WebsocketServer.cpp | tangtgithub/common_robotframe | f098d688bde1d2b2d5d6fac430c98b952621b7c1 | [
"MIT"
] | 5 | 2021-07-21T11:38:09.000Z | 2021-11-26T03:16:09.000Z | src/componentLib/websocketServer/WebsocketServer.cpp | tangtgithub/common_robotframe | f098d688bde1d2b2d5d6fac430c98b952621b7c1 | [
"MIT"
] | null | null | null | src/componentLib/websocketServer/WebsocketServer.cpp | tangtgithub/common_robotframe | f098d688bde1d2b2d5d6fac430c98b952621b7c1 | [
"MIT"
] | null | null | null | #include "WebsocketServer.h"
#include <sys/prctl.h>
#include <chrono>
#include "websocketServerCommon.h"
#include "UdpServerWs.h"
#include "UdpClientWs.h"
WebsocketServer::WebsocketServer()
: m_sessionid(0)
{
m_server.set_access_channels(websocketpp::log::alevel::none);
m_server.init_asio();
m_server.set_open_handler(bind(&WebsocketServer::onOpen, this, ::_1));
m_server.set_close_handler(bind(&WebsocketServer::onClose, this, ::_1));
m_server.set_message_handler(bind(&WebsocketServer::onMessage, this, ::_1, ::_2));
}
WebsocketServer::~WebsocketServer()
{
}
void WebsocketServer::onOpen(connection_hdl hdl)
{
ConnectionData data;
{
std::lock_guard<std::mutex> guard(m_connectMutex);
if (m_connections.size() > 10)
{
m_server.close(hdl, 0, "timeout");
SPDLOG_ERROR("too much connection,forbid new connect.close this connection");
return;
}
data.sessionid = ++m_sessionid;
data.timeLastHeart = time(NULL);
if (m_sessionid >= 60)
m_sessionid = 0;
m_connections[hdl] = data;
SPDLOG_INFO("connect success,sessionid:{}", m_sessionid);
}
if(m_onOpenCb)
{
m_onOpenCb(data.sessionid);
}
}
void WebsocketServer::onClose(connection_hdl hdl)
{
try {
std::lock_guard<std::mutex> guard(m_connectMutex);
ConnectionData data = getDataFromConnHandle(hdl);
SPDLOG_INFO("close connection success,sessionid:{}", data.sessionid);
m_connections.erase(hdl);
if (m_onCloseCb)
m_onCloseCb(data.sessionid);
}
catch (std::invalid_argument &info) {
SPDLOG_INFO("close connection success");
}
catch (...)
{
SPDLOG_ERROR("other error");
}
}
ConnectionData WebsocketServer::getDataFromConnHandle(connection_hdl hdl)
{
auto it = m_connections.find(hdl);
if (it == m_connections.end())
{
// this connection is not in the list. This really shouldn't happen
// and probably means something else is wrong.
throw std::invalid_argument("No data available for session");
}
return it->second;
}
connection_hdl WebsocketServer::getHandleFromSessionId(int sessionId)
{
for (auto it = m_connections.begin(); it != m_connections.end(); it++)
{
if (it->second.sessionid == sessionId)
return it->first;
}
throw std::invalid_argument("No data available for session");
}
void WebsocketServer::onMessage(connection_hdl hdl, message_ptr msg)
{
MsgHandler msgHandler;
try {
ConnectionData data;
{
std::lock_guard<std::mutex> guard(m_connectMutex);
data = getDataFromConnHandle(hdl);
}
memcpy(&msgHandler, &data, sizeof(ConnectionData));
msgHandler.msg = msg->get_payload();
std::lock_guard<std::mutex> guard(m_msgMutex);
m_msgs.push_back(msgHandler);
cvMsg.notify_all();
//Debug << "通知处理线程收到数据\n";
}
catch (std::invalid_argument &info) {
//nonexistent
SPDLOG_ERROR("warn:receive unexpected info,connection abnormal");
}
catch (...)
{
SPDLOG_ERROR("other error");
}
}
int WebsocketServer::startServer()
{
std::thread recvThread(&WebsocketServer::run, this);
std::thread monitorThread(&WebsocketServer::monitorHeart, this);
std::thread handleMsgThread(&WebsocketServer::handleMsg, this);
std::thread serverIpThread(&WebsocketServer::serverIpBroadcast, this);
recvThread.detach();
monitorThread.detach();
handleMsgThread.detach();
serverIpThread.detach();
return SUCCESS;
}
void WebsocketServer::serverIpBroadcast()
{
prctl(PR_SET_NAME, "serverIpBroadcast");
UdpClient udpClient;
UdpServer udpServer;
udpClient.initClient(kServerBroadcastPort);
udpServer.initServer(kAppBroadcastPort);
while (1)
{
char buf[100] = { 0 };
char sendBuf[] = "res_server_ip";
std::string strIp;
if (udpServer.readData(buf, sizeof(buf) - 1, strIp))
{
continue;
}
if (!strncmp(buf, "query_server_ip", sizeof("query_server_ip")))
{
udpClient.writeData(sendBuf, static_cast<int>(strlen(sendBuf)), strIp, kServerBroadcastPort);
SPDLOG_INFO("receive query_server_ip,send res_server_ip");
}
}
}
int WebsocketServer::run()
{
try {
m_server.set_reuse_addr(true);
m_server.listen(12236);
// Start the server accept loop
m_server.start_accept();
// Start the ASIO io_service run loop
m_server.run();
}
catch (websocketpp::exception const& e) {
std::cout << e.what() << std::endl;
return FAILURE;
}
catch (...)
{
SPDLOG_ERROR("other exception");
return FAILURE;
}
return FAILURE;
}
void WebsocketServer::monitorHeart()
{
prctl(PR_SET_NAME, "websocketSerMonitorHeart");
time_t now;
while (1)
{
now = time(nullptr);
{
std::lock_guard<std::mutex> guard(m_connectMutex);
for (auto it = m_connections.begin(); it != m_connections.end();)
{
if (now - it->second.timeLastHeart > 20)//超时未收到心跳,关闭连接
{
SPDLOG_ERROR("heartbeat timeout,close connection,sessionid:{}", it->second.sessionid);
m_server.pause_reading(it->first);
m_server.close(it->first, 0, "timeout");
if (m_onCloseCb)
m_onCloseCb(it->second.sessionid);
m_connections.erase(it++);
}
else
it++;
}
}
sleep(5);
}
}
void WebsocketServer::handleMsg()
{
prctl(PR_SET_NAME, "websocketSerMsgHandle");
while (1)
{
MsgHandler msgHandler;
{
std::unique_lock<std::mutex> lock(m_msgMutex);
while (m_msgs.empty())
{
cvMsg.wait(lock);
}
auto x = m_msgs.front();
msgHandler.connData.sessionid = x.connData.sessionid;
msgHandler.msg = x.msg;
m_msgs.pop_front();
}
if (m_onMsgCb)
m_onMsgCb(msgHandler.connData.sessionid, msgHandler.msg);
}
}
/*
* 功能:发送消息给ws客户端
* 参数:
* 备注:如果需要打印发送的消息请填正确填写type,否则可不传递type值
* 示例:sendMsg(1000,"hello",11011)//打印发送的消息
* 示例:sendMsg(1000,"hello")//不打印发送的消息
*/
void WebsocketServer::sendMsg(int sessionId, std::string& res, int type)
{
int idAct = sessionId / kMultiplyNum;
connection_hdl hdl;
SPDLOG_DEBUG("res to app/screen,msg={}", res);
if (type != 0)
{
if (res.size() < 700)
{
SPDLOG_INFO("res to app/screen,msg={}", res);
}
else
{
SPDLOG_INFO("res to app/screen,msg= The first 300 characters: {}", res.substr(0, 300));
SPDLOG_INFO("res to app/screen,msg= The last 300 characters: {}", res.substr(res.size() - 301, 300));
}
}
try {
std::lock_guard<std::mutex> guard(m_connectMutex);
hdl = getHandleFromSessionId(idAct);
m_server.send(hdl, res, websocketpp::frame::opcode::value::text);
}
catch (std::invalid_argument& info) {
SPDLOG_ERROR("unrecognized sessionId,sessionId{} type {},msg{}", sessionId, type, info.what());
}
catch (std::exception& e)
{
SPDLOG_ERROR("websocketpp-send:{}", e.what());
}
catch (...)
{
SPDLOG_ERROR("websocketpp-send error");
}
}
void WebsocketServer::sendMsg2AllSessions(std::string& res)
{
SPDLOG_DEBUG("res to app/screen,msg={}", res);
try {
std::lock_guard<std::mutex> guard(m_connectMutex);
for (const auto& kv : m_connections)
{
m_server.send(kv.first, res, websocketpp::frame::opcode::value::text);
}
}
catch (std::exception& e)
{
SPDLOG_ERROR("websocketpp-send:{}", e.what());
}
catch (...)
{
SPDLOG_ERROR("websocketpp-send error");
}
}
| 25.867089 | 114 | 0.596036 | tangtgithub |
ac3f4f2db1413e6bb9307ec9355a83fe890d468a | 4,665 | cpp | C++ | src/sources/colorschemes.cpp | Amuwa/TeXpen | d0d7ae74463f88980beb8ceb2958182ac2df021e | [
"MIT"
] | 5 | 2019-03-04T08:47:52.000Z | 2022-01-28T12:53:55.000Z | src/sources/colorschemes.cpp | Amuwa/TeXpen | d0d7ae74463f88980beb8ceb2958182ac2df021e | [
"MIT"
] | 3 | 2019-02-22T05:41:49.000Z | 2020-03-16T13:37:23.000Z | src/sources/colorschemes.cpp | Amuwa/TeXpen | d0d7ae74463f88980beb8ceb2958182ac2df021e | [
"MIT"
] | 7 | 2019-02-22T06:04:13.000Z | 2022-01-28T12:54:15.000Z | // Copyright (C) 2013 Alex-97
// This file is part of textpad-editor.
//
// textpad-editor is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// textpad-editor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with textpad-editor. If not, see <http://www.gnu.org/licenses/>.
#include "headers/mainwindow.h"
#include <QAction>
QString commentColor="#aaffaa";
void MainWindow::CreateStyle(int SelectedTheme) {
Settings.ColorScheme = SelectedTheme;
QString Color;
QString BackgroundColor;
QString SelectionColor;
QString SelectionBackgroundColor;
QString StyleSheet;
switch (Settings.ColorScheme) {
case 1:
// This is the "Console" theme
Color = "rgb(200, 200, 200)";
BackgroundColor = "#000000";
SelectionColor = "#000000";
SelectionBackgroundColor = "rgb(200, 200, 200)";
commentColor="#ddcc88";
ConsoleColor->setChecked(true);
break;
case 2:
// This is the "Dusk" theme
Color = "";
BackgroundColor = "";
SelectionColor = "";
SelectionBackgroundColor = "";
DuskColor->setChecked(true);
commentColor="#2aff3a";
break;
case 3:
// This is the "Hacker" theme
Color = "#00CC00";
BackgroundColor = "#000000";
SelectionColor = "#000000";
SelectionBackgroundColor = "#00CC00";
commentColor="#ff22ed";
HackerColor->setChecked(true);
break;
case 4:
// This is the "Light" theme
Color = "#000000";
BackgroundColor = "rgb(240, 240, 240)";
SelectionColor = "rgb(200, 200, 200)";
SelectionBackgroundColor = "rgb(40, 40, 40)";
LightColor->setChecked(true);
commentColor="#11ff0a";
break;
case 5:
// This is the "Navy" theme
Color = "rgb(237, 247, 241)";
BackgroundColor = "rgb(16, 28, 42)";
SelectionColor = "rgb(237, 247, 241)";
SelectionBackgroundColor = "rgb(24, 97, 129)";
commentColor="#4aff4a";
NavyColor->setChecked(true);
break;
case 6:
// This is the "Night" theme
Color = "rgb(234, 234, 234)";
BackgroundColor = "rgb(63, 63, 63)";
SelectionColor = "rgb(63, 63, 63)";
SelectionBackgroundColor = "rgb(206, 255, 132)";
commentColor="#8aff8f";
NightColor->setChecked(true);
break;
case 7:
// This is the "Normal" theme
Color.clear();
BackgroundColor.clear();
SelectionColor.clear();
SelectionBackgroundColor.clear();
commentColor="#66ff66";
NormalColor->setChecked(true);
break;
case 8:
// This is the "Paper" theme
Color = "#000000";
BackgroundColor = "rgb(248, 248, 248)";
SelectionColor = "#000000";
SelectionBackgroundColor = "rgb(206, 255, 132)";
commentColor="#66ff66";
PaperColor->setChecked(true);
break;
}
QString StyleSheet2;
if (SelectedTheme != 7) {
// Create the stylesheet with the selected values
StyleSheet = ("QPlainTextEdit {"
"color: " + Color + ";"
"background-color: " + BackgroundColor + ";"
"selection-color: " + SelectionColor + ";"
"selection-background-color: " + SelectionBackgroundColor + ";"
"};"
);
StyleSheet2 = (
"QTreeWidget {"
"color: " + Color + ";"
"background-color: " + BackgroundColor + ";"
"selection-color: " + SelectionColor + ";"
"selection-background-color: " + SelectionBackgroundColor + ";"
"};"
);
}
else if (SelectedTheme == 7) {
// Use the system style (Normal Color)
StyleSheet.clear();
StyleSheet2.clear();
}
TextEdit->setThemeId(Settings.ColorScheme);
TextEdit->setStyleSheet(StyleSheet);
structure->setStyleSheet(StyleSheet2);
if(highlighter!=NULL){
highlighter->useTheme(Settings.ColorScheme);
highlighter->rehighlight();
}
}
| 33.321429 | 85 | 0.576849 | Amuwa |
ac3f94d6da833e652b1681c6e1dbc0f5049e3f5b | 2,141 | cpp | C++ | src/amos/overlap.cpp | mariokostelac/asqg2afg | c40862046f04241c9091b5c55e53486953d4d67a | [
"MIT"
] | null | null | null | src/amos/overlap.cpp | mariokostelac/asqg2afg | c40862046f04241c9091b5c55e53486953d4d67a | [
"MIT"
] | 3 | 2015-03-25T16:03:14.000Z | 2015-03-28T10:42:17.000Z | src/amos/overlap.cpp | mariokostelac/asqg2afg | c40862046f04241c9091b5c55e53486953d4d67a | [
"MIT"
] | null | null | null | #include "overlap.h"
using std::endl;
namespace AMOS {
Overlap::Overlap(const uint32_t r1, const uint32_t r2, const char adj, const int32_t ahg, const int32_t bhg, const int32_t scr)
:read1(r1), read2(r2), adjacency(adj), a_hang(ahg), b_hang(bhg), score(scr)
{}
// from http://sourceforge.net/p/amos/mailman/message/19965222/.
//
// read a -------------------|--------------> bhang
// read b ahang ---------------|--------------->
//
// read a -ahang ---------------|--------------->
// read b -------------------|--------------> -bhang
Overlap::Overlap(const uint32_t r1, const uint32_t r2, bool second_complement,
const int32_t start1, const int32_t end1, const int32_t len1,
const int32_t start2, const int32_t end2, const int32_t len2,
const int32_t scr)
:read1(r1), read2(r2), score(scr)
{
adjacency = second_complement ? 'I' : 'N';
int overlap_len_a = end1 - start1;
int overlap_len_b = end2 - start2;
int a_not_matching = len1 - overlap_len_a;
int b_not_matching = len2 - overlap_len_b;
if (start1 == 0 && end1 == len1) {
// first contained
a_hang = -start2;
b_hang = len2 - end2;
} else if (start2 == 0 && end2 == len2) {
// second contained
a_hang = start1;
b_hang = -(len1 - end1);
} else if (end1 == len1) {
// first case from the comment
a_hang = a_not_matching;
b_hang = b_not_matching;
} else if (end2 == len2) {
// second case from the comment
a_hang = -b_not_matching;
b_hang = -a_not_matching;
} else {
fprintf(stderr, "%d %d %d, %d %d %d %c\n", start1, end1, len1, start2, end2, len2, adjacency);
assert(false);
}
}
ostream& operator << (ostream &o, const AMOS::Overlap& overlap) {
o << "{OVL" << endl;
o << "adj:" << overlap.adjacency << endl;
o << "rds:" << overlap.read1 << "," << overlap.read2 << endl;
o << "ahg:" << overlap.a_hang << endl;
o << "bhg:" << overlap.b_hang << endl;
o << "scr:" << overlap.score << endl;
o << "}" << endl;
return o;
}
}
| 33.453125 | 129 | 0.543204 | mariokostelac |
ac42f53847260c7eee0dc2492ba4bd3de38128c4 | 1,311 | cpp | C++ | Source/Collections/collectionspritesheetmodel.cpp | erayzesen/turquoise2D | 33bd2e85169bba4c82c388c1619b2de55065eb7b | [
"Zlib"
] | 13 | 2020-05-24T23:52:48.000Z | 2020-12-01T02:43:03.000Z | Source/Collections/collectionspritesheetmodel.cpp | erayzesen/turquoise2D | 33bd2e85169bba4c82c388c1619b2de55065eb7b | [
"Zlib"
] | 3 | 2020-05-26T22:19:49.000Z | 2020-12-01T09:31:25.000Z | Source/Collections/collectionspritesheetmodel.cpp | erayzesen/turquoise2D | 33bd2e85169bba4c82c388c1619b2de55065eb7b | [
"Zlib"
] | 3 | 2020-05-26T01:35:20.000Z | 2020-05-26T13:51:07.000Z | #include "collectionspritesheetmodel.h"
CollectionSpriteSheetModel::CollectionSpriteSheetModel(QObject *parent) : QStandardItemModel(parent)
{
}
void CollectionSpriteSheetModel::setTarget(QString targetPath)
{
this->clear();
SpriteSheet *spriteSheet=new SpriteSheet(targetPath);
QPixmap resourceImage(spriteSheet->resourceImagePath);
for(int i=0;i<spriteSheet->frame.keys().count();i++){
//nss is a QStandartItem object
QStandardItem *nss=new QStandardItem();
nss->setText(spriteSheet->frame.keys().at(i));
QPixmap iconImage=resourceImage.copy(spriteSheet->frame[spriteSheet->frame.keys().at(i)]);
iconImage=iconImage.scaled(48,48,Qt::KeepAspectRatio);
QIcon itemIcon(iconImage);
nss->setIcon(itemIcon);
nss->setDragEnabled(true);
nss->setEditable(false);
nss->setData(targetPath+"?frameName="+spriteSheet->frame.keys().at(i));
this->appendRow(nss);
}
}
QMimeData *CollectionSpriteSheetModel::mimeData(const QModelIndexList &indexes) const
{
QList<QUrl> urls;
for (int i=0; i<indexes.count(); i++){
QString data=this->data(indexes.at(i),Qt::UserRole+1).toString();
urls << QUrl(data);
}
QMimeData *data = new QMimeData();
data->setUrls(urls);
return data;
}
| 32.775 | 100 | 0.680397 | erayzesen |
ac44114138b8698bbe2b2385d2e2863ee32d543c | 5,391 | hpp | C++ | src/gDeadCodeDeletion.hpp | lyj-514328/T1010 | f6bd5a75b249abb63f5023f205ead28b133b3dbc | [
"Apache-2.0"
] | null | null | null | src/gDeadCodeDeletion.hpp | lyj-514328/T1010 | f6bd5a75b249abb63f5023f205ead28b133b3dbc | [
"Apache-2.0"
] | null | null | null | src/gDeadCodeDeletion.hpp | lyj-514328/T1010 | f6bd5a75b249abb63f5023f205ead28b133b3dbc | [
"Apache-2.0"
] | null | null | null | #ifndef GDEADCODEDELETION_HPP
#define GDEADCODEDELETION_HPP
#include <queue>
#include "globalPolicyExecutor.hpp"
using namespace std;
class GDeadCodeDeletion:
public GlobalPolicyExecutor
{
public:
GDeadCodeDeletion();
~GDeadCodeDeletion();
void runOptimizer(void);
void printInfoOfOptimizer(void);
bool runOptimizer(FunctionBlock* block,
FuncPropertyGetter* funcPropertyGetter);//运行优化器
};
GDeadCodeDeletion::GDeadCodeDeletion(/* args */)
{
m_name = "死代码删除器";
}
GDeadCodeDeletion::~GDeadCodeDeletion()
{
}
void GDeadCodeDeletion::printInfoOfOptimizer(void)
{
}
//TODO
//删掉的变量名字也得抹去或者存起来
bool GDeadCodeDeletion::runOptimizer(FunctionBlock* block,
FuncPropertyGetter* funcPropertyGetter)
{
//得到没有使用的节点
m_block = block;
vector<BasicBlock*>& basicBlocks = m_block->getBasicBlocks();
unordered_map<string,SsaSymb*>& uName2SsaSymbs = m_block->getUName2SsaSymbs();
unordered_map<string,SsaSymb*>& tName2SsaSymbs = m_block->getTName2SsaSymbs();
queue<SsaSymb*> deadSymbList;
while(!deadSymbList.empty())deadSymbList.pop();
unordered_map<string,SsaSymb*>::iterator it = uName2SsaSymbs.begin();
for(;it != uName2SsaSymbs.end();it++)
{
if(it->second->useTimes != 0)continue;
deadSymbList.push(it->second);
}
it = tName2SsaSymbs.begin();
for(;it != tName2SsaSymbs.end();it++)
{
if(it->second->useTimes != 0)continue;
deadSymbList.push(it->second);
}
//开始拓扑
vector<string> needDeleteVarList;
needDeleteVarList.clear();
while(!deadSymbList.empty())
{
SsaSymb* needDelVar = deadSymbList.front();
needDeleteVarList.push_back(needDelVar->name);
deadSymbList.pop();
SsaTac* needDelTac = needDelVar->defPoint;
switch(needDelTac->type)
{
case TAC_ADD:
case TAC_SUB:
case TAC_MUL:
case TAC_DIV:
case TAC_EQ:
case TAC_MOD:
case TAC_NE:
case TAC_LT:
case TAC_LE:
case TAC_GT:
case TAC_GE:
case TAC_OR:
case TAC_AND:
if((needDelTac->second->type == SYM_VAR &&
needDelTac->second->name[0] == 'u') ||
needDelTac->second->name[0] == 't')
{
needDelTac->second->useTimes--;
if(needDelTac->second->useTimes == 0)
deadSymbList.push(needDelTac->second);
//删掉 needDelTac->first 中对这个的使用链
deleteUseSsaTac(needDelTac->secondPoint);
needDelTac->secondPoint = NULL;
}
if((needDelTac->third->type == SYM_VAR &&
needDelTac->third->name[0] == 'u') ||
needDelTac->third->name[0] == 't')
{
needDelTac->third->useTimes--;
if(needDelTac->third->useTimes == 0)
deadSymbList.push(needDelTac->third);
//删掉 needDelTac->first 中对这个的使用链
deleteUseSsaTac(needDelTac->thirdPoint);
needDelTac->thirdPoint = NULL;
}
needDelTac->type = TAC_UNDEF;
break;
case TAC_NEG:
case TAC_POSI:
case TAC_NOT:
case TAC_COPY:
if((needDelTac->second->type == SYM_VAR &&
needDelTac->second->name[0] == 'u') ||
needDelTac->second->name[0] == 't')
{
needDelTac->second->useTimes--;
if(needDelTac->second->useTimes == 0)
deadSymbList.push(needDelTac->second);
//删掉 needDelTac->first 中对这个的使用链
deleteUseSsaTac(needDelTac->secondPoint);
needDelTac->secondPoint = NULL;
}
needDelTac->type = TAC_UNDEF;
break;
case TAC_FORMAL:
//什么也不做
break;
case TAC_INSERT:
{
for(uint i = 0;i < needDelTac->functionSymb.size();i++)
{
//u0d0问题,为什么他的functionSymb2Tac[i]不为空呢
if(needDelTac->functionSymb2Tac[i]==NULL)continue;
SsaSymb* varSymb = needDelTac->functionSymb[i];
if((varSymb->type == SYM_VAR &&
varSymb->name[0] == 'u') ||
varSymb->name[0] == 't')
{
varSymb->useTimes--;
if(varSymb->useTimes == 0)
deadSymbList.push(varSymb);
//删掉 needDelTac->first 中对这个的使用链
deleteUseSsaTac(needDelTac->functionSymb2Tac[i]);
needDelTac->functionSymb2Tac[i] = NULL;
}
}
}
needDelTac->type = TAC_UNDEF;
break;
case TAC_CALL:
needDelTac->first = NULL;
break;
}
}
bool isOptimize = false;
//清理垃圾
for(uint i = 0;i < basicBlocks.size();i++)
{
basicBlocks[i]->cleanDirtyTac();
}
for(uint i = 0;i < needDeleteVarList.size();i++)
{
isOptimize = true;
if(needDeleteVarList[i].c_str()[0] == 't')
tName2SsaSymbs.erase(needDeleteVarList[i]);
else uName2SsaSymbs.erase(needDeleteVarList[i]);
}
return isOptimize;
}
#endif
| 32.089286 | 82 | 0.540716 | lyj-514328 |
ac44e91b8a2bed7692721a99119874dd88c0d31d | 4,360 | cc | C++ | test/testsupport/file_utils_override.cc | shishuo365/webrtc | 96e60852faaa8ab4cf6477fa92c80a434921625d | [
"BSD-3-Clause"
] | 1 | 2016-06-23T01:26:53.000Z | 2016-06-23T01:26:53.000Z | test/testsupport/file_utils_override.cc | shishuo365/webrtc | 96e60852faaa8ab4cf6477fa92c80a434921625d | [
"BSD-3-Clause"
] | null | null | null | test/testsupport/file_utils_override.cc | shishuo365/webrtc | 96e60852faaa8ab4cf6477fa92c80a434921625d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/testsupport/file_utils_override.h"
#include <limits.h>
#include <stdio.h>
#if defined(WEBRTC_WIN)
#include <direct.h>
#include <tchar.h>
#include <windows.h>
#include <algorithm>
#include <codecvt>
#include <locale>
#include "Shlwapi.h"
#include "WinDef.h"
#include "rtc_base/win32.h"
#define GET_CURRENT_DIR _getcwd
#else
#include <unistd.h>
#define GET_CURRENT_DIR getcwd
#endif
#if defined(WEBRTC_IOS)
#include "test/testsupport/ios_file_utils.h"
#endif
#if defined(WEBRTC_MAC)
#include "test/testsupport/mac_file_utils.h"
#endif
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "rtc_base/arraysize.h"
#include "rtc_base/checks.h"
#include "rtc_base/string_utils.h"
#include "rtc_base/strings/string_builder.h"
namespace webrtc {
namespace test {
std::string DirName(absl::string_view path);
bool CreateDir(absl::string_view directory_name);
namespace internal {
namespace {
#if defined(WEBRTC_WIN)
const absl::string_view kPathDelimiter = "\\";
#elif !defined(WEBRTC_IOS)
const absl::string_view kPathDelimiter = "/";
#endif
#if defined(WEBRTC_ANDROID)
// This is a special case in Chrome infrastructure. See
// base/test/test_support_android.cc.
const absl::string_view kAndroidChromiumTestsRoot =
"/sdcard/chromium_tests_root/";
#endif
#if !defined(WEBRTC_IOS)
const absl::string_view kResourcesDirName = "resources";
#endif
} // namespace
// Finds the WebRTC src dir.
// The returned path always ends with a path separator.
absl::optional<std::string> ProjectRootPath() {
#if defined(WEBRTC_ANDROID)
return std::string(kAndroidChromiumTestsRoot);
#elif defined WEBRTC_IOS
return IOSRootPath();
#elif defined(WEBRTC_MAC)
std::string path;
GetNSExecutablePath(&path);
std::string exe_dir = DirName(path);
// On Mac, tests execute in out/Whatever, so src is two levels up except if
// the test is bundled (which our tests are not), in which case it's 5 levels.
return DirName(DirName(exe_dir)) + std::string(kPathDelimiter);
#elif defined(WEBRTC_POSIX)
char buf[PATH_MAX];
ssize_t count = ::readlink("/proc/self/exe", buf, arraysize(buf));
if (count <= 0) {
RTC_DCHECK_NOTREACHED() << "Unable to resolve /proc/self/exe.";
return absl::nullopt;
}
// On POSIX, tests execute in out/Whatever, so src is two levels up.
std::string exe_dir = DirName(absl::string_view(buf, count));
return DirName(DirName(exe_dir)) + std::string(kPathDelimiter);
#elif defined(WEBRTC_WIN)
wchar_t buf[MAX_PATH];
buf[0] = 0;
if (GetModuleFileNameW(NULL, buf, MAX_PATH) == 0)
return absl::nullopt;
std::string exe_path = rtc::ToUtf8(std::wstring(buf));
std::string exe_dir = DirName(exe_path);
return DirName(DirName(exe_dir)) + std::string(kPathDelimiter);
#endif
}
std::string OutputPath() {
#if defined(WEBRTC_IOS)
return IOSOutputPath();
#elif defined(WEBRTC_ANDROID)
return std::string(kAndroidChromiumTestsRoot);
#else
absl::optional<std::string> path_opt = ProjectRootPath();
RTC_DCHECK(path_opt);
std::string path = *path_opt + "out";
if (!CreateDir(path)) {
return "./";
}
return path + std::string(kPathDelimiter);
#endif
}
std::string WorkingDir() {
#if defined(WEBRTC_ANDROID)
return std::string(kAndroidChromiumTestsRoot);
#else
char path_buffer[FILENAME_MAX];
if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) {
fprintf(stderr, "Cannot get current directory!\n");
return "./";
} else {
return std::string(path_buffer);
}
#endif
}
std::string ResourcePath(absl::string_view name, absl::string_view extension) {
#if defined(WEBRTC_IOS)
return IOSResourcePath(name, extension);
#else
absl::optional<std::string> path_opt = ProjectRootPath();
RTC_DCHECK(path_opt);
rtc::StringBuilder os(*path_opt);
os << kResourcesDirName << kPathDelimiter << name << "." << extension;
return os.Release();
#endif
}
} // namespace internal
} // namespace test
} // namespace webrtc
| 27.25 | 80 | 0.730734 | shishuo365 |
ac455735baa60702d641a4def41c190e62e89498 | 4,426 | cc | C++ | allegro_utils.cc | trago/alleigen | cfa8262762e7ed002f987bca0bafbad485b2f72f | [
"MIT"
] | null | null | null | allegro_utils.cc | trago/alleigen | cfa8262762e7ed002f987bca0bafbad485b2f72f | [
"MIT"
] | null | null | null | allegro_utils.cc | trago/alleigen | cfa8262762e7ed002f987bca0bafbad485b2f72f | [
"MIT"
] | null | null | null | //
// Created by julio on 1/31/17.
//
#include "allegro_utils.h"
using namespace Eigen;
void create_gbitmap_from_arrayf(const ArrayXXf &im, ALLEGRO_BITMAP **bitmap)
{
ALLEGRO_BITMAP* current_bitmap;
if(*bitmap != NULL)
al_destroy_bitmap(*bitmap);
current_bitmap = al_get_target_bitmap();
int flags = al_get_new_bitmap_flags();
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR);
*bitmap = al_create_bitmap(im.cols(), im.rows());
al_lock_bitmap(*bitmap, ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_WRITEONLY);
al_set_target_bitmap(*bitmap);
ALLEGRO_COLOR color;
for(int n = 0; n<im.cols(); n++)
for(int m = 0; m<im.rows(); m++){
color = al_map_rgb_f(im(m,n), im(m,n), im(m,n));
al_put_pixel(n, m, color);
}
al_unlock_bitmap(*bitmap);
al_set_target_bitmap(current_bitmap);
al_set_new_bitmap_flags(flags);
//al_convert_bitmap(*bitmap);
}
void normalize_arrayf(Eigen::ArrayXXf& im, const float min, const float max)
{
const float a = im.minCoeff();
const float b = im.maxCoeff();
im = (im-a)*((max-min)/(b-a)) + min;
}
void get_rgb_arraysf(ALLEGRO_BITMAP *bitmap, Eigen::ArrayXXf& R,
Eigen::ArrayXXf& G, Eigen::ArrayXXf& B)
{
const int M = al_get_bitmap_height(bitmap);
const int N = al_get_bitmap_width(bitmap);
ALLEGRO_BITMAP *current_bitmap, *mem_bitmap;
current_bitmap = al_get_target_bitmap();
int flags = al_get_new_bitmap_flags();
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR);
mem_bitmap = al_clone_bitmap(bitmap);
al_lock_bitmap(mem_bitmap, ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READONLY);
al_set_target_bitmap(mem_bitmap);
ALLEGRO_COLOR color;
R.resize(M,N);
G.resize(M,N);
B.resize(M,N);
float r,g,b;
for(int n = 0; n<N; n++)
for(int m = 0; m<M; m++){
color = al_get_pixel(mem_bitmap, n, m);
al_unmap_rgb_f(color, &r, &g, &b);
R(m,n) = r;
G(m,n) = b;
B(m,n) = b;
}
al_unlock_bitmap(mem_bitmap);
al_set_target_bitmap(current_bitmap);
al_set_new_bitmap_flags(flags);
al_destroy_bitmap(mem_bitmap);
}
void get_grey_arraysf(ALLEGRO_BITMAP *bitmap, Eigen::ArrayXXf& G)
{
const int M = al_get_bitmap_height(bitmap);
const int N = al_get_bitmap_width(bitmap);
ALLEGRO_BITMAP *current_bitmap, *mem_bitmap;
current_bitmap = al_get_target_bitmap();
int flags = al_get_new_bitmap_flags();
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR);
mem_bitmap = al_clone_bitmap(bitmap);
al_lock_bitmap(mem_bitmap, ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READONLY);
al_set_target_bitmap(mem_bitmap);
ALLEGRO_COLOR color;
G.resize(M,N);
float r,g,b;
for(int n = 0; n<N; n++)
for(int m = 0; m<M; m++){
color = al_get_pixel(mem_bitmap, n, m);
al_unmap_rgb_f(color, &r, &g, &b);
G(m,n) = 0.2989*r + 0.5870*g + 0.1140*b;
}
al_unlock_bitmap(mem_bitmap);
al_set_target_bitmap(current_bitmap);
al_set_new_bitmap_flags(flags);
al_destroy_bitmap(mem_bitmap);
}
void create_cbitmap_from_arraysf(const Eigen::ArrayXXf &R,
const Eigen::ArrayXXf &G,
const Eigen::ArrayXXf &B,
ALLEGRO_BITMAP **bitmap)
{
ALLEGRO_BITMAP* current_bitmap;
if(*bitmap != NULL)
al_destroy_bitmap(*bitmap);
current_bitmap = al_get_target_bitmap();
int flags = al_get_new_bitmap_flags();
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR);
*bitmap = al_create_bitmap(R.cols(), R.rows());
al_lock_bitmap(*bitmap, ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_WRITEONLY);
al_set_target_bitmap(*bitmap);
ALLEGRO_COLOR color;
for(int n = 0; n<R.cols(); n++)
for(int m = 0; m<R.rows(); m++){
color = al_map_rgb_f(R(m,n), G(m,n), B(m,n));
al_put_pixel(n, m, color);
}
al_unlock_bitmap(*bitmap);
al_set_target_bitmap(current_bitmap);
al_set_new_bitmap_flags(flags);
}
void read_cimage_arrayf(const char *fname, Eigen::ArrayXXf &R,
Eigen::ArrayXXf &G,
Eigen::ArrayXXf &B)
{
ALLEGRO_BITMAP* image;
image = al_load_bitmap(fname);
get_rgb_arraysf(image, R, G, B);
al_destroy_bitmap(image);
}
void read_gimage_arrayf(const char *fname, Eigen::ArrayXXf &G)
{
ALLEGRO_BITMAP* image;
image = al_load_bitmap(fname);
get_grey_arraysf(image, G);
al_destroy_bitmap(image);
} | 27.320988 | 78 | 0.684139 | trago |
ac473557fd6afa3f80b11a1141f3ea757486d66a | 1,203 | hpp | C++ | source/framework/benchmark/include/lue/framework/benchmark/algorithm_benchmark_result.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/framework/benchmark/include/lue/framework/benchmark/algorithm_benchmark_result.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/framework/benchmark/include/lue/framework/benchmark/algorithm_benchmark_result.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include "lue/framework/core/define.hpp"
#include <array>
#include <vector>
namespace lue {
namespace benchmark {
class AlgorithmBenchmarkResult
{
public:
using Shape = std::vector<Count>;
AlgorithmBenchmarkResult()=default;
explicit AlgorithmBenchmarkResult(
Shape const& shape_in_partitions);
template<
Rank rank>
explicit AlgorithmBenchmarkResult(
std::array<Count, rank> const& shape_in_partitions):
_shape_in_partitions{
shape_in_partitions.begin(), shape_in_partitions.end()}
{
}
AlgorithmBenchmarkResult(AlgorithmBenchmarkResult const&)=default;
AlgorithmBenchmarkResult(AlgorithmBenchmarkResult&&)=default;
~AlgorithmBenchmarkResult()=default;
AlgorithmBenchmarkResult&
operator=(AlgorithmBenchmarkResult const&)=default;
AlgorithmBenchmarkResult&
operator=(AlgorithmBenchmarkResult&&)=default;
Shape const& shape_in_partitions () const;
private:
Shape _shape_in_partitions;
};
} // namespace benchmark
} // namespace lue
| 21.872727 | 85 | 0.645054 | computationalgeography |
ac4859011e0e731ce97983050e202023a458652c | 2,056 | cpp | C++ | sp/src/game/client/fmod/fmodmanager.cpp | fuzzzzzz/jurassic-life | 3105fe79977460c57c433cb960e91783d47626ed | [
"Unlicense"
] | 1 | 2016-08-30T07:01:29.000Z | 2016-08-30T07:01:29.000Z | sp/src/game/client/fmod/fmodmanager.cpp | fuzzzzzz/jurassic-life-code | 3105fe79977460c57c433cb960e91783d47626ed | [
"Unlicense"
] | null | null | null | sp/src/game/client/fmod/fmodmanager.cpp | fuzzzzzz/jurassic-life-code | 3105fe79977460c57c433cb960e91783d47626ed | [
"Unlicense"
] | 3 | 2015-03-09T22:40:35.000Z | 2019-02-17T16:15:44.000Z | #include "cbase.h"
#include "FMODManager.h"
#include "fmod_errors.h"
#include <string>
using namespace FMOD;
EventSystem *pEventSystem;
Event *pEvent = NULL;
FMOD_RESULT result;
CFMODManager gFMODMng;
CFMODManager* FMODManager()
{
return &gFMODMng;
}
void ERRCHECK(FMOD_RESULT result)
{
if (result != FMOD_OK)
{
Warning("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
}
}
CFMODManager::CFMODManager()
{
}
CFMODManager::~CFMODManager()
{
}
// Starts FMOD
void CFMODManager::InitFMOD( void )
{
ERRCHECK(result = FMOD::EventSystem_Create(&pEventSystem));
ERRCHECK(result = pEventSystem->init(64, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL));
std::string path = engine->GetGameDirectory();
path += "\\";
DevMsg("FMOD path %s\n",path.c_str());
ERRCHECK(result = pEventSystem->setMediaPath(path.c_str()));
}
// Stops FMOD
void CFMODManager::ExitFMOD( void )
{
ERRCHECK(result = pEventSystem->release());
}
bool CFMODManager::LoadDesignerFile(const char *filename)
{
if (m_sCurrentFile != filename)
{
m_sCurrentFile = filename;
DevMsg("FMOD file : %s\n",filename);
pEventSystem->unload();
ERRCHECK(result = pEventSystem->load(filename, 0, 0));
pEventSystem->update();
return result != 0;
}
return false;
}
void CFMODManager::UnloadDesignerFile()
{
pEventSystem->unload();
}
bool CFMODManager::SetEvent(const char *eventName)
{
if (pEvent)
pEvent->stop();
m_sCurrentEvent = eventName;
ERRCHECK(result = pEventSystem->getEvent(eventName, FMOD_EVENT_DEFAULT, &pEvent));
if (pEvent)
pEvent->start();
pEventSystem->update();
return true;
}
bool CFMODManager::SetParameter(const char *name, float value)
{
if (pEvent)
{
FMOD::EventParameter *param;
//float param_min, param_max;
ERRCHECK(result = pEvent->getParameter(name, ¶m));
//ERRCHECK(result = param->getRange(¶m_min, ¶m_max));
ERRCHECK(result = param->setValue(value));
pEventSystem->update();
return true;
}
return false;
}
void CFMODManager::Stop()
{
if (pEvent)
pEvent->stop();
}
| 18.522523 | 88 | 0.700389 | fuzzzzzz |
ac4c19e6c277f4bf925512f8a63455c6e25b08f7 | 9,214 | hpp | C++ | gungi/include/gtypes.hpp | hkpeprah/gungi | adf04d2d3a67204101448605c3acd69204ae8160 | [
"MIT"
] | 1 | 2018-02-14T19:51:21.000Z | 2018-02-14T19:51:21.000Z | gungi/include/gtypes.hpp | hkpeprah/gungi | adf04d2d3a67204101448605c3acd69204ae8160 | [
"MIT"
] | null | null | null | gungi/include/gtypes.hpp | hkpeprah/gungi | adf04d2d3a67204101448605c3acd69204ae8160 | [
"MIT"
] | 2 | 2017-06-14T12:10:25.000Z | 2018-05-24T19:57:57.000Z | // gtypes.hpp -*-C++-*-
#pragma once
//@DESCRIPTION:
// This component provides the base types and identifiers used throughout the
// Gungi game library. Used for identifying pieces, specifying moves, and
// piece effects.
//
//@TYPES:
// 'gungi::colour_t': enumeration specifying the player colours.
// 'gungi::piece_id_t': enumeration specifying the identifiers for pieces.
// 'gungi::move_dir_t': enumeration specifying the different move directions.
// 'gungi::move_mod_t': enumeration specifying how to interpret a move.
// 'gungi::move_t': structure representing a move which is a mod and dir pair.
// 'gungi::move_vector_t': type definition for a vector of moves.
// 'gungi::moveset_t': type definition for the piece moves in a tower.
// 'gungi::moveset_ptr_t': type definition for a pointer to a move vector.
// 'gungi::const_moveset_ptr_t': constant 'gungi::moveset_ptr'.
// 'gungi::effect_t': enumeration specifying the identifiers for effects.
// 'gungi::effect_bitfield_t': type definition for effect bitfields
// 'gungi::tier_t': type definition for tiers in a tower.
// 'gungi::error_t': enumeration for the various different error codes.
//
//@CONSTANTS:
// 'gungi::k_MAX_POSITION_REPETITIONS': constant for max position repetitions.
// 'gungi::k_MAX_TOWER_SIZE': constant for the max size of a tower.
// 'gungi::k_START_PIECE_COUNT': constant for a player's starting piece count.
// 'gungi::k_BOARD_LENGTH': length of the gungi board.
// 'gungi::k_UNIT_EFFECT': array of unit effect bitfields.
// 'gungi::k_UNIT_IMMUNITY': array of unit immunity bitfields.
// 'gungi::k_UNIT_MOVES': array of unit movesets.
// 'gungi::k_START_HAND': starting hand for a player.
#include <vector>
namespace gungi {
#define GASSERT(cond, ...) gassert(__FILE__, __LINE__, #cond, (cond), ## __VA_ARGS__)
const unsigned int k_MAX_POSITION_REPETITIONS = 4;
// Maximum number of times the position on a board can repeat.
const unsigned int k_MAX_TOWER_SIZE = 3;
// The maximum size a tower can be in Gungi.
const unsigned int k_START_PIECE_COUNT = 23;
// Count of the total number of pieces each player starts with at the start
// of the game.
const unsigned int k_BOARD_LENGTH = 9;
// Length of the board. Since the board is square, the total size of the
// board is 'k_BOARD_LENGTH * k_BOARD_LENGTH'.
typedef enum colour_t {
// The different player colours.
WHITE = (1 << 0),
BLACK = (1 << 1),
} colour_t;
typedef enum piece_id_t {
GUNGI_PIECE_NONE = -1,
GUNGI_PIECE_PAWN = 0,
GUNGI_PIECE_BOW,
GUNGI_PIECE_PRODIGY,
GUNGI_PIECE_HIDDEN_DRAGON,
GUNGI_PIECE_FORTRESS,
GUNGI_PIECE_CATAPULT,
GUNGI_PIECE_SPY,
GUNGI_PIECE_SAMURAI,
GUNGI_PIECE_CAPTAIN,
GUNGI_PIECE_COMMANDER,
GUNGI_PIECE_BRONZE,
GUNGI_PIECE_SILVER,
GUNGI_PIECE_GOLD,
GUNGI_PIECE_ARROW,
GUNGI_PIECE_PHOENIX,
GUNGI_PIECE_DRAGON_KING,
GUNGI_PIECE_LANCE,
GUNGI_PIECE_CLANDESTINITE,
GUNGI_PIECE_PIKE,
GUNGI_PIECE_PISTOL,
GUNGI_NUM_PIECES
} piece_id_t;
typedef enum move_dir_t {
// Placeholder.
GUNGI_MOVE_DIR_NONE = 0,
// Moves are written as bit fields. So diagonal movement can be written as
// 'GUNGI_MOVE_DIR_UP | GUNGI_MOVE_DIR_LEFT', which would correspond to up
// and to the left (left diagonal).
GUNGI_MOVE_DIR_UP = (1 << 1),
GUNGI_MOVE_DIR_DOWN = (1 << 2),
GUNGI_MOVE_DIR_LEFT = (1 << 3),
GUNGI_MOVE_DIR_RIGHT = (1 << 4),
// Combination movements from the above list.
GUNGI_MOVE_DIR_UP_LEFT = GUNGI_MOVE_DIR_UP | GUNGI_MOVE_DIR_LEFT,
GUNGI_MOVE_DIR_UP_RIGHT = GUNGI_MOVE_DIR_UP | GUNGI_MOVE_DIR_RIGHT,
GUNGI_MOVE_DIR_DOWN_LEFT = GUNGI_MOVE_DIR_DOWN | GUNGI_MOVE_DIR_LEFT,
GUNGI_MOVE_DIR_DOWN_RIGHT = GUNGI_MOVE_DIR_DOWN | GUNGI_MOVE_DIR_RIGHT
} move_dir_t;
typedef enum move_mod_t {
// No modifier for the movement.
GUNGI_MOVE_MOD_NONE,
// Movement is unlimited in the given movement direction.
GUNGI_MOVE_MOD_UNLIMITED
} move_mod_t;
typedef struct move_t {
// Direction of the movement.
move_dir_t move_direction;
// Modifier for the particular movement.
move_mod_t move_modifier;
} move_t;
typedef std::vector<std::vector<move_t> > move_vector_t;
// Type definition for a vector of moves. A piece has multiple moves it can
// make based on its height within a tower. This vector is used to contain
// the moves at a particular height.
typedef move_vector_t moveset_t[k_MAX_TOWER_SIZE];
// Type definition for a set of moves. A piece has a different list of moves
// based on its height within a tower; the set is the entire collection of
// the available moves for every height.
typedef move_vector_t* moveset_ptr_t;
// Type definition for a pointer to a move vector.
typedef move_vector_t const * const_moveset_ptr_t;
// Type definition for a pointer to an array of constant move vectors.
typedef enum effect_t {
// Placeholder.
GUNGI_EFFECT_NONE = 0,
// Standard set of effects.
GUNGI_EFFECT_LAND_LINK = (1 << 1),
GUNGI_EFFECT_MOBILE_RANGE_EXPANSION_1 = (1 << 2), // Fortress
GUNGI_EFFECT_MOBILE_RANGE_EXPANSION_2 = (1 << 3), // Catapult
GUNGI_EFFECT_1_3_TIER_EXCHANGE = (1 << 4),
GUNGI_EFFECT_SUBSTITUTION = (1 << 5),
GUNGI_EFFECT_BETRAYAL = (1 << 6),
GUNGI_EFFECT_FORCED_RECOVERY = (1 << 7),
GUNGI_EFFECT_FORCED_REARRANGEMENT = (1 << 8),
// Pieces with the no tower effect cannot be stacked upon.
GUNGI_EFFECT_NO_TOWER = (1 << 9),
// Pieces with the passive effect cannot attack.
GUNGI_EFFECT_PASSIVE = (1 << 10),
// Pieces with the 'no stack' effect cannot stack on other units.
GUNGI_EFFECT_NO_STACK = (1 << 11),
// Pieces with this effect can only have 'front' pieces dropped onto them.
GUNGI_EFFECT_FRONT_DROP_ONLY = (1 << 12), // Clandestinite
// Pieces with this effect can only have 'back' pieces dropped onto them.
GUNGI_EFFECT_BACK_DROP_ONLY = (1 << 13), // Spy
// Piece can jump over other pieces.
GUNGI_EFFECT_JUMP = (1 << 14), // Spy, Bow, Clandestinite
} effect_t;
typedef unsigned int effect_bitfield_t;
// Type definition for a bitfield of 'effect_t's.
typedef int tier_t;
// Type definition for a tier.
typedef enum error_t {
GUNGI_ERROR_NONE = 0,
GUNGI_ERROR_INVALID_IDX,
GUNGI_ERROR_NO_BACK,
GUNGI_ERROR_FULL_TOWER,
GUNGI_ERROR_NOT_A_MEMBER,
GUNGI_ERROR_OUT_OF_RANGE,
GUNGI_ERROR_DUPLICATE,
GUNGI_ERROR_NO_WALK,
GUNGI_ERROR_GAME_OVER,
GUNGI_ERROR_INVALID_UNIT,
GUNGI_ERROR_CHECK,
GUNGI_ERROR_TERRITORY,
GUNGI_ERROR_NOT_TOP,
GUNGI_ERROR_PAWN_FILE,
GUNGI_ERROR_BRONZE_FILE,
GUNGI_ERROR_LAND_LINK,
GUNGI_ERROR_SAME_TEAM,
GUNGI_ERROR_PAWN_CHECKMATE,
GUNGI_ERROR_BRONZE_CHECKMATE,
GUNGI_ERROR_NO_TOWER,
GUNGI_ERROR_BACK_ONLY,
GUNGI_ERROR_FRONT_ONLY,
GUNGI_ERROR_IMMUNE,
GUNGI_ERROR_INVALID_EXCHANGE,
GUNGI_ERROR_INVALID_SUB,
GUNGI_ERROR_NO_STACK,
GUNGI_ERROR_NOT_TURN,
GUNGI_ERROR_DROPS_ONLY,
GUNGI_ERROR_INVALID_STATE,
GUNGI_NUM_ERRORS
} error_t;
extern const effect_bitfield_t k_UNIT_EFFECT[GUNGI_NUM_PIECES];
// Effect bitfields specifying the effects each unit has.
extern const effect_bitfield_t k_UNIT_IMMUNITY[GUNGI_NUM_PIECES];
// Effect bitfields specifying immunities for each unit.
extern const moveset_t k_UNIT_MOVES[GUNGI_NUM_PIECES];
// Moveset for each unit.
extern const int k_START_HAND[12][3];
// Multi-dimensional array specifying the number of front pieces of a
// particular unit in the starting hand with the specified back.
// =========
// FUNCTIONS
// =========
const char *error_to_string(error_t err);
// Returns a string corresponding to the error message for the given 'err'.
// Raises an exception if the given 'err' is not a valid error identifier.
const char *piece_to_string(piece_id_t piece);
// Returns a string corresponding to the name for the given 'piece'. Raises
// an assertion if the given 'id' is not a valid piece identifier.
const char *piece_to_gn_identifier(piece_id_t piece);
// Returns a string corresponding to the Gungi Notation identifier for the
// given piece, 'piece'.
piece_id_t gn_identifier_to_piece(const char *id);
// Returns the piece identifier for the given 'id' if found, otherwise
// 'GUNGI_PIECE_NONE'.
void gassert(const char *file,
unsigned int line,
const char *condition,
bool status);
// Triggers an assertion if the given 'status' is 'False', else 'True',
// printing a message to standard error, formatted with the given 'file' and
// given 'line'.
void gassert(const char *file,
unsigned int line,
const char *condition,
bool status,
const char *message,
...);
// Triggers an assertion if the given 'status' is 'False', else 'True',
// printing a message to standard error, formatted with the given 'file' and
// given 'line'.
} // close 'gungi' namespace
| 35.713178 | 85 | 0.710766 | hkpeprah |
ac4ec0560a82acb465041daa6ed4e3bbf5303817 | 7,854 | cpp | C++ | examples/timelines/mainwindow.cpp | minimoog/QTweetLib | e8c62faccd38c694dcfc7a5d3e55982cf7daaffc | [
"Apache-2.0"
] | 43 | 2015-02-27T07:55:10.000Z | 2022-02-20T13:37:48.000Z | examples/timelines/mainwindow.cpp | minimoog/QTweetLib | e8c62faccd38c694dcfc7a5d3e55982cf7daaffc | [
"Apache-2.0"
] | 3 | 2015-11-25T18:05:37.000Z | 2019-07-24T19:58:32.000Z | examples/timelines/mainwindow.cpp | minimoog/QTweetLib | e8c62faccd38c694dcfc7a5d3e55982cf7daaffc | [
"Apache-2.0"
] | 14 | 2015-01-29T18:50:58.000Z | 2019-12-31T07:35:39.000Z | /* Copyright 2010 Antonie Jovanoski
*
* 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.
*
* Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
*/
#include <QNetworkAccessManager>
#include <QTimer>
#include <QDateTime>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "oauthtwitter.h"
#include "qtweethometimeline.h"
#include "qtweetmentions.h"
#include "qtweetusertimeline.h"
#include "qtweetdirectmessages.h"
#include "qtweetstatus.h"
#include "qtweetdmstatus.h"
#include "qtweetuser.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_sinceidHomeTimeline = 0;
m_sinceidMentions = 0;
m_sinceidUserTimeline = 0;
m_sinceidDirectMessages = 0;
m_oauthTwitter = new OAuthTwitter(this);
m_oauthTwitter->setNetworkAccessManager(new QNetworkAccessManager(this));
connect(m_oauthTwitter, SIGNAL(authorizeXAuthFinished()), this, SLOT(xauthFinished()));
connect(m_oauthTwitter, SIGNAL(authorizeXAuthError()), this, SLOT(xauthError()));
m_timer = new QTimer(this);
m_timer->setInterval(60000);
connect(m_timer, SIGNAL(timeout()), this, SLOT(timerTimeOut()));
connect(ui->authorizePushButton, SIGNAL(clicked()), this, SLOT(authorizeButtonClicked()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::authorizeButtonClicked()
{
m_oauthTwitter->authorizeXAuth(ui->usernameLineEdit->text(), ui->passwordLineEdit->text());
}
void MainWindow::xauthFinished()
{
ui->statusBar->showMessage("xauth succesfull");
m_timer->start();
timerTimeOut();
}
void MainWindow::xauthError()
{
ui->statusBar->showMessage("xauth failed");
}
void MainWindow::timerTimeOut()
{
QTweetHomeTimeline *homeTimeline = new QTweetHomeTimeline(m_oauthTwitter, this);
homeTimeline->fetch(m_sinceidHomeTimeline);
connect(homeTimeline, SIGNAL(parsedStatuses(QList<QTweetStatus>)),
this, SLOT(homeTimelineStatuses(QList<QTweetStatus>)));
QTweetMentions *mentions = new QTweetMentions(m_oauthTwitter, this);
mentions->fetch(m_sinceidMentions);
connect(mentions, SIGNAL(parsedStatuses(QList<QTweetStatus>)),
this, SLOT(mentionsStatuses(QList<QTweetStatus>)));
QTweetUserTimeline *userTimeline = new QTweetUserTimeline(m_oauthTwitter, this);
userTimeline->fetch(0, QString(), m_sinceidUserTimeline);
connect(userTimeline, SIGNAL(parsedStatuses(QList<QTweetStatus>)),
this, SLOT(userTimelineStatuses(QList<QTweetStatus>)));
QTweetDirectMessages *dmTimeline = new QTweetDirectMessages(m_oauthTwitter, this);
dmTimeline->fetch(m_sinceidDirectMessages);
connect(dmTimeline, SIGNAL(parsedDirectMessages(QList<QTweetDMStatus>)),
this, SLOT(directMessages(QList<QTweetDMStatus>)));
}
void MainWindow::homeTimelineStatuses(const QList<QTweetStatus> &statuses)
{
QTweetHomeTimeline *homeTimeline = qobject_cast<QTweetHomeTimeline*>(sender());
if (homeTimeline) {
if (statuses.count()) {
//order is messed up, but this is just example
foreach (const QTweetStatus& status, statuses) {
ui->homeTimelineTextEdit->append("id: " + QString::number(status.id()));
ui->homeTimelineTextEdit->append("text: " + status.text());
ui->homeTimelineTextEdit->append("created: " + status.createdAt().toString());
QTweetUser userinfo = status.user();
ui->homeTimelineTextEdit->append("screen name: " + userinfo.screenName());
ui->homeTimelineTextEdit->append("user id: " + QString::number(userinfo.id()));
//is it retweet?
QTweetStatus rtStatus = status.retweetedStatus();
if (rtStatus.id()) {
ui->homeTimelineTextEdit->append("retweet text: " + rtStatus.text());
}
ui->homeTimelineTextEdit->append("----------------------------------------");
}
m_sinceidHomeTimeline = statuses.at(0).id();
}
homeTimeline->deleteLater();
}
}
void MainWindow::mentionsStatuses(const QList<QTweetStatus> &statuses)
{
QTweetMentions *mentions = qobject_cast<QTweetMentions*>(sender());
if (mentions) {
if (statuses.count()) {
foreach (const QTweetStatus& status, statuses) {
ui->mentionsTextEdit->append("id: " + QString::number(status.id()));
ui->mentionsTextEdit->append("text: " + status.text());
ui->mentionsTextEdit->append("created: " + status.createdAt().toString());
QTweetUser userinfo = status.user();
ui->mentionsTextEdit->append("screen name: " + userinfo.screenName());
ui->mentionsTextEdit->append("user id: " + QString::number(userinfo.id()));
ui->mentionsTextEdit->append("----------------------------------------");
}
m_sinceidMentions = statuses.at(0).id();
}
mentions->deleteLater();
}
}
void MainWindow::userTimelineStatuses(const QList<QTweetStatus> &statuses)
{
QTweetUserTimeline *userTimeline = qobject_cast<QTweetUserTimeline*>(sender());
if (userTimeline) {
if (statuses.count()) {
//order is messed up, but this is just example
foreach (const QTweetStatus& status, statuses) {
ui->userTimelineTextEdit->append("id: " + QString::number(status.id()));
ui->userTimelineTextEdit->append("text: " + status.text());
ui->userTimelineTextEdit->append("created: " + status.createdAt().toString());
QTweetUser userinfo = status.user();
ui->userTimelineTextEdit->append("screen name: " + userinfo.screenName());
ui->userTimelineTextEdit->append("user id: " + QString::number(userinfo.id()));
ui->userTimelineTextEdit->append("----------------------------------------");
}
m_sinceidUserTimeline = statuses.at(0).id();
}
userTimeline->deleteLater();
}
}
void MainWindow::directMessages(const QList<QTweetDMStatus> &directMessages)
{
QTweetDirectMessages *dmTimeline = qobject_cast<QTweetDirectMessages*>(sender());
if (dmTimeline) {
if (directMessages.count()) {
foreach (const QTweetDMStatus& message, directMessages) {
ui->directMessagesTextEdit->append("id: " + QString::number(message.id()));
ui->directMessagesTextEdit->append("text: " + message.text());
ui->directMessagesTextEdit->append("created: " + message.createdAt().toString());
ui->directMessagesTextEdit->append("sender: " + message.senderScreenName());
ui->directMessagesTextEdit->append("sender id: " + QString::number(message.senderId()));
ui->directMessagesTextEdit->append("----------------------------------------");
}
m_sinceidDirectMessages = directMessages.at(0).id();
}
}
dmTimeline->deleteLater();
}
| 35.378378 | 104 | 0.640183 | minimoog |
ac535f91559ae32147aa093d38dd8501dc35413a | 5,346 | cpp | C++ | src/libs/qlib/qradio.cpp | 3dhater/Racer | d7fe4014b1efefe981528547649dc397da7fa780 | [
"Unlicense"
] | null | null | null | src/libs/qlib/qradio.cpp | 3dhater/Racer | d7fe4014b1efefe981528547649dc397da7fa780 | [
"Unlicense"
] | null | null | null | src/libs/qlib/qradio.cpp | 3dhater/Racer | d7fe4014b1efefe981528547649dc397da7fa780 | [
"Unlicense"
] | 1 | 2021-01-03T16:16:47.000Z | 2021-01-03T16:16:47.000Z | /*
* QRadio - radio buttons
* 18-06-97: Created!
* (C) MarketGraph/RVG
*/
#include <qlib/radio.h>
#include <qlib/canvas.h>
#include <qlib/event.h>
#include <qlib/app.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <time.h>
#include <qlib/debug.h>
DEBUG_ENABLE
#define QBSW 4 // Shadow size
#define BOXSIZE 16 // Checkbox size
#define BOXSPACE 4 // Space between box & text
QRadio::QRadio(QWindow *parent,QRect *ipos,string itext,int igroup)
: QWindow(parent,ipos->x,ipos->y,ipos->wid,ipos->hgt)
{
//printf("QRadio ctor, text=%p this=%p\n",itext,this);
//printf("button '%s'\n",itext);
// Shadow lines
colText=new QColor(0,0,0);
font=app->GetSystemFont();
if(itext)
text=qstrdup(itext);
else text=0;
group=igroup;
// Size check so it fits text
if(text)
{
Size(font->GetWidth(text)+BOXSPACE+BOXSIZE,font->GetHeight(text));
//pos.wid=font->GetWidth(text)+BOXSPACE+BOXSIZE;
//pos.hgt=font->GetHeight(text);
//if(pos.hgt<BOXSIZE)pos.hgt=BOXSIZE;
}
state=DISARMED;
chkState=0;
// No shortcut key
scKey=0; scMod=0;
eventType=QEVENT_CLICK;
Create();
// Take minimal amount of events
// Include keystrokes because a shortcut key may be assigned to each button
Catch(CF_BUTTONPRESS|CF_BUTTONRELEASE|CF_KEYPRESS);
//printf("QRadio ctor RET\n");
}
QRadio::~QRadio()
{
}
void QRadio::SetText(string ntext)
{ if(text)qfree(text);
text=qstrdup(ntext);
}
void QRadio::SetTextColor(QColor *col)
{ colText->SetRGBA(col->GetR(),col->GetG(),col->GetB(),col->GetA());
}
void QRadio::SetState(bool yn)
{ chkState=yn;
}
void QRadio::Paint(QRect *r)
{ QRect rr;
int sw=4; // Shadow width/height
Restore();
// Paint insides
//cv->Insides(pos.x,pos.y,BOXSIZE,BOXSIZE);
//qdbg("inside\n");
#ifdef OBS
// Paint border
if(state==ARMED)
cv->Inline(pos.x,pos.y,BOXSIZE,BOXSIZE);
else
cv->Outline(pos.x,pos.y,BOXSIZE,BOXSIZE);
#endif
QRect pos;
GetPos(&pos);
pos.x=0; pos.y=0;
pos.y+=2; // Offset for SGI
cv->SetColor(80,80,80);
cv->Rectfill(pos.x+4,pos.y+0,4,1);
cv->Rectfill(pos.x+2,pos.y+1,1,3);
cv->Rectfill(pos.x+1,pos.y+2,3,1);
cv->Rectfill(pos.x+0,pos.y+4,1,4);
cv->Rectfill(pos.x+1,pos.y+9,1,1);
cv->Rectfill(pos.x+2,pos.y+10,2,1);
cv->Rectfill(pos.x+4,pos.y+11,5,1);
cv->Rectfill(pos.x+9,pos.y+1,1,1);
cv->Rectfill(pos.x+10,pos.y+2,1,2);
cv->Rectfill(pos.x+11,pos.y+4,1,5);
cv->Rectfill(pos.x+9,pos.y+9,1,1);
cv->Rectfill(pos.x+10,pos.y+9,1,1);
cv->SetColor(0,0,0);
cv->Rectfill(pos.x+3,pos.y+1,6,1);
cv->Rectfill(pos.x+2,pos.y+2,1,1);
cv->Rectfill(pos.x+9,pos.y+2,1,1);
cv->Rectfill(pos.x+1,pos.y+3,1,6);
cv->Rectfill(pos.x+2,pos.y+9,1,1);
cv->SetColor(255,255,255);
cv->Rectfill(pos.x+4,pos.y+12,5,1);
cv->Rectfill(pos.x+9,pos.y+11,2,1);
cv->Rectfill(pos.x+11,pos.y+9,1,2);
cv->Rectfill(pos.x+12,pos.y+4,1,5);
cv->SetColor(255,255,255);
cv->Rectfill(pos.x+4,pos.y+2,5,9);
cv->Rectfill(pos.x+3,pos.y+3,7,7);
cv->Rectfill(pos.x+2,pos.y+4,9,5);
if(chkState!=0)
{ // Hilite dot
cv->SetColor(80,80,80);
cv->Rectfill(pos.x+5,pos.y+3,3,7);
cv->Rectfill(pos.x+3,pos.y+5,7,3);
cv->SetColor(0,0,0);
cv->Rectfill(pos.x+4,pos.y+4,5,5);
}
pos.y-=2;
//skip_shadow2:
// Draw text if any
if(text)
{ int tx,ty,twid,thgt;
cv->SetColor(colText);
cv->SetFont(font);
// Align just outside rect
thgt=font->GetHeight();
twid=font->GetWidth(text);
tx=pos.x+BOXSIZE+BOXSPACE;
ty=(pos.hgt-thgt)/2+pos.y;
/*printf("twid=%d, hgt=%d, x=%d, y=%d (pos=%d,%d %dx%d)\n",
twid,thgt,tx,ty,pos.x,pos.y,pos.wid,pos.hgt);*/
cv->Text(text,tx,ty);
//skip_text:;
}
//qdbg(" paint RET\n");
}
// Events
bool QRadio::EvButtonPress(int button,int x,int y)
{
//qdbg("QRadio::EvButtonPress\n");
state=ARMED;
Paint();
//Focus(TRUE);
return TRUE;
}
bool QRadio::EvButtonRelease(int button,int x,int y)
{ QEvent e;
QWindow *w;
int i;
//qdbg("QRadio::EvButtonRelease, this=%p\n",this);
if(state==DISARMED)return FALSE;
state=DISARMED;
// Deselect other radio buttons belonging to this group
for(i=0;;i++)
{ w=app->GetWindowManager()->GetWindowN(i);
if(!w)break;
if(!strcmp(w->ClassName(),"radio")) // RTTI?
{ QRadio *r=(QRadio*)w;
if(r->GetGroup()==group)
{ r->SetState(0);
r->Paint();
}
}
}
// Select this one
chkState=1;
Paint();
//Focus(FALSE);
// Generate click event
e.type=eventType;
e.win=this;
app->GetWindowManager()->PushEvent(&e);
return TRUE;
}
bool QRadio::EvKeyPress(int key,int x,int y)
{
//printf("QRadio keypress $%x @%d,%d\n",key,x,y);
if(scKey==key)
{ // Simulate button press
EvButtonPress(1,x,y);
QNap(CLK_TCK/50); // Make sure it shows
EvButtonRelease(1,x,y);
return TRUE; // Eat the event
}
return FALSE;
}
// Behavior
void QRadio::ShortCut(int key,int mod)
{
//printf("shortcut %x %x\n",key,mod);
scKey=key;
scMod=mod;
}
void QRadio::SetEventType(int eType)
// If eType==0, normal click events are generated
// Otherwise, special 'eType' events are generated
// eType must be a user event
{
if(eType==0)
{ eventType=QEVENT_CLICK;
} else
{ QASSERT_V(eType>=QEVENT_USER); // Button event type
eventType=eType;
}
}
| 22.944206 | 77 | 0.628133 | 3dhater |
ac5592d7bf5cd0f5e7f5ce7d7ed157c0a7469e54 | 2,184 | cpp | C++ | apps/network/network-host.cpp | UCLA-VAST/tapa | 2b9a5d3a201875e4a7cb0fcc04d64ef92ab2d66a | [
"MIT"
] | 24 | 2021-01-27T17:37:47.000Z | 2022-03-30T21:42:45.000Z | apps/network/network-host.cpp | UCLA-VAST/tapa | 2b9a5d3a201875e4a7cb0fcc04d64ef92ab2d66a | [
"MIT"
] | 56 | 2020-11-21T02:20:13.000Z | 2022-03-31T23:16:37.000Z | apps/network/network-host.cpp | UCLA-VAST/tapa | 2b9a5d3a201875e4a7cb0fcc04d64ef92ab2d66a | [
"MIT"
] | 7 | 2021-01-27T17:44:58.000Z | 2022-03-30T01:17:45.000Z | #include <cmath>
#include <algorithm>
#include <bitset>
#include <chrono>
#include <iostream>
#include <limits>
#include <random>
#include <vector>
#include <gflags/gflags.h>
#include <tapa.h>
using std::abs;
using std::clog;
using std::endl;
using std::vector;
using std::chrono::duration;
using std::chrono::high_resolution_clock;
using pkt_t = uint64_t;
constexpr int kN = 8; // kN x kN network
using pkt_vec_t = tapa::vec_t<pkt_t, kN>;
void Network(tapa::mmap<pkt_vec_t> input, tapa::mmap<pkt_vec_t> output,
uint64_t n);
DEFINE_string(bitstream, "", "path to bitstream file, run csim if empty");
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
uint64_t n = 1ULL << 15;
vector<pkt_t> input(n);
std::mt19937 gen;
std::uniform_int_distribution<uint64_t> dist(0, 1ULL << 32);
for (uint64_t i = 0; i < n; ++i) {
input[i] = (dist(gen) & ~7) | i;
}
std::random_shuffle(input.begin(), input.end());
vector<pkt_t> output(n);
const auto start = high_resolution_clock::now();
tapa::invoke(Network, FLAGS_bitstream,
tapa::read_only_mmap<pkt_t>(input).vectorized<kN>(),
tapa::write_only_mmap<pkt_t>(output).vectorized<kN>(), n / kN);
const auto stop = high_resolution_clock::now();
duration<double> elapsed = stop - start;
clog << "elapsed time: " << elapsed.count() << " s" << endl;
uint64_t num_errors = 0;
const uint64_t threshold = 10; // only report up to these errors
for (uint64_t i = 0; i < n / kN; ++i) {
for (uint64_t j = 0; j < kN; ++j) {
std::bitset<3> actual = output[i * kN + j];
std::bitset<3> expected = j;
if (expected != actual) {
if (num_errors < threshold) {
clog << "expected: " << expected << ", actual: " << actual << endl;
} else if (num_errors == threshold) {
clog << "...";
}
++num_errors;
}
}
}
if (num_errors == 0) {
clog << "PASS!" << endl;
} else {
if (num_errors > threshold) {
clog << " (+" << (num_errors - threshold) << " more errors)" << endl;
}
clog << "FAIL!" << endl;
}
return num_errors > 0 ? 1 : 0;
}
| 26.634146 | 78 | 0.599359 | UCLA-VAST |
ac564687f0117cd45a4c9baeb52eb2c3b17b32a0 | 546 | hxx | C++ | base/cluster/resdll/spooler/splsvc/global.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/cluster/resdll/spooler/splsvc/global.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/cluster/resdll/spooler/splsvc/global.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1996 Microsoft Corporation
All rights reserved.
Module Name:
global.hxx
Abstract:
Contains all global definitions. This will be included in precomp.hxx,
so it should be kept to a bare minimum of things that change
infrequently.
Author:
Albert Ting (AlbertT) 16-Oct-96
Revision History:
--*/
#ifndef _GLOBAL_HXX
#define _GLOBAL_HXX
#include "debug.hxx"
#ifndef COUNTOF
#define COUNTOF( a ) (sizeof( a ) / sizeof( a[0] ))
#endif
#endif // ifndef _GLOBAL_HXX
| 15.6 | 76 | 0.657509 | npocmaka |
ac577bc5604480c2e4d50d1da27b24dfba807e77 | 1,312 | hpp | C++ | include/nbdl/detail/wrap_promise.hpp | ricejasonf/nbdl | ae63717c96ab2c36107bc17b2b00115f96e9d649 | [
"BSL-1.0"
] | 47 | 2016-06-20T01:41:24.000Z | 2021-11-16T10:53:27.000Z | include/nbdl/detail/wrap_promise.hpp | ricejasonf/nbdl | ae63717c96ab2c36107bc17b2b00115f96e9d649 | [
"BSL-1.0"
] | 21 | 2015-11-12T23:05:47.000Z | 2019-07-17T19:01:40.000Z | include/nbdl/detail/wrap_promise.hpp | ricejasonf/nbdl | ae63717c96ab2c36107bc17b2b00115f96e9d649 | [
"BSL-1.0"
] | 6 | 2015-11-12T21:23:29.000Z | 2019-05-09T17:54:25.000Z | //
// Copyright Jason Rice 2017
// 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 NBDL_DETAIL_WRAP_PROMISE_HPP
#define NBDL_DETAIL_WRAP_PROMISE_HPP
#include <nbdl/fwd/detail/wrap_promise.hpp>
#include <nbdl/promise.hpp>
#include <nbdl/fwd/detail/promise_join.hpp>
#include <boost/hana/core/is_a.hpp>
#include <stdexcept>
#include <utility>
namespace nbdl::detail
{
namespace hana = boost::hana;
// Implicity wraps functions
// and pipes
// with the promise interface.
template <typename X>
auto wrap_promise_fn::operator()(X&& x) const
{
if constexpr(hana::is_a<promise_tag, X>())
{
return std::forward<X>(x);
}
else
{
auto temp = std::forward<X>(x); //??
return nbdl::promise([fn = std::move(temp)](auto&& resolver, auto&& ...args)
{
using Return = decltype(fn(std::forward<decltype(args)>(args)...));
// handle void edge case
if constexpr(std::is_void<Return>::value)
{
fn(std::forward<decltype(args)>(args)...);
resolver.resolve();
}
else
{
resolver.resolve(fn(std::forward<decltype(args)>(args)...));
}
});
}
};
}
#endif
| 23.854545 | 82 | 0.622713 | ricejasonf |
ac59fc38a54ef7e1029bd7449775eae9b8f8568f | 18,789 | cpp | C++ | src/JsonHandle.cpp | DoomHammer/jsonhandle | bf07059fa400c292ee28f0993a3219c0ece4b0d7 | [
"MIT"
] | null | null | null | src/JsonHandle.cpp | DoomHammer/jsonhandle | bf07059fa400c292ee28f0993a3219c0ece4b0d7 | [
"MIT"
] | null | null | null | src/JsonHandle.cpp | DoomHammer/jsonhandle | bf07059fa400c292ee28f0993a3219c0ece4b0d7 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2010,2011 Thomas Davis
*
* 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 "JsonHandle.h"
#include "_JS0.h"
#include <stdio.h>
#include <ios>
#ifdef HAS_JSON_STATS
static struct stats {
unsigned allocs;
unsigned frees;
} stats;
#endif
#define PRINTERR(foo,msg) fprintf(stderr,"JsonHandle::%s: %s\n", foo, msg)
#define STATE_NEW_NODE 0
#define STATE_HAS_NODE 1
#define STATE_NEW_CHILD_BY_KEY 2
#define STATE_NEW_CHILD_BY_STLKEY 3
#define STATE_NEW_CHILD_BY_INDEX 4
#define STATE_ORPHAN 5
const std::string JsonHandle::EMPTY_STRING;
int JsonHandle::defaultPrecision = 4;
JsonHandle JsonHandle::JSON_ERROR(NULL);
JsonHandle::~JsonHandle() {
#ifdef HAS_JSON_STATS
stats.frees++;
#endif
if (parent) {
parent->release();
parent = 0;
}
if (state == STATE_HAS_NODE) {
vapor.node->release();
state = STATE_ORPHAN;
}
}
JsonHandle::JsonHandle(const JsonHandle &from) :
parent(from.parent), state(from.state), vapor(from.vapor) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
if (state == STATE_HAS_NODE
)
vapor.node->reserve();
if (parent)
parent->reserve();
}
JsonHandle::JsonHandle() :
parent(0), state(STATE_NEW_NODE) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
}
JsonHandle::JsonHandle(_JS0 *node) :
parent(0) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
if (node) {
node->reserve();
vapor.node = node;
state = STATE_HAS_NODE;
} else {
vapor.node = (_JS0 *) -1;
state = STATE_ORPHAN;
}
if (parent)
parent->reserve();
}
JsonHandle::JsonHandle(_JS0 *node, _JS0 *parent) :
parent(parent) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
if (node) {
node->reserve();
vapor.node = node;
state = STATE_HAS_NODE;
} else {
state = STATE_ORPHAN;
}
if (parent)
parent->reserve();
}
JsonHandle::JsonHandle(_JS0 *parent, int index) :
parent(parent) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
parent->reserve();
state = STATE_NEW_CHILD_BY_INDEX;
vapor.index = index;
}
JsonHandle::JsonHandle(_JS0 *parent, const char *key) :
parent(parent) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
parent->reserve();
state = STATE_NEW_CHILD_BY_KEY;
vapor.key = key;
}
JsonHandle::JsonHandle(_JS0 *parent, const std::string &key) :
parent(parent) {
#ifdef HAS_JSON_STATS
stats.allocs++;
#endif
parent->reserve();
state = STATE_NEW_CHILD_BY_STLKEY;
vapor.stlkey = &key;
}
JsonHandle &
JsonHandle::copy(const JsonHandle &from) {
if (state != STATE_HAS_NODE) {
makeVaporNode("copy()");
if (state != STATE_HAS_NODE
)
return *this;
}
if (from.state == STATE_HAS_NODE
)
vapor.node->copy(*(from.vapor.node));
else
vapor.node->setBoolean(false);
return *this;
}
JsonHandle &
JsonHandle::operator=(const JsonHandle &from) {
if (&from != this && from.state == STATE_HAS_NODE) {
if (state != STATE_HAS_NODE) {
if (state != STATE_HAS_NODE) {
makeVaporNode("operator[](int)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
}
}
vapor.node->copy(*from.vapor.node);
}
return *this;
}
JsonHandle JsonHandle::operator[](int index) {
if (state != STATE_HAS_NODE) {
makeVaporNode("operator[](int)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
vapor.node->setArray();
}
int len = size();
if (index == -1 || index == len) // may be trying to append item
return JsonHandle(vapor.node, len);
if (index < 0 || index > len) {
PRINTERR("operator[](int)", "index out of bounds");
return JsonHandle::JSON_ERROR;
}
_JS0 *n = vapor.node->getByIndex(index);
return n ? JsonHandle(n, vapor.node) : JsonHandle(vapor.node, index);
}
JsonHandle JsonHandle::operator[](const char *key) {
if (key == NULL)
{
PRINTERR("operator[](char *)", "null key pointer");
return JsonHandle::JSON_ERROR;
}
if (state != STATE_HAS_NODE) {
makeVaporNode("operator[](char *)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
vapor.node->setObject();
}
_JS0 *n = vapor.node->getByKey(key);
return n ? JsonHandle(n, vapor.node) : JsonHandle(vapor.node, key);
}
JsonHandle JsonHandle::operator[](const std::string &key) {
if (state != STATE_HAS_NODE) {
makeVaporNode("operator[](string &)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
vapor.node->setObject();
}
_JS0 *n = vapor.node->getByKey(key);
return n ? JsonHandle(n, vapor.node) : JsonHandle(vapor.node, key);
}
JsonHandle JsonHandle::at(int index) {
if (state != STATE_HAS_NODE) {
makeVaporNode("at(int)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
vapor.node->setArray();
}
int len = size();
if (index == -1 || index == len) // may be trying to append item
return JsonHandle(vapor.node, len);
if (index < 0 || index > len) {
PRINTERR("at(int)", "index out of bounds");
return JsonHandle::JSON_ERROR;
}
_JS0 *n = vapor.node->getByIndex(index);
return n ? JsonHandle(n, vapor.node) : JsonHandle(vapor.node, index);
}
JsonHandle JsonHandle::at(const char *key) {
if (key == NULL)
{
PRINTERR("at(char *)", "null key pointer");
return JsonHandle::JSON_ERROR;
}
if (state != STATE_HAS_NODE) {
makeVaporNode("at(char *)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
vapor.node->setObject();
}
_JS0 *n = vapor.node->getByKey(key);
return n ? JsonHandle(n, vapor.node) : JsonHandle(vapor.node, key);
}
JsonHandle JsonHandle::at(const std::string &key) {
if (state != STATE_HAS_NODE) {
makeVaporNode("operator[](string &)");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
vapor.node->setObject();
}
_JS0 *n = vapor.node->getByKey(key);
return n ? JsonHandle(n, vapor.node) : JsonHandle(vapor.node, key);
}
int JsonHandle::size() {
return (state == STATE_HAS_NODE
&& (vapor.node->getType() == _JS0::ARRAY
|| vapor.node->getType() == _JS0::OBJECT)) ?
vapor.node->length() : 0;
}
JsonHandle&
JsonHandle::setLong(int64_t x) {
if (state != STATE_HAS_NODE) {
makeVaporNode("setLong()");
if (state != STATE_HAS_NODE
)
return *this;
}
vapor.node->setLong(x);
return *this;
}
JsonHandle&
JsonHandle::setBoolean(bool x) {
if (state != STATE_HAS_NODE) {
makeVaporNode("setBoolean()");
if (state != STATE_HAS_NODE
)
return *this;
}
vapor.node->setBoolean(x);
return *this;
}
JsonHandle&
JsonHandle::setDouble(long double x) {
if (state != STATE_HAS_NODE) {
makeVaporNode("setDouble()");
if (state != STATE_HAS_NODE
)
return *this;
}
vapor.node->setDouble(x);
return *this;
}
JsonHandle&
JsonHandle::setString(const char *x) {
if (state != STATE_HAS_NODE) {
makeVaporNode("setString(char *)");
if (state != STATE_HAS_NODE
)
return *this;
}
if (x == NULL
)
vapor.node->setNull();
else
vapor.node->setString(x);
return *this;
}
JsonHandle&
JsonHandle::setString(const std::string &x) {
if (state != STATE_HAS_NODE) {
makeVaporNode("setString(string &)");
if (state != STATE_HAS_NODE
)
return *this;
}
vapor.node->setString(x);
return *this;
}
void JsonHandle::makeVaporNode(const char *foo) {
if (!parent && state == STATE_ORPHAN) {
PRINTERR(foo, "null reference error");
return;
}
if (parent && (state == STATE_ORPHAN)) {
PRINTERR(foo, "internal error, no vapor");
return;
}
_JS0 *n = new _JS0();
if (n == 0) {
PRINTERR(foo, "error: cannot allocate node");
return;
}
n->reserve();
if (parent) {
if (state == STATE_NEW_CHILD_BY_STLKEY) {
parent->setByKey(*(vapor.stlkey), n);
} else if (state == STATE_NEW_CHILD_BY_KEY) {
parent->setByKey(vapor.key, n);
} else {
parent->setByIndex(vapor.index, n);
}
}
vapor.node = n;
state = STATE_HAS_NODE;
}
static bool parseLong(const std::string &s, int64_t &value) {
const char *p = s.c_str();
bool isneg = (*p == '-');
if (isneg)
p++;
if (*p < '0' || *p > '9')
return false;
value = *p++ - '0';
while (*p) {
if (*p < '0' || *p > '9')
return false;
value = value * 10 + (*p++ - '0');
}
if (isneg)
value = -value;
return true;
}
static bool parseDouble(const std::string &s, long double &value) {
const char *p = s.c_str();
bool isneg = (*p == '-');
if (isneg)
p++;
if (*p < '0' || *p > '9')
return false;
int64_t ip = *p++ - '0';
while (*p) {
if (*p < '0' || *p > '9') {
if (*p == '.')
break;
return false;
}
ip = ip * 10 + (*p++ - '0');
}
value = (long double) ip;
if (*p == '.') {
p++;
ip = 10;
while (*p) {
if (*p < '0' || *p > '9')
return false;
value += (long double) (*p++ - '0') / (long double) ip;
ip *= 10;
}
}
if (isneg)
value = -value;
return true;
}
static bool parseBoolean(const std::string &s, bool &value) {
#define IS_LCC(i,c) ((((unsigned)(s[i]))|32)==(unsigned)(c))
if (s.length() == 5) {
if (IS_LCC(0,'f') && IS_LCC(1,'a') && IS_LCC(2,'l') && IS_LCC(3,'s')
&& IS_LCC(3,'e')) {
value = false;
return true;
}
}
if (s.length() == 4) {
if (IS_LCC(0,'t') && IS_LCC(1,'r') && IS_LCC(2,'u') && IS_LCC(3,'e')) {
value = true;
return true;
}
}
if (s.length() == 3) {
if (IS_LCC(0,'y') && IS_LCC(1,'e') && IS_LCC(2,'s')) {
value = true;
return true;
}
if (IS_LCC(0,'o') && IS_LCC(1,'f') && IS_LCC(2,'f')) {
value = false;
return true;
}
}
if (s.length() == 2) {
if (IS_LCC(0,'o') && IS_LCC(1,'n')) {
value = true;
return true;
}
}
if (s.length() == 1) {
if (IS_LCC(0,'t') || IS_LCC(0,'1') || IS_LCC(0,'y')) {
value = true;
return true;
}
if (IS_LCC(0,'f') || IS_LCC(0,'0') || IS_LCC(0,'n')) {
value = false;
return true;
}
}
return false;
}
int64_t JsonHandle::longValue(int64_t defaultValue) const {
if (state == STATE_HAS_NODE) {
if (vapor.node->getType() == _JS0::NUMBER_LONG
|| vapor.node->getType() == _JS0::NUMBER_DOUBLE)
return vapor.node->longValue();
if (vapor.node->getType() == _JS0::BOOLEAN)
return vapor.node->booleanValue() ? 1 : 0;
if (vapor.node->getType() == _JS0::STRING) {
const std::string &s = vapor.node->stringValue();
int64_t value;
if (parseLong(s, value)) {
vapor.node->setLong(value);
return value;
}
}
}
return defaultValue;
}
bool JsonHandle::booleanValue(bool defaultValue) const {
if (state == STATE_HAS_NODE) {
if (vapor.node->getType() == _JS0::BOOLEAN)
return vapor.node->booleanValue();
if (vapor.node->getType() == _JS0::NUMBER_LONG
|| vapor.node->getType() == _JS0::NUMBER_DOUBLE)
return vapor.node->longValue() ? true : false;
if (vapor.node->getType() == _JS0::STRING) {
const std::string &s = vapor.node->stringValue();
bool value;
if (parseBoolean(s, value)) {
vapor.node->setBoolean(value);
return value;
}
}
}
return defaultValue;
}
long double JsonHandle::doubleValue(long double defaultValue) const {
if (state == STATE_HAS_NODE) {
if (vapor.node->getType() == _JS0::NUMBER_DOUBLE
|| vapor.node->getType() == _JS0::NUMBER_LONG)
return vapor.node->doubleValue();
if (vapor.node->getType() == _JS0::BOOLEAN)
return vapor.node->booleanValue() ? 1 : 0;
if (vapor.node->getType() == _JS0::STRING) {
const std::string &s = vapor.node->stringValue();
long double value;
if (parseDouble(s, value)) {
vapor.node->setDouble(value);
return value;
}
}
}
return defaultValue;
}
const std::string &
JsonHandle::stringValue(std::string const &defaultValue) const {
if (state == STATE_HAS_NODE) {
if (vapor.node->getType() == _JS0::STRING)
return vapor.node->stringValue();
if (vapor.node->getType() == _JS0::BOOLEAN) {
vapor.node->setString(
vapor.node->booleanValue() ? "true" : "false");
return vapor.node->stringValue();
}
if (vapor.node->getType() == _JS0::NUMBER_LONG
|| vapor.node->getType() == _JS0::NUMBER_DOUBLE) {
std::string s;
vapor.node->appendStringValue(s, defaultPrecision);
vapor.node->setString(s);
return vapor.node->stringValue();
}
}
return defaultValue;
}
const char *
JsonHandle::stringValuePtr(const char *defaultValue) const {
if (state == STATE_HAS_NODE) {
if (vapor.node->getType() == _JS0::STRING) {
const std::string &s = vapor.node->stringValue();
return s.c_str();
}
if (vapor.node->getType() == _JS0::BOOLEAN) {
vapor.node->setString(
vapor.node->booleanValue() ? "true" : "false");
const std::string &s = vapor.node->stringValue();
return s.c_str();
}
if (vapor.node->getType() == _JS0::NUMBER_LONG
|| vapor.node->getType() == _JS0::NUMBER_DOUBLE) {
std::string st;
vapor.node->appendStringValue(st, defaultPrecision);
vapor.node->setString(st);
const std::string &s = vapor.node->stringValue();
return s.c_str();
}
}
return defaultValue;
}
std::string &
JsonHandle::toString(std::string &buffer, int precision) const {
if (state == STATE_HAS_NODE
)
vapor.node->appendJsonString(buffer, true, precision, 0);
return buffer;
}
const std::string &
JsonHandle::key(int index) const {
return (state == STATE_HAS_NODE) ?
vapor.node->getKeyAtIndex(index) : *(std::string*) 0;
}
bool
JsonHandle::exists(std::string const &key) const {
_JS0 *n = vapor.node->getByKey(key);
return n != NULL;
}
std::string &
JsonHandle::toCompactString(std::string &buffer, int precision) const {
if (state == STATE_HAS_NODE
)
vapor.node->appendJsonString(buffer, false, precision, 0);
return buffer;
}
JsonHandle &
JsonHandle::clear() {
if (state == STATE_HAS_NODE
)
vapor.node->clear();
return *this;
}
JsonHandle &
JsonHandle::erase(int index) {
if (state == STATE_HAS_NODE
)
vapor.node->erase(index);
return *this;
}
JsonHandle &
JsonHandle::erase(const char *key) {
if (state == STATE_HAS_NODE
)
vapor.node->erase(key);
return *this;
}
JsonHandle &
JsonHandle::erase(const std::string &key) {
if (state == STATE_HAS_NODE
)
vapor.node->erase(key);
return *this;
}
bool JsonHandle::isNull() const {
return state == STATE_HAS_NODE && vapor.node->getType() == _JS0::NULLVALUE;
}
bool JsonHandle::isArray() const {
return state == STATE_HAS_NODE && vapor.node->getType() == _JS0::ARRAY;
}
bool JsonHandle::isObject() const {
return state == STATE_HAS_NODE && vapor.node->getType() == _JS0::OBJECT;
}
bool JsonHandle::isString() const {
return state == STATE_HAS_NODE && vapor.node->getType() == _JS0::STRING;
}
bool JsonHandle::isNumber() const {
return state == STATE_HAS_NODE
&& (vapor.node->getType() == _JS0::NUMBER_LONG
|| vapor.node->getType() == _JS0::NUMBER_DOUBLE);
}
bool JsonHandle::isBoolean() const {
return state == STATE_HAS_NODE && vapor.node->getType() == _JS0::BOOLEAN;
}
JsonHandle &
JsonHandle::fromString(const std::string &from) {
if (state != STATE_HAS_NODE) {
makeVaporNode("fromString()");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
}
if (!vapor.node->setFromJsonStlString(from)) {
return JsonHandle::JSON_ERROR;
}
return *this;
}
JsonHandle &
JsonHandle::fromString(const char *from) {
if (state != STATE_HAS_NODE) {
makeVaporNode("fromString()");
if (state != STATE_HAS_NODE
)
return JsonHandle::JSON_ERROR;
}
if (from == 0 || !vapor.node->setFromJsonString(from)) {
return JsonHandle::JSON_ERROR;
}
return *this;
}
void JsonHandle::dumpStats() {
#ifdef HAS_JSON_STATS
fprintf(stderr, "\n+------------------------------+\n");
fprintf(stderr, "| JsonHandle Stats |\n");
fprintf(stderr, "|------------------------------|\n");
fprintf(stderr, "| handle allocs | %10u |\n", stats.allocs);
fprintf(stderr, "| frees | %10u |\n", stats.frees);
fprintf(stderr, "| node allocs | %10u |\n", _JS0::stats.allocs);
fprintf(stderr, "| frees | %10u |\n", _JS0::stats.frees);
fprintf(stderr, "| reserves | %10u |\n", _JS0::stats.reserves);
fprintf(stderr, "| releases | %10u |\n", _JS0::stats.releases);
fprintf(stderr, "+------------------------------+\n\n");
#else
fprintf(stderr,"JsonHandle: dumpStats() not compiled in with -DHAS_JSON_STATS\n");
#endif
}
JsonHandle &
JsonHandle::fromFile(const char *file) {
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
FILE* fp = 0;
if ( fopen_s( &fp, file, "r" ) )
fp = 0;
#else
FILE *fp = fopen(file, "r");
#endif
if (fp == 0) {
PRINTERR("fromFile()", "could not read file");
return JsonHandle::JSON_ERROR;
}
long length = 0;
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buf = new char[length + 1];
if (buf == 0) {
// could not allocate memory, file too large?
PRINTERR("fromFile()", "could not allocate memory");
fclose(fp);
return JsonHandle::JSON_ERROR;
}
if (!fread(buf, length, 1, fp)) length = 0;
fclose(fp);
buf[length] = 0;
JsonHandle &ret = fromString(buf);
delete []buf;
return ret;
}
bool JsonHandle::toFile(const char *file, int precision) const {
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
FILE* fp = 0;
if ( fopen_s( &fp, file, "w" ) )
fp = 0;
#else
FILE *fp = fopen(file, "w");
#endif
if (fp == 0) {
PRINTERR("toFile()", "could not write file");
return false;
}
std::string buffer;
toString(buffer, precision);
fwrite(buffer.data(), 1, buffer.length(), fp);
fclose(fp);
return true;
}
std::istream &
JsonHandle::fromStream(std::istream &stream) {
if (stream.rdstate() & std::ios_base::failbit)
return stream;
if (state != STATE_HAS_NODE) {
makeVaporNode("fromStream()");
if (state != STATE_HAS_NODE
) {
stream.setstate(stream.rdstate() | std::ios_base::failbit);
return stream;
}
}
if (!vapor.node->setFromStream(stream)) {
stream.setstate(stream.rdstate() | std::ios_base::failbit);
return stream;
}
return stream;
}
std::ostream &
JsonHandle::toStream(std::ostream &stream) {
if (state == STATE_HAS_NODE
) {
std::string buf;
vapor.node->appendStream(stream);
}
return stream;
}
| 23.753477 | 83 | 0.646549 | DoomHammer |
ac5b1f9fb5de9f951bbdc7bf921622f6c22f41a3 | 2,686 | hpp | C++ | include/Lz/Map.hpp | ExternalRepositories/cpp-lazy | df9295a5a2a7f4c3ef4657f73d5e84b576fc82c3 | [
"MIT"
] | 263 | 2020-06-24T19:46:43.000Z | 2022-03-29T08:47:01.000Z | include/Lz/Map.hpp | ExternalRepositories/cpp-lazy | df9295a5a2a7f4c3ef4657f73d5e84b576fc82c3 | [
"MIT"
] | 11 | 2020-07-15T14:24:42.000Z | 2021-09-11T14:50:00.000Z | include/Lz/Map.hpp | ExternalRepositories/cpp-lazy | df9295a5a2a7f4c3ef4657f73d5e84b576fc82c3 | [
"MIT"
] | 11 | 2020-09-10T02:32:26.000Z | 2022-01-26T04:24:31.000Z | #pragma once
#ifndef LZ_MAP_HPP
#define LZ_MAP_HPP
#include "detail/BasicIteratorView.hpp"
#include "detail/MapIterator.hpp"
namespace lz {
template<LZ_CONCEPT_ITERATOR Iterator, class Function>
class Map final : public internal::BasicIteratorView<internal::MapIterator<Iterator, Function>> {
public:
using iterator = internal::MapIterator<Iterator, Function>;
using const_iterator = iterator;
using value_type = typename iterator::value_type;
LZ_CONSTEXPR_CXX_20 Map(Iterator begin, Iterator end, Function function) :
internal::BasicIteratorView<iterator>(iterator(std::move(begin), function), iterator(std::move(end), function)) {
}
constexpr Map() = default;
};
// Start of group
/**
* @addtogroup ItFns
* @{
*/
/**
* @brief Returns a random access map object. If MSVC and the type is an STL iterator, pass a pointer iterator, not
* an actual iterator object.
* @details E.g. `map({std::pair(1, 2), std::pair(3, 2)}, [](std::pair<int, int> pairs) { return pair.first; });`
* will return all pairs first values in the sequence, that is, `1` and `3`.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param function A function that takes a value type as parameter. It may return anything.
* @return A Map object from [begin, end) that can be converted to an arbitrary container or can be iterated over
* using `for (auto... lz::map(...))`.
*/
template<class Function, LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Map<Iterator, Function> mapRange(Iterator begin, Iterator end, Function function) {
return { std::move(begin), std::move(end), std::move(function) };
}
/**
* @brief Returns a bidirectional map object.
* @details E.g. `map({std::pair(1, 2), std::pair(3, 2)}, [](std::pair<int, int> pairs) { return pair.first; });`
* will return all pairs first values in the sequence, that is, `1` and `3`.
* @param iterable The iterable to do the mapping over.
* @param function A function that takes a value type as parameter. It may return anything.
* @return A Map object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::map(...))`.
*/
template<class Function, LZ_CONCEPT_ITERABLE Iterable>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Map<internal::IterTypeFromIterable<Iterable>, Function>
map(Iterable&& iterable, Function function) {
return mapRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(function));
}
// End of group
/**
* @}
*/
} // namespace lz
#endif | 39.5 | 122 | 0.69248 | ExternalRepositories |
ac61ce543c9bb87ada9d46abdb4d10bacb997906 | 32,116 | cpp | C++ | OS2.1/CPinti/core/core.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 1 | 2021-05-05T20:42:24.000Z | 2021-05-05T20:42:24.000Z | OS2.1/CPinti/core/core.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | null | null | null | OS2.1/CPinti/core/core.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | null | null | null | /*
=============================================
== CPinti ---> Gestionnaire de threads ==
=============================================
Developpe entierement par Sebastien FAVIER
Description
Module permettant la commutation des threads en se basant sur le PIT
Creation
17/05/2018
Mise a jour
22/01/2019
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dos.h>
#include <signal.h>
#include <math.h>
#include <cstdio>
#include <unistd.h>
#include <cstdlib>
#include <stdio.h>
#include <dpmi.h>
#include "debug.h"
#include "Func_cpi.h"
#include "core.h"
// #include "leakchk.h"
extern "C" long cpc_clean ();
namespace cpinti
{
namespace gestionnaire_tache
{
void IamInLive()
{
// Ne pas calculer si le CPU est en evaluation
if(EVALUATION_CPU == false)
{
begin_SectionCritique();
// Cette fonction met a jour les cycles CPU
// ce qui permet d'estimer avec une precision de 60%
// de la charge du CPU
InLiveCompteur++;
if(InLiveCompteur > 27483600) // unsigned long
InLiveCompteur = 0; // On reinitialise pour eviter les plantages
// Ceci permet d'economiser du temps CPU
saut_comptage++;
if(saut_comptage > 24)
{
saut_comptage = 0;
time(&Temps_Actuel);
Temps_total = difftime(Temps_Actuel, Temps_Depart);
if(Temps_total >= 1) // Si 1 seconde
{
NombreCycles = InLiveCompteur;
InLiveCompteur = 0; // On reset le compteur
time(&Temps_Depart);
}
}
end_SectionCritique();
}
}
void eval_cycle_cpu()
{
// Permet d'evaluer le CPU de maniere breve en 1 seconde
// Notifier pour ne pas fausser le resultat
EVALUATION_CPU = true;
time(&Temps_Actuel);
time(&Temps_Depart);
InLiveCompteur = 0;
while(Temps_total <= 1)
{
InLiveCompteur++;
if(InLiveCompteur > 27483600) // unsigned long
if(InLiveCompteur > 27483600) // unsigned long
break; // On reinitialise pour eviter les plantages
doevents(1);
time(&Temps_Actuel);
Temps_total = difftime(Temps_Actuel, Temps_Depart);
}
// Recuperer le nombre MAX de cycles
NombreCyles_MAX = (InLiveCompteur * 3) - (InLiveCompteur / 4); // 3 car il y a 3 ImInLive()
EVALUATION_CPU = false;
}
unsigned long get_cycle_MAX_cpu()
{
if(NombreCyles_MAX <= 0)
NombreCyles_MAX = 10;
return NombreCyles_MAX;
}
unsigned long get_cycle_cpu()
{
if(NombreCycles > NombreCyles_MAX)
return NombreCyles_MAX;
else if(NombreCycles <= 0)
return 0;
else
return NombreCycles;
}
volatile long SectionCritique_RECURSIF = 0;
void begin_SectionCritique()
{
// Rendre le systeme non interruptible
SECTION_CRITIQUE = true;
disable();
// Plus on l'appel plus il faudra le remonter pour finir la scope
SectionCritique_RECURSIF++;
}
void end_SectionCritique()
{
// Rendre le systeme interruptible
SectionCritique_RECURSIF--;
// Rendre interruptible quand le compteur sera a zero
if(SectionCritique_RECURSIF <=0)
{
SectionCritique_RECURSIF = 0;
SECTION_CRITIQUE = false;
enable();
}
}
bool state_SectionCritique()
{
// Retourner l'etat de la section critique
return SECTION_CRITIQUE;
}
bool initialiser_Multitache()
{
// Initialiser le multitasking
void* test = malloc(123);
cpinti_dbg::CPINTI_DEBUG("Preparation du multitache en cours.",
"Preparating multitask in progress. ",
"core::gestionnaire_tache", "initialiser_Multitache()",
Ligne_saute, Alerte_surbrille, Date_avec, Ligne_r_normal);
time(&Temps_Depart);
// Interdire toutes interruptions
begin_SectionCritique();
// Allouer un espace memoire pour chaque threads
for(long index_id = 0; index_id <= MAX_THREAD-1; index_id++)
{
Liste_Threads[index_id].Etat_Thread = _ARRETE;
Liste_Threads[index_id].Priorite = 0;
Liste_Threads[index_id].KID = 0;
Liste_Threads[index_id].OID = 0;
Liste_Threads[index_id].UID = 0;
Liste_Threads[index_id].PID = 0;
// strncpy((char*) Liste_Threads[index_id].Nom_Thread, (const char*) '\0', 32);
}
/*** Creer un thread principal "Thread_Updater" ***/
cpinti_dbg::CPINTI_DEBUG("Creation du thread principal 'Thread_Updater'...",
"Creating main thread 'Thread_Updater'...",
"core::gestionnaire_tache", "initialiser_Multitache()",
Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal);
// Incremente le nombre de threads
Nombre_Threads++;
// Priorite
Liste_Threads[0].Priorite = _PRIORITE_THRD_FAIBLE;
// Son numero de TID (Thread IDentifiant)
Liste_Threads[0].TID = 0;
// Etat en execution (A modifier en PAUSE)
Liste_Threads[0].Etat_Thread = _EN_EXECUTION;
Liste_Threads[0].DM_arret = false;
long toto = 0;
pthread_create(&Liste_Threads->thread, NULL, Thread_Updater, (void*) &toto);
// std::string offset_fonction = std::to_string((unsigned long) Thread_Updater);
cpinti_dbg::CPINTI_DEBUG(" [OK] TID:0. Fonction offset 0x" + std::to_string((unsigned long) Thread_Updater),
" [OK] TID:0. Offset function 0x" + std::to_string((unsigned long) Thread_Updater),
"", "",
Ligne_saute, Alerte_validation, Date_sans, Ligne_r_normal);
// Reexecuter le scheduler normalement
end_SectionCritique();
Thread_en_cours = 0;
Interruption_Timer(0);
// Retourner l'ID
return true;
}
bool fermer_core()
{
unsigned long nombre_threads = 0;
// Cette fonction permet de fermer le core en terminant tous les threads
for(unsigned long boucle = 1; boucle < MAX_THREAD; boucle++)
{
// Si le thread n'est pas arrete ou n'est pas zombie on ferme
if(Liste_Threads[boucle].Etat_Thread != _ARRETE)
if(Liste_Threads[boucle].Etat_Thread != _ZOMBIE)
{
nombre_threads++;
supprimer_Thread(boucle, false);
}
}
std::string nombre_threads_STR = std::to_string((unsigned long) nombre_threads);
cpinti_dbg::CPINTI_DEBUG("Signal de fermeture envoye aux " + nombre_threads_STR + " thread(s). Attente",
"Closing signal sent to " + nombre_threads_STR + " threads(s). Waiting",
"", "",
Ligne_saute, Alerte_avertissement, Date_sans, Ligne_r_normal);
fflush(stdout);
// On attend un peut
usleep(1500000);
fflush(stdout);
// Bloquer tout autres interruptions
ENTRER_SectionCritique();
unsigned long Nombre_Zombie = check_Thread_zombie(true, true);
std::string Nombre_Zombie_STR = std::to_string((unsigned long) Nombre_Zombie);
cpinti_dbg::CPINTI_DEBUG(Nombre_Zombie_STR + " thread(s) zombies ferme(s) sur " + nombre_threads_STR,
Nombre_Zombie_STR + " zombies thread(s) closed on " + nombre_threads_STR,
"", "",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
puts("Bye from kernel\n");
// cpc_clean();
// Activer les interruptions materiel
enable();
exit(0);
return true;
}
/******** PROCESSUS ********/
unsigned long get_EtatProcessus(unsigned long PID)
{
// Obtenir l'etat d'un processus
return Liste_Processus[PID].Etat_Processus;
}
void set_EtatProcessus(unsigned long PID, unsigned long Etat)
{
// Definir l'etat d'un processus
Liste_Processus[PID].Etat_Processus = Etat;
}
unsigned long get_NombreProcessus()
{
// Retourner le nombre de threads en cours
return Nombre_Processus;
}
unsigned long ajouter_Processus(const char* NomProcessus)
{
// Cette fonction permet de creer un processus pour heberger des threads
std::string NomProcessus_STR = NomProcessus;
// Si on atteint le nombre maximum de processus
if(Nombre_Processus >= MAX_PROCESSUS)
{
std::string nombre_processus_STR = std::to_string((unsigned long) MAX_PROCESSUS);
cpinti_dbg::CPINTI_DEBUG("[ERREUR] Impossible d'attribuer un nouveau PID. Le nombre est fixe a " + nombre_processus_STR + " processus maximum.",
"[ERROR] Unable to attrib new PID. The maximal process number value is " + nombre_processus_STR,
"", "",
Ligne_saute, Alerte_erreur, Date_avec, Ligne_r_normal);
return 0;
}
cpinti_dbg::CPINTI_DEBUG("Creation du processus '" + NomProcessus_STR + "'...",
"Creating process '" + NomProcessus_STR + "'...",
"core::gestionnaire_tache", "ajouter_Processus()",
Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal);
unsigned long Nouveau_PID = 0;
// Rechercher un emplacement ID vide
for(unsigned long b = 1; b <= MAX_PROCESSUS; b++)
{
if(Liste_Processus[b].PID == 0)
{
Nouveau_PID = b;
break;
}
}
if(Nouveau_PID == 0)
{
std::string nombre_threads_STR = std::to_string((unsigned long) MAX_THREAD);
cpinti_dbg::CPINTI_DEBUG(" [ERREUR] Impossible d'attribuer un nouveau PID. Aucune zone memoire libere",
" [ERROR] Unable to attrib new PID. No free memory",
"", "",
Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal);
return 0;
}
// Incremente le nombre de processus
Nombre_Processus++;
// Nom du processus
strncpy((char*) Liste_Processus[Nouveau_PID].Nom_Processus, NomProcessus, 32);
// Son numero de TID (Thread IDentifiant)
Liste_Processus[Nouveau_PID].PID = Nouveau_PID;
// Etat en execution
Liste_Processus[Nouveau_PID].Etat_Processus = _EN_EXECUTION;
std::string Nouveau_PID_STR = std::to_string((unsigned long) Nouveau_PID);
cpinti_dbg::CPINTI_DEBUG(" [OK] PID " + Nouveau_PID_STR + ".",
" [OK] PID " + Nouveau_PID_STR + ".",
"", "",
Ligne_saute, Alerte_validation, Date_sans, Ligne_r_normal);
// Retourner l'ID
return Nouveau_PID;
}
bool supprimer_Processus(unsigned long pid, bool force)
{
// Cette fonction permet de signaler l'arret d'un processus
// et donc de tous ses threads
// si force=true
volatile long compteur_thread = 0;
if(pid == 0)
return false;
// std::string pid_STR = std::to_string((unsigned long) pid);
if (Liste_Processus[pid].Etat_Processus == _ARRETE)
{
cpinti_dbg::CPINTI_DEBUG("Le processus " + std::to_string((unsigned long) pid) + " est deja arrete",
"Process " + std::to_string((unsigned long) pid) + " is already stopped",
"", "",
Ligne_saute, Alerte_avertissement, Date_sans, Ligne_r_normal);
}
else if (Liste_Processus[pid].Etat_Processus == _EN_ARRET)
{
cpinti_dbg::CPINTI_DEBUG("Arret du processus " + std::to_string((unsigned long) pid) + " deja signale",
"Process stopping " + std::to_string((unsigned long) pid) + " is already signaled",
"", "",
Ligne_saute, Alerte_avertissement, Date_sans, Ligne_r_normal);
}
else
{
cpinti_dbg::CPINTI_DEBUG("Arret du processus PID " + std::to_string((unsigned long) pid) + " en cours...",
"Stopping process PID " + std::to_string((unsigned long) pid) + " in progress",
"core::gestionnaire_tache", "supprimer_Processus()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
// Mettre le processus en etat STOP = 0
Liste_Processus[pid].Etat_Processus = _EN_ARRET;
// Signaler l'arret a tous les threads heberges
for(unsigned long tid = 1; tid < MAX_THREAD; tid++)
{
// Si le thread est bien heberge dans le processus
if(Liste_Processus[pid].Threads_Enfant[tid] == true)
{
// Attendre 1ms entre chaque signalements
usleep(100);
// On signale l'arret du thread
supprimer_Thread(tid, false);
// Compter le nombre de threads signales
compteur_thread++;
}
// Dans tous les cas on met a FALSE
Liste_Processus[pid].Threads_Enfant[tid] = false;
}
cpinti_dbg::CPINTI_DEBUG("P4",
"P4",
"", "",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
// Attendre 10ms pour etre SAFE
// usleep(1000);
cpinti_dbg::CPINTI_DEBUG("P5",
"P5",
"", "",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
if(compteur_thread > 0)
{
// std::string compteur_thread_STR = std::to_string(compteur_thread);
// Declarer le processus mort (On conserve certaines infos pour le debug)
cpinti_dbg::CPINTI_DEBUG("Un signal d'arret a ete envoye a " + std::to_string(compteur_thread) + " thread(s)",
"Stopping signal has been sent to " + std::to_string(compteur_thread) + " thread(s)",
"core::gestionnaire_tache", "supprimer_Processus()",
Ligne_saute, Alerte_ok, Date_avec, Ligne_r_normal);
}
else
{
cpinti_dbg::CPINTI_DEBUG("Aucun threads heberge dans le processus. Hm.. parfait!",
"Nothing hosted threads in the process. Hm.. perfect!",
"core::gestionnaire_tache", "supprimer_Processus()",
Ligne_saute, Alerte_ok, Date_avec, Ligne_r_normal);
}
// Declarer le processus mort (On conserve certaines infos pour le debug)
cpinti_dbg::CPINTI_DEBUG("Envoi d'un signal d'arret au processus (Attente de la fermeture des threads) ...",
"Sending stopping signal to process (Waiting threads closing) ...",
"core::gestionnaire_tache", "supprimer_Processus()",
Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal);
if(Liste_Processus[pid].Nom_Processus != NULL)
memset(Liste_Processus[pid].Nom_Processus, 0, 32);
// free(Liste_Processus[pid].Nom_Processus);
Liste_Processus[pid].Etat_Processus = _ARRETE;
Liste_Processus[pid].PID = 0;
cpinti_dbg::CPINTI_DEBUG(" [OK]",
" [OK]",
"", "",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
}
Nombre_Processus--;
cpinti_dbg::CPINTI_DEBUG("Processus " + std::to_string((unsigned long) pid) + " supprime!",
"Process " + std::to_string((unsigned long) pid) + " deleted!",
"core::gestionnaire_tache", "supprimer_Processus()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
return true;
}
/******** THREADS ********/
unsigned long get_EtatThread(unsigned long TID)
{
return Liste_Threads[TID].Etat_Thread;
}
void set_EtatThread(unsigned long TID, unsigned long Etat)
{
Liste_Threads[TID].Etat_Thread = Etat;
}
const char* get_NomThread(unsigned long TID)
{
return (const char*) Liste_Threads[TID].Nom_Thread;
}
unsigned long get_NombreThreads()
{
// Retourner le nombre de threads en cours
return Nombre_Threads;
}
unsigned long get_NombreTimer()
{
// Retourner le nombre de timer executes
return Nombre_Timer;
}
unsigned long get_ThreadEnCours()
{
// Retourner la thread en cours
return Thread_en_cours;
}
unsigned long ajouter_Thread(void* (* Fonction) (void* arg), const char* NomThread, unsigned long pid, long Priorite, unsigned long Arguments)
{
// Cette fonction permet d'ajouter une thread (Thread)
unsigned long Nouveau_TID = 0;
// std::string NomThread_STR = NomThread;
// Si on atteint le nombre maximum de threads
if(Nombre_Threads >= MAX_THREAD)
{
// std::string nombre_threads_STR = std::to_string((unsigned long) MAX_THREAD);
cpinti_dbg::CPINTI_DEBUG("[ERREUR] Impossible d'attribuer un nouveau TID. Le nombre est fixe a " + std::to_string(MAX_THREAD) + " thread(s) maximum.",
"[ERROR] Unable to attrib new TID. The maximal thread(s) number value is " + std::to_string(MAX_THREAD),
"", "ajouter_Thread()",
Ligne_saute, Alerte_erreur, Date_avec, Ligne_r_normal);
return 0;
}
std::string pid_STR = std::to_string((unsigned long) pid);
cpinti_dbg::CPINTI_DEBUG("Creation du thread '" + std::string(NomThread) + "' dans le processus " + pid_STR + "...",
"Creating thread '" + std::string(NomThread) + "' in the process " + pid_STR + "...",
"core::gestionnaire_tache", "ajouter_Thread()",
Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal);
// Si le processus n'existe pas
if(Liste_Processus[pid].PID != pid)
{
cpinti_dbg::CPINTI_DEBUG(" [ERREUR] Le PID " + pid_STR + " n'existe pas. Impossible d'heberger un nouveau thread.",
" [ERROR] PID " + pid_STR + " not exist. Unable to host the new thread.",
"", "ajouter_Thread()",
Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal);
return 0;
}
ENTRER_SectionCritique();
// Rechercher un emplacement ID vide
for(unsigned long b = 1; b <= MAX_THREAD; b++)
{
if(Liste_Threads[b].PID == 0)
{
Nouveau_TID = b;
break;
}
}
if(Nouveau_TID == 0)
{
cpinti_dbg::CPINTI_DEBUG(" [ERREUR] Impossible d'attribuer un nouveau TID. Aucune zone memoire libere",
" [ERROR] Unable to attrib new TID. No free memory",
"core::gestionnaire_tache", "ajouter_Thread()",
Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal);
SORTIR_SectionCritique();
return 0;
}
// Incremente le nombre de threads
Nombre_Threads++;
// Nom du thread
strncpy((char*) Liste_Threads[Nouveau_TID].Nom_Thread, NomThread, 30);
// Corriger les priorites
if(Liste_Threads[Thread_en_cours].Priorite < 2)
Priorite = 2;
else if(Liste_Threads[Thread_en_cours].Priorite > MAX_CYCLES)
Priorite = MAX_CYCLES;
// Priorite
Liste_Threads[Nouveau_TID].Priorite = Priorite;
// Son numero de PID (Processus IDentifiant)
Liste_Threads[Nouveau_TID].PID = pid;
// Son numero de TID (Thread IDentifiant)
Liste_Threads[Nouveau_TID].TID = Nouveau_TID;
// Etat en execution (A modifier en PAUSE)
Liste_Threads[Nouveau_TID].Etat_Thread = _EN_EXECUTION;
// NE pas demander d'arret, ca serai un peu con
Liste_Threads[Nouveau_TID].DM_arret = false;
// Point d'entree
Liste_Threads[Nouveau_TID]._eip = (unsigned long*) &Fonction;
// Incrire le thread dans le processsus
Liste_Processus[pid].Threads_Enfant[Nouveau_TID] = true;
// Mettre a jour le TID dans l'adresse memoire
ptr_Update_TID(Arguments, Nouveau_TID);
// Creer le thread
pthread_create(&Liste_Threads[Nouveau_TID].thread, NULL, *Fonction, (void*) Arguments);
// Liste_Threads[Nouveau_TID].PTID = (unsigned long) &Liste_Threads[Nouveau_TID].thread;
// std::string offset_fonction_STR = std::to_string((unsigned long) Fonction);
// std::string tid_STR = std::to_string((unsigned long) Nouveau_TID);
cpinti_dbg::CPINTI_DEBUG(" [OK] TID:" + std::to_string((unsigned long) Nouveau_TID) + ". Fonction offset 0x" + std::to_string((unsigned long) Fonction),
" [OK] TID:" + std::to_string((unsigned long) Nouveau_TID) + ". Offset function 0x" + std::to_string((unsigned long) Fonction),
"", "",
Ligne_saute, Alerte_validation, Date_sans, Ligne_r_normal);
SORTIR_SectionCritique();
Thread_en_cours = Nouveau_TID;
Interruption_Timer(0);
// Retourner l'ID
return Nouveau_TID;
}
unsigned long check_Thread_zombie(bool liberer, bool debug)
{
// Cette fonction permet de detecter tous les thread zombie
// et selon la variable "liberer" il enclanche la liberation memoire du thread
unsigned long compteur_zombie = 0;
// Retourner le nombre de threads zombie
return compteur_zombie;
}
bool free_Thread_zombie(unsigned long tid)
{
// Cette fonction permet de supprimer un thread zombie
// Un thread zombie conserve encore sa segmentation memoire
// conserve dans le registre ESP, son point execution EIP
// et autres registres. Cette fonction va tout supprimer et
// liberer l'index TID!
return true;
}
bool supprimer_Thread(unsigned long tid, bool force)
{
// Cette fonction permet de signaler l'arret d'un thread
// si force=true
// std::string tid_STR = std::to_string((unsigned long) tid);
// std::string pid_STR = std::to_string((unsigned long) Liste_Threads[tid].PID);
if(force == true)
{
Nombre_Threads--;
// std::string Nombre_Threads_STR = std::to_string((unsigned long) Nombre_Threads);
// std::string NomThread_STR = std::string(Liste_Threads[tid].Nom_Thread);
cpinti_dbg::CPINTI_DEBUG("Suppression du thread '" + std::string(Liste_Threads[tid].Nom_Thread) + "' TID:" + std::to_string((unsigned long) tid) + " PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID) + ". " + std::to_string((unsigned long) Nombre_Threads) + " thread(s) restant(s)",
"Deleting thread '" + std::string(Liste_Threads[tid].Nom_Thread) + "' TID:" + std::to_string((unsigned long) tid) + " PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID) + ". " + std::to_string((unsigned long) Nombre_Threads) + "remaining thread(s)",
"core::gestionnaire_tache", "supprimer_Thread()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
if(Liste_Threads[tid].Nom_Thread != NULL)
memset(Liste_Threads[tid].Nom_Thread, 0, 30);
// free(Liste_Threads[tid].Nom_Thread);
Liste_Threads[tid].Priorite = 0;
Liste_Processus[Liste_Threads[tid].PID].Threads_Enfant[tid] = false;
Liste_Threads[tid].PID = 0;
Liste_Threads[tid].TID = 0;
Liste_Threads[tid].Etat_Thread = _ARRETE;
// Liste_Threads[tid].DM_arret = false;
Liste_Threads[tid]._eip = NULL;
// Quitter le thread
pthread_exit(&Liste_Threads[tid].thread);
}
else
{
cpinti_dbg::CPINTI_DEBUG("Envoi d'un signal d'arret au thread '" + std::to_string((unsigned long) tid) + "' PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID),
"Sending stopping signal to thread '" + std::to_string((unsigned long) tid) + "' PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID),
"core::gestionnaire_tache", "supprimer_Thread()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
// Ce changement d'etat va provoquer un arret "automatique" du thread
// Au bout de quelques secondes le thread va passer en mode "zombie"
set_EtatThread(tid, _EN_ARRET);
Liste_Threads[tid].DM_arret = true;
doevents(1000);
}
return true;
}
static bool Alterner = false;
static bool Executer = false;
void Interruption_Timer(long Priorite)
{
if(state_SectionCritique() == false)
{
begin_SectionCritique();
// Si il a excute le nombre de cycle/priorite on reloop
Liste_Threads[Thread_en_cours].Priorite_count++;
// Correctif (En cas de corruption, eviter un SIGFPE)
if(Liste_Threads[Thread_en_cours].Priorite < 2)
Liste_Threads[Thread_en_cours].Priorite = 2;
else if(Liste_Threads[Thread_en_cours].Priorite > MAX_CYCLES)
Liste_Threads[Thread_en_cours].Priorite = MAX_CYCLES;
if(Liste_Threads[Thread_en_cours].Priorite_count >= (MAX_CYCLES / Liste_Threads[Thread_en_cours].Priorite))
{
Liste_Threads[Thread_en_cours].Priorite_count = 0;
Executer = true;
Alterner = false;
}
// Liste_Threads[Thread_en_cours].Priorite_count++;
// if(Liste_Threads[Thread_en_cours].Priorite_count >= Liste_Threads[Thread_en_cours].Priorite)
// {
// Liste_Threads[Thread_en_cours].Priorite_count = 0;
// Executer = true;
// Alterner = false;
// }
if(Alterner == true)
{
Alterner = false;
end_SectionCritique();
__dpmi_yield();
begin_SectionCritique();
}
else
Alterner = true;
if(Executer == true)
{
unsigned long Precedent = Thread_en_cours;
Alterner = true;
Executer = false;
// fprintf(stdout, " ****** SWITCH ! %u -->", Thread_en_cours);
end_SectionCritique();
if(Liste_Threads[Thread_en_cours].DM_arret == true)
{
cpinti_dbg::CPINTI_DEBUG("Thread zombie TID:" + std::to_string(Thread_en_cours) + " Dernier essais : " + std::to_string(Liste_Threads[Thread_en_cours].Zombie_Count) + "/" + std::to_string(_ZOMBIE_ESSAI) + " .",
"Zombie Thread TID:" + std::to_string(Thread_en_cours) + " Last chance : " + std::to_string(Liste_Threads[Thread_en_cours].Zombie_Count) + "/" + std::to_string(_ZOMBIE_ESSAI) + " .",
"core::gestionnaire_tache", "Interruption_Timer()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
// Ah il a repondu il s'est termine tout seul, on arrete!
if(Liste_Threads[Thread_en_cours].Etat_Thread == _ARRETE)
{
Liste_Threads[Thread_en_cours].DM_arret = false;
cpinti_dbg::CPINTI_DEBUG("Oh! Le zombie s'est reveille et s'est auto-detruit!",
"Oh! The zombie awoke and self-destructed!",
"core::gestionnaire_tache", "Interruption_Timer()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
}
if(Liste_Threads[Thread_en_cours].Zombie_Count >= _ZOMBIE_ESSAI)
{
// Declarer le thread en ZOMBIE
Liste_Threads[Thread_en_cours].Etat_Thread = _ZOMBIE;
cpinti_dbg::CPINTI_DEBUG("Thread TID:" + std::to_string(Thread_en_cours) + " declare ZOMBIE. Bannissement du scheduler.",
"Zombie Thread TID:" + std::to_string(Thread_en_cours) + " declared ZOMBIE. Ban from scheduler.",
"core::gestionnaire_tache", "Interruption_Timer()",
Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal);
// Adieu thread! On t'a surement aime!
while(true)
{
usleep(5000000); // bloquer le thread 5 secondes a l'infinit
}
}
else
{
Liste_Threads[Thread_en_cours].Zombie_Count++;
// 6 Cycles avant son arret, on enleve un thread
if(Liste_Threads[Thread_en_cours].Zombie_Count == _ZOMBIE_ESSAI - 6)
Nombre_Threads--;
}
}
usleep(10);
begin_SectionCritique();
Thread_en_cours = Precedent;
}
end_SectionCritique();
}
}
void switch_context()
{
// Cette fonction permet de switcher de thread en thread
return;
/** S'il y a pas de threads, inutile d'aller plus loin **/
if(Thread_en_cours == 0)
if(Nombre_Threads < 1)
return;
/** On bloque le scheduler **/
begin_SectionCritique();
/** Sauvegarder le contexte actuel **/
if(SAUVEGARDER_CONTEXTE(Thread_en_cours) == true)
return;
/** Chercher le prochain thread a executer **/
Thread_en_cours = SCHEDULER(Thread_en_cours);
/** On reexcute le scheduler normalement **/
end_SectionCritique();
/** Et on restaure le prochain thread **/
RESTAURER_CONTEXTE(Thread_en_cours);
}
unsigned long SCHEDULER(unsigned long ancien)
{
// SCHEDULER : Cette fonction permet de selectionner
// le prochain thread a executer
unsigned long nouveau = ancien;
unsigned long compteur_ = 0;
while(true)
{
nouveau++;
compteur_++;
// Si on depasse le nombre on repart de zero
if(nouveau >= MAX_THREAD)
nouveau = 0;
if(Liste_Threads[nouveau].Etat_Thread != _ARRETE)
if(Liste_Threads[nouveau].Etat_Thread != _ZOMBIE)
return nouveau;
if(compteur_ > MAX_THREAD*2)
break;
}
cpinti_dbg::CPINTI_DEBUG("Oups.. Tous les threads sont a l'arret",
"Oops.. All threads are stopped",
"core::gestionnaire_tache", "SCHEDULER()",
Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal);
return 0;
}
bool SAUVEGARDER_CONTEXTE(unsigned long Thread_ID)
{
// Cette fonction permet de sauvegarder les registres d'un thread
// Si le thread est pas vide
if(Liste_Threads[Thread_ID].Etat_Thread != _ARRETE)
if(Liste_Threads[Thread_ID].Etat_Thread != _ZOMBIE)
{
// Reexecuter le scheduler normalement
end_SectionCritique();
// Recuperer les info (registres...) du thread actuel
if (setjmp(Liste_Threads[Thread_ID].Buffer_Thread) == 1)
{
return true;
}
// On bloque le scheduler courant
begin_SectionCritique();
}
return false;
}
void RESTAURER_CONTEXTE(unsigned long Thread_ID)
{
// Cette fonction permet de restaurer les registres d'un thread
longjmp(Liste_Threads[Thread_ID].Buffer_Thread, 1);
}
void loop_MAIN()
{
// Cette fonction permet creer un point de terminaison du main en executant
// la premiere thread
Thread_en_cours = 0;
longjmp(Liste_Threads[0].Buffer_Thread, 1);
}
/************************** TIMER **************************/
bool initialiser_PIT(long frequence, long Intervalle_INTERNE)
{
// Cette fonction permet de reprogrammer l'intervalle du PIT
// -1:Pas de modification de la frequence
// 0:Frequence MAX par defaut
// >0:Modification de la frequence d'horloge du PIT (Max:65535)
if(frequence == 0)
{
outportb(0x43, 0x36);
outportb(0x40, 0);
outportb(0x40, 0);
}
else if ((frequence > 0) && frequence <= 65535)
{
outportb(0x43, 0x36);
outportb(0x40, ((1193180L / frequence) & 0x00ff));
outportb(0x40, (((1193180L / frequence) >> 8) & 0x00ff));
}
// Modification du clock de la routine interne
__djgpp_clock_tick_interval = Intervalle_INTERNE;
return true;
}
unsigned long ajouter_Timer(unsigned long fonction)
{
// Cette fonction permet d'ajouter un Timer
// Si on atteint le nombre maximum de timers
if(Nombre_Timer >= MAX_TIMERS)
{
// (" ERREUR : Nombre maximum de timer autorise est de %d.", MAX_TIMERS);
return 0;
}
// NE PAS laisser le scheduler switcher pendant cette operation
begin_SectionCritique();
// Incremente le nombre de timers
Nombre_Timer++;
// Initialise l'instance a zero
instance_Timer[Nombre_Timer].it_interval.tv_sec = 0;
instance_Timer[Nombre_Timer].it_interval.tv_usec = 0;
instance_Timer[Nombre_Timer].it_value.tv_sec = 0;
instance_Timer[Nombre_Timer].it_value.tv_usec = 0;
// Definir le timer
signal(SIGALRM, (void (*)(int)) fonction);
setitimer(ITIMER_REAL, &instance_Timer[Nombre_Timer], NULL);
// Reexecuter le scheduler normalement
end_SectionCritique();
// Retourner l'ID
return Nombre_Timer;
}
bool demarrer_SCHEDULER(unsigned long id_TIMER, long temps_us)
{
// Cette fonction permet de demarrer le scheduling d'un timer
// en definissant le temps en intervalle en micro-secondes
// s'il y en a pas, retour!
if(Nombre_Timer < 1)
return false;
// Definir l'intervalle
instance_Timer[id_TIMER].it_interval.tv_sec = 0;
instance_Timer[id_TIMER].it_interval.tv_usec = temps_us;
instance_Timer[id_TIMER].it_value.tv_sec = 0;
instance_Timer[id_TIMER].it_value.tv_usec = temps_us;
// On envoie tout ca
setitimer(ITIMER_REAL, &instance_Timer[id_TIMER], NULL);
return true;
}
bool stop_SCHEDULER(long id_TIMER)
{
// Cette fonction permet d'arreter le scheduler
// Initialise l'instance a zero
instance_Timer[id_TIMER].it_interval.tv_sec = 0;
instance_Timer[id_TIMER].it_interval.tv_usec = 0;
instance_Timer[id_TIMER].it_value.tv_sec = 0;
instance_Timer[id_TIMER].it_value.tv_usec = 0;
// On envoie tout ca
setitimer(ITIMER_REAL, &instance_Timer[id_TIMER], NULL);
return true;
}
} // namespace
} // namespace cpinti
void Interruption_Timer(long signal)
{
// fprintf(stdout, " **CORE 3\n");
cpinti::gestionnaire_tache::Interruption_Timer(signal);
// fprintf(stdout, " **CORE 3.1\n");
}
| 29.30292 | 299 | 0.649053 | Cwc-Test |
ac6462866b594fb9bbd04cdd0a6ae3d54fb9acaa | 1,235 | hh | C++ | analysis/machine_learning/include/timer.hh | ssrg-vt/aira | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | [
"Unlicense"
] | 3 | 2018-12-17T08:20:40.000Z | 2020-02-24T02:08:23.000Z | analysis/machine_learning/include/timer.hh | ssrg-vt/aira | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | [
"Unlicense"
] | null | null | null | analysis/machine_learning/include/timer.hh | ssrg-vt/aira | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | [
"Unlicense"
] | null | null | null | #ifndef _TIMER_HH
#define _TIMER_HH
#include <iostream>
#include <vector>
#include <ctime>
class Timer {
private:
struct timespec clock_start;
std::vector<uint64_t> times;
public:
void start() {
clock_gettime(CLOCK_REALTIME, &clock_start);
}
void stop() {
struct timespec clock_end;
clock_gettime(CLOCK_REALTIME, &clock_end);
uint64_t s = clock_end.tv_sec - clock_start.tv_sec;
uint64_t ns = clock_end.tv_nsec - clock_start.tv_nsec; // May be negative
uint64_t t = (s * 1000000000) + ns;
times.push_back(t);
}
uint64_t average() const {
assert((times.size() > 0) && "No timing data recorded yet");
uint64_t count = 0;
for (auto it : times) {
count += it;
}
return count / times.size();
}
friend std::ostream& operator<< (std::ostream &out, const Timer &timer) {
uint64_t t = timer.average();
if (t > 1000000000) {
double t2 = ((double)t)/1000000000;
out << t2 << "s";
} else if (t > 1000000) {
double t2 = ((double)t)/1000000;
out << t2 << "ms";
} else if (t > 1000) {
double t2 = ((double)t)/1000;
out << t2 << "μs";
} else {
out << t << "ns";
}
return out;
}
};
#endif // _TIMER_HH
| 22.454545 | 77 | 0.593522 | ssrg-vt |
ac6530658c67e15a634ead0ae3d492090da6389a | 928 | cpp | C++ | EglCpp/Sources/Reflection/Reflectable.cpp | Egliss/EglCppBase | 94d24b6e5e91da880833237a879138760ae9c669 | [
"MIT"
] | null | null | null | EglCpp/Sources/Reflection/Reflectable.cpp | Egliss/EglCppBase | 94d24b6e5e91da880833237a879138760ae9c669 | [
"MIT"
] | 2 | 2020-08-04T18:14:51.000Z | 2020-08-06T19:19:11.000Z | EglCpp/Sources/Reflection/Reflectable.cpp | Egliss/EglCppBase | 94d24b6e5e91da880833237a879138760ae9c669 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Reflectable.hpp"
#include "DynamicType.hpp"
#include "../Utility/StringUtility.hpp"
using namespace Egliss::Reflection;
void Reflectable::Validate(int typeId)
{
if (this->TryFastValidate(typeId))
return;
if (DynamicTypeManager::Find(typeId) == nullptr)
throw std::exception(StringUtility::Format("inputed type id({0}) not found", typeId).c_str());
if (DynamicTypeManager::Find(TypeId) == nullptr)
throw std::exception(StringUtility::Format("instance saved type id({0}) not found", TypeId).c_str());
auto text = StringUtility::Format("instance saved type id is {0}({1}) but, input type is {2}({3}). please check deriver type's constructor.",
DynamicTypeManager::TypeOf(typeId).name,
DynamicTypeManager::TypeOf(typeId).id,
DynamicTypeManager::TypeOf(TypeId).name,
DynamicTypeManager::TypeOf(TypeId).id
);
throw std::exception(text.c_str());
}
| 37.12 | 142 | 0.704741 | Egliss |
ac661674fe1f088ca7613e2efe04fdfb86e9aff5 | 2,632 | hpp | C++ | src/util/position.hpp | BruJu/AdventOfCode | a9161649882429bc1f995424544ce4cdafb69caa | [
"WTFPL",
"MIT"
] | 1 | 2020-12-11T13:37:06.000Z | 2020-12-11T13:37:06.000Z | src/util/position.hpp | BruJu/AdventOfCode2020 | a9161649882429bc1f995424544ce4cdafb69caa | [
"WTFPL",
"MIT"
] | null | null | null | src/util/position.hpp | BruJu/AdventOfCode2020 | a9161649882429bc1f995424544ce4cdafb69caa | [
"WTFPL",
"MIT"
] | null | null | null | #pragma once
#include <optional>
namespace bj {
enum class Direction { Left, Right, Top, Down };
inline std::optional<Direction> to_direction_from_lrtd(const char symbol, const char * symbols) {
if (symbol == symbols[0]) return Direction::Left;
if (symbol == symbols[1]) return Direction::Right;
if (symbol == symbols[2]) return Direction::Top;
if (symbol == symbols[3]) return Direction::Down;
return std::nullopt;
}
// Sortable position
struct Position {
int x = 0;
int y = 0;
[[nodiscard]] bool operator<(const Position & rhs) const {
if (x < rhs.x) return true;
if (x > rhs.x) return false;
if (y < rhs.y) return true;
if (y > rhs.y) return false;
return false;
}
[[nodiscard]] bool operator==(const Position & rhs) const {
return x == rhs.x && y == rhs.y;
}
[[nodiscard]] bool operator!=(const Position & rhs) const {
return !(*this == rhs);
}
void move(Direction direction) {
switch (direction) {
case Direction::Left: x -= 1; break;
case Direction::Right: x += 1; break;
case Direction::Top: y -= 1; break;
case Direction::Down: y += 1; break;
}
}
template<typename Consumer>
void for_each_neighbour(Consumer c) const {
for (Direction d : { Direction::Left, Direction::Right, Direction::Down, Direction::Top }) {
Position copy = *this;
copy.move(d);
c(copy);
}
}
[[nodiscard]] std::vector<bj::Position> get_8_neighbours() const {
std::vector<bj::Position> retval;
for (int x_ = -1 ; x_ <= 1 ; ++x_) {
for (int y_ = -1 ; y_ <= 1 ; ++y_) {
if (y_ == 0 && x_ == 0) continue;
retval.push_back(Position { x + x_, y + y_ });
}}
return retval;
}
};
struct Rectangle {
int left;
int right;
int top;
int bottom;
Rectangle(int left, int top, int right, int bottom)
: left(left), right(right), top(top), bottom(bottom) {}
template <typename Consumer>
void for_each_position(Consumer consumer) const {
for (int i = left ; i <= right ; ++i) {
for (int j = top ; j <= bottom ; ++j) {
consumer(Position { i, j });
}
}
}
};
} | 30.252874 | 104 | 0.483283 | BruJu |
ac686e97ae6b511f157d50c84dc1f9f1c9a4358e | 2,077 | cpp | C++ | N0023-Merge-k-Sorted-Lists/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0023-Merge-k-Sorted-Lists/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N0023-Merge-k-Sorted-Lists/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | 2 | 2022-01-25T05:31:31.000Z | 2022-02-26T07:22:23.000Z | //
// main.cpp
// LeetCode-Solution
//
// Created by Loyio Hex on 3/1/22.
//
#include <iostream>
#include <chrono>
#include <vector>
#include <queue>
using namespace std;
using namespace std::chrono;
struct ListNode{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {};
ListNode(int x) : val(x), next(nullptr) {};
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution{
public:
struct Node_status {
int val;
ListNode *ptr;
bool operator < (const Node_status &rhs) const {
return val > rhs.val;
}
};
priority_queue<Node_status> que;
ListNode* mergeKLists(vector<ListNode*>& lists) {
for (auto node: lists) {
if(node) que.push({node->val, node});
}
ListNode head, *tail = &head;
while (!que.empty()){
auto f = que.top();
que.pop();
tail->next = f.ptr;
tail = tail->next;
if (f.ptr->next){
que.push({f.ptr->next->val, f.ptr->next});
}
}
return head.next;
}
};
int main(int argc, const char * argv[]) {
auto start = high_resolution_clock::now();
// Main Start
vector<vector<int>> lists_num = {{1, 4, 5}, {1, 3, 4}, {2, 6}};
ListNode *p, *res;
vector<ListNode*> lists(lists_num.size());
for (int i = 0; i < lists_num.size(); ++i) {
p = nullptr;
for (int j = 0; j < lists_num[i].size(); ++j) {
if(!p){
lists[i] = p = new ListNode(lists_num[i][j]);
}else{
p->next = new ListNode(lists_num[i][j]);
p = p->next;
}
}
}
Solution solution;
res = solution.mergeKLists(lists);
while(res){
cout << res->val << endl;
res = res->next;
}
// Main End
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << endl << "Runnig time : " << duration.count() << "ms;" << endl;
return 0;
}
| 24.72619 | 74 | 0.512277 | loyio |
ac6b40c405ccda93eb67fc725d373fc6c4d51f63 | 262 | hpp | C++ | examples/trivial/trivial.hpp | dcblack/systemc-complete | b018b76254de95673a4294052317d23a6325918b | [
"RSA-MD"
] | 1 | 2021-06-03T15:19:51.000Z | 2021-06-03T15:19:51.000Z | examples/trivial/trivial.hpp | dcblack/systemc-complete | b018b76254de95673a4294052317d23a6325918b | [
"RSA-MD"
] | null | null | null | examples/trivial/trivial.hpp | dcblack/systemc-complete | b018b76254de95673a4294052317d23a6325918b | [
"RSA-MD"
] | null | null | null | //FILE: trivial.hpp
#ifndef TRIVIAL_HPP
#define TRIVIAL_HPP
#include <systemc>
struct Trivial_module : sc_core::sc_module
{
Trivial_module( sc_core::sc_module_name instance );
~Trivial_module( void ) = default;
private:
void main_thread( void );
};
#endif
| 20.153846 | 53 | 0.751908 | dcblack |
ac720042415480b1a9f4c26d9f4197ffe6e1c59f | 15,344 | cpp | C++ | src/graph/Graph.cpp | AvocadoML/Avocado | 9595cc5994d916f0ecb24873a5afa98437977fb5 | [
"Apache-2.0"
] | null | null | null | src/graph/Graph.cpp | AvocadoML/Avocado | 9595cc5994d916f0ecb24873a5afa98437977fb5 | [
"Apache-2.0"
] | null | null | null | src/graph/Graph.cpp | AvocadoML/Avocado | 9595cc5994d916f0ecb24873a5afa98437977fb5 | [
"Apache-2.0"
] | null | null | null | /*
* Graph.cpp
*
* Created on: Feb 16, 2021
* Author: Maciej Kozarzewski
*/
#include <Avocado/graph/Graph.hpp>
#include <Avocado/graph/GraphNode.hpp>
#include <Avocado/core/Device.hpp>
#include <Avocado/core/Context.hpp>
#include <Avocado/core/Scalar.hpp>
#include <Avocado/layers/Input.hpp>
#include <Avocado/utils/json.hpp>
#include <Avocado/inference/calibration.hpp>
#include <algorithm>
namespace
{
template<typename T>
int indexOf(const std::vector<T> &vec, T value)
{
for (size_t i = 0; i < vec.size(); i++)
if (vec[i] == value)
return i;
return -1;
}
template<typename T>
void removeByIndex(std::vector<T> &vec, size_t idx)
{
if (idx < vec.size())
vec.erase(vec.begin() + idx);
}
template<typename T>
void removeByValue(std::vector<T> &vec, T value)
{
removeByIndex(vec, indexOf(vec, value));
}
}
namespace avocado
{
Graph::Graph(Device device) :
m_context(device)
{
}
Device Graph::device() const noexcept
{
return m_context.device();
}
DataType Graph::dtype() const noexcept
{
return m_datatype;
}
const Context& Graph::context() const noexcept
{
return m_context;
}
GraphNodeID Graph::addInput(const Shape &shape)
{
return add_node(Input(shape), { });
}
GraphNodeID Graph::add(const Layer &layer, GraphNodeID node)
{
return add_node(layer, { node });
}
GraphNodeID Graph::add(const Layer &layer, std::initializer_list<GraphNodeID> nodes)
{
if (nodes.size() == 0)
throw LogicError(METHOD_NAME, "nodes list must not be empty");
return add_node(layer, nodes);
}
void Graph::addOutput(GraphNodeID node, const LossFunction &loss)
{
m_output_nodes.push_back(get_node(node));
m_losses.push_back(std::unique_ptr<LossFunction>(loss.clone()));
m_targets.push_back(nullptr);
bool successfully_combined = m_losses.back()->tryCombineWith(get_node(node)->getLayer());
if (successfully_combined)
get_node(node)->bypassDuringBackward();
}
void Graph::addOutput(GraphNodeID node)
{
m_output_nodes.push_back(get_node(node));
m_losses.push_back(nullptr);
m_targets.push_back(nullptr);
}
const Tensor& Graph::getInput(int index) const
{
return m_input_nodes.at(index)->getOutputTensor();
}
const Tensor& Graph::getOutput(int index) const
{
return m_output_nodes.at(index)->getOutputTensor();
}
const Tensor& Graph::getGradient(int index) const
{
return m_output_nodes.at(index)->getGradientTensor();
}
const Tensor& Graph::getTarget(int index) const
{
if (not isTrainable())
throw LogicError(METHOD_NAME, "Graph is not trainable");
if (m_targets.at(index) == nullptr)
throw UninitializedObject(METHOD_NAME, "target tensor was not initialized");
return *(m_targets.at(index));
}
Tensor& Graph::getInput(int index)
{
return m_input_nodes.at(index)->getOutputTensor();
}
Tensor& Graph::getOutput(int index)
{
return m_output_nodes.at(index)->getOutputTensor();
}
Tensor& Graph::getGradient(int index)
{
return m_output_nodes.at(index)->getGradientTensor();
}
Tensor& Graph::getTarget(int index)
{
if (m_targets.at(index) == nullptr)
m_targets.at(index) = std::make_unique<Tensor>(getOutput(index).shape(), dtype(), device());
return *(m_targets.at(index));
}
Shape Graph::getInputShape(int index) const
{
return m_input_nodes.at(index)->getOutputShape();
}
Shape Graph::getOutputShape(int index) const
{
return m_output_nodes.at(index)->getOutputShape();
}
int Graph::numberOfInputs() const noexcept
{
return static_cast<int>(m_input_nodes.size());
}
int Graph::numberOfOutputs() const noexcept
{
return static_cast<int>(m_output_nodes.size());
}
int Graph::maxBatchSize() const
{
if (numberOfInputs() == 0)
return 0;
else
return getOutputShape().firstDim();
}
void Graph::moveTo(Device newDevice)
{
if (newDevice == device())
return;
m_context = Context(newDevice);
for (size_t i = 0; i < m_layers.size(); i++)
m_layers[i]->changeContext(m_context);
for (size_t i = 0; i < m_nodes.size(); i++)
m_nodes[i]->moveTo(newDevice);
if (m_backup_tensor != nullptr)
m_backup_tensor->moveTo(newDevice);
for (size_t i = 0; i < m_targets.size(); i++)
if (m_targets[i] != nullptr)
m_targets[i]->moveTo(newDevice);
}
void Graph::setInputShape(const Shape &shape)
{
setInputShape(std::vector<Shape>( { shape }));
}
void Graph::setInputShape(const std::vector<Shape> &list)
{
for (int i = 0; i < numberOfInputs(); i++)
m_input_nodes[i]->getLayer().setInputShape(list[i]);
for (size_t i = 0; i < m_nodes.size(); i++)
m_nodes[i]->resolveInputShapes();
m_backup_tensor = nullptr;
}
void Graph::setOptimizer(const Optimizer &optimizer)
{
if (not isTrainable())
throw LogicError(METHOD_NAME, "Graph is not trainable");
for (size_t i = 0; i < m_layers.size(); i++)
m_layers[i]->setOptimizer(optimizer);
}
void Graph::setRegularizer(const Regularizer ®ularizer)
{
if (not isTrainable())
throw LogicError(METHOD_NAME, "Graph is not trainable");
for (size_t i = 0; i < m_layers.size(); i++)
m_layers[i]->setRegularizer(regularizer);
}
void Graph::init()
{
for (size_t i = 0; i < m_layers.size(); i++)
m_layers[i]->init();
}
void Graph::forward(int batchSize)
{
for (size_t i = 0; i < m_nodes.size(); i++)
m_nodes[i]->forward(batchSize);
}
void Graph::backward(int batchSize)
{
if (not isTrainable())
throw LogicError(METHOD_NAME, "Graph is not trainable");
if (m_backup_tensor == nullptr)
create_backup_tensor();
for (size_t i = 0; i < m_nodes.size(); i++)
m_nodes[i]->prepareForBackward();
for (size_t i = 0; i < m_targets.size(); i++)
{
Shape tmp(getTarget(i).shape());
tmp[0] = batchSize;
Tensor gradient = getGradient(i).view(tmp);
Tensor output = getOutput(i).view(tmp);
Tensor target = getTarget(i).view(tmp);
m_losses[i]->getGradient(context(), gradient, output, target);
}
for (int i = static_cast<int>(m_nodes.size()) - 1; i >= 0; i--)
m_nodes[i]->backward(batchSize, *m_backup_tensor);
}
std::vector<Scalar> Graph::getLoss(int batchSize)
{
if (not isTrainable())
throw LogicError(METHOD_NAME, "Graph is not trainable");
std::vector<Scalar> result(numberOfOutputs());
for (size_t i = 0; i < m_targets.size(); i++)
{
Shape tmp(getTarget(i).shape());
tmp[0] = batchSize;
Tensor output = getOutput(i).view(tmp);
Tensor target = getTarget(i).view(tmp);
result[i] = m_losses[i]->getLoss(context(), output, target);
}
return result;
}
void Graph::learn()
{
if (not isTrainable())
throw LogicError(METHOD_NAME, "Graph is not trainable");
for (int i = 0; i < numberOfLayers(); i++)
m_layers[i]->learn();
}
void Graph::print() const
{
for (size_t i = 0; i < m_nodes.size(); i++)
{
GraphNode *node = m_nodes[i].get();
std::cout << i << ' ' << m_nodes[i]->getLayer().name() << " (" << m_nodes[i]->getLayer().getNonlinearity() << ") : "
<< node->getOutputShape() << " : {";
for (int j = 0; j < node->numberOfInputs(); j++)
{
if (j != 0)
std::cout << ',';
std::cout << index_of_node(node->getInputNode(j));
}
std::cout << "} -> {";
for (int j = 0; j < node->numberOfOutputs(); j++)
{
if (j != 0)
std::cout << ',';
std::cout << index_of_node(node->getOutputNode(j));
}
std::cout << "}\n";
}
for (size_t i = 0; i < m_output_nodes.size(); i++)
std::cout << "Output:" << i << " : {" << index_of_node(m_output_nodes[i]) << "} : " << m_output_nodes[i]->getOutputShape() << std::endl;
}
void Graph::makeNonTrainable()
{
for (int i = 0; i < numberOfLayers(); i++)
{
getLayer(i).getWeights().setTrainable(false);
getLayer(i).getBias().setTrainable(false);
}
for (int i = 0; i < numberOfNodes(); i++)
getNode(i).makeNonTrainable();
}
bool Graph::isTrainable() const noexcept
{
return m_targets.size() == m_output_nodes.size();
}
void Graph::calibrate(inference::CalibrationTable &table) const
{
for (size_t i = 0; i < m_nodes.size(); i++)
{
size_t indeOfLayer = index_of_layer(&(m_nodes[i]->getLayer()));
table.getHistogram(indeOfLayer).collectStatistics(m_nodes[i]->getOutputTensor());
}
}
int Graph::numberOfLayers() const noexcept
{
return static_cast<int>(m_layers.size());
}
const Layer& Graph::getLayer(int index) const
{
return *(m_layers.at(index));
}
Layer& Graph::getLayer(int index)
{
return *(m_layers.at(index));
}
int Graph::numberOfNodes() const noexcept
{
return static_cast<int>(m_nodes.size());
}
const GraphNode& Graph::getNode(int index) const
{
return *(m_nodes.at(index));
}
GraphNode& Graph::getNode(int index)
{
return *(m_nodes.at(index));
}
GraphNodeID Graph::getNodeID(const GraphNode *node) const noexcept
{
return index_of_node(node);
}
void Graph::clear()
{
m_context = Context();
m_layers.clear();
m_nodes.clear();
m_losses.clear();
m_targets.clear();
m_input_nodes.clear();
m_output_nodes.clear();
m_backup_tensor.reset();
m_datatype = DataType::FLOAT32;
}
Json Graph::save(SerializedObject &binary_data) const
{
Json result;
result["losses"] = Json(JsonType::Array);
for (size_t i = 0; i < m_losses.size(); i++)
result["losses"][i] = m_losses[i]->serialize(binary_data);
result["layers"] = Json(JsonType::Array);
for (int i = 0; i < numberOfLayers(); i++)
{
Json tmp = getLayer(i).getConfig();
tmp.append(getLayer(i).saveParameters(binary_data));
result["layers"][i] = tmp;
}
result["nodes"] = Json(JsonType::Array);
for (int i = 0; i < static_cast<int>(m_nodes.size()); i++)
result["nodes"][i] = save_node(m_nodes[i].get());
return result;
}
void Graph::load(const Json &json, const SerializedObject &binary_data)
{
clear();
const Json &losses = json["losses"];
for (int i = 0; i < losses.size(); i++)
{
m_losses.push_back(loadLossFunction(losses[i], binary_data));
m_targets.push_back(nullptr);
}
const Json &layers = json["layers"];
for (int i = 0; i < layers.size(); i++)
{
m_layers.push_back(loadLayer(layers[i], binary_data));
m_layers.back()->changeContext(m_context);
}
const Json &nodes = json["nodes"];
for (int i = 0; i < nodes.size(); i++)
load_node(nodes[i]);
for (int i = 0; i < numberOfLayers(); i++)
getLayer(i).loadParameters(layers[i], binary_data);
}
GraphNodeID Graph::add_node(const Layer &layer, const std::vector<GraphNodeID> &inputs)
{
m_layers.push_back(std::unique_ptr<Layer>(layer.clone(layer.getConfig())));
m_layers.back()->changeContext(m_context);
std::vector<GraphNode*> tmp(inputs.size());
for (size_t i = 0; i < inputs.size(); i++)
tmp[i] = get_node(inputs[i]);
m_nodes.push_back(std::make_unique<GraphNode>(m_layers.back().get(), tmp));
if (m_nodes.back()->isInputNode())
m_input_nodes.push_back(m_nodes.back().get());
return static_cast<GraphNodeID>(m_nodes.size() - 1);
}
void Graph::insert_node_with_layer(std::unique_ptr<Layer> &&new_layer, const std::vector<GraphNode*> &inputs,
const std::vector<GraphNode*> &outputs)
{
int last_of_input = 0;
for (size_t i = 0; i < inputs.size(); i++)
{
int tmp = index_of_node(inputs[i]);
if (tmp == -1)
throw LogicError(METHOD_NAME, "no such node in this graph");
last_of_input = std::max(last_of_input, tmp);
}
int first_of_output = numberOfNodes();
for (size_t i = 0; i < outputs.size(); i++)
{
int tmp = index_of_node(outputs[i]);
if (tmp == -1)
throw LogicError(METHOD_NAME, "no such node in this graph");
first_of_output = std::min(first_of_output, tmp);
}
if (last_of_input > first_of_output)
throw LogicError(METHOD_NAME, "insertion would form a cycle");
std::unique_ptr<GraphNode> tmp = std::make_unique<GraphNode>(new_layer.get(), inputs);
GraphNode::link(tmp.get(), outputs);
m_nodes.insert(m_nodes.begin() + last_of_input + 1, std::move(tmp));
new_layer->changeContext(m_context);
m_layers.push_back(std::move(new_layer));
}
void Graph::remove_node(GraphNode *node)
{
auto index_in_input_nodes = std::find(m_input_nodes.begin(), m_input_nodes.end(), node);
auto index_in_output_nodes = std::find(m_output_nodes.begin(), m_output_nodes.end(), node);
if (index_in_input_nodes != m_input_nodes.end())
{
if (node->numberOfOutputs() > 1)
throw LogicError(METHOD_NAME, "trying to remove input node");
else
*index_in_input_nodes = node->getOutputNode(0);
}
if (index_in_output_nodes != m_output_nodes.end())
{
if (node->numberOfInputs() > 1)
throw LogicError(METHOD_NAME, "trying to remove output node");
else
*index_in_output_nodes = node->getInputNode(0);
}
node->removeAllLinks();
removeByIndex(m_layers, index_of_layer(&(node->getLayer())));
removeByIndex(m_nodes, index_of_node(node));
}
std::unique_ptr<Layer> Graph::replaceLayer(int index, const Layer &newLayer)
{
std::unique_ptr<Layer> result = std::move(m_layers[index]);
m_layers[index] = std::unique_ptr<Layer>(newLayer.clone(newLayer.getConfig()));
m_layers[index]->changeContext(m_context);
std::vector<Shape> tmp;
for (int i = 0; i < result->numberOfInputs(); i++)
tmp.push_back(result->getInputShape(i));
m_layers[index]->setInputShape(tmp);
for (size_t i = 0; i < m_nodes.size(); i++)
if (&(m_nodes[i]->getLayer()) == result.get())
m_nodes[i]->replaceLayer(m_layers[index].get());
return result;
}
void Graph::create_backup_tensor()
{
int tmp = 0;
for (size_t i = 0; i < m_nodes.size(); i++)
tmp = std::max(tmp, m_nodes[i]->getBackupStorage());
m_backup_tensor = std::make_unique<Tensor>(Shape( { tmp }), dtype(), device());
}
Json Graph::save_node(const GraphNode *node) const
{
Json result;
result["is_input_node"] = node->isInputNode();
result["is_output_node"] = node->isOutputNode();
result["layer_id"] = index_of_layer(&(node->getLayer()));
result["input_nodes"] = Json(JsonType::Array);
for (int i = 0; i < node->numberOfInputs(); i++)
result["input_nodes"][i] = index_of_node(node->getInputNode(i));
return result;
}
void Graph::load_node(const Json &json)
{
Layer *layer = m_layers[static_cast<int>(json["layer_id"])].get();
std::vector<GraphNode*> inputs;
for (int i = 0; i < json["input_nodes"].size(); i++)
inputs.push_back(m_nodes[static_cast<int>(json["input_nodes"][i])].get());
m_nodes.push_back(std::make_unique<GraphNode>(layer, inputs));
if (json["is_input_node"])
m_input_nodes.push_back(m_nodes.back().get());
if (json["is_output_node"])
m_output_nodes.push_back(m_nodes.back().get());
}
int Graph::index_of_node(const GraphNode *node) const noexcept
{
for (size_t i = 0; i < m_nodes.size(); i++)
if (m_nodes[i].get() == node)
return i;
return -1;
}
int Graph::index_of_layer(const Layer *layer) const noexcept
{
for (size_t i = 0; i < m_layers.size(); i++)
if (m_layers[i].get() == layer)
return i;
return -1;
}
const GraphNode* Graph::get_node(GraphNodeID index) const
{
if (index < 0 || index >= numberOfNodes())
throw IndexOutOfBounds(METHOD_NAME, "index", index, numberOfNodes());
return m_nodes[index].get();
}
GraphNode* Graph::get_node(GraphNodeID index)
{
if (index < 0 || index >= numberOfNodes())
throw IndexOutOfBounds(METHOD_NAME, "index", index, numberOfNodes());
return m_nodes[index].get();
}
} /* namespace avocado */
| 28.362292 | 139 | 0.666449 | AvocadoML |
ac7378987845f7a3a7f24f79ea8ccfb093cd3c64 | 1,321 | cpp | C++ | Server/Canasta/server.cpp | vivibau/CanastaCSharpOld | 2aadde306450837244b6ec4364d9156e076322b0 | [
"MIT"
] | null | null | null | Server/Canasta/server.cpp | vivibau/CanastaCSharpOld | 2aadde306450837244b6ec4364d9156e076322b0 | [
"MIT"
] | null | null | null | Server/Canasta/server.cpp | vivibau/CanastaCSharpOld | 2aadde306450837244b6ec4364d9156e076322b0 | [
"MIT"
] | 1 | 2020-06-04T14:13:04.000Z | 2020-06-04T14:13:04.000Z | /*#include <iostream>
using namespace std;
int main()
{
return 0;
}
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include "TCPAcceptor.h"
#include "Game.h"
#include "Parser.h"
#include "Includes.h"
int main(int argc, char** argv)
{
/*
if (argc < 2 || argc > 4) {
printf("usage: server <port>\n");
exit(1);
}
*/
TCPStream* stream = NULL;
TCPAcceptor* acceptor = NULL;
std::vector<Game*> games;
srand(time(NULL));
// acceptor = new TCPAcceptor(atoi(argv[1]));
acceptor = new TCPAcceptor(3291);
if (acceptor->start() == 0) {
while (1) {
stream = acceptor->accept();
if (stream != NULL) {
ssize_t len;
char line[1024];
while ((len = stream->receive(line, sizeof(line))) > 0) {
Parser* parser = new Parser(line, len);
parser->parseData();
parser->updateGame(games);
std::string response = parser->getResponse();
stream->send(response.c_str(), response.length());
if (parser) delete(parser);
}
delete stream;
}
}
// if (acceptor) delete(acceptor);
}
exit(0);
}
| 22.016667 | 73 | 0.500379 | vivibau |
ac7437c58cc1a6d8071d9aef2e470355a538c8fa | 2,592 | cc | C++ | src/cobalt/bin/system-metrics/memory_stats_fetcher_impl.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | src/cobalt/bin/system-metrics/memory_stats_fetcher_impl.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | src/cobalt/bin/system-metrics/memory_stats_fetcher_impl.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia 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 "src/cobalt/bin/system-metrics/memory_stats_fetcher_impl.h"
#include <fcntl.h>
#include <fuchsia/cobalt/cpp/fidl.h>
#include <fuchsia/boot/c/fidl.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fdio.h>
#include <lib/zx/resource.h>
#include <trace/event.h>
#include <zircon/status.h>
#include "lib/syslog/cpp/logger.h"
namespace cobalt {
MemoryStatsFetcherImpl::MemoryStatsFetcherImpl() { InitializeRootResourceHandle(); }
bool MemoryStatsFetcherImpl::FetchMemoryStats(zx_info_kmem_stats_t* mem_stats) {
TRACE_DURATION("system_metrics", "MemoryStatsFetcherImpl::FetchMemoryStats");
if (root_resource_handle_ == ZX_HANDLE_INVALID) {
FX_LOGS(ERROR) << "MemoryStatsFetcherImpl: No root resource"
<< "present. Reconnecting...";
InitializeRootResourceHandle();
return false;
}
zx_status_t err = zx_object_get_info(root_resource_handle_, ZX_INFO_KMEM_STATS, mem_stats,
sizeof(*mem_stats), NULL, NULL);
if (err != ZX_OK) {
FX_LOGS(ERROR) << "MemoryStatsFetcherImpl: Fetching "
<< "ZX_INFO_KMEM_STATS through syscall returns " << zx_status_get_string(err);
return false;
}
return true;
}
// TODO(CF-691) When Component Stats (CS) supports memory metrics,
// switch to Component Stats / iquery, by creating a new class with the
// interface MemoryStatsFetcher.
void MemoryStatsFetcherImpl::InitializeRootResourceHandle() {
zx::channel local, remote;
zx_status_t status = zx::channel::create(0, &local, &remote);
if (status != ZX_OK) {
return;
}
static const char kRootResourceSvc[] = "/svc/fuchsia.boot.RootResource";
status = fdio_service_connect(kRootResourceSvc, remote.release());
if (status != ZX_OK) {
FX_LOGS(ERROR) << "Cobalt SystemMetricsDaemon: Error getting root_resource_handle_. "
<< "Cannot open fuchsia.boot.RootResource: " << zx_status_get_string(status);
return;
}
zx_status_t fidl_status = fuchsia_boot_RootResourceGet(local.get(), &root_resource_handle_);
if (fidl_status != ZX_OK) {
FX_LOGS(ERROR) << "Cobalt SystemMetricsDaemon: Error getting root_resource_handle_. "
<< zx_status_get_string(fidl_status);
return;
} else if (root_resource_handle_ == ZX_HANDLE_INVALID) {
FX_LOGS(ERROR) << "Cobalt SystemMetricsDaemon: Failed to get root_resource_handle_.";
return;
}
}
} // namespace cobalt
| 38.117647 | 97 | 0.713349 | OpenTrustGroup |
ac78dedea2fd0f8902243213d929ae4e97fd5063 | 3,019 | cpp | C++ | Sample/ApplicationSample/sample_cpp/Browser/SampleInfoLayer.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 37 | 2015-07-12T14:21:03.000Z | 2020-10-17T03:08:17.000Z | Sample/ApplicationSample/sample_cpp/Browser/SampleInfoLayer.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 91 | 2015-06-14T10:47:22.000Z | 2020-06-29T18:05:21.000Z | Sample/ApplicationSample/sample_cpp/Browser/SampleInfoLayer.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 14 | 2015-07-13T04:15:20.000Z | 2021-09-30T01:34:51.000Z | #include "SampleInfoLayer.h"
#include "SampleBrowser.h"
using namespace std;
SampleInfoLayer::SampleInfoLayer(float scrollBarHeight, float totalHeight)
: totalHeight(totalHeight)
{
scrollBar = make_shared<asd::GeometryObject2D>();
{
auto rect = asd::RectF(0, 0, ScrollBarWidth, scrollBarHeight);
auto shape = make_shared<asd::RectangleShape>();
shape->SetDrawingArea(rect);
scrollBar->SetShape(shape);
}
scrollBar->SetColor(asd::Color(64, 64, 64, 255));
scrollBar->SetPosition(asd::Vector2DF(640 - ScrollBarWidth - SampleBrowser::Margin, 20 + SampleBrowser::Margin));
AddObject(scrollBar);
SetName(asd::ToAString("Info"));
auto panel = make_shared<asd::GeometryObject2D>();
{
auto rect = asd::RectF(0, 0, 640, PanelHeight);
auto shape = make_shared<asd::RectangleShape>();
shape->SetDrawingArea(rect);
panel->SetShape(shape);
}
panel->SetColor(asd::Color(16, 16, 16, 255));
panel->SetPosition(asd::Vector2DF(0, 480 - PanelHeight));
AddObject(panel);
auto font = asd::Engine::GetGraphics()->CreateDynamicFont(u"", 12, asd::Color(255, 255, 255, 255), 1, asd::Color(0, 0, 0, 255));
title = make_shared<asd::TextObject2D>();
title->SetFont(font);
title->SetText(asd::ToAString("").c_str());
title->SetColor(asd::Color(255, 255, 0, 255));
title->SetPosition(asd::Vector2DF(2, 2));
title->SetDrawingPriority(1);
className = make_shared<asd::TextObject2D>();
className->SetFont(font);
className->SetText(asd::ToAString("").c_str());
className->SetColor(asd::Color(128, 255, 225, 255));
className->SetPosition(asd::Vector2DF(2, 2));
className->SetDrawingPriority(1);
description = make_shared<asd::TextObject2D>();
description->SetFont(font);
description->SetText(asd::ToAString("").c_str());
description->SetColor(asd::Color(255, 255, 255, 255));
description->SetPosition(asd::Vector2DF(6, 22));
description->SetDrawingPriority(1);
panel->AddChild(title, asd::ChildManagementMode::RegistrationToLayer, asd::ChildTransformingMode::Position);
panel->AddChild(className, asd::ChildManagementMode::RegistrationToLayer, asd::ChildTransformingMode::Position);
panel->AddChild(description, asd::ChildManagementMode::RegistrationToLayer, asd::ChildTransformingMode::Position);
}
void SampleInfoLayer::Show(SampleInfo info)
{
if (info.isAvailable)
{
title->SetText(info.readableTitle.c_str());
className->SetText(info.title.c_str());
description->SetText(info.description.c_str());
className->SetPosition(asd::Vector2DF(
title->GetFont()->CalcTextureSize(title->GetText(), asd::WritingDirection::Horizontal).X + 8,
2));
}
else
{
title->SetText(asd::ToAString("").c_str());
className->SetText(asd::ToAString("").c_str());
description->SetText(asd::ToAString("").c_str());
}
}
void SampleInfoLayer::MoveScrollBar(float pos)
{
float yOffset = pos / totalHeight * (480 - 20 - PanelHeight - SampleBrowser::Margin);
scrollBar->SetPosition(asd::Vector2DF(
640 - ScrollBarWidth - SampleBrowser::Margin,
20 + SampleBrowser::Margin / 2 + yOffset));
} | 35.104651 | 129 | 0.725075 | GCLemon |
ac794c9c6de51b32a5e62cafbdec641c9b9d6e1a | 3,725 | cpp | C++ | options/posix/generic/grp-stubs.cpp | CPL-1/mlibc | 0726f99c28629e4fc7730d8897909e0cdb5b2545 | [
"MIT"
] | null | null | null | options/posix/generic/grp-stubs.cpp | CPL-1/mlibc | 0726f99c28629e4fc7730d8897909e0cdb5b2545 | [
"MIT"
] | null | null | null | options/posix/generic/grp-stubs.cpp | CPL-1/mlibc | 0726f99c28629e4fc7730d8897909e0cdb5b2545 | [
"MIT"
] | null | null | null |
#include <grp.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <bits/ensure.h>
#include <mlibc/debug.hpp>
namespace {
thread_local group global_entry;
template<typename F>
void walk_segments(frg::string_view line, char delimiter, F fn) {
size_t s = 0;
while(true) {
size_t d = line.find_first(':', s);
if(d == size_t(-1))
break;
auto chunk = line.sub_string(s, d - s);
fn(chunk);
s = d + 1;
}
if(line[s]) {
auto chunk = line.sub_string(s, line.size() - s);
fn(chunk);
}
}
bool extract_entry(frg::string_view line, group *entry) {
__ensure(!entry->gr_name);
__ensure(!entry->gr_mem);
frg::string_view segments[5];
// Parse the line into exactly 4 segments.
size_t s = 0;
int n;
for(n = 0; n < 4; n++) {
size_t d = line.find_first(':', s);
if(d == size_t(-1))
break;
segments[n] = line.sub_string(s, d - s);
s = d + 1;
}
if(line.find_first(':', s) != size_t(-1))
return false;
segments[n] = line.sub_string(s, line.size() - s);
n++;
if(n < 4)
return false;
// segments[1] is the password; it is not exported to struct group.
// The other segments are consumed below.
// TODO: Handle strndup() and malloc() failure.
auto name = strndup(segments[0].data(), segments[0].size());
__ensure(name);
auto gid = segments[2].to_number<int>();
if(!gid)
return false;
size_t n_members = 0;
walk_segments(segments[3], ',', [&] (frg::string_view) {
n_members++;
});
auto members = reinterpret_cast<char **>(malloc(sizeof(char *) * (n_members + 1)));
__ensure(members);
size_t k = 0;
walk_segments(segments[3], ',', [&] (frg::string_view m) {
members[k] = strndup(m.data(), m.size());
__ensure(members[k]);
k++;
});
members[k] = nullptr;
entry->gr_name = name;
entry->gr_gid = *gid;
entry->gr_mem = members;
return true;
}
void clear_entry(group *entry) {
free(entry->gr_name);
if(entry->gr_mem) {
for(size_t i = 0; entry->gr_mem[i]; i++)
free(entry->gr_mem[i]);
free(entry->gr_mem);
}
entry->gr_name = nullptr;
entry->gr_mem = nullptr;
}
template<typename C>
group *walk_file(C cond) {
auto file = fopen("/etc/group", "r");
if(!file)
return nullptr;
char line[512];
while(fgets(line, 512, file)) {
clear_entry(&global_entry);
if(!extract_entry(line, &global_entry))
continue;
if(cond(&global_entry)) {
fclose(file);
return &global_entry;
}
}
fclose(file);
errno = ESRCH;
return nullptr;
}
}
void endgrent(void) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
struct group *getgrent(void) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
struct group *getgrgid(gid_t gid) {
return walk_file([&] (group *entry) {
return entry->gr_gid == gid;
});
}
int getgrgid_r(gid_t, struct group *, char *, size_t, struct group **) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
struct group *getgrnam(const char *name) {
return walk_file([&] (group *entry) {
return !strcmp(entry->gr_name, name);
});
}
int getgrnam_r(const char *, struct group *, char *, size_t, struct group **) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
void setgrent(void) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int setgroups(size_t size, const gid_t *list) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int initgroups(const char *user, gid_t group) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int putgrent(const struct group *, FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
struct group *fgetgrent(FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
| 21.783626 | 85 | 0.640537 | CPL-1 |
ac7f18198c4b7ebb51428ca0e212c7bff5992afc | 746 | cpp | C++ | Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T12:03:32.000Z | 2022-03-03T12:03:32.000Z | Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2020-11-27T09:41:18.000Z | 2020-11-27T09:41:18.000Z | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berrySingleNodeSelection.h"
#include "mitkDataNode.h"
namespace berry
{
void SingleNodeSelection::SetNode( mitk::DataNode* _SelectedNode )
{
m_Node = _SelectedNode;
}
mitk::DataNode* SingleNodeSelection::GetNode() const
{
return m_Node;
}
bool SingleNodeSelection::IsEmpty() const
{
return ( m_Node == nullptr );
}
}
| 20.722222 | 78 | 0.568365 | zhaomengxiao |
ac806388da5d8e24ed0e5846395902524c11f99a | 783 | cpp | C++ | C_Plus_Plus/Basic/save_image/main.cpp | Asadullah-Dal17/learn-opencv-python | 2892e1b253f1c8977662148a8721d8efb7bd63b6 | [
"MIT"
] | 1 | 2021-12-12T12:17:03.000Z | 2021-12-12T12:17:03.000Z | C_Plus_Plus/Basic/save_image/main.cpp | Asadullah-Dal17/learn-opencv-python | 2892e1b253f1c8977662148a8721d8efb7bd63b6 | [
"MIT"
] | null | null | null | C_Plus_Plus/Basic/save_image/main.cpp | Asadullah-Dal17/learn-opencv-python | 2892e1b253f1c8977662148a8721d8efb7bd63b6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <opencv2/opencv.hpp>
int main(int, char**) {
std::string image_path ="C:/Users/Asadullah/Projects/Opencv/Course/coding_pubic/learn-opencv-python/images/shapes_image.png";
std::string saving_path ="C:/Users/Asadullah/Projects/Opencv/Course/coding_pubic/learn-opencv-python/C_Plus_Plus/Basic/save_image/save_image.png";
// std::cout<<test;
cv::Mat image; // creating Mat data type for image
image = cv::imread(image_path,0);
cv::imwrite(saving_path, image);
cv::imshow("Images", image); //showing image on screen
cv::waitKey(0); // making window wait until key is pressed on keyboard
cv::Mat loading_saved = cv::imread(saving_path);
cv::imshow("saved_image",loading_saved);
cv::waitKey(0);
return 0;
}
| 41.210526 | 150 | 0.707535 | Asadullah-Dal17 |
ac813c9b719672b1d58e01b342dc9615d3540e0e | 640 | cpp | C++ | src/random.cpp | navkagleb/Random | adb8ea30178582dc77af0b460f3895ca8e4cb641 | [
"MIT"
] | 1 | 2021-06-02T15:46:00.000Z | 2021-06-02T15:46:00.000Z | src/random.cpp | navkagleb/Random | adb8ea30178582dc77af0b460f3895ca8e4cb641 | [
"MIT"
] | null | null | null | src/random.cpp | navkagleb/Random | adb8ea30178582dc77af0b460f3895ca8e4cb641 | [
"MIT"
] | null | null | null | #include "random.hpp"
namespace ng::random {
bool NextBool(float probability) {
return _detail::BoolDistribution(std::max(0.0f, std::min(1.0f, probability)))(_detail::GetMersenneTwisterEngine());
}
std::string NextString(std::size_t size, char from, char to) {
std::string next(size, '\0');
for (auto& character : next) {
character = NextIntegral<char>(from, to);
}
return next;
}
std::string NextString(std::size_t size, const std::function<char()>& get_random_char) {
std::string next(size, '\0');
for (auto& character : next) {
character = get_random_char();
}
return next;
}
} // namespace ng::random
| 21.333333 | 117 | 0.673438 | navkagleb |
ac82131e62f6b39d4c94a6eebe93eeba4ad5e920 | 8,614 | hxx | C++ | include/nifty/distributed/distributed_graph.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | null | null | null | include/nifty/distributed/distributed_graph.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | null | null | null | include/nifty/distributed/distributed_graph.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | null | null | null | #pragma once
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include "nifty/distributed/graph_extraction.hxx"
namespace nifty {
namespace distributed {
// A simple directed graph,
// that can be constructed from the distributed region graph outputs
// We use this instead of the nifty graph api, because we need to support
// non-dense node indices
class Graph {
// private graph typedefs
// NodeAdjacency: maps nodes that are adjacent to a given node to the corresponding edge-id
typedef std::map<NodeType, EdgeIndexType> NodeAdjacency;
// NodeStorage: storage of the adjacency for all nodes
typedef std::unordered_map<NodeType, NodeAdjacency> NodeStorage;
// EdgeStorage: dense storage of pairs of edges
typedef std::vector<EdgeType> EdgeStorage;
public:
// API: we can construct the graph from blocks that were extracted via `extractGraphFromRoi`
// or `mergeSubgraphs` from `region_graph.hxx`
Graph(const std::string & blockPath, const int nThreads=1) : nodeMaxId_(0) {
loadEdges(blockPath, edges_, 0, nThreads);
initGraph();
}
// This is a bit weird (constructor with side effects....)
// but I don't want the edge id mapping to be part of this class
Graph(const std::vector<std::string> & blockPaths,
std::vector<EdgeIndexType> & edgeIdsOut,
const int nThreads=1) : nodeMaxId_(0) {
// load all the edges and edge-id mapping in the blocks
// to tmp objects
std::vector<EdgeType> edgesTmp;
std::vector<EdgeIndexType> edgeIdsTmp;
for(const auto & blockPath : blockPaths) {
loadEdges(blockPath, edgesTmp, edgesTmp.size(), nThreads);
loadEdgeIndices(blockPath, edgeIdsTmp, edgeIdsTmp.size(), nThreads);
}
// get the indices that would sort the edge uv's
// (we need to sort the edge uvs AND the edgeIds in the same manner here)
std::vector<std::size_t> indices(edgesTmp.size());
std::iota(indices.begin(), indices.end(), 0);
std::sort(indices.begin(), indices.end(), [&](const std::size_t a, const std::size_t b){
return edgesTmp[a] < edgesTmp[b];
});
// copy tmp edges in sorted order
edges_.resize(edgesTmp.size());
for(std::size_t ii = 0; ii < edges_.size(); ++ii) {
edges_[ii] = edgesTmp[indices[ii]];
}
// make edges unique
edges_.resize(std::unique(edges_.begin(), edges_.end()) - edges_.begin());
// copy tmp edge ids to the out vector in sorted order
edgeIdsOut.resize(edgeIdsTmp.size());
for(std::size_t ii = 0; ii < edgeIdsOut.size(); ++ii) {
edgeIdsOut[ii] = edgeIdsTmp[indices[ii]];
}
// make edge ids unique
edgeIdsOut.resize(std::unique(edgeIdsOut.begin(),
edgeIdsOut.end()) - edgeIdsOut.begin());
// init the graph
initGraph();
}
// non-constructor API
// Find edge-id corresponding to the nodes u, v
// returns -1 if no such edge exists
EdgeIndexType findEdge(NodeType u, NodeType v) const {
// find the node iterator
auto uIt = nodes_.find(u);
// don't find the u node -> return -1
if(uIt == nodes_.end()) {
return -1;
}
// check if v is in the adjacency of u
auto vIt = uIt->second.find(v);
// v node is not in u's adjacency -> return -1
if(vIt == uIt->second.end()) {
return -1;
}
// otherwise we have found the edge and return the edge id
return vIt->second;
}
// get the node adjacency
const NodeAdjacency & nodeAdjacency(const NodeType node) const {
return nodes_.at(node);
}
// extract the subgraph uv-ids (with dense node labels)
// as well as inner and outer edges associated with the node list
template<class NODE_ARRAY>
void extractSubgraphFromNodes(const xt::xexpression<NODE_ARRAY> & nodesExp,
const bool allowInvalidNodes,
std::vector<EdgeIndexType> & innerEdgesOut,
std::vector<EdgeIndexType> & outerEdgesOut) const {
const auto & nodes = nodesExp.derived_cast();
// build hash set for fast look-up
std::unordered_set<NodeType> nodeSet(nodes.begin(), nodes.end());
// then iterate over the adjacency and extract inner and outer edges
for(const NodeType u : nodes) {
//const auto & uAdjacency = nodes_.at(u);
// we might allow invalid nodes
auto adjIt = nodes_.find(u);
if(adjIt == nodes_.end()) {
if(allowInvalidNodes) {
continue;
} else {
throw std::runtime_error("Invalid node in sub-graph extraction");
}
}
const auto & uAdjacency = adjIt->second;
for(const auto & adj : uAdjacency) {
const NodeType v = adj.first;
const EdgeIndexType edge = adj.second;
// we do the look-up in the node-mapping instead of the node-list, because it's a hash-map
// (and thus faster than array lookup)
if(nodeSet.find(v) != nodeSet.end()) {
// we will encounter inner edges twice, so we only add them for u < v
if(u < v) {
innerEdgesOut.push_back(edge);
}
} else {
// outer edges occur only once by construction
outerEdgesOut.push_back(edge);
}
}
}
}
// number of nodes and edges
std::size_t numberOfNodes() const {return nodes_.size();}
std::size_t numberOfEdges() const {return edges_.size();}
std::size_t maxNodeId() const {return nodeMaxId_;}
// edges are always consecutive
std::size_t maxEdgeId() const {return edges_.size() - 1;}
const EdgeStorage & edges() const {return edges_;}
void nodes(std::set<NodeType> & out) const{
for(auto nodeIt = nodes_.begin(); nodeIt != nodes_.end(); ++nodeIt) {
out.insert(nodeIt->first);
}
}
void nodes(std::vector<NodeType> & out) const{
out.clear();
out.resize(numberOfNodes());
std::size_t nodeId = 0;
for(auto nodeIt = nodes_.begin(); nodeIt != nodes_.end(); ++nodeIt, ++nodeId) {
out[nodeId] = nodeIt->first;
}
}
private:
// init the graph from the edges
void initGraph() {
// iterate over the edges we have
NodeType u, v;
NodeType maxNode;
EdgeIndexType edgeId = 0;
for(const auto & edge : edges_) {
u = edge.first;
v = edge.second;
// insert v in the u adjacency
auto uIt = nodes_.find(u);
if(uIt == nodes_.end()) {
// if u is not in the nodes vector yet, insert it
nodes_.insert(std::make_pair(u, NodeAdjacency{{v, edgeId}}));
} else {
uIt->second[v] = edgeId;
}
// insert u in the v adjacency
auto vIt = nodes_.find(v);
if(vIt == nodes_.end()) {
// if v is not in the nodes vector yet, insert it
nodes_.insert(std::make_pair(v, NodeAdjacency{{u, edgeId}}));
} else {
vIt->second[u] = edgeId;
}
// increase the edge id
++edgeId;
// update the node max id
maxNode = std::max(u, v);
if(maxNode > nodeMaxId_) {
nodeMaxId_ = maxNode;
}
}
}
NodeType nodeMaxId_;
NodeStorage nodes_;
EdgeStorage edges_;
};
}
}
| 38.284444 | 110 | 0.519039 | konopczynski |
12bf32e9897b8b75641db3f0ed1b09a6a9005083 | 26,948 | cpp | C++ | src/preferences/filetypes/IconView.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/preferences/filetypes/IconView.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/preferences/filetypes/IconView.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2006-2007, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#include "IconView.h"
#include <new>
#include <stdlib.h>
#include <strings.h>
#include <Application.h>
#include <AppFileInfo.h>
#include <Attributes.h>
#include <Bitmap.h>
#include <Catalog.h>
#include <IconEditorProtocol.h>
#include <IconUtils.h>
#include <Locale.h>
#include <MenuItem.h>
#include <Mime.h>
#include <NodeMonitor.h>
#include <PopUpMenu.h>
#include <Resources.h>
#include <Roster.h>
#include <Size.h>
#include "FileTypes.h"
#include "MimeTypeListView.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Icon View"
using namespace std;
status_t
icon_for_type(const BMimeType& type, uint8** _data, size_t* _size,
icon_source* _source)
{
if (_data == NULL || _size == NULL)
return B_BAD_VALUE;
icon_source source = kNoIcon;
uint8* data;
size_t size;
if (type.GetIcon(&data, &size) == B_OK)
source = kOwnIcon;
if (source == kNoIcon) {
// check for icon from preferred app
char preferred[B_MIME_TYPE_LENGTH];
if (type.GetPreferredApp(preferred) == B_OK) {
BMimeType preferredApp(preferred);
if (preferredApp.GetIconForType(type.Type(), &data, &size) == B_OK)
source = kApplicationIcon;
}
}
if (source == kNoIcon) {
// check super type for an icon
BMimeType superType;
if (type.GetSupertype(&superType) == B_OK) {
if (superType.GetIcon(&data, &size) == B_OK)
source = kSupertypeIcon;
else {
// check the super type's preferred app
char preferred[B_MIME_TYPE_LENGTH];
if (superType.GetPreferredApp(preferred) == B_OK) {
BMimeType preferredApp(preferred);
if (preferredApp.GetIconForType(superType.Type(),
&data, &size) == B_OK)
source = kSupertypeIcon;
}
}
}
}
if (source != kNoIcon) {
*_data = data;
*_size = size;
} // NOTE: else there is no data, so nothing is leaked.
if (_source)
*_source = source;
return source != kNoIcon ? B_OK : B_ERROR;
}
status_t
icon_for_type(const BMimeType& type, BBitmap& bitmap, icon_size size,
icon_source* _source)
{
icon_source source = kNoIcon;
if (type.GetIcon(&bitmap, size) == B_OK)
source = kOwnIcon;
if (source == kNoIcon) {
// check for icon from preferred app
char preferred[B_MIME_TYPE_LENGTH];
if (type.GetPreferredApp(preferred) == B_OK) {
BMimeType preferredApp(preferred);
if (preferredApp.GetIconForType(type.Type(), &bitmap, size) == B_OK)
source = kApplicationIcon;
}
}
if (source == kNoIcon) {
// check super type for an icon
BMimeType superType;
if (type.GetSupertype(&superType) == B_OK) {
if (superType.GetIcon(&bitmap, size) == B_OK)
source = kSupertypeIcon;
else {
// check the super type's preferred app
char preferred[B_MIME_TYPE_LENGTH];
if (superType.GetPreferredApp(preferred) == B_OK) {
BMimeType preferredApp(preferred);
if (preferredApp.GetIconForType(superType.Type(),
&bitmap, size) == B_OK)
source = kSupertypeIcon;
}
}
}
}
if (_source)
*_source = source;
return source != kNoIcon ? B_OK : B_ERROR;
}
// #pragma mark -
Icon::Icon()
:
fLarge(NULL),
fMini(NULL),
fData(NULL),
fSize(0)
{
}
Icon::Icon(const Icon& source)
:
fLarge(NULL),
fMini(NULL),
fData(NULL),
fSize(0)
{
*this = source;
}
Icon::~Icon()
{
delete fLarge;
delete fMini;
free(fData);
}
void
Icon::SetTo(const BAppFileInfo& info, const char* type)
{
Unset();
uint8* data;
size_t size;
if (info.GetIconForType(type, &data, &size) == B_OK) {
// we have the vector icon, no need to get the rest
AdoptData(data, size);
return;
}
BBitmap* icon = AllocateBitmap(B_LARGE_ICON, B_CMAP8);
if (icon && info.GetIconForType(type, icon, B_LARGE_ICON) == B_OK)
AdoptLarge(icon);
else
delete icon;
icon = AllocateBitmap(B_MINI_ICON, B_CMAP8);
if (icon && info.GetIconForType(type, icon, B_MINI_ICON) == B_OK)
AdoptMini(icon);
else
delete icon;
}
void
Icon::SetTo(const entry_ref& ref, const char* type)
{
Unset();
BFile file(&ref, B_READ_ONLY);
BAppFileInfo info(&file);
if (file.InitCheck() == B_OK
&& info.InitCheck() == B_OK)
SetTo(info, type);
}
void
Icon::SetTo(const BMimeType& type, icon_source* _source)
{
Unset();
uint8* data;
size_t size;
if (icon_for_type(type, &data, &size, _source) == B_OK) {
// we have the vector icon, no need to get the rest
AdoptData(data, size);
return;
}
BBitmap* icon = AllocateBitmap(B_LARGE_ICON, B_CMAP8);
if (icon && icon_for_type(type, *icon, B_LARGE_ICON, _source) == B_OK)
AdoptLarge(icon);
else
delete icon;
icon = AllocateBitmap(B_MINI_ICON, B_CMAP8);
if (icon && icon_for_type(type, *icon, B_MINI_ICON) == B_OK)
AdoptMini(icon);
else
delete icon;
}
status_t
Icon::CopyTo(BAppFileInfo& info, const char* type, bool force) const
{
status_t status = B_OK;
if (fLarge != NULL || force)
status = info.SetIconForType(type, fLarge, B_LARGE_ICON);
if (fMini != NULL || force)
status = info.SetIconForType(type, fMini, B_MINI_ICON);
if (fData != NULL || force)
status = info.SetIconForType(type, fData, fSize);
return status;
}
status_t
Icon::CopyTo(const entry_ref& ref, const char* type, bool force) const
{
BFile file;
status_t status = file.SetTo(&ref, B_READ_ONLY);
if (status < B_OK)
return status;
BAppFileInfo info(&file);
status = info.InitCheck();
if (status < B_OK)
return status;
return CopyTo(info, type, force);
}
status_t
Icon::CopyTo(BMimeType& type, bool force) const
{
status_t status = B_OK;
if (fLarge != NULL || force)
status = type.SetIcon(fLarge, B_LARGE_ICON);
if (fMini != NULL || force)
status = type.SetIcon(fMini, B_MINI_ICON);
if (fData != NULL || force)
status = type.SetIcon(fData, fSize);
return status;
}
status_t
Icon::CopyTo(BMessage& message) const
{
status_t status = B_OK;
if (status == B_OK && fLarge != NULL) {
BMessage archive;
status = fLarge->Archive(&archive);
if (status == B_OK)
status = message.AddMessage("icon/large", &archive);
}
if (status == B_OK && fMini != NULL) {
BMessage archive;
status = fMini->Archive(&archive);
if (status == B_OK)
status = message.AddMessage("icon/mini", &archive);
}
if (status == B_OK && fData != NULL)
status = message.AddData("icon", B_VECTOR_ICON_TYPE, fData, fSize);
return B_OK;
}
void
Icon::SetLarge(const BBitmap* large)
{
if (large != NULL) {
if (fLarge == NULL)
fLarge = new BBitmap(BRect(0, 0, 31, 31), B_CMAP8);
memcpy(fLarge->Bits(), large->Bits(), min_c(large->BitsLength(),
fLarge->BitsLength()));
} else {
delete fLarge;
fLarge = NULL;
}
}
void
Icon::SetMini(const BBitmap* mini)
{
if (mini != NULL) {
if (fMini == NULL)
fMini = new BBitmap(BRect(0, 0, 15, 15), B_CMAP8);
memcpy(fMini->Bits(), mini->Bits(), min_c(mini->BitsLength(),
fMini->BitsLength()));
} else {
delete fMini;
fMini = NULL;
}
}
void
Icon::SetData(const uint8* data, size_t size)
{
free(fData);
fData = NULL;
if (data != NULL) {
fData = (uint8*)malloc(size);
if (fData != NULL) {
fSize = size;
//fType = B_VECTOR_ICON_TYPE;
memcpy(fData, data, size);
}
}
}
void
Icon::Unset()
{
delete fLarge;
delete fMini;
free(fData);
fLarge = fMini = NULL;
fData = NULL;
}
bool
Icon::HasData() const
{
return fData != NULL || fLarge != NULL || fMini != NULL;
}
status_t
Icon::GetData(icon_size which, BBitmap** _bitmap) const
{
BBitmap* source;
switch (which) {
case B_LARGE_ICON:
source = fLarge;
break;
case B_MINI_ICON:
source = fMini;
break;
default:
return B_BAD_VALUE;
}
if (source == NULL)
return B_ENTRY_NOT_FOUND;
BBitmap* bitmap = new (nothrow) BBitmap(source);
if (bitmap == NULL || bitmap->InitCheck() != B_OK) {
delete bitmap;
return B_NO_MEMORY;
}
*_bitmap = bitmap;
return B_OK;
}
status_t
Icon::GetData(uint8** _data, size_t* _size) const
{
if (fData == NULL)
return B_ENTRY_NOT_FOUND;
uint8* data = (uint8*)malloc(fSize);
if (data == NULL)
return B_NO_MEMORY;
memcpy(data, fData, fSize);
*_data = data;
*_size = fSize;
return B_OK;
}
status_t
Icon::GetIcon(BBitmap* bitmap) const
{
if (bitmap == NULL)
return B_BAD_VALUE;
if (fData != NULL
&& BIconUtils::GetVectorIcon(fData, fSize, bitmap) == B_OK)
return B_OK;
int32 width = bitmap->Bounds().IntegerWidth() + 1;
if (width == B_LARGE_ICON && fLarge != NULL) {
bitmap->SetBits(fLarge->Bits(), fLarge->BitsLength(), 0,
fLarge->ColorSpace());
return B_OK;
}
if (width == B_MINI_ICON && fMini != NULL) {
bitmap->SetBits(fMini->Bits(), fMini->BitsLength(), 0,
fMini->ColorSpace());
return B_OK;
}
return B_ENTRY_NOT_FOUND;
}
Icon&
Icon::operator=(const Icon& source)
{
Unset();
SetData(source.fData, source.fSize);
SetLarge(source.fLarge);
SetMini(source.fMini);
return *this;
}
void
Icon::AdoptLarge(BBitmap *large)
{
delete fLarge;
fLarge = large;
}
void
Icon::AdoptMini(BBitmap *mini)
{
delete fMini;
fMini = mini;
}
void
Icon::AdoptData(uint8* data, size_t size)
{
free(fData);
fData = data;
fSize = size;
}
/*static*/ BBitmap*
Icon::AllocateBitmap(int32 size, int32 space)
{
int32 kSpace = B_RGBA32;
if (space == -1)
space = kSpace;
BBitmap* bitmap = new (nothrow) BBitmap(BRect(0, 0, size - 1, size - 1),
(color_space)space);
if (bitmap == NULL || bitmap->InitCheck() != B_OK) {
delete bitmap;
return NULL;
}
return bitmap;
}
// #pragma mark -
IconView::IconView(const char* name, uint32 flags)
: BControl(name, NULL, NULL, B_WILL_DRAW | flags),
fModificationMessage(NULL),
fIconSize(B_LARGE_ICON),
fIcon(NULL),
fHeapIcon(NULL),
fHasRef(false),
fHasType(false),
fIconData(NULL),
fTracking(false),
fDragging(false),
fDropTarget(false),
fShowEmptyFrame(true)
{
}
IconView::~IconView()
{
delete fIcon;
delete fModificationMessage;
}
void
IconView::AttachedToWindow()
{
AdoptParentColors();
fTarget = this;
// SetTo() was already called before we were a valid messenger
if (fHasRef || fHasType)
_StartWatching();
}
void
IconView::DetachedFromWindow()
{
_StopWatching();
}
void
IconView::MessageReceived(BMessage* message)
{
if (message->WasDropped() && message->ReturnAddress() != BMessenger(this)
&& AcceptsDrag(message)) {
// set icon from message
BBitmap* mini = NULL;
BBitmap* large = NULL;
const uint8* data = NULL;
ssize_t size = 0;
message->FindData("icon", B_VECTOR_ICON_TYPE, (const void**)&data,
&size);
BMessage archive;
if (message->FindMessage("icon/large", &archive) == B_OK)
large = (BBitmap*)BBitmap::Instantiate(&archive);
if (message->FindMessage("icon/mini", &archive) == B_OK)
mini = (BBitmap*)BBitmap::Instantiate(&archive);
if (large != NULL || mini != NULL || (data != NULL && size > 0))
_SetIcon(large, mini, data, size);
else {
entry_ref ref;
if (message->FindRef("refs", &ref) == B_OK)
_SetIcon(&ref);
}
delete large;
delete mini;
return;
}
switch (message->what) {
case kMsgIconInvoked:
case kMsgEditIcon:
case kMsgAddIcon:
_AddOrEditIcon();
break;
case kMsgRemoveIcon:
_RemoveIcon();
break;
case B_NODE_MONITOR:
{
if (!fHasRef)
break;
int32 opcode;
if (message->FindInt32("opcode", &opcode) != B_OK
|| opcode != B_ATTR_CHANGED)
break;
const char* name;
if (message->FindString("attr", &name) != B_OK)
break;
if (!strcmp(name, kAttrMiniIcon)
|| !strcmp(name, kAttrLargeIcon)
|| !strcmp(name, kAttrIcon))
Update();
break;
}
case B_META_MIME_CHANGED:
{
if (!fHasType)
break;
const char* type;
int32 which;
if (message->FindString("be:type", &type) != B_OK
|| message->FindInt32("be:which", &which) != B_OK)
break;
if (!strcasecmp(type, fType.Type())) {
switch (which) {
case B_MIME_TYPE_DELETED:
Unset();
break;
case B_ICON_CHANGED:
Update();
break;
default:
break;
}
} else if (fSource != kOwnIcon
&& message->FindString("be:extra_type", &type) == B_OK
&& !strcasecmp(type, fType.Type())) {
// this change could still affect our current icon
if (which == B_MIME_TYPE_DELETED
|| which == B_PREFERRED_APP_CHANGED
|| which == B_SUPPORTED_TYPES_CHANGED
|| which == B_ICON_FOR_TYPE_CHANGED)
Update();
}
break;
}
case B_ICON_DATA_EDITED:
{
const uint8* data;
ssize_t size;
if (message->FindData("icon data", B_VECTOR_ICON_TYPE,
(const void**)&data, &size) < B_OK)
break;
_SetIcon(NULL, NULL, data, size);
break;
}
default:
BControl::MessageReceived(message);
break;
}
}
bool
IconView::AcceptsDrag(const BMessage* message)
{
if (!IsEnabled())
return false;
type_code type;
int32 count;
if (message->GetInfo("refs", &type, &count) == B_OK && count == 1
&& type == B_REF_TYPE) {
// if we're bound to an entry, check that no one drops this to us
entry_ref ref;
if (fHasRef && message->FindRef("refs", &ref) == B_OK && fRef == ref)
return false;
return true;
}
if ((message->GetInfo("icon/large", &type) == B_OK
&& type == B_MESSAGE_TYPE)
|| (message->GetInfo("icon", &type) == B_OK
&& type == B_VECTOR_ICON_TYPE)
|| (message->GetInfo("icon/mini", &type) == B_OK
&& type == B_MESSAGE_TYPE))
return true;
return false;
}
BRect
IconView::BitmapRect() const
{
return BRect(0, 0, fIconSize - 1, fIconSize - 1);
}
void
IconView::Draw(BRect updateRect)
{
SetDrawingMode(B_OP_ALPHA);
if (fHeapIcon != NULL)
DrawBitmap(fHeapIcon, BitmapRect().LeftTop());
else if (fIcon != NULL)
DrawBitmap(fIcon, BitmapRect().LeftTop());
else if (!fDropTarget && fShowEmptyFrame) {
// draw frame so that the user knows here is something he
// might be able to click on
SetHighColor(tint_color(ViewColor(), B_DARKEN_1_TINT));
StrokeRect(BitmapRect());
}
if (IsFocus()) {
// mark this view as a having focus
SetHighColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR));
StrokeRect(BitmapRect());
}
if (fDropTarget) {
// mark this view as a drop target
SetHighColor(0, 0, 0);
SetPenSize(2);
BRect rect = BitmapRect();
// TODO: this is an incompatibility between R5 and Haiku and should be fixed!
// (Necessary adjustment differs.)
rect.left++;
rect.top++;
StrokeRect(rect);
SetPenSize(1);
}
}
void
IconView::GetPreferredSize(float* _width, float* _height)
{
if (_width)
*_width = fIconSize;
if (_height)
*_height = fIconSize;
}
BSize
IconView::MinSize()
{
float width, height;
GetPreferredSize(&width, &height);
return BSize(width, height);
}
BSize
IconView::PreferredSize()
{
return MinSize();
}
BSize
IconView::MaxSize()
{
return MinSize();
}
void
IconView::MouseDown(BPoint where)
{
if (!IsEnabled())
return;
int32 buttons = B_PRIMARY_MOUSE_BUTTON;
int32 clicks = 1;
if (Looper() != NULL && Looper()->CurrentMessage() != NULL) {
if (Looper()->CurrentMessage()->FindInt32("buttons", &buttons) != B_OK)
buttons = B_PRIMARY_MOUSE_BUTTON;
if (Looper()->CurrentMessage()->FindInt32("clicks", &clicks) != B_OK)
clicks = 1;
}
if ((buttons & B_PRIMARY_MOUSE_BUTTON) != 0
&& BitmapRect().Contains(where)) {
if (clicks == 2) {
// double click - open Icon-O-Matic
Invoke();
} else if (fIcon != NULL) {
// start tracking - this icon might be dragged around
fDragPoint = where;
fTracking = true;
SetMouseEventMask(B_POINTER_EVENTS, B_NO_POINTER_HISTORY);
}
}
if ((buttons & B_SECONDARY_MOUSE_BUTTON) != 0) {
// show context menu
ConvertToScreen(&where);
BPopUpMenu* menu = new BPopUpMenu("context");
menu->SetFont(be_plain_font);
bool hasIcon = fHasType ? fSource == kOwnIcon : fIcon != NULL;
if (hasIcon) {
menu->AddItem(new BMenuItem(
B_TRANSLATE("Edit icon" B_UTF8_ELLIPSIS),
new BMessage(kMsgEditIcon)));
} else {
menu->AddItem(new BMenuItem(
B_TRANSLATE("Add icon" B_UTF8_ELLIPSIS),
new BMessage(kMsgAddIcon)));
}
BMenuItem* item = new BMenuItem(
B_TRANSLATE("Remove icon"), new BMessage(kMsgRemoveIcon));
if (!hasIcon)
item->SetEnabled(false);
menu->AddItem(item);
menu->SetTargetForItems(fTarget);
menu->Go(where, true, false, true);
}
}
void
IconView::MouseUp(BPoint where)
{
fTracking = false;
fDragging = false;
if (fDropTarget) {
fDropTarget = false;
Invalidate();
}
}
void
IconView::MouseMoved(BPoint where, uint32 transit, const BMessage* dragMessage)
{
if (fTracking && !fDragging && fIcon != NULL
&& (abs((int32)(where.x - fDragPoint.x)) > 3
|| abs((int32)(where.y - fDragPoint.y)) > 3)) {
// Start drag
BMessage message(B_SIMPLE_DATA);
::Icon* icon = fIconData;
if (fHasRef || fHasType) {
icon = new ::Icon;
if (fHasRef)
icon->SetTo(fRef, fType.Type());
else if (fHasType)
icon->SetTo(fType);
}
icon->CopyTo(message);
if (icon != fIconData)
delete icon;
BBitmap *dragBitmap = new BBitmap(fIcon->Bounds(), B_RGBA32, true);
dragBitmap->Lock();
BView *view
= new BView(dragBitmap->Bounds(), B_EMPTY_STRING, B_FOLLOW_NONE, 0);
dragBitmap->AddChild(view);
view->SetHighColor(B_TRANSPARENT_COLOR);
view->FillRect(dragBitmap->Bounds());
view->SetBlendingMode(B_CONSTANT_ALPHA, B_ALPHA_COMPOSITE);
view->SetDrawingMode(B_OP_ALPHA);
view->SetHighColor(0, 0, 0, 160);
view->DrawBitmap(fIcon);
view->Sync();
dragBitmap->Unlock();
DragMessage(&message, dragBitmap, B_OP_ALPHA,
fDragPoint - BitmapRect().LeftTop(), this);
fDragging = true;
}
if (dragMessage != NULL && !fDragging && AcceptsDrag(dragMessage)) {
bool dropTarget = transit == B_ENTERED_VIEW || transit == B_INSIDE_VIEW;
if (dropTarget != fDropTarget) {
fDropTarget = dropTarget;
Invalidate();
}
} else if (fDropTarget) {
fDropTarget = false;
Invalidate();
}
}
void
IconView::KeyDown(const char* bytes, int32 numBytes)
{
if (numBytes == 1) {
switch (bytes[0]) {
case B_DELETE:
case B_BACKSPACE:
_RemoveIcon();
return;
case B_ENTER:
case B_SPACE:
Invoke();
return;
}
}
BControl::KeyDown(bytes, numBytes);
}
void
IconView::MakeFocus(bool focus)
{
if (focus != IsFocus())
Invalidate();
BControl::MakeFocus(focus);
}
void
IconView::SetTo(const entry_ref& ref, const char* fileType)
{
Unset();
fHasRef = true;
fRef = ref;
if (fileType != NULL)
fType.SetTo(fileType);
else
fType.Unset();
_StartWatching();
Update();
}
void
IconView::SetTo(const BMimeType& type)
{
Unset();
if (type.Type() == NULL)
return;
fHasType = true;
fType.SetTo(type.Type());
_StartWatching();
Update();
}
void
IconView::SetTo(::Icon* icon)
{
if (fIconData == icon)
return;
Unset();
fIconData = icon;
Update();
}
void
IconView::Unset()
{
if (fHasRef || fHasType)
_StopWatching();
fHasRef = false;
fHasType = false;
fType.Unset();
fIconData = NULL;
}
void
IconView::Update()
{
delete fIcon;
fIcon = NULL;
Invalidate();
// this will actually trigger a redraw *after* we updated the icon below
BBitmap* icon = NULL;
if (fHasRef) {
BFile file(&fRef, B_READ_ONLY);
if (file.InitCheck() != B_OK)
return;
BNodeInfo info;
if (info.SetTo(&file) != B_OK)
return;
icon = Icon::AllocateBitmap(fIconSize);
if (icon != NULL && info.GetTrackerIcon(icon,
(icon_size)fIconSize) != B_OK) {
delete icon;
return;
}
} else if (fHasType) {
icon = Icon::AllocateBitmap(fIconSize);
if (icon != NULL && icon_for_type(fType, *icon, (icon_size)fIconSize,
&fSource) != B_OK) {
delete icon;
return;
}
} else if (fIconData) {
icon = Icon::AllocateBitmap(fIconSize);
if (fIconData->GetIcon(icon) != B_OK) {
delete icon;
icon = NULL;
}
}
fIcon = icon;
}
void
IconView::SetIconSize(int32 size)
{
if (size < B_MINI_ICON)
size = B_MINI_ICON;
if (size > 256)
size = 256;
if (size == fIconSize)
return;
fIconSize = size;
Update();
}
void
IconView::ShowIconHeap(bool show)
{
if (show == (fHeapIcon != NULL))
return;
if (show) {
BResources* resources = be_app->AppResources();
if (resources != NULL) {
const void* data = NULL;
size_t size;
data = resources->LoadResource('VICN', "icon heap", &size);
if (data != NULL) {
// got vector icon data
fHeapIcon = Icon::AllocateBitmap(B_LARGE_ICON, B_RGBA32);
if (BIconUtils::GetVectorIcon((const uint8*)data,
size, fHeapIcon) != B_OK) {
// bad data
delete fHeapIcon;
fHeapIcon = NULL;
data = NULL;
}
}
if (data == NULL) {
// no vector icon or failed to get bitmap
// try bitmap icon
data = resources->LoadResource(B_LARGE_ICON_TYPE, "icon heap",
NULL);
if (data != NULL) {
fHeapIcon = Icon::AllocateBitmap(B_LARGE_ICON, B_CMAP8);
if (fHeapIcon != NULL) {
memcpy(fHeapIcon->Bits(), data,
fHeapIcon->BitsLength());
}
}
}
}
} else {
delete fHeapIcon;
fHeapIcon = NULL;
}
}
void
IconView::ShowEmptyFrame(bool show)
{
if (show == fShowEmptyFrame)
return;
fShowEmptyFrame = show;
if (fIcon == NULL)
Invalidate();
}
status_t
IconView::SetTarget(const BMessenger& target)
{
fTarget = target;
return B_OK;
}
void
IconView::SetModificationMessage(BMessage* message)
{
delete fModificationMessage;
fModificationMessage = message;
}
status_t
IconView::Invoke(BMessage* message)
{
if (message == NULL)
fTarget.SendMessage(kMsgIconInvoked);
else
fTarget.SendMessage(message);
return B_OK;
}
Icon*
IconView::Icon()
{
return fIconData;
}
status_t
IconView::GetRef(entry_ref& ref) const
{
if (!fHasRef)
return B_BAD_TYPE;
ref = fRef;
return B_OK;
}
status_t
IconView::GetMimeType(BMimeType& type) const
{
if (!fHasType)
return B_BAD_TYPE;
type.SetTo(fType.Type());
return B_OK;
}
void
IconView::_AddOrEditIcon()
{
BMessage message;
if (fHasRef && fType.Type() == NULL) {
// in ref mode, Icon-O-Matic can change the icon directly, and
// we'll pick it up via node monitoring
message.what = B_REFS_RECEIVED;
message.AddRef("refs", &fRef);
} else {
// in static or MIME type mode, Icon-O-Matic needs to return the
// buffer it changed once its done
message.what = B_EDIT_ICON_DATA;
message.AddMessenger("reply to", BMessenger(this));
::Icon* icon = fIconData;
if (icon == NULL) {
icon = new ::Icon();
if (fHasRef)
icon->SetTo(fRef, fType.Type());
else
icon->SetTo(fType);
}
if (icon->HasData()) {
uint8* data;
size_t size;
if (icon->GetData(&data, &size) == B_OK) {
message.AddData("icon data", B_VECTOR_ICON_TYPE, data, size);
free(data);
}
// TODO: somehow figure out how names of objects in the icon
// can be preserved. Maybe in a second (optional) attribute
// where ever a vector icon attribute is present?
}
if (icon != fIconData)
delete icon;
}
be_roster->Launch("application/x-vnd.haiku-icon_o_matic", &message);
}
void
IconView::_SetIcon(BBitmap* large, BBitmap* mini, const uint8* data,
size_t size, bool force)
{
if (fHasRef) {
BFile file(&fRef, B_READ_WRITE);
if (is_application(file)) {
BAppFileInfo info(&file);
if (info.InitCheck() == B_OK) {
if (large != NULL || force)
info.SetIconForType(fType.Type(), large, B_LARGE_ICON);
if (mini != NULL || force)
info.SetIconForType(fType.Type(), mini, B_MINI_ICON);
if (data != NULL || force)
info.SetIconForType(fType.Type(), data, size);
}
} else {
BNodeInfo info(&file);
if (info.InitCheck() == B_OK) {
if (large != NULL || force)
info.SetIcon(large, B_LARGE_ICON);
if (mini != NULL || force)
info.SetIcon(mini, B_MINI_ICON);
if (data != NULL || force)
info.SetIcon(data, size);
}
}
// the icon shown will be updated using node monitoring
} else if (fHasType) {
if (large != NULL || force)
fType.SetIcon(large, B_LARGE_ICON);
if (mini != NULL || force)
fType.SetIcon(mini, B_MINI_ICON);
if (data != NULL || force)
fType.SetIcon(data, size);
// the icon shown will be updated automatically - we're watching
// any changes to the MIME database
} else if (fIconData != NULL) {
if (large != NULL || force)
fIconData->SetLarge(large);
if (mini != NULL || force)
fIconData->SetMini(mini);
if (data != NULL || force)
fIconData->SetData(data, size);
// replace visible icon
if (fIcon == NULL && fIconData->HasData())
fIcon = Icon::AllocateBitmap(fIconSize);
if (fIconData->GetIcon(fIcon) != B_OK) {
delete fIcon;
fIcon = NULL;
}
Invalidate();
}
if (fModificationMessage)
Invoke(fModificationMessage);
}
void
IconView::_SetIcon(entry_ref* ref)
{
// retrieve icons from file
BFile file(ref, B_READ_ONLY);
BAppFileInfo info(&file);
if (file.InitCheck() != B_OK || info.InitCheck() != B_OK)
return;
// try vector/PNG icon first
uint8* data = NULL;
size_t size = 0;
if (info.GetIcon(&data, &size) == B_OK) {
_SetIcon(NULL, NULL, data, size);
free(data);
return;
}
// try large/mini icons
bool hasMini = false;
bool hasLarge = false;
BBitmap* large = new BBitmap(BRect(0, 0, 31, 31), B_CMAP8);
if (large->InitCheck() != B_OK) {
delete large;
large = NULL;
}
BBitmap* mini = new BBitmap(BRect(0, 0, 15, 15), B_CMAP8);
if (mini->InitCheck() != B_OK) {
delete mini;
mini = NULL;
}
if (large != NULL && info.GetIcon(large, B_LARGE_ICON) == B_OK)
hasLarge = true;
if (mini != NULL && info.GetIcon(mini, B_MINI_ICON) == B_OK)
hasMini = true;
if (!hasMini && !hasLarge) {
// TODO: don't forget device icons!
// try MIME type icon
char type[B_MIME_TYPE_LENGTH];
if (info.GetType(type) != B_OK)
return;
BMimeType mimeType(type);
if (icon_for_type(mimeType, &data, &size) != B_OK) {
// only try large/mini icons when there is no vector icon
if (large != NULL
&& icon_for_type(mimeType, *large, B_LARGE_ICON) == B_OK)
hasLarge = true;
if (mini != NULL
&& icon_for_type(mimeType, *mini, B_MINI_ICON) == B_OK)
hasMini = true;
}
}
if (data != NULL) {
_SetIcon(NULL, NULL, data, size);
free(data);
} else if (hasLarge || hasMini)
_SetIcon(large, mini, NULL, 0);
delete large;
delete mini;
}
void
IconView::_RemoveIcon()
{
_SetIcon(NULL, NULL, NULL, 0, true);
}
void
IconView::_StartWatching()
{
if (Looper() == NULL) {
// we are not a valid messenger yet
return;
}
if (fHasRef) {
BNode node(&fRef);
node_ref nodeRef;
if (node.InitCheck() == B_OK
&& node.GetNodeRef(&nodeRef) == B_OK)
watch_node(&nodeRef, B_WATCH_ATTR, this);
} else if (fHasType)
BMimeType::StartWatching(this);
}
void
IconView::_StopWatching()
{
if (fHasRef)
stop_watching(this);
else if (fHasType)
BMimeType::StopWatching(this);
}
#if __GNUC__ == 2
status_t
IconView::SetTarget(BMessenger target)
{
return BControl::SetTarget(target);
}
status_t
IconView::SetTarget(const BHandler* handler, const BLooper* looper = NULL)
{
return BControl::SetTarget(handler,
looper);
}
#endif
| 19.004231 | 82 | 0.656524 | Kirishikesan |
12bf7201cb974498cd57acd4e1c0b691255d842a | 3,274 | cpp | C++ | Aether Framework/src/Audio/AudioDevice.cpp | WiktorKasjaniuk/Aether-Framework | 75b3e064e6ccee81784636aa7cc45b4cae663d46 | [
"BSD-3-Clause"
] | null | null | null | Aether Framework/src/Audio/AudioDevice.cpp | WiktorKasjaniuk/Aether-Framework | 75b3e064e6ccee81784636aa7cc45b4cae663d46 | [
"BSD-3-Clause"
] | null | null | null | Aether Framework/src/Audio/AudioDevice.cpp | WiktorKasjaniuk/Aether-Framework | 75b3e064e6ccee81784636aa7cc45b4cae663d46 | [
"BSD-3-Clause"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2021, Wiktor Kasjaniuk
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////
#include "Audio/AudioDevice.hpp"
#include "Audio/Listener.hpp"
#include "Audio/Music.hpp"
#include "Core/OpenALCalls.hpp"
#include "Core/Preprocessor.hpp"
#include "System/LogError.hpp"
#include <OpenALSoft/al.h>
#include <OpenALSoft/alc.h>
namespace ae {
namespace internal {
AudioDevice AudioDevice::s_instance;
void AudioDevice::Initialize()
{
// open default device
ALCdevice* device = alcOpenDevice(nullptr);
ALCcontext* context = nullptr;
// the application will be muted if no device are present at this point
// or potentially crash if the default one is turned off after creation
if (!device) {
AE_WARNING("[Aether] Could not open OpenAL Soft device");
}
else {
context = alcCreateContext(device, nullptr);
bool context_current = alcMakeContextCurrent(context);
AE_ASSERT_WARNING(context_current, "[Aether] Could not create and make current OpenAL Soft context");
}
// initialize listener
Listener.Initialize();
// update
s_instance.m_native_device = static_cast<void*>(device);
s_instance.m_native_context = static_cast<void*>(context);
}
void AudioDevice::Terminate() {
s_instance.m_is_running = false;
Music::s_streaming_thread.join();
alcMakeContextCurrent(NULL);
alcDestroyContext(static_cast<ALCcontext*>(s_instance.m_native_context));
alcCloseDevice(static_cast<ALCdevice*>(s_instance.m_native_device));
}
bool AudioDevice::IsRunning() { return s_instance.m_is_running; }
}
} | 38.069767 | 105 | 0.711057 | WiktorKasjaniuk |
12c097c0a363d5ddf94e57a6c758a49a938ee077 | 47 | hpp | C++ | src/boost_date_time_compiler_config.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_date_time_compiler_config.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_date_time_compiler_config.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/date_time/compiler_config.hpp>
| 23.5 | 46 | 0.829787 | miathedev |
12c53ba0bf5726820b495f029a641b18b50d04a5 | 1,638 | cpp | C++ | 12-circle/circle.cpp | skaadin/learning-projects | 977efa1eabab038566d57c455e649da8b440c7e9 | [
"MIT"
] | 143 | 2016-07-28T06:00:43.000Z | 2022-03-30T14:08:50.000Z | 12-circle/circle.cpp | skaadin/learning-projects | 977efa1eabab038566d57c455e649da8b440c7e9 | [
"MIT"
] | 3 | 2017-11-28T10:09:52.000Z | 2021-08-30T09:20:41.000Z | 12-circle/circle.cpp | skaadin/learning-projects | 977efa1eabab038566d57c455e649da8b440c7e9 | [
"MIT"
] | 24 | 2016-10-27T02:02:44.000Z | 2022-02-06T07:37:07.000Z | #include <iostream>
#include <math.h> // M_PI, sqrt
class Circle {
private:
float area;
float radius;
float diameter;
public:
Circle(float area = 0, float radius = 0, float diameter = 0) :
area{area}, radius{radius}, diameter{diameter} {}
static Circle from_radius(float radius) {
return Circle(M_PI * (radius * radius), radius, radius * 2);
}
static Circle from_diameter(float diameter) {
float radius = diameter / 2.0;
return Circle(M_PI * (radius * radius), radius, diameter);
}
static Circle from_area(float area) {
float diameter = sqrt(area / M_PI);
return Circle(area, diameter / 2.0, diameter);
}
void print() {
std::cout << "Circle(area: " << area
<< ", radius: " << radius
<< ", diameter: " << diameter << ")" << std::endl;
}
};
int main() {
std::cout << "Pick an option: " << std::endl;
std::cout << "1. Area" << std::endl;
std::cout << "2. Radius" << std::endl;
std::cout << "3. Diameter" << std::endl;
int choice;
std::cin >> choice;
if(!std::cin) {
std::cout << "Enter a number!" << std::endl;
return 1;
}
std::cout << "Enter size: ";
int size;
std::cin >> size;
if(!std::cin) {
std::cout << "Enter a number!" << std::endl;
return 1;
}
Circle circle;
switch(choice) {
case 1:
circle = Circle::from_area(size);
break;
case 2:
circle = Circle::from_radius(size);
break;
case 3:
circle = Circle::from_diameter(size);
break;
default:
std::cout << "Pick an option from the list!" << std::endl;
return 1;
}
circle.print();
return 0;
} | 20.734177 | 64 | 0.571429 | skaadin |
12c8d739d7b9fd3710b92e087a918918833cba55 | 6,899 | cc | C++ | lullaby/modules/file/asset_loader.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 1,198 | 2017-06-09T08:10:52.000Z | 2022-03-21T13:39:50.000Z | lullaby/modules/file/asset_loader.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 14 | 2017-06-10T00:47:46.000Z | 2020-12-31T05:19:55.000Z | lullaby/modules/file/asset_loader.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 183 | 2017-06-09T22:19:20.000Z | 2022-02-23T03:31:35.000Z | /*
Copyright 2017-2019 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/modules/file/asset_loader.h"
#ifdef __ANDROID__
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <jni.h>
#endif
#include <fstream>
#include <limits>
#ifdef __ANDROID__
#include "lullaby/util/android_context.h"
#endif
#include "lullaby/util/error.h"
#include "lullaby/util/logging.h"
#include "lullaby/util/time.h"
#ifndef LULLABY_ASSET_LOADER_LOG_TIMES
#define LULLABY_ASSET_LOADER_LOG_TIMES 0
#endif
namespace lull {
static bool LoadFileDirect(const std::string& filename, std::string* dest) {
std::ifstream file(filename, std::ios::binary);
if (!file) {
LOG(ERROR) << "Failed to open file " << filename;
return false;
}
file.seekg(0, std::ios::end);
const std::streamoff length = file.tellg();
if (length < 0) {
LOG(ERROR) << "Failed to get file size for " << filename;
return false;
}
dest->resize(static_cast<size_t>(length));
file.seekg(0, std::ios::beg);
file.read(&(*dest)[0], dest->size());
return file.good();
}
#ifdef __ANDROID__
static bool LoadFileUsingAAssetManager(AAssetManager* android_asset_manager,
const std::string& filename,
std::string* dest) {
if (!android_asset_manager) {
LOG(ERROR) << "Missing AAssetManager.";
return false;
}
AAsset* asset = AAssetManager_open(android_asset_manager, filename.c_str(),
AASSET_MODE_STREAMING);
if (!asset) {
LOG(ERROR) << "Failed to open asset " << filename;
return false;
}
const off_t len = AAsset_getLength(asset);
dest->resize(static_cast<size_t>(len));
const int rlen = AAsset_read(asset, &(*dest)[0], len);
AAsset_close(asset);
return len == rlen && len > 0;
}
static bool LoadFileAndroid(Registry* registry, const std::string& filename,
std::string* dest) {
AAssetManager* android_asset_manager = nullptr;
auto* android_context = registry->Get<AndroidContext>();
if (android_context) {
android_asset_manager = android_context->GetAndroidAssetManager();
}
if (android_asset_manager && !filename.empty() && filename[0] != '\\') {
const bool loaded =
LoadFileUsingAAssetManager(android_asset_manager, filename, dest);
if (loaded) {
return loaded;
}
}
return LoadFileDirect(filename, dest);
}
#endif // __ANDROID__
AssetLoader::LoadRequest::LoadRequest(const std::string& filename,
const AssetPtr& asset)
: asset(asset), filename(filename), error(kErrorCode_Ok) {
asset->SetFilename(filename);
}
AssetLoader::AssetLoader(Registry* registry) : registry_(registry) {
SetLoadFunction(nullptr);
}
AssetLoader::AssetLoader(LoadFileFn load_fn) {
SetLoadFunction(std::move(load_fn));
}
void AssetLoader::LoadImpl(const std::string& filename, const AssetPtr& asset,
LoadMode mode) {
switch (mode) {
case kImmediate: {
LoadRequest req(filename, asset);
DoLoad(&req, mode);
DoFinalize(&req, mode);
break;
}
case kAsynchronous: {
LoadRequestPtr req(new LoadRequest(filename, asset));
++pending_requests_;
processor_.Enqueue(
req, [=](LoadRequestPtr* req) { DoLoad(req->get(), mode); });
break;
}
}
}
int AssetLoader::Finalize() {
return Finalize(std::numeric_limits<int>::max());
}
int AssetLoader::Finalize(int max_num_assets_to_finalize) {
while (max_num_assets_to_finalize > 0) {
LoadRequestPtr req = nullptr;
if (!processor_.Dequeue(&req)) {
break;
}
DoFinalize(req.get(), kAsynchronous);
--pending_requests_;
--max_num_assets_to_finalize;
}
return pending_requests_;
}
void AssetLoader::DoLoad(LoadRequest* req, LoadMode mode) const {
#if LULLABY_ASSET_LOADER_LOG_TIMES
Timer load_timer;
#endif
// Actually load the data using the provided load function.
const bool success = load_fn_(req->filename.c_str(), &req->data);
#if LULLABY_ASSET_LOADER_LOG_TIMES
{
const auto dt = MillisecondsFromDuration(load_timer.GetElapsedTime());
LOG(INFO) << "[" << dt << "] " << req->filename << " LoadFn: " << mode;
}
#endif
if (success == false) {
// TODO: Change the LoadFileFn signature to allow for arbitrary
// error codes.
req->error = kErrorCode_NotFound;
return;
}
#if LULLABY_ASSET_LOADER_LOG_TIMES
Timer on_load_timer;
#endif
// Notify the Asset of the loaded data.
req->error = req->asset->OnLoadWithError(req->filename, &req->data);
#if LULLABY_ASSET_LOADER_LOG_TIMES
{
const auto dt = MillisecondsFromDuration(on_load_timer.GetElapsedTime());
LOG(INFO) << "[" << dt << "] " << req->filename << " OnLoad: " << mode;
}
#endif
}
void AssetLoader::DoFinalize(LoadRequest* req, LoadMode mode) const {
#if LULLABY_ASSET_LOADER_LOG_TIMES
Timer timer;
#endif
// Notify the Asset to finalize the data on the finalizer thread.
if (req->error == kErrorCode_Ok) {
req->error = req->asset->OnFinalizeWithError(req->filename, &req->data);
}
#if LULLABY_ASSET_LOADER_LOG_TIMES
const auto dt = MillisecondsFromDuration(timer.GetElapsedTime());
LOG(INFO) << "[" << dt << "] " << req->filename << " OnFinalize: " << mode;
#endif
// Notify the Asset if an error occurred at any point during the load.
if (req->error != kErrorCode_Ok) {
req->asset->OnError(req->filename, req->error);
if (error_fn_) {
error_fn_(req->filename, req->error);
}
}
}
void AssetLoader::SetLoadFunction(LoadFileFn load_fn) {
if (load_fn) {
load_fn_ = std::move(load_fn);
} else {
load_fn_ = GetDefaultLoadFunction();
}
}
AssetLoader::LoadFileFn AssetLoader::GetLoadFunction() const {
return load_fn_;
}
AssetLoader::LoadFileFn AssetLoader::GetDefaultLoadFunction() const {
#ifdef __ANDROID__
Registry* registry = registry_;
if (registry) {
return [registry](const std::string& filename, std::string* dest) {
return LoadFileAndroid(registry, filename, dest);
};
}
#endif
return LoadFileDirect;
}
void AssetLoader::SetOnErrorFunction(OnErrorFn error_fn) {
error_fn_ = std::move(error_fn);
}
void AssetLoader::StartAsyncLoads() { processor_.Start(); }
void AssetLoader::StopAsyncLoads() { processor_.Stop(); }
} // namespace lull
| 28.27459 | 78 | 0.680823 | dherbst |
12cafc788130c4f41d61175a4059fc4d9be2a0d0 | 965 | cpp | C++ | code/leetcode/src/0054.Spiral-Matrix.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | 1 | 2021-09-01T14:39:12.000Z | 2021-09-01T14:39:12.000Z | code/leetcode/src/0054.Spiral-Matrix.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | code/leetcode/src/0054.Spiral-Matrix.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | /**
* @date 2020-08-22 19:55:51
* @authors Lewis Tian (taseikyo@gmail.com)
* @link github.com/taseikyo
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() < 1) {
return {};
} else if (matrix.size() == 1) {
return matrix[0];
}
int m = matrix.size();
int n = matrix[0].size();
vector<int> ans;
help(matrix, ans, 0, 0, m - 1, n - 1);
return ans;
}
void help(vector<vector<int>>& matrix, vector<int> &ans,
int x1, int y1,
int x2, int y2) {
if (x1 > x2 || y1 > y2) {
return;
}
for (int i = y1; i <= y2; ++i) {
ans.push_back(matrix[x1][i]);
}
for (int i = x1 + 1; i <= x2; ++i) {
ans.push_back(matrix[i][y2]);
}
for (int i = y2 - 1; i >= y1 && x2 > x1; --i) {
ans.push_back(matrix[x2][i]);
}
for (int i = x2 - 1; i > x1 && y2 > y1; --i) {
ans.push_back(matrix[i][y1]);
}
help(matrix, ans, x1 + 1, y1 + 1, x2 - 1, y2 - 1);
}
}; | 23.536585 | 57 | 0.516062 | taseikyo |
12cc3c124d3bb2e576a518e9528dac0b58b5be31 | 34,568 | cc | C++ | alljoyn_c/unit_test/AboutObjTest.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 33 | 2018-01-12T00:37:43.000Z | 2022-03-24T02:31:36.000Z | alljoyn_c/unit_test/AboutObjTest.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 1 | 2020-01-05T05:51:27.000Z | 2020-01-05T05:51:27.000Z | alljoyn_c/unit_test/AboutObjTest.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 30 | 2017-12-13T23:24:00.000Z | 2022-01-25T02:11:19.000Z | /******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include <gtest/gtest.h>
#include <alljoyn_c/AboutData.h>
#include <alljoyn_c/AboutListener.h>
#include <alljoyn_c/AboutObj.h>
#include <alljoyn_c/AboutObjectDescription.h>
#include <alljoyn_c/AboutProxy.h>
#include <alljoyn_c/BusAttachment.h>
#include <alljoyn_c/AjAPI.h>
#include <alljoyn/MsgArg.h>
#include "ajTestCommon.h"
#include "alljoyn/DBusStd.h"
#include <qcc/Thread.h>
#include <qcc/GUID.h>
/*
* This test uses the GUID128 in multiple places to generate a random string.
* We are using random strings in many of the interface names to prevent multiple
* tests interfering with one another. Some automated build systems could run this
* same test on multiple platforms at one time. Since the names announced could
* be seen across platforms we want to make the names unique so we know we are
* responding to an advertisement we have made.
*/
/*
* The unit test use many busy wait loops. The busy wait loops were chosen
* over thread sleeps because of the ease of understanding the busy wait loops.
* Also busy wait loops do not require any platform specific threading code.
*/
#define WAIT_TIME 5
using namespace ajn;
static QCC_BOOL AJ_CALL my_sessionportlistener_acceptsessionjoiner(const void* context,
alljoyn_sessionport sessionPort,
const char* joiner,
const alljoyn_sessionopts opts)
{
QCC_UNUSED(context);
QCC_UNUSED(sessionPort);
QCC_UNUSED(joiner);
QCC_UNUSED(opts);
return QCC_TRUE;
}
static void AJ_CALL echo_aboutobject(alljoyn_busobject object,
const alljoyn_interfacedescription_member* member,
alljoyn_message message)
{
QCC_UNUSED(member);
alljoyn_msgarg arg = alljoyn_message_getarg(message, 0);
QStatus status = alljoyn_busobject_methodreply_args(object, message, arg, 1);
EXPECT_EQ(ER_OK, status) << "Echo: Error sending reply, Actual Status: " << QCC_StatusText(status);
}
static alljoyn_busobject create_about_obj_test_bus_object(alljoyn_busattachment bus,
const char* path,
const char* interfaceName)
{
QStatus status = ER_FAIL;
alljoyn_busobject result = NULL;
result = alljoyn_busobject_create(path, QCC_FALSE, NULL, NULL);
alljoyn_interfacedescription iface = alljoyn_busattachment_getinterface(bus, interfaceName);
EXPECT_TRUE(iface != NULL) << "NULL InterfaceDescription* for " << interfaceName;
if (iface == NULL) {
printf("The interfaceDescription pointer for %s was NULL when it should not have been.", interfaceName);
return NULL;
}
alljoyn_busobject_addinterface(result, iface);
alljoyn_busobject_setannounceflag(result, iface, ANNOUNCED);
/* Register the method handlers with the object */
alljoyn_interfacedescription_member echomember;
alljoyn_interfacedescription_getmember(iface, "Echo", &echomember);
const alljoyn_busobject_methodentry methodEntries[] = { { &echomember, echo_aboutobject } };
status = alljoyn_busobject_addmethodhandlers(result, methodEntries, sizeof(methodEntries) / sizeof(methodEntries[0]));
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
return result;
}
static void destroy_about_obj_test_bus_object(alljoyn_busobject obj)
{
if (obj) {
alljoyn_busobject_destroy(obj);
obj = NULL;
}
}
typedef struct about_obj_test_about_listener_2_t {
int announceListenerFlag;
int aboutObjectPartOfAnnouncement;
char* busName;
alljoyn_sessionport port;
alljoyn_aboutlistener listener;
uint16_t version;
}about_obj_test_about_listener_2;
static void AJ_CALL about_obj_test_about_listener_announced_cb(const void* context,
const char* busName,
uint16_t version,
alljoyn_sessionport port,
const alljoyn_msgarg objectDescriptionArg,
const alljoyn_msgarg aboutDataArg)
{
QCC_UNUSED(aboutDataArg);
about_obj_test_about_listener_2* listener = (about_obj_test_about_listener_2*)(context);
EXPECT_FALSE(listener->announceListenerFlag == 1)
<< "We don't expect the flag to already be true when an AnnouceSignal is received.";
size_t busNameLen = strlen(busName);
if (listener->busName) {
free(listener->busName);
listener->busName = NULL;
}
listener->busName = (char*) malloc(sizeof(char) * (busNameLen + 1));
strncpy(listener->busName, busName, busNameLen);
listener->busName[busNameLen] = '\0';
listener->port = port;
listener->version = version;
alljoyn_aboutobjectdescription aod = alljoyn_aboutobjectdescription_create();
QStatus status = alljoyn_aboutobjectdescription_createfrommsgarg(aod, objectDescriptionArg);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
listener->aboutObjectPartOfAnnouncement =
alljoyn_aboutobjectdescription_hasinterface(aod, "org.alljoyn.About");
listener->announceListenerFlag = QCC_TRUE;
alljoyn_aboutobjectdescription_destroy(aod);
}
static about_obj_test_about_listener_2* create_about_obj_test_about_listener_2()
{
about_obj_test_about_listener_2* result =
(about_obj_test_about_listener_2*) malloc(sizeof(about_obj_test_about_listener_2));
alljoyn_aboutlistener_callback callbacks = {
&about_obj_test_about_listener_announced_cb
};
result->listener = alljoyn_aboutlistener_create(&callbacks, result);
result->port = 0;
result->busName = NULL;
result->announceListenerFlag = 0;
result->aboutObjectPartOfAnnouncement = 0;
return result;
}
static void destroy_about_obj_test_about_listener_2(about_obj_test_about_listener_2* listener)
{
if (listener != NULL) {
if (listener->busName) {
free(listener->busName);
listener->busName = NULL;
}
if (listener->listener) {
alljoyn_aboutlistener_destroy(listener->listener);
listener->listener = NULL;
}
free(listener);
}
}
class AboutObjTest : public testing::Test {
public:
AboutObjTest()
{
port = 25;
aboutData = alljoyn_aboutdata_create("en");
serviceBus = NULL;
}
virtual void SetUp()
{
QStatus status = ER_FAIL;
serviceBus = alljoyn_busattachment_create("AboutObjTestServiceBus", QCC_TRUE);
status = alljoyn_busattachment_start(serviceBus);
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_busattachment_connect(serviceBus, NULL);
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* Setup the about data */
qcc::GUID128 appId;
status = alljoyn_aboutdata_setappid(aboutData, appId.GetBytes(), qcc::GUID128::SIZE);
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setdevicename(aboutData, "My Device Name", "en");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
qcc::GUID128 deviceId;
status = alljoyn_aboutdata_setdeviceid(aboutData, deviceId.ToString().c_str());
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setappname(aboutData, "Application", "en");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setmanufacturer(aboutData, "Manufacturer", "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setmodelnumber(aboutData, "123456");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setdescription(aboutData,
"A poetic description of this application",
"en");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setdateofmanufacture(aboutData, "2014-03-24");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setsoftwareversion(aboutData, "0.1.2");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_sethardwareversion(aboutData, "0.0.1");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setsupporturl(aboutData, "http://www.example.com");
ASSERT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_TRUE(alljoyn_aboutdata_isvalid(aboutData, "en"));
alljoyn_sessionportlistener_callbacks callbacks = {
&my_sessionportlistener_acceptsessionjoiner
};
alljoyn_sessionopts opts =
alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, QCC_FALSE,
ALLJOYN_PROXIMITY_ANY,
ALLJOYN_TRANSPORT_ANY);
listener = alljoyn_sessionportlistener_create(&callbacks, NULL);
status = alljoyn_busattachment_bindsessionport(serviceBus, &port, opts, listener);
alljoyn_sessionopts_destroy(opts);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
}
virtual void TearDown()
{
if (serviceBus) {
alljoyn_busattachment_stop(serviceBus);
alljoyn_busattachment_join(serviceBus);
alljoyn_busattachment_destroy(serviceBus);
serviceBus = NULL;
}
if (aboutData) {
alljoyn_aboutdata_destroy(aboutData);
aboutData = NULL;
}
if (listener) {
alljoyn_sessionportlistener_destroy(listener);
listener = NULL;
}
}
alljoyn_sessionportlistener listener;
alljoyn_busattachment serviceBus;
alljoyn_aboutdata aboutData;
alljoyn_sessionport port;
};
TEST_F(AboutObjTest, AnnounceSessionPortNotBound) {
QStatus status = ER_FAIL;
alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(serviceBus, UNANNOUNCED);
/* The SessionPort 5154 is not bound so should return ER_ABOUT_SESSIONPORT_NOT_BOUND error */
status = alljoyn_aboutobj_announce(aboutObj, (alljoyn_sessionport)(5154), aboutData);
EXPECT_EQ(ER_ABOUT_SESSIONPORT_NOT_BOUND, status)
<< " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutobj_destroy(aboutObj);
}
TEST_F(AboutObjTest, AnnounceMissingRequiredField) {
QStatus status = ER_FAIL;
alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(serviceBus, UNANNOUNCED);
alljoyn_aboutdata badAboutData = alljoyn_aboutdata_create("en");
/* DefaultLanguage and other required fields are missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setdefaultlanguage(badAboutData, "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
uint8_t originalAppId[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
status = alljoyn_aboutdata_setappid(badAboutData, originalAppId, 16);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* DeviceId and other required fields are missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setdeviceid(badAboutData, "fakeID");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* AppName and other required fields are missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setappname(badAboutData, "Application", "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* Manufacturer and other required fields are missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setmanufacturer(badAboutData, "Manufacturer", "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* ModelNumber and other required fields are missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setmodelnumber(badAboutData, "123456");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* Description and other required fields are missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setdescription(badAboutData,
"A poetic description of this application",
"en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* SoftwareVersion missing */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_ABOUT_ABOUTDATA_MISSING_REQUIRED_FIELD, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_aboutdata_setsoftwareversion(badAboutData, "0.1.2");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
/* Now all required fields are set for the default language */
status = alljoyn_aboutobj_announce(aboutObj, port, badAboutData);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutdata_destroy(badAboutData);
alljoyn_aboutobj_destroy(aboutObj);
}
TEST_F(AboutObjTest, SetAnnounceFlag) {
QStatus status = ER_FAIL;
char interfaceName[] = "org.alljoyn.About";
alljoyn_interfacedescription iface =
alljoyn_busattachment_getinterface(serviceBus, interfaceName);
EXPECT_TRUE(iface != NULL) << "NULL InterfaceDescription* for " << interfaceName;
alljoyn_busobject busObj = alljoyn_busobject_create("/test/alljoyn/AboutObj",
QCC_FALSE, NULL, NULL);
status = alljoyn_busobject_addinterface_announced(busObj, iface);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_busobject_setannounceflag(busObj, iface, UNANNOUNCED);
size_t numIfaces = alljoyn_busobject_getannouncedinterfacenames(busObj, NULL, 0);
ASSERT_EQ(static_cast<size_t>(0), numIfaces);
status = alljoyn_busobject_setannounceflag(busObj, iface, ANNOUNCED);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
numIfaces = alljoyn_busobject_getannouncedinterfacenames(busObj, NULL, 0);
ASSERT_EQ(static_cast<size_t>(1), numIfaces);
const char* interfaces[1];
numIfaces = alljoyn_busobject_getannouncedinterfacenames(busObj, interfaces, numIfaces);
EXPECT_STREQ("org.alljoyn.About", interfaces[0]);
alljoyn_interfacedescription dbusIface =
alljoyn_busattachment_getinterface(serviceBus,
org::freedesktop::DBus::InterfaceName);
status = alljoyn_busobject_setannounceflag(busObj, dbusIface, ANNOUNCED);
EXPECT_EQ(ER_BUS_OBJECT_NO_SUCH_INTERFACE, status)
<< " Actual Status: " << QCC_StatusText(status);
status = alljoyn_busobject_setannounceflag(busObj, iface, UNANNOUNCED);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
numIfaces = alljoyn_busobject_getannouncedinterfacenames(busObj, NULL, 0);
ASSERT_EQ(static_cast<size_t>(0), numIfaces);
alljoyn_busobject_destroy(busObj);
}
TEST_F(AboutObjTest, CancelAnnouncement) {
QStatus status = ER_FAIL;
alljoyn_busattachment clientBus =
alljoyn_busattachment_create("AboutObjTestClient", QCC_TRUE);
status = alljoyn_busattachment_start(clientBus);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_busattachment_connect(clientBus, NULL);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
about_obj_test_about_listener_2* testAboutListener2 = create_about_obj_test_about_listener_2();
alljoyn_busattachment_registeraboutlistener(clientBus, testAboutListener2->listener);
status = alljoyn_busattachment_whoimplements_interface(clientBus, "org.alljoyn.About");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(serviceBus, ANNOUNCED);
status = alljoyn_aboutobj_announce(aboutObj, port, aboutData);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
for (uint32_t msec = 0; msec < 5000; msec += WAIT_TIME) {
if (testAboutListener2->announceListenerFlag == QCC_TRUE) {
break;
}
qcc::Sleep(WAIT_TIME);
}
EXPECT_TRUE(testAboutListener2->announceListenerFlag)
<< "The announceListenerFlag must be true to continue this test.";
EXPECT_TRUE(testAboutListener2->aboutObjectPartOfAnnouncement)
<< "The org.alljoyn.About interface was not part of the announced object description.";
const char* serviceBusUniqueName = alljoyn_busattachment_getuniquename(serviceBus);
EXPECT_STREQ(serviceBusUniqueName, testAboutListener2->busName);
EXPECT_EQ(port, testAboutListener2->port);
status = alljoyn_aboutobj_unannounce(aboutObj);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_busattachment_stop(clientBus);
alljoyn_busattachment_join(clientBus);
alljoyn_aboutobj_destroy(aboutObj);
alljoyn_busattachment_destroy(clientBus);
destroy_about_obj_test_about_listener_2(testAboutListener2);
}
TEST_F(AboutObjTest, AnnounceTheAboutObj) {
QStatus status = ER_FAIL;
alljoyn_busattachment clientBus =
alljoyn_busattachment_create("AboutObjTestClient", QCC_TRUE);
status = alljoyn_busattachment_start(clientBus);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_busattachment_connect(clientBus, NULL);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
about_obj_test_about_listener_2* testAboutListener2 = create_about_obj_test_about_listener_2();
alljoyn_busattachment_registeraboutlistener(clientBus, testAboutListener2->listener);
status = alljoyn_busattachment_whoimplements_interface(clientBus, "org.alljoyn.About");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(serviceBus, ANNOUNCED);
status = alljoyn_aboutobj_announce(aboutObj, port, aboutData);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
for (uint32_t msec = 0; msec < 5000; msec += WAIT_TIME) {
if (testAboutListener2->announceListenerFlag == QCC_TRUE) {
break;
}
qcc::Sleep(WAIT_TIME);
}
EXPECT_TRUE(testAboutListener2->announceListenerFlag) << "The announceListenerFlag must be true to continue this test.";
EXPECT_TRUE(testAboutListener2->aboutObjectPartOfAnnouncement) << "The org.alljoyn.About interface was not part of the announced object description.";
const char* serviceBusUniqueName = alljoyn_busattachment_getuniquename(serviceBus);
EXPECT_STREQ(serviceBusUniqueName, testAboutListener2->busName);
EXPECT_EQ(port, testAboutListener2->port);
alljoyn_busattachment_stop(clientBus);
alljoyn_busattachment_join(clientBus);
alljoyn_aboutobj_destroy(aboutObj);
alljoyn_busattachment_destroy(clientBus);
destroy_about_obj_test_about_listener_2(testAboutListener2);
}
TEST_F(AboutObjTest, Announce) {
QStatus status = ER_FAIL;
qcc::GUID128 interface_rand_string;
qcc::String ifaceNameQcc = "test.about.a" + interface_rand_string.ToString();
qcc::String interfaceQcc = "<node>"
"<interface name='" + ifaceNameQcc + "'>"
" <method name='Echo'>"
" <arg name='out_arg' type='s' direction='in' />"
" <arg name='return_arg' type='s' direction='out' />"
" </method>"
"</interface>"
"</node>";
const char* ifaceName = ifaceNameQcc.c_str();
const char* interface = interfaceQcc.c_str();
status = alljoyn_busattachment_createinterfacesfromxml(serviceBus, interface);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_busobject busObject =
create_about_obj_test_bus_object(serviceBus, "/test/alljoyn/AboutObj", ifaceName);
status = alljoyn_busattachment_registerbusobject(serviceBus, busObject);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_busattachment clientBus =
alljoyn_busattachment_create("AboutObjTestClient", QCC_TRUE);
status = alljoyn_busattachment_start(clientBus);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_busattachment_connect(clientBus, NULL);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
about_obj_test_about_listener_2* aboutListener = create_about_obj_test_about_listener_2();
alljoyn_busattachment_registeraboutlistener(clientBus, aboutListener->listener);
status = alljoyn_busattachment_whoimplements_interface(clientBus, ifaceName);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(serviceBus, UNANNOUNCED);
status = alljoyn_aboutobj_announce(aboutObj, port, aboutData);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
for (uint32_t msec = 0; msec < 5000; msec += WAIT_TIME) {
if (aboutListener->announceListenerFlag == QCC_TRUE) {
break;
}
qcc::Sleep(WAIT_TIME);
}
ASSERT_TRUE(aboutListener->announceListenerFlag)
<< "The announceListenerFlag must be true to continue this test.";
EXPECT_STREQ(alljoyn_busattachment_getuniquename(serviceBus), aboutListener->busName);
EXPECT_EQ(port, aboutListener->port);
alljoyn_sessionid sessionId;
alljoyn_sessionopts sessionOpts =
alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, QCC_FALSE,
ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY);
status = alljoyn_busattachment_joinsession(clientBus, aboutListener->busName,
aboutListener->port, NULL,
&sessionId, sessionOpts);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_proxybusobject proxy =
alljoyn_proxybusobject_create(clientBus, aboutListener->busName,
"/test/alljoyn/AboutObj", sessionId);
status = alljoyn_proxybusobject_parsexml(proxy, interface, NULL);
EXPECT_EQ(ER_OK, status) << " Actual Status: "
<< QCC_StatusText(status) << "\n" << interface;
QCC_BOOL isImplementsIface =
alljoyn_proxybusobject_implementsinterface(proxy, ifaceName);
EXPECT_TRUE(isImplementsIface) << interface << "\n" << ifaceName;
alljoyn_msgarg arg =
alljoyn_msgarg_create_and_set("s", "String that should be Echoed back.");
alljoyn_message replyMsg = alljoyn_message_create(clientBus);
status = alljoyn_proxybusobject_methodcall(proxy, ifaceName, "Echo", arg,
1, replyMsg, 25000, 0);
EXPECT_EQ(ER_OK, status) << " Actual Status: "
<< QCC_StatusText(status) << " " << "Invalid arg";
char* echoReply;
alljoyn_msgarg arg0 = alljoyn_message_getarg(replyMsg, 0);
status = alljoyn_msgarg_get(arg0, "s", &echoReply);
EXPECT_STREQ("String that should be Echoed back.", echoReply);
alljoyn_busattachment_stop(clientBus);
alljoyn_busattachment_join(clientBus);
destroy_about_obj_test_about_listener_2(aboutListener);
destroy_about_obj_test_bus_object(busObject);
alljoyn_proxybusobject_destroy(proxy);
alljoyn_sessionopts_destroy(sessionOpts);
alljoyn_msgarg_destroy(arg);
alljoyn_message_destroy(replyMsg);
alljoyn_aboutobj_destroy(aboutObj);
alljoyn_busattachment_destroy(clientBus);
}
TEST_F(AboutObjTest, ProxyAccessToAboutObj) {
QStatus status = ER_FAIL;
qcc::GUID128 interface_rand_string;
qcc::String ifaceNameQcc = "test.about.a" + interface_rand_string.ToString();
qcc::String interfaceQcc = "<node>"
"<interface name='" + ifaceNameQcc + "'>"
" <method name='Echo'>"
" <arg name='out_arg' type='s' direction='in' />"
" <arg name='return_arg' type='s' direction='out' />"
" </method>"
"</interface>"
"</node>";
const char* ifaceName = ifaceNameQcc.c_str();
const char* interface = interfaceQcc.c_str();
status = alljoyn_busattachment_createinterfacesfromxml(serviceBus, interface);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_busobject busObject =
create_about_obj_test_bus_object(serviceBus, "/test/alljoyn/AboutObj", ifaceName);
status = alljoyn_busattachment_registerbusobject(serviceBus, busObject);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_busattachment clientBus =
alljoyn_busattachment_create("AboutObjTestClient", QCC_TRUE);
status = alljoyn_busattachment_start(clientBus);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
status = alljoyn_busattachment_connect(clientBus, NULL);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
about_obj_test_about_listener_2* aboutListener = create_about_obj_test_about_listener_2();
alljoyn_busattachment_registeraboutlistener(clientBus, aboutListener->listener);
status = alljoyn_busattachment_whoimplements_interface(clientBus, ifaceName);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutobj aboutObj = alljoyn_aboutobj_create(serviceBus, UNANNOUNCED);
status = alljoyn_aboutobj_announce(aboutObj, port, aboutData);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
for (uint32_t msec = 0; msec < 5000; msec += WAIT_TIME) {
if (aboutListener->announceListenerFlag == QCC_TRUE) {
break;
}
qcc::Sleep(WAIT_TIME);
}
ASSERT_TRUE(aboutListener->announceListenerFlag)
<< "The announceListenerFlag must be true to continue this test.";
EXPECT_STREQ(alljoyn_busattachment_getuniquename(serviceBus), aboutListener->busName);
EXPECT_EQ(port, aboutListener->port);
alljoyn_sessionid sessionId;
alljoyn_sessionopts sessionOpts =
alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, QCC_FALSE,
ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY);
alljoyn_busattachment_enableconcurrentcallbacks(clientBus);
status = alljoyn_busattachment_joinsession(clientBus, aboutListener->busName,
aboutListener->port, NULL,
&sessionId, sessionOpts);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutproxy aProxy = alljoyn_aboutproxy_create(clientBus, aboutListener->busName, sessionId);
/*
* Call each of the proxy methods
* GetObjDescription
* GetAboutData
* GetVersion
*/
uint16_t ver;
status = alljoyn_aboutproxy_getversion(aProxy, &ver);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_EQ(aboutListener->version, ver);
alljoyn_msgarg aboutArg = alljoyn_msgarg_create();
status = alljoyn_aboutproxy_getaboutdata(aProxy, "en", aboutArg);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutdata testAboutData = alljoyn_aboutdata_create_full(aboutArg, "en");
char* appName;
status = alljoyn_aboutdata_getappname(testAboutData, &appName, "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("Application", appName);
char* manufacturer;
status = alljoyn_aboutdata_getmanufacturer(testAboutData, &manufacturer, "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("Manufacturer", manufacturer);
char* modelNum;
status = alljoyn_aboutdata_getmodelnumber(testAboutData, &modelNum);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("123456", modelNum);
char* desc;
status = alljoyn_aboutdata_getdescription(testAboutData, &desc, "en");
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("A poetic description of this application", desc);
char* dom;
status = alljoyn_aboutdata_getdateofmanufacture(testAboutData, &dom);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("2014-03-24", dom);
char* softVer;
status = alljoyn_aboutdata_getsoftwareversion(testAboutData, &softVer);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("0.1.2", softVer);
char* hwVer;
status = alljoyn_aboutdata_gethardwareversion(testAboutData, &hwVer);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("0.0.1", hwVer);
char* support;
status = alljoyn_aboutdata_getsupporturl(testAboutData, &support);
EXPECT_EQ(ER_OK, status) << " Actual Status: " << QCC_StatusText(status);
EXPECT_STREQ("http://www.example.com", support);
/*
* French is specified language. Expect success as the default
* language will be used instead. See RFC 4647 for more discussion.
*/
alljoyn_msgarg aboutArg_fr = alljoyn_msgarg_create();
status = alljoyn_aboutproxy_getaboutdata(aProxy, "fr", aboutArg_fr);
EXPECT_EQ(ER_OK, status)
<< " Actual Status: " << QCC_StatusText(status);
alljoyn_msgarg objDesc = alljoyn_msgarg_create();
alljoyn_aboutproxy_getobjectdescription(aProxy, objDesc);
EXPECT_EQ(ER_OK, status)
<< " Actual Status: " << QCC_StatusText(status);
alljoyn_aboutobjectdescription aObjDesc =
alljoyn_aboutobjectdescription_create_full(objDesc);
EXPECT_TRUE(alljoyn_aboutobjectdescription_haspath(aObjDesc, "/test/alljoyn/AboutObj"));
EXPECT_TRUE(alljoyn_aboutobjectdescription_hasinterface(aObjDesc, ifaceName));
alljoyn_busattachment_stop(clientBus);
alljoyn_busattachment_join(clientBus);
alljoyn_aboutobjectdescription_destroy(aObjDesc);
alljoyn_msgarg_destroy(objDesc);
alljoyn_msgarg_destroy(aboutArg);
alljoyn_msgarg_destroy(aboutArg_fr);
alljoyn_aboutdata_destroy(testAboutData);
destroy_about_obj_test_about_listener_2(aboutListener);
destroy_about_obj_test_bus_object(busObject);
alljoyn_aboutproxy_destroy(aProxy);
alljoyn_sessionopts_destroy(sessionOpts);
alljoyn_aboutobj_destroy(aboutObj);
alljoyn_busattachment_destroy(clientBus);
}
| 46.587601 | 154 | 0.686357 | liuxiang88 |
12ce3badabe97ef44dd3b4a4dc5cd51317f71e35 | 15,249 | tcc | C++ | libraries/predictors/tcc/ForestPredictor.tcc | Dream-maerD/ELL-master | 9554afa876cc9e8e87529df3f3d99220abc711d6 | [
"MIT"
] | 1 | 2018-11-08T06:19:31.000Z | 2018-11-08T06:19:31.000Z | libraries/predictors/tcc/ForestPredictor.tcc | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | null | null | null | libraries/predictors/tcc/ForestPredictor.tcc | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2020-12-10T17:49:07.000Z | 2020-12-10T17:49:07.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: ForestPredictor.tcc (predictors)
// Authors: Ofer Dekel
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "ForestPredictor.h"
// utilities
#include "Exception.h"
namespace ell
{
namespace predictors
{
template <typename SplitRuleType, typename EdgePredictorType>
ForestPredictor<SplitRuleType, EdgePredictorType>::SplittableNodeId::SplittableNodeId(size_t parentNodeIndex, size_t childPosition)
: _isRoot(false), _parentNodeIndex(parentNodeIndex), _childPosition(childPosition)
{
}
template <typename SplitRuleType, typename EdgePredictorType>
ForestPredictor<SplitRuleType, EdgePredictorType>::SplitAction::SplitAction(SplittableNodeId nodeId, SplitRuleType _splitRule, std::vector<EdgePredictorType> edgePredictors)
: _nodeId(std::move(nodeId)), _splitRule(std::move(_splitRule)), _edgePredictors(std::move(edgePredictors))
{
}
template <typename SplitRuleType, typename EdgePredictorType>
ForestPredictor<SplitRuleType, EdgePredictorType>::Edge::Edge(const EdgePredictorType& predictor)
: _predictor(predictor), _targetNodeIndex(0)
{
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::Edge::SetTargetNodeIndex(size_t targetNodeIndex)
{
_targetNodeIndex = targetNodeIndex;
}
template <typename SplitRuleType, typename EdgePredictorType>
bool ForestPredictor<SplitRuleType, EdgePredictorType>::IsTrivial() const
{
if (_rootIndices.size() == 0 && _bias == 0.0)
{
return true;
}
else
{
return false;
}
}
template <typename SplitRuleType, typename EdgePredictorType>
size_t ForestPredictor<SplitRuleType, EdgePredictorType>::NumInteriorNodes(size_t interiorNodeIndex) const
{
if (interiorNodeIndex >= _interiorNodes.size())
{
return 0;
}
auto const& interiorNode = _interiorNodes[interiorNodeIndex];
size_t numInteriorNodes = 1;
for (const auto& edge : interiorNode._outgoingEdges)
{
if (edge.IsTargetInterior())
{
numInteriorNodes += NumInteriorNodes(edge.GetTargetNodeIndex());
}
}
return numInteriorNodes;
}
template <typename SplitRuleType, typename EdgePredictorType>
size_t ForestPredictor<SplitRuleType, EdgePredictorType>::NumEdges(size_t interiorNodeIndex) const
{
if (interiorNodeIndex >= _interiorNodes.size())
{
return 0;
}
auto const& interiorNode = _interiorNodes[interiorNodeIndex];
size_t numEdges = interiorNode._outgoingEdges.size();
for (const auto& edge : interiorNode._outgoingEdges)
{
if (edge.IsTargetInterior())
{
numEdges += NumEdges(edge.GetTargetNodeIndex());
}
}
return numEdges;
}
template <typename SplitRuleType, typename EdgePredictorType>
double ForestPredictor<SplitRuleType, EdgePredictorType>::Predict(const DataVectorType& input) const
{
double output = _bias;
for (auto treeRootIndex : _rootIndices)
{
output += Predict(input, treeRootIndex);
}
return output;
}
template <typename SplitRuleType, typename EdgePredictorType>
double ForestPredictor<SplitRuleType, EdgePredictorType>::Predict(const DataVectorType& input, size_t interiorNodeIndex) const
{
if (interiorNodeIndex >= _interiorNodes.size())
{
return 0.0;
}
double output = 0.0;
VisitEdgePathToLeaf(input, interiorNodeIndex, [&](const InteriorNode& interiorNode, size_t edgePosition) { output += interiorNode._outgoingEdges[edgePosition]._predictor.Predict(input); });
return output;
}
template <typename SplitRuleType, typename EdgePredictorType>
std::vector<bool> ForestPredictor<SplitRuleType, EdgePredictorType>::GetEdgeIndicatorVector(const DataVectorType& input) const
{
std::vector<bool> edgeIndicator(_numEdges);
for (auto treeRootIndex : _rootIndices)
{
SetEdgeIndicatorVector(input, edgeIndicator, treeRootIndex);
}
return edgeIndicator;
}
template <typename SplitRuleType, typename EdgePredictorType>
std::vector<bool> ForestPredictor<SplitRuleType, EdgePredictorType>::GetEdgeIndicatorVector(const DataVectorType& input, size_t interiorNodeIndex) const
{
std::vector<bool> edgeIndicator(_numEdges);
SetEdgeIndicatorVector(input, edgeIndicator, interiorNodeIndex);
return edgeIndicator;
}
template <typename SplitRuleType, typename EdgePredictorType>
size_t ForestPredictor<SplitRuleType, EdgePredictorType>::NumChildren(size_t interiorNodeIndex) const
{
if (interiorNodeIndex >= _interiorNodes.size())
{
return 0;
}
return _interiorNodes[interiorNodeIndex]._outgoingEdges.size();
}
template <typename SplitRuleType, typename EdgePredictorType>
typename ForestPredictor<SplitRuleType, EdgePredictorType>::SplittableNodeId ForestPredictor<SplitRuleType, EdgePredictorType>::GetChildId(size_t parentNodeIndex, size_t childPosition) const
{
// check that the parent exists
if (parentNodeIndex >= _interiorNodes.size())
{
throw utilities::LogicException(utilities::LogicExceptionErrors::illegalState, "invalid identifier requested - parent does not exist");
}
// check that the splittable node exists
if (childPosition >= _interiorNodes[parentNodeIndex]._outgoingEdges.size())
{
throw utilities::LogicException(utilities::LogicExceptionErrors::illegalState, "invalid identifier requested - child does not exist");
}
return SplittableNodeId(parentNodeIndex, childPosition);
}
template <typename SplitRuleType, typename EdgePredictorType>
size_t ForestPredictor<SplitRuleType, EdgePredictorType>::Split(const SplitAction& splitAction)
{
if (splitAction._nodeId._isRoot)
{
// add interior Node
size_t interiorNodeIndex = AddInteriorNode(splitAction);
// add new tree
_rootIndices.push_back(interiorNodeIndex);
// return ID of new root
return interiorNodeIndex;
}
else
{
// check that this node wasn't previously split
auto& incomingEdge = _interiorNodes[splitAction._nodeId._parentNodeIndex]._outgoingEdges[splitAction._nodeId._childPosition];
if (incomingEdge.IsTargetInterior())
{
throw utilities::LogicException(utilities::LogicExceptionErrors::illegalState, "invalid split in decision tree - node previously split");
}
// add interior Node
size_t interiorNodeIndex = AddInteriorNode(splitAction);
// update the parent about the new interior node
incomingEdge.SetTargetNodeIndex(interiorNodeIndex);
// return ID of new interior node
return interiorNodeIndex;
}
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::AddToBias(double value)
{
_bias += value;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::WriteToArchive(utilities::Archiver& archiver) const
{
archiver["interiorNodes"] << _interiorNodes;
archiver["rootIndices"] << _rootIndices;
archiver["bias"] << _bias;
archiver["numEdges"] << _numEdges;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::ReadFromArchive(utilities::Unarchiver& archiver)
{
archiver["interiorNodes"] >> _interiorNodes;
archiver["rootIndices"] >> _rootIndices;
archiver["bias"] >> _bias;
archiver["numEdges"] >> _numEdges;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::SetEdgeIndicatorVector(const DataVectorType& input, std::vector<bool>& output, size_t interiorNodeIndex) const
{
if (interiorNodeIndex >= _interiorNodes.size())
{
return;
}
VisitEdgePathToLeaf(input, interiorNodeIndex, [&output](const InteriorNode& interiorNode, size_t edgePosition) { output[interiorNode._firstEdgeIndex + edgePosition] = true; });
}
template <typename SplitRuleType, typename EdgePredictorType>
size_t ForestPredictor<SplitRuleType, EdgePredictorType>::AddInteriorNode(const SplitAction& splitAction)
{
size_t numEdges = splitAction._edgePredictors.size();
// check correctness of splitAction
if (numEdges != splitAction._splitRule.NumOutputs())
{
throw utilities::LogicException(utilities::LogicExceptionErrors::illegalState, "invalid split in decision tree - number of split rule outputs doesn't match fan-out");
}
// get indices
size_t interiorNodeIndex = _interiorNodes.size();
// create the new interior node
InteriorNode interiorNode(splitAction, _numEdges);
_interiorNodes.push_back(std::move(interiorNode));
// increment global edge count
_numEdges += numEdges;
return interiorNodeIndex;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::VisitEdgePathToLeaf(const DataVectorType& input, size_t interiorNodeIndex, std::function<void(const InteriorNode&, size_t edgePosition)> operation) const
{
size_t nodeIndex = interiorNodeIndex;
do
{
const auto& interiorNode = _interiorNodes[nodeIndex];
// which way do we go?
int edgePosition = static_cast<int>(interiorNode._splitRule.Predict(input));
// check for early eject
if (edgePosition < 0)
{
break;
}
// apply the operation
operation(interiorNode, edgePosition);
//follow the edge to the next node
const auto& edge = interiorNode._outgoingEdges[edgePosition];
nodeIndex = edge.GetTargetNodeIndex();
} while (nodeIndex != 0);
}
//
// InteriorNode
//
template <typename SplitRuleType, typename EdgePredictorType>
ForestPredictor<SplitRuleType, EdgePredictorType>::InteriorNode::InteriorNode(const SplitAction& splitAction, size_t _firstEdgeIndex)
: _splitRule(splitAction._splitRule), _firstEdgeIndex(_firstEdgeIndex)
{
std::copy(splitAction._edgePredictors.begin(), splitAction._edgePredictors.end(), std::back_inserter(_outgoingEdges));
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::InteriorNode::WriteToArchive(utilities::Archiver& archiver) const
{
archiver["splitRule"] << _splitRule;
archiver["outgoingEdges"] << _outgoingEdges;
archiver["firstEdgeIndex"] << _firstEdgeIndex;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::InteriorNode::ReadFromArchive(utilities::Unarchiver& archiver)
{
archiver["splitRule"] >> _splitRule;
archiver["outgoingEdges"] >> _outgoingEdges;
archiver["firstEdgeIndex"] >> _firstEdgeIndex;
}
//
// debugging code
//
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::SplittableNodeId::Print(std::ostream& os) const
{
if (_isRoot)
{
os << "root";
}
else
{
os << "child " << _childPosition << " of node " << _parentNodeIndex;
}
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::SplitAction::PrintLine(std::ostream& os, size_t tabs) const
{
os << std::string(tabs * 4, ' ') << "action = split ";
_nodeId.Print(os);
os << "\n";
os << std::string(tabs * 4, ' ') << "rule:\n";
_splitRule.PrintLine(os, tabs + 1);
os << std::string(tabs * 4, ' ') << "edge predictors:\n";
for (const auto& predictor : _edgePredictors)
{
predictor.PrintLine(os, tabs + 1);
}
}
//
// debugging members
//
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::PrintLine(std::ostream& os, size_t tabs) const
{
os << std::string(tabs * 4, ' ') << "Forest Predictor: bias = " << _bias << "\n";
for (const auto& interiorNode : _interiorNodes)
{
interiorNode.PrintLine(os, tabs + 1);
}
for (auto treeRootIndex : _rootIndices)
{
os << std::string(tabs * 4, ' ') << "Tree: root index = " << treeRootIndex << "\n";
}
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::InteriorNode::PrintLine(std::ostream& os, size_t tabs) const
{
os << std::string(tabs * 4, ' ') << "InteriorNode:\n";
_splitRule.PrintLine(os, tabs + 1);
for (const auto& edge : _outgoingEdges)
{
edge.PrintLine(os, tabs + 1);
}
}
//
// Edge
//
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::Edge::PrintLine(std::ostream& os, size_t tabs) const
{
os << std::string(tabs * 4, ' ') << "Edge:\n";
_predictor.PrintLine(os, tabs + 1);
os << std::string(tabs * 4, ' ') << "Target node index = " << _targetNodeIndex << "\n";
}
template <typename SplitRuleType, typename EdgePredictorType>
bool ForestPredictor<SplitRuleType, EdgePredictorType>::Edge::IsTargetInterior() const
{
return _targetNodeIndex == 0 ? false : true;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::Edge::WriteToArchive(utilities::Archiver& archiver) const
{
archiver["predictor"] << _predictor;
archiver["targetNodeIndex"] << _targetNodeIndex;
}
template <typename SplitRuleType, typename EdgePredictorType>
void ForestPredictor<SplitRuleType, EdgePredictorType>::Edge::ReadFromArchive(utilities::Unarchiver& archiver)
{
archiver["predictor"] >> _predictor;
archiver["targetNodeIndex"] >> _targetNodeIndex;
}
}
}
| 37.10219 | 213 | 0.656633 | Dream-maerD |
12d2e88f92eace73422104e3e939ac717e36ad95 | 13,726 | cpp | C++ | TerrainSDK/vtlib/core/PagedLodGrid.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | 4 | 2019-02-08T13:51:26.000Z | 2021-12-07T13:11:06.000Z | TerrainSDK/vtlib/core/PagedLodGrid.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | null | null | null | TerrainSDK/vtlib/core/PagedLodGrid.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | 7 | 2017-12-03T10:13:17.000Z | 2022-03-29T09:51:18.000Z | //
// PagedLodGrid.cpp
//
// Copyright (c) 2007-2011 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "Structure3d.h"
#include "vtdata/LocalCS.h"
#include "vtdata/HeightField.h"
#include "vtdata/vtLog.h"
#include "PagedLodGrid.h"
#include <algorithm> // for sort
vtPagedStructureLOD::vtPagedStructureLOD() : vtLOD()
{
m_iNumConstructed = 0;
m_bAddedToQueue = false;
SetCenter(FPoint3(0, 0, 0));
SetOsgNode(this);
}
void vtPagedStructureLOD::SetRange(float range)
{
m_fRange = range;
}
/**
* \param fDistance The distance in meters to check against.
* \param bLoad If true, and this cell is within the distance, and it isn't
* loaded, then load it.
*/
bool vtPagedStructureLOD::TestVisible(float fDistance, bool bLoad)
{
if (fDistance < m_fRange)
{
// Check if this group has any unbuilt structures
if (bLoad && !m_bAddedToQueue &&
m_iNumConstructed != m_StructureRefs.size() &&
m_pGrid->m_LoadingEnabled)
{
AppendToQueue();
m_bAddedToQueue = true;
}
return true;
}
return false;
}
void vtPagedStructureLOD::AppendToQueue()
{
int count = 0;
for (uint i = 0; i < m_StructureRefs.size(); i++)
{
StructureRef &ref = m_StructureRefs[i];
// Don't queue structures from layers that aren't visible
if (ref.pArray->GetEnabled() == false)
continue;
if (m_pGrid->AddToQueue(this, ref.pArray, ref.iIndex))
count++;
}
if (count > 0)
VTLOG("Added %d buildings to queue.\n", count);
// We have just added a lump of structures, sort them by distance
m_pGrid->SortQueue();
}
void vtPagedStructureLOD::Add(vtStructureArray3d *pArray, int iIndex)
{
StructureRef ref;
ref.pArray = pArray;
ref.iIndex = iIndex;
m_StructureRefs.push_back(ref);
}
void vtPagedStructureLOD::Remove(vtStructureArray3d *pArray, int iIndex)
{
StructureRefVector::iterator it = m_StructureRefs.begin();
while (it != m_StructureRefs.end())
{
if (it->pArray == pArray && it->iIndex == iIndex)
{
vtStructure3d *s3d = it->pArray->GetStructure3d(it->iIndex);
if (s3d->IsCreated())
m_iNumConstructed--;
it = m_StructureRefs.erase(it);
}
else
it++;
}
}
///////////////////////////////////////////////////////////////////////
// vtPagedStructureLodGrid
#define CellIndex(a,b) ((a*m_dim)+b)
vtPagedStructureLodGrid::vtPagedStructureLodGrid()
{
m_pCells = NULL;
m_LoadingEnabled = true;
m_iLoadCount = 0;
}
void vtPagedStructureLodGrid::Setup(const FPoint3 &origin, const FPoint3 &size,
int iDimension, float fLODDistance, vtHeightField3d *pHF)
{
m_origin = origin;
m_size = size;
m_dim = iDimension;
m_fLODDistance = fLODDistance;
m_step = m_size / (float)m_dim;
// wrap with an array of simple LOD nodes
m_pCells = (vtPagedStructureLOD **)malloc(m_dim * m_dim * sizeof(vtPagedStructureLOD *));
int a, b;
for (a = 0; a < m_dim; a++)
{
for (b = 0; b < m_dim; b++)
{
m_pCells[CellIndex(a,b)] = NULL;
}
}
m_pHeightField = pHF;
}
void vtPagedStructureLodGrid::Cleanup()
{
// get rid of children first
removeChildren(0, getNumChildren());
// free all our pointers to them
free(m_pCells);
m_pCells = NULL;
}
void vtPagedStructureLodGrid::AllocateCell(int a, int b)
{
int i = CellIndex(a,b);
m_pCells[i] = new vtPagedStructureLOD;
vtString name;
name.Format("LOD cell %d %d", a, b);
m_pCells[i]->setName(name);
m_pCells[i]->SetRange(m_fLODDistance);
// determine LOD center
FPoint3 lod_center;
lod_center.x = m_origin.x + ((m_size.x / m_dim) * (a + 0.5f));
lod_center.y = m_origin.y + (m_size.y / 2.0f);
lod_center.z = m_origin.z + ((m_size.z / m_dim) * (b + 0.5f));
if (m_pHeightField)
m_pHeightField->FindAltitudeAtPoint(lod_center, lod_center.y);
m_pCells[i]->SetCenter(lod_center);
// and a radius to give the LOD a bounding sphere, for efficient culling
FPoint2 diag(m_size.x / m_dim, m_size.z / m_dim);
float diagonal = diag.Length();
float radius = diagonal/2;
// Increase it a little, because some structures might visually extend outside
// the minimal bounding sphere
radius *= 1.6f;
m_pCells[i]->setRadius(radius);
m_pCells[i]->SetGrid(this);
addChild(m_pCells[i]);
}
osg::Group *vtPagedStructureLodGrid::GetCell(int a, int b)
{
int i = CellIndex(a, b);
return m_pCells[i];
}
vtPagedStructureLOD *vtPagedStructureLodGrid::FindPagedCellParent(const FPoint3 &point)
{
int a, b;
DetermineCell(point, a, b);
if (a < 0 || a >= m_dim || b < 0 || b >= m_dim)
return NULL;
const int i = CellIndex(a, b);
if (!m_pCells[i])
AllocateCell(a, b);
return m_pCells[i];
}
osg::Group *vtPagedStructureLodGrid::FindCellParent(const FPoint3 &point)
{
return FindPagedCellParent(point);
}
void vtPagedStructureLodGrid::SetDistance(float fLODDistance)
{
m_fLODDistance = fLODDistance;
for (int a = 0; a < m_dim; a++)
{
for (int b = 0; b < m_dim; b++)
{
vtPagedStructureLOD *lod = m_pCells[CellIndex(a,b)];
if (lod)
lod->SetRange(m_fLODDistance);
}
}
}
/**
* For a given vtStructure, find the lod group parent for it, using the
* structure's earth extents.
*/
vtPagedStructureLOD *vtPagedStructureLodGrid::FindGroup(vtStructure *str)
{
DRECT rect;
if (str->GetExtents(rect))
{
float xmin, xmax, zmin, zmax;
m_pHeightField->m_LocalCS.EarthToLocal(rect.left, rect.bottom, xmin, zmin);
m_pHeightField->m_LocalCS.EarthToLocal(rect.right, rect.top, xmax, zmax);
const FPoint3 mid((xmin+xmax) / 2, 0.0f, (zmin+zmax)/2);
return FindPagedCellParent(mid);
}
return NULL;
}
bool vtPagedStructureLodGrid::AppendToGrid(vtStructureArray3d *pArray, int iIndex)
{
// Get 2D extents from the unbuild structure
vtStructure *str = pArray->at(iIndex);
vtPagedStructureLOD *pGroup = FindGroup(str);
if (pGroup)
{
pGroup->Add(pArray, iIndex);
return true;
}
return false;
}
void vtPagedStructureLodGrid::RemoveFromGrid(vtStructureArray3d *pArray, int iIndex)
{
// Get 2D extents from the unbuild structure
vtStructure *str = pArray->at(iIndex);
vtPagedStructureLOD *pGroup = FindGroup(str);
if (pGroup)
pGroup->Remove(pArray, iIndex);
}
vtPagedStructureLOD *vtPagedStructureLodGrid::GetPagedCell(int a, int b)
{
return m_pCells[CellIndex(a,b)];
}
void vtPagedStructureLodGrid::DeconstructCell(vtPagedStructureLOD *pLOD)
{
int count = 0;
StructureRefVector &refs = pLOD->m_StructureRefs;
//VTLOG("Deconstruction check on %d structures: ", indices.GetSize());
for (uint i = 0; i < refs.size(); i++)
{
StructureRef &ref = refs[i];
vtStructure3d *str3d = ref.pArray->GetStructure3d(ref.iIndex);
osg::Node *node = str3d->GetContainer();
if (!node)
node = str3d->GetGeom();
if (!node)
continue;
pLOD->removeChild(node);
str3d->DeleteNode();
count++;
}
//VTLOG("%d decon.\n", count);
pLOD->m_iNumConstructed = 0;
pLOD->m_bAddedToQueue = false;
}
void vtPagedStructureLodGrid::RemoveCellFromQueue(vtPagedStructureLOD *pLOD)
{
if (!pLOD->m_bAddedToQueue)
return;
if (pLOD->m_iNumConstructed == pLOD->m_StructureRefs.size())
return;
const StructureRefVector &refs = pLOD->m_StructureRefs;
int count = 0;
for (uint i = 0; i < refs.size(); i++)
{
if (RemoveFromQueue(refs[i].pArray, refs[i].iIndex))
count++;
}
if (count != 0)
VTLOG("Dequeued %d of %d.\n", count, refs.size());
pLOD->m_bAddedToQueue = false;
}
void vtPagedStructureLodGrid::CullFarawayStructures(const FPoint3 &CamPos,
int iMaxStructures,
float fDistance)
{
m_iTotalConstructed = 0;
for (int a = 0; a < m_dim; a++)
{
for (int b = 0; b < m_dim; b++)
{
vtPagedStructureLOD *lod = m_pCells[CellIndex(a,b)];
if (lod) m_iTotalConstructed += lod->getNumChildren();
}
}
// If we have too many or have items in the queue
if (m_iTotalConstructed > iMaxStructures || m_Queue.size() > 0)
{
//VTLOG("CullFarawayStructures: %d in Queue, ", m_Queue.size());
int total = 0, removed = 0;
// Delete/dequeue the ones that are very far
FPoint3 center;
for (int a = 0; a < m_dim; a++)
{
for (int b = 0; b < m_dim; b++)
{
vtPagedStructureLOD *lod = m_pCells[CellIndex(a,b)];
if (!lod)
continue;
total++;
lod->GetCenter(center);
float dist = (center - CamPos).Length();
// If very far, delete the structures entirely
if (lod->m_iNumConstructed != 0 &&
m_iTotalConstructed > iMaxStructures &&
dist > fDistance)
DeconstructCell(lod);
// If it has fallen out of the frustum, remove them
// from the queue
if (dist > m_fLODDistance)
{
RemoveCellFromQueue(lod);
removed++;
}
}
}
//VTLOG(" %d cells, %d cell removed\n", total, removed);
}
}
bool operator<(const QueueEntry& a, const QueueEntry& b)
{
// Reverse-sort, to put smallest values (closest points) at the end
// of the list so they can be efficiently removed
return a.fDistance > b.fDistance;
}
void vtPagedStructureLodGrid::SortQueue()
{
vtCamera *cam = vtGetScene()->GetCamera();
FPoint3 CamPos = cam->GetTrans();
FPoint3 CamDir = cam->GetDirection();
// Prioritization is by distance.
// We can measure horizontal distance, which is faster.
DPoint3 cam_epos, cam_epos2;
m_pHeightField->m_LocalCS.LocalToEarth(CamPos, cam_epos);
m_pHeightField->m_LocalCS.LocalToEarth(CamPos+CamDir, cam_epos2);
DPoint2 cam_pos(cam_epos.x, cam_epos.y);
DPoint2 cam_dir(cam_epos2.x - cam_epos.x, cam_epos2.y - cam_epos.y);
cam_dir.Normalize();
DPoint2 p;
for (uint i = 0; i < m_Queue.size(); i++)
{
QueueEntry &e = m_Queue[i];
vtStructure *st = e.pStructureArray->at(e.iStructIndex);
vtBuilding *bld = st->GetBuilding();
vtStructInstance *inst = st->GetInstance();
if (bld)
p = bld->GetOuterFootprint(0).Centroid();
else if (inst)
p = inst->GetPoint();
else
continue;
// Calculate distance
DPoint2 diff = p-cam_pos;
e.fDistance = (float) diff.Length();
// Is point behind the camera? If so, give it lowest priority
if (diff.Dot(cam_dir) < 0)
e.fDistance += 1E5;
}
std::sort(m_Queue.begin(), m_Queue.end());
}
void vtPagedStructureLodGrid::ClearQueue(vtStructureArray3d *pArray)
{
QueueVector::iterator it = m_Queue.begin();
while (it != m_Queue.end())
{
if (it->pStructureArray == pArray)
it = m_Queue.erase(it);
else
it++;
}
}
/**
* In case the paging grid did not load some structure before (because the
* structures were hidden), tell it to check again.
* You should call this when a structure layer becomes enabled (un-hidden).
*/
void vtPagedStructureLodGrid::RefreshPaging(vtStructureArray3d *pArray)
{
for (uint i = 0; i < pArray->size(); i++)
{
// Get 2D extents from the unbuild structure
vtStructure *str = pArray->at(i);
vtPagedStructureLOD *pGroup = FindGroup(str);
if (pGroup)
pGroup->m_bAddedToQueue = false;
}
}
void vtPagedStructureLodGrid::DoPaging(const FPoint3 &CamPos,
int iMaxStructures, float fDeleteDistance)
{
static float last_cull = 0.0f, last_load = 0.0f, last_prioritize = 0.0f;
float current = vtGetTime();
if (current - last_prioritize > 1.0f)
{
// Do a re-priortization every 1 second.
SortQueue();
last_prioritize = current;
}
else if (current - last_cull > 0.25f)
{
// Do a paging cleanup pass every 1/4 of a second
// Unload/unqueue anything excessive
CullFarawayStructures(CamPos, iMaxStructures, fDeleteDistance);
last_cull = current;
}
else if (current - last_load > 0.01f && !m_Queue.empty())
{
// Do loading every other available frame
last_load = current;
// Check if the camera is not moving; if so, construct more.
int construct;
static FPoint3 last_campos;
if (CamPos == last_campos)
construct = 5;
else
construct = 1;
for (int i = 0; i < construct && m_Queue.size() > 0; i++)
{
// Gradually load anything that needs loading
const QueueEntry &e = m_Queue.back();
ConstructByIndex(e.pLOD, e.pStructureArray, e.iStructIndex);
m_Queue.pop_back();
}
last_campos = CamPos;
}
}
void vtPagedStructureLodGrid::ConstructByIndex(vtPagedStructureLOD *pLOD,
vtStructureArray3d *pArray,
uint iStructIndex)
{
bool bSuccess = pArray->ConstructStructure(iStructIndex);
if (bSuccess)
{
vtStructure3d *str3d = pArray->GetStructure3d(iStructIndex);
vtTransform *pTrans = str3d->GetContainer();
if (pTrans)
pLOD->addChild(pTrans);
else
{
vtGeode *pGeode = str3d->GetGeom();
if (pGeode)
pLOD->addChild(pGeode);
}
pLOD->m_iNumConstructed ++;
// Keep track of overall number of loads
m_iLoadCount++;
}
else
{
VTLOG("Error: couldn't construct index %d\n", iStructIndex);
vtStructInstance *si = pArray->GetInstance(iStructIndex);
if (si)
{
const char *fname = si->GetValueString("filename", true);
VTLOG("\tinstance fname: '%s'\n", fname ? fname : "null");
}
}
}
bool vtPagedStructureLodGrid::AddToQueue(vtPagedStructureLOD *pLOD,
vtStructureArray3d *pArray, int iIndex)
{
// Check if it's already built
vtStructure3d *str3d = pArray->GetStructure3d(iIndex);
if (str3d && str3d->IsCreated())
return false;
// Check if it's already in the queue
for (QueueVector::iterator it = m_Queue.begin(); it != m_Queue.end(); it++)
{
if (it->pStructureArray == pArray && it->iStructIndex == iIndex)
return false;
}
// If not, add it
QueueEntry e;
e.pLOD = pLOD;
e.pStructureArray = pArray;
e.iStructIndex = iIndex;
e.fDistance = 1E9;
m_Queue.push_back(e);
return true;
}
bool vtPagedStructureLodGrid::RemoveFromQueue(vtStructureArray3d *pArray, int iIndex)
{
// Check if it's in the queue
for (QueueVector::iterator it = m_Queue.begin(); it != m_Queue.end(); it++)
{
if (it->pStructureArray == pArray && it->iStructIndex == iIndex)
{
m_Queue.erase(it);
return true;
}
}
return false;
}
| 24.598566 | 90 | 0.683375 | nakijun |
12d3cf11cb874027db4ecfaead2fb54d13967e27 | 16,970 | cpp | C++ | src/xray/editor/world/sources/sound_object_cook.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/editor/world/sources/sound_object_cook.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/editor/world/sources/sound_object_cook.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 21.12.2009
// Author : Evgeniy Obertyukh
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#pragma managed(push)
#pragma unmanaged
#include <xray/resources.h>
#include <xray/resources_cook_classes.h>
#include <xray/resources_fs.h>
#include <xray/fs_path_string.h>
#pragma managed(pop)
#include "memory.h"
//#include <conio.h>
#pragma managed(push)
#pragma unmanaged
#include <xray/core/sources/resources_manager.h>
#include <xray/core/sources/resources_managed_allocator.h>
#pragma managed(pop)
#include "sound_object_cook.h"
#include "raw_file_property_struct.h"
#include "sound_editor.h"
#pragma managed(push)
#pragma unmanaged
#include <xray/fs_utils.h>
#include <xray/linkage_helper.h>
#pragma managed(pop)
DECLARE_LINKAGE_ID(resources_test)
using namespace System;
using namespace System::IO;
using namespace System::Diagnostics;
using namespace System::Windows::Forms;
using xray::editor::raw_file_property_struct;
using xray::editor::sound_editor;
using xray::editor::unmanaged_string;
using xray::resources::fs_iterator;
#pragma message(XRAY_TODO("fix cooks"))
#if 0 // commented by Lain
namespace xray
{
namespace resources
{
static void make_sound_options (fs::path_string& file_path);
static void encode_sound_file (
fs::path_string &end_file_path,
int bits_per_sample,
int number_of_chanels,
int samples_per_second,
int output_bitrate
);
//ogg_resource class
sound_object_resource::sound_object_resource(pcbyte data_raw)
{
XRAY_UNREFERENCED_PARAMETER(data_raw);
m_options_resource_ptr = NULL;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
ogg_sound_cook_wrapper::ogg_sound_cook_wrapper ()
: cook( ogg_sound_wrapper_class, flag_process|flag_generate_if_no_file|flag_translate_query, threading::current_thread_id()/*use_cooker_thread_id*/) {}
void ogg_sound_cook_wrapper::translate_query ( resources::query_result& result )
{
//prepare paths
fs::path_string old_path (result.get_requested_path());
fs::path_string root_path;
fs::path_string* resource_path = MT_NEW(fs::path_string);
pcstr find_str = strstr(old_path.c_str(), "sounds");
root_path.append (old_path.begin(), find_str+6);
resource_path->append (find_str+23, old_path.end());
resources::query_fs_iterator(
root_path.c_str(),
boost::bind(&ogg_sound_cook_wrapper::on_fs_iterator_ready, this, resource_path, &result, _1),
result.get_user_allocator()
);
}
void ogg_sound_cook_wrapper::on_fs_iterator_ready (fs::path_string* resource_path, query_result_for_cook* parent, xray::resources::fs_iterator fs_it)
{
//
// if converted ogg isn't exists -> convert it and options
//
fs::path_string converted_path;
converted_path.append ("converted_local/");
converted_path.append (resource_path->c_str());
converted_path.append (".ogg");
fs_iterator fs_it_converted = fs_it.find_child(converted_path.c_str());
if(fs_it_converted.is_end())
{
request_convertion (resource_path, parent);
MT_DELETE (resource_path);
return;
}
//
// if converted ogg is old or source options younger than converted ogg -> convert ogg and options
//
fs::path_string source_path;
source_path.append ("sources/");
source_path.append (resource_path->c_str());
source_path.append (".wav");
fs_iterator fs_it_source = fs_it.find_child(source_path.c_str());
fs::path_string source_options_path;
source_options_path.append ("sources/");
source_options_path.append (resource_path->c_str());
source_options_path.append (".options");
fs_iterator fs_it_source_options = fs_it.find_child(source_options_path.c_str());
fs::path_info source_info;
fs::path_info converted_info;
fs::path_info source_options_info;
fs::path_string source_absolute_path;
fs::path_string converted_absolute_path;
fs::path_string source_options_absolute_path;
fs_it_source.get_disk_path (source_absolute_path);
fs_it_converted.get_disk_path (converted_absolute_path);
fs_it_source_options.get_disk_path (source_options_absolute_path);
fs::get_path_info (&source_info, source_absolute_path.c_str());
fs::get_path_info (&converted_info, converted_absolute_path.c_str());
fs::get_path_info (&source_options_info, source_options_absolute_path.c_str());
if( source_info.file_last_modify_time > converted_info.file_last_modify_time ||
source_options_info.file_last_modify_time > converted_info.file_last_modify_time)
{
request_convertion (resource_path, parent);
MT_DELETE (resource_path);
return;
}
//
// if converted options isn't exists -> convert it
//
fs::path_string converted_options_path;
converted_options_path.append ("converted_local/");
converted_options_path.append (resource_path->c_str());
converted_options_path.append (".options");
xray::resources::fs_iterator fs_it_converted_options = fs_it.find_child(converted_options_path.c_str());
if(fs_it_converted_options.is_end())
{
request_convertion_options (resource_path, parent);
MT_DELETE (resource_path);
return;
}
//
// if converted options is old -> convert it
//
fs::path_info converted_options_info;
fs::path_string converted_options_absolute_path;
fs_it_converted_options.get_disk_path (converted_options_absolute_path);
fs::get_path_info (&converted_options_info, converted_options_absolute_path.c_str());
if( converted_options_info.file_last_modify_time < converted_info.file_last_modify_time)
{
request_convertion_options (resource_path, parent);
MT_DELETE (resource_path);
return;
}
//
// otherwise request sound
//
query_resource(
parent->get_requested_path(),
ogg_sound_class,
boost::bind(&ogg_sound_cook_wrapper::sound_loaded, this, _1),
&memory::g_mt_allocator,
0,
parent
);
MT_DELETE (resource_path);
}
void ogg_sound_cook_wrapper::request_convertion (fs::path_string* resource_path, query_result_for_cook* parent)
{
//prepare paths
fs::path_string ogg_path;
fs::path_string tga_path;
ogg_path.append ("resources/sounds/converted_local/");
ogg_path.append (resource_path->c_str());
ogg_path.append (".ogg");
query_resource(
ogg_path.c_str(),
ogg_converter_class,
boost::bind(&ogg_sound_cook_wrapper::on_sound_converted, this, false, _1),
&memory::g_mt_allocator,
0,
parent
);
}
void ogg_sound_cook_wrapper::request_convertion_options (fs::path_string* resource_path, query_result_for_cook* parent)
{
//prepare paths
fs::path_string ogg_path;
fs::path_string tga_path;
ogg_path.append ("resources/sounds/converted_local/");
ogg_path.append (resource_path->c_str());
ogg_path.append (".options");
query_resource(
ogg_path.c_str(),
ogg_options_converter_class,
boost::bind(&ogg_sound_cook_wrapper::on_sound_converted, this, true, _1),
&memory::g_mt_allocator,
0,
parent
);
}
void ogg_sound_cook_wrapper::on_sound_converted (bool is_options_complete, resources::queries_result& result)
{
resources::query_result_for_cook * const parent = result.get_parent_query();
if(is_options_complete)
{
query_resource(
parent->get_requested_path(),
ogg_sound_class,
boost::bind(&ogg_sound_cook_wrapper::sound_loaded, this, _1),
&memory::g_mt_allocator,
0,
parent
);
}
else
{
fs::path_string old_path (result[0].get_requested_path());
fs::path_string resource_path;
pcstr find_str = strstr(old_path.c_str(), "converted_local");
resource_path.append (find_str+16, old_path.end()-4);
request_convertion_options (&resource_path, parent);
}
}
void ogg_sound_cook_wrapper::sound_loaded (queries_result& result)
{
query_result_for_cook * const parent = result.get_parent_query();
if(result.is_failed())
{
parent->finish_translated_query (result_error);
return;
}
parent->set_unmanaged_resource (result[0].get_unmanaged_resource().get());
parent->finish_translated_query (result_dont_reuse);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//ogg_sound_cook class
ogg_sound_cook::ogg_sound_cook ()
: cook( ogg_sound_class, cook::flag_translate_query, use_cooker_thread_id) {}
void ogg_sound_cook::translate_query (query_result& parent)
{
pstr request_ogg = 0;
STR_JOINA (
request_ogg,
parent.get_requested_path(),
".ogg"
);
pstr request_options = 0;
STR_JOINA (
request_options,
parent.get_requested_path(),
".options"
);
request arr[] = {
{ request_ogg, ogg_class },
{ request_options, config_lua_class },
};
query_resources (arr,
2,
boost::bind(&ogg_sound_cook::on_sub_resources_loaded, this, _1),
parent.get_user_allocator(),
0,
&parent);
}
void ogg_sound_cook::on_sub_resources_loaded (queries_result & result)
{
query_result_for_cook * const parent = result.get_parent_query();
unmanaged_resource_ptr ogg_res;
if ( result[0].is_success() && result[1].is_success() )
{
ogg_res = result[0].get_unmanaged_resource();
static_cast_checked<sound_object_resource*>( ogg_res.get()) -> m_options_resource_ptr =
(result[1].get_unmanaged_resource());
}
else
{
parent->finish_translated_query (result_error);
return;
}
parent->set_unmanaged_resource (ogg_res.get());
parent->finish_translated_query (result_reuse_unmanaged);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
ogg_cook::ogg_cook() : cook(ogg_class, flag_process|flag_generate_if_no_file) {}
cook::result_enum ogg_cook::process (query_result_for_cook& query, u32& final_managed_resource_size)
{
XRAY_UNREFERENCED_PARAMETER ( final_managed_resource_size );
sound_object_resource * out = NULL;
if (!query.is_success())
return result_error;
mutable_buffer data = query.get_file_data();
pcbyte data_raw = (pcbyte)data.data();
out = MT_NEW(sound_object_resource)(data_raw);
query.set_unmanaged_resource (out);
return result_reuse_unmanaged;
}
void ogg_cook::delete_unmanaged (unmanaged_resource* res)
{
MT_DELETE (res);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void encode_sound_file (
fs::path_string &end_file_path,
int bits_per_sample,
int number_of_chanels,
int samples_per_second,
int output_bitrate );
ogg_converter::ogg_converter() : cook(ogg_converter_class, flag_process|flag_generate_if_no_file) {}
cook::result_enum ogg_converter::process(query_result_for_cook& query, u32& final_managed_resource_size)
{
XRAY_UNREFERENCED_PARAMETER ( final_managed_resource_size );
//prepare paths
fs::path_string dest_path (query.get_requested_path());
fs::path_string source_options_path;
pcstr find_str = strstr(dest_path.c_str(), "converted_local");
source_options_path.append (dest_path.begin(), find_str);
source_options_path.append ("sources");
source_options_path.append (find_str+15, dest_path.end()-4);
source_options_path.append (".options");
fs::path_string disk_path;
CURE_ASSERT (query.select_disk_path_from_request_path(& disk_path),
return result_error);
query_resource (
source_options_path.c_str(),
config_lua_class,
boost::bind(&ogg_converter::on_raw_properties_loaded, this, _1),
& memory::g_mt_allocator,
0,
& query);
return result_postponed;
}
void ogg_converter::on_raw_properties_loaded (queries_result& result)
{
query_result_for_cook * const parent = result.get_parent_query();
if ( result.is_failed() )
{
parent->finish_postponed (result_error);
return;
}
configs::lua_config_ptr config = static_cast_intrusive_ptr<configs::lua_config_ptr>(result[0].get_unmanaged_resource());
configs::lua_config_value const& config_root = config->get_root();
configs::lua_config_value value = config_root["options"];
fs::path_string disk_path;
CURE_ASSERT (parent->select_disk_path_from_request_path(&disk_path), parent->finish_postponed(result_error));
encode_sound_file(
disk_path,
value["bits_per_sample"],
value["number_of_chanels"],
value["samples_per_second"],
value["output_bitrate"]
);
parent->finish_postponed (result_dont_reuse);
}
static void encode_sound_file(
fs::path_string &end_file_path,
int bits_per_sample,
int number_of_chanels,
int samples_per_second,
int output_bitrate)
{
//make path's
fs::path_string src_file_path;
char* sources_offset = strstr(end_file_path.c_str(), "converted_local");
src_file_path.append (end_file_path.begin(), sources_offset);
src_file_path.append ("sources");
src_file_path.append (sources_offset+15, end_file_path.end());
src_file_path.set_length(src_file_path.length()-4);
src_file_path.append (".wav");
//if destination directory is not exists -> make it
fs::path_string dir;
dir = end_file_path;
dir.set_length(dir.rfind('/'));
if(fs::get_path_info(NULL, dir.c_str()) == fs::path_info::type_nothing)
{
fs::make_dir_r(dir.c_str());
}
STARTUPINFO si;
ZeroMemory ( &si, sizeof(si) );
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = 0;
si.dwFlags = STARTF_USESHOWWINDOW;
PROCESS_INFORMATION pi;
ZeroMemory ( &pi, sizeof(pi) );
char buf[12];
fixed_string512 cl_args;
cl_args += "oggenc.exe";
cl_args += " -B ";
_itoa_s(bits_per_sample, buf, 10);
cl_args += buf;
cl_args += " -C ";
_itoa_s(number_of_chanels, buf, 10);
cl_args += buf;
cl_args += " -R ";
_itoa_s(samples_per_second, buf, 10);
cl_args += buf;
cl_args += " -b ";
_itoa_s(output_bitrate, buf, 10);
cl_args += buf;
cl_args += " -o \"";
cl_args += end_file_path.c_str();
cl_args += "\" \"";
cl_args += src_file_path.c_str();
cl_args += "\"";
if(CreateProcess(NULL,cl_args.c_str(),NULL, NULL, FALSE,0, NULL, NULL, &si, &pi))
WaitForSingleObject(pi.hProcess, INFINITE);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static void make_sound_options(fs::path_string& end_file_path);
ogg_options_converter::ogg_options_converter() : cook(ogg_options_converter_class, flag_process|flag_generate_if_no_file) {}
cook::result_enum ogg_options_converter::process(query_result_for_cook& query, u32& final_managed_resource_size)
{
XRAY_UNREFERENCED_PARAMETER ( final_managed_resource_size );
//if no requested file
fs::path_string disk_path;
if(query.select_disk_path_from_request_path(& disk_path))
make_sound_options (disk_path);
return result_dont_reuse;
}
static void make_sound_options(fs::path_string& end_file_path)
{
//make path's
fs::path_string file_path;
file_path = end_file_path;
file_path.set_length (file_path.length()-8);
file_path.append (".ogg");
STARTUPINFO si;
ZeroMemory ( &si, sizeof(si) );
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = 0;
si.dwFlags = STARTF_USESHOWWINDOW;
PROCESS_INFORMATION pi;
ZeroMemory ( &pi, sizeof(pi) );
fixed_string512 cl_args;
cl_args += "xray_rms_generator-debug.exe";
cl_args += " -o=\"";
cl_args += end_file_path.c_str();
cl_args += "\" -i=\"";
cl_args += file_path.c_str();
cl_args += "\"";
if(CreateProcess(NULL, cl_args.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
WaitForSingleObject(pi.hProcess, INFINITE);
}
}//namespace resources
}//namespace xray
#endif // #if 0 // commented by Lain
| 30.521583 | 154 | 0.652858 | ixray-team |
12d713f4f1018305d22d3ca9d75f1b702414b0b2 | 7,430 | cpp | C++ | game.cpp | block8437/GameEngine | e4b452c33781566e55e9339efee9441ddb924f58 | [
"MIT"
] | null | null | null | game.cpp | block8437/GameEngine | e4b452c33781566e55e9339efee9441ddb924f58 | [
"MIT"
] | 1 | 2017-04-05T00:58:21.000Z | 2017-04-05T00:58:21.000Z | game.cpp | block8437/GameEngine | e4b452c33781566e55e9339efee9441ddb924f58 | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include "game.h"
namespace GameEngine {
Game gameObject;
GameContactListener myContactListenerInstance;
void _display_redirect() {
gameObject.display();
}
void _reshape_redirect(GLsizei width, GLsizei height) {
gameObject.reshape(width, height);
}
void _exit_redirect() {
gameObject.onExit();
}
void _timer_redirect(int value) {
gameObject.timer(value);
}
void _keyboardUp_redirect(unsigned char key, int x, int y) {
gameObject.keyboardUp(key, x, y);
}
void _keyboardDown_redirect(unsigned char key, int x, int y) {
gameObject.keyboardDown(key, x, y);
}
void _specialKeys_redirect(int key, int x, int y) {
gameObject.specialKeys(key, x, y);
}
void _mouse_redirect(int button, int state, int x, int y) {
gameObject.mouse(button, state, x, y);
}
Game::Game() {
}
Game::Game(char* _title, int width, int height, int _argc, char** _argv) {
title = _title;
originalWindowWidth = width;
originalWindowHeight = height;
windowWidth = originalWindowWidth;
windowHeight = originalWindowHeight;
windowPosX = 50;
windowPosY = 50;
argc = _argc;
argv = _argv;
refreshMillis = 15.0f;
base_time = 0;
fps = 0;
frames = 0;
fullScreenMode = false;
}
void Game::initGL() {
keys[0] = false;
keys[1] = false;
keys[2] = false;
keys[3] = false;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_ALPHA | GLUT_STENCIL);
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition(windowPosX, windowPosY);
glutCreateWindow(title);
glutDisplayFunc(_display_redirect);
glutReshapeFunc(_reshape_redirect);
glutTimerFunc(0, _timer_redirect, 0);
glutSpecialFunc(_specialKeys_redirect);
glutKeyboardUpFunc(_keyboardUp_redirect);
glutKeyboardFunc(_keyboardDown_redirect);
printf("*** Initializing GL Version: %s\n", (const char*)glGetString(GL_VERSION));
if(fullScreenMode)
glutFullScreen();
glutMouseFunc(_mouse_redirect);
B2_NOT_USED(argc);
B2_NOT_USED(argv);
}
void Game::begin() {
universe.getWorld()->SetContactListener(&myContactListenerInstance);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glOrtho(0.0f,windowWidth,0.0f,windowHeight,0.0f,1.0f);
glClearColor(0.0, 0.0, 0.0, 0.0);
GLenum error = glGetError();
if(error != GL_NO_ERROR) {
printf( "***Error initializing OpenGL! %s\n", gluErrorString( error ) );
exit(0);
}
GLint GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult) {
printf("***Error initializing GLEW! %s\n",glewGetErrorString(GlewInitResult));
exit(EXIT_FAILURE);
}
setShader("light","","light.glsl");
light = Light(&universe, 400, 100, 1.0, 1.0f, 0.0f, windowWidth, windowHeight, getShader("light"));
glutMainLoop();
}
void Game::initGame() {
loadLevel("level1.json", &universe, windowWidth, windowHeight);
PlayerObject* player = new PlayerObject(universe.getSpritesheet("playersprites"), 2.0f, 50.0f, 300.0f, universe.getWorld(), 640, 480);
universe.setActivatePlayer(player);
}
void Game::keyboardDown(unsigned char key, int x, int y) {
switch (key) {
case 'd':
keys[3] = true;
break;
case 'a':
keys[2] = true;
break;
case 'w':
keys[0] = true;
break;
case 's':
keys[1] = true;
break;
case 27: // ESC key
exit(0);
break;
}
}
void Game::keyboardUp(unsigned char key, int x, int y) {
switch (key) {
case 'd':
keys[3] = false;
break;
case 'a':
keys[2] = false;
break;
case 'w':
keys[0] = false;
break;
case 's':
keys[1] = false;
break;
}
}
void Game::specialKeys(int key, int x, int y) {
switch (key) {
case GLUT_KEY_F1:
fullScreenMode = !fullScreenMode;
if (fullScreenMode) {
originalWindowWidth = windowWidth;
originalWindowHeight = windowHeight;
windowPosX = glutGet(GLUT_WINDOW_X);
windowPosY = glutGet(GLUT_WINDOW_Y);
windowWidth = glutGet(GLUT_WINDOW_WIDTH);
windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
reshape(windowWidth, windowHeight);
glutFullScreen();
}
else {
windowWidth = originalWindowWidth;
windowHeight = originalWindowHeight;
glutReshapeWindow(windowWidth, windowHeight);
glutPositionWindow(windowPosX, windowPosX);
}
break;
}
}
void Game::mouse(int button, int state, int x, int y) {
if(!state) {
//addMoreBlocks(x, windowHeight - y);
printf("Mouse clicked %d (%d,%d)\n", state, x, y);
}
}
void Game::timer(int value) {
glutPostRedisplay();
glutTimerFunc(refreshMillis, _timer_redirect, 0);
}
void Game::display() {
frames++;
calculateFrameRate();
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
light.render();
universe.render();
universe.update(keys[0], keys[1], keys[2], keys[3]);
glutSwapBuffers();
}
void Game::reshape(GLsizei width, GLsizei height) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
windowWidth = width;
windowHeight = height;
glOrtho(0.0f,windowWidth,0.0f,windowHeight,0.0f,1.0f);
glViewport(0, 0, width, height);
}
void Game::calculateFrameRate() {
int time = glutGet(GLUT_ELAPSED_TIME);
if ((time - base_time) > 1000.0)
{
fps = frames*1000.0/(time - base_time);
base_time = time;
frames = 0;
}
}
float Game::getFrameRate() {
return fps;
}
void Game::onExit() {
universe.clean();
}
void Game::setShader(std::string name, const char* vertex_file, const char* fragment_file) {
bool use_vert = vertex_file != "" ? true : false;
bool use_frag = fragment_file != "" ? true : false;
GLuint program = glCreateProgram();
programMap[name] = program;
if(use_vert && use_frag) {
vertexMap[name] = glCreateShader(GL_VERTEX_SHADER);
fragmentMap[name] = glCreateShader(GL_FRAGMENT_SHADER);
std::string vss = get_file_contents(vertex_file);
std::string fss = get_file_contents(fragment_file);
const char* vv = vss.c_str();
const char* ff = fss.c_str();
glShaderSource(vertexMap[name], 1, &vv, NULL);
glShaderSource(fragmentMap[name], 1, &ff, NULL);
glCompileShader(vertexMap[name]);
glCompileShader(fragmentMap[name]);
glAttachShader(programMap[name], vertexMap[name]);
glAttachShader(programMap[name], fragmentMap[name]);
}
else {
if(use_vert && !use_frag) {
vertexMap[name] = glCreateShader(GL_VERTEX_SHADER);
std::string vss = get_file_contents(vertex_file);
const char* vv = vss.c_str();
glShaderSource(vertexMap[name], 1, &vv, NULL);
glCompileShader(vertexMap[name]);
glAttachShader(programMap[name], vertexMap[name]);
}
else {
if(!use_vert && use_frag) {
fragmentMap[name] = glCreateShader(GL_FRAGMENT_SHADER);
std::string fss = get_file_contents(fragment_file);
const char* ff = fss.c_str();
glShaderSource(fragmentMap[name], 1, &ff, NULL);
glCompileShader(fragmentMap[name]);
glAttachShader(programMap[name], fragmentMap[name]);
}
else
return; // no shader!!
}
}
glLinkProgram(programMap[name]);
glValidateProgram(programMap[name]);
printf("*** Shader Program '%s' initialized!\n", name.c_str());
}
GLuint Game::getShader(std::string name) {
return programMap[name];
}
Game* NewGame(char* title, int windowWidth, int windowHeight, int argc, char** argv) {
gameObject = Game(title, windowWidth, windowHeight, argc, argv);
return &gameObject;
}
} | 24.045307 | 136 | 0.673351 | block8437 |
12d788c3b34c43755b41891974e020fe89b4e04d | 3,497 | cpp | C++ | lotus/src/scene/SceneManager.cpp | mayant15/lotus | 6b01b6bc204c66f3f22c5d3ad59dc08312f1ad20 | [
"MIT"
] | 6 | 2020-11-13T14:02:02.000Z | 2021-11-30T14:26:50.000Z | lotus/src/scene/SceneManager.cpp | sps1112/lotus | 28c048b04a2f30cc1620f7fd10279038c101bd48 | [
"MIT"
] | 1 | 2020-07-16T10:51:56.000Z | 2020-07-16T10:51:56.000Z | lotus/src/scene/SceneManager.cpp | sps1112/lotus | 28c048b04a2f30cc1620f7fd10279038c101bd48 | [
"MIT"
] | 3 | 2020-07-13T11:36:29.000Z | 2020-10-20T09:13:32.000Z | #include <lotus/scene/SceneManager.h>
#include <lotus/ecs/ComponentRegistry.h>
#include <lotus/debug.h>
#include <lotus/filesystem.h>
#include <stdexcept>
#include <lotus/ecs/EventManager.h>
namespace Lotus::SceneManager
{
SRef<Scene> currentScene;
SRef<Scene> GetCurrentScene()
{
return currentScene;
}
inline void attachComponents(Entity entity, const nlohmann::json& info)
{
auto reg = currentScene->GetRegistry();
auto id = (EntityID) entity;
// TODO: Transform should be created first. Right now, component create events are non-immediate, so they're
// called only after all components are attached. While that works for now, we should really have some sort of
// strict order here.
// if (info.contains("CTransform"))
// {
// // Add a transform first as other components might depend on it
// auto entity = CreateEntity();
// CTransform transform;
// from_json(entityInfo.at("CTransform"), transform);
// entity.AddComponent<CTransform>(transform);
// }
if (!info.contains("CDisplayName"))
{
entity.AddComponent<CDisplayName>("Entity " + std::to_string((unsigned int) id));
}
for (auto& comp : info.items())
{
if (comp.key() != "Prefab")
{
auto info = GetComponentInfo(comp.key());
info.assignFn(id, *reg, comp.value());
}
}
}
void LoadScene(const std::string& relpath)
{
currentScene = std::make_shared<Scene>();
currentScene->detail.path = relpath;
auto fullpath = ExpandPath(relpath);
std::ifstream infile (fullpath);
nlohmann::json data;
infile >> data;
// if (!data.is_array())
if (!data.contains("components"))
{
throw std::runtime_error { "Invalid scene format" };
}
// for (auto& entityInfo : data)
for (auto& entityInfo : data["components"])
{
if (entityInfo.contains("Prefab"))
{
auto entity = currentScene->CreateEntity(ExpandPath(entityInfo.at("Prefab").get<std::string>()));
attachComponents(entity, entityInfo);
}
else
{
auto entity = currentScene->CreateEntity();
attachComponents(entity, entityInfo);
}
}
// TODO: Generate the scene tree
EventManager::Get().Dispatch(SceneLoadEvent { currentScene.get() });
}
void OnSimulationBegin(const SimulationBeginEvent& event)
{
// Save a snapshot of the scene
}
void OnSimulationEnd(const SimulationEndEvent& event)
{
// Restore the scene with snapshot
}
void SaveScene()
{
// TODO: Save changes to disk. I'll probably need to fix the serialization thing once and for all
// TODO: The above is done, sort of. Save prefab information too.
LOG_INFO("Saving scene...");
auto* reg = currentScene->GetRegistry();
OutputArchive archive { reg };
// Save all components
SerializeComponents(archive);
// Dump to file
archive.DumpToFile(Lotus::ExpandPath(currentScene->detail.path));
LOG_INFO("Saved!");
}
}
| 30.408696 | 120 | 0.560766 | mayant15 |
12d87943a99b04bdf0c3a0c6421bb9d224ba0234 | 356 | cpp | C++ | HackerRank/Recursion/reverse_string.cpp | nullpointxr/HackerRankSolutions | 052c9ab66bfd66268b81d8e7888c3d7504ab988f | [
"Apache-2.0"
] | 1 | 2020-10-25T16:12:09.000Z | 2020-10-25T16:12:09.000Z | HackerRank/Recursion/reverse_string.cpp | abhishek-sankar/Competitive-Coding-Solutions | 052c9ab66bfd66268b81d8e7888c3d7504ab988f | [
"Apache-2.0"
] | 3 | 2020-11-12T05:44:24.000Z | 2021-04-05T08:09:01.000Z | HackerRank/Recursion/reverse_string.cpp | nullpointxr/HackerRankSolutions | 052c9ab66bfd66268b81d8e7888c3d7504ab988f | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
string reverse(string name){
// 3 steps
// one step simpler?
// My function CAN
// how will I use the function which can do 1 step simpler to solve present problem?
// Base case:
if(name.length()<=1)
return name;
return reverse(name.substr(1))+name[0];
}
int main(){
cout<<reverse("kehsihbA")<<endl;
} | 23.733333 | 85 | 0.685393 | nullpointxr |
12db14f05af5c98a3b912e29cda983f9834fbab6 | 629 | hpp | C++ | public/sketch/application.hpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | public/sketch/application.hpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | public/sketch/application.hpp | vladislavmarkov/sketch | 5afed3edd0245942ed2010df1d092fc7d1ed8610 | [
"MIT"
] | null | null | null | #pragma once
#ifndef SK_APPLICATION_HPP
#define SK_APPLICATION_HPP
#include <sketch/window.hpp>
namespace sk {
class application_t final {
std::vector<window_t> _windows;
bool _running = {true};
public:
application_t& operator=(const application_t&) = delete;
application_t& operator=(application_t&&) = delete;
application_t(const application_t&) = delete;
application_t(application_t&&) = delete;
application_t();
~application_t();
void add(window_t&&);
int run();
void quit();
bool is_running() const;
};
}
#endif // SK_APPLICATION_HPP
| 20.966667 | 60 | 0.655008 | vladislavmarkov |
12db277ac52faaebad57c93f4dd9d5665a3b7c55 | 2,124 | cpp | C++ | Headers/OGL/GlobalContext.cpp | baku89/RichterStrip | 223c40c54cda0a028f20167a78ea61710e06f480 | [
"MIT",
"Unlicense"
] | 6 | 2020-11-30T05:31:17.000Z | 2020-12-01T12:40:20.000Z | Headers/OGL/GlobalContext.cpp | baku89/RichterStrip | 223c40c54cda0a028f20167a78ea61710e06f480 | [
"MIT",
"Unlicense"
] | null | null | null | Headers/OGL/GlobalContext.cpp | baku89/RichterStrip | 223c40c54cda0a028f20167a78ea61710e06f480 | [
"MIT",
"Unlicense"
] | 1 | 2020-12-02T03:04:52.000Z | 2020-12-02T03:04:52.000Z | #include "GlobalContext.h"
#include "Debug.h"
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
namespace OGL {
GlobalContext::GlobalContext() {
angle::Library *mEntryPointsLib = angle::OpenSharedLibrary("libEGL", angle::SearchType::ApplicationDir);
PFNEGLGETPROCADDRESSPROC getProcAddress;
mEntryPointsLib->getAs("eglGetProcAddress", &getProcAddress);
if (!getProcAddress) {
return;
}
angle::LoadEGL(getProcAddress);
if (!eglGetPlatformDisplayEXT) {
return;
}
EGLint dispattrs[] = {
EGL_PLATFORM_ANGLE_TYPE_ANGLE,
EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE,
EGL_NONE
};
display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE,
reinterpret_cast<void *>(EGL_DEFAULT_DISPLAY),
dispattrs);
eglInitialize(display, nullptr, nullptr);
assertEGLError("eglInitialize");
EGLConfig config;
EGLint num_config;
eglChooseConfig(display, nullptr, &config, 1, &num_config);
if (!assertEGLError("eglChooseConfig")) {
return;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (!assertEGLError("eglBindAPI")) {
return;
}
context = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
if (!assertEGLError("eglCreateContext")) {
return;
}
surface = eglCreatePbufferSurface(display, config, nullptr);
if (!assertEGLError("eglCreatePbufferSurface")) {
return;
}
// On succeeded
this->initialized = true;
}
void GlobalContext::bind() {
eglMakeCurrent(this->display, this->surface, this->surface, this->context);
}
bool GlobalContext::assertEGLError(const std::string &msg) {
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
FX_LOG("OpenGL error 0x" << std::hex << error << " at " << msg);
return false;
} else {
return true;
}
}
GlobalContext::~GlobalContext() {
eglDestroyContext(this->display, this->context);
eglTerminate(this->display);
}
} // namespace OGL
| 23.865169 | 108 | 0.624765 | baku89 |
12e1de9878cc3d4aa88a9cb99bb560e034b69a85 | 1,663 | cpp | C++ | perception_oru-port-kinetic/graph_map/src/template/template_reg_type.cpp | lllray/ndt-loam | 331867941e0764b40e1a980dd85d2174f861e9c8 | [
"BSD-3-Clause"
] | 1 | 2020-11-14T08:21:13.000Z | 2020-11-14T08:21:13.000Z | perception_oru-port-kinetic/graph_map/src/template/template_reg_type.cpp | lllray/ndt-loam | 331867941e0764b40e1a980dd85d2174f861e9c8 | [
"BSD-3-Clause"
] | 1 | 2021-07-28T04:47:56.000Z | 2021-07-28T04:47:56.000Z | perception_oru-port-kinetic/graph_map/src/template/template_reg_type.cpp | lllray/ndt-loam | 331867941e0764b40e1a980dd85d2174f861e9c8 | [
"BSD-3-Clause"
] | 2 | 2020-12-18T11:25:53.000Z | 2022-02-19T12:59:59.000Z | #include "graph_map/template/template_reg_type.h"
namespace perception_oru{
namespace libgraphMap{
TemplateRegType::TemplateRegType(const Affine3d &sensor_pose,RegParamPtr paramptr):registrationType(sensor_pose,paramptr){
TemplateRegTypeParamPtr param = boost::dynamic_pointer_cast< TemplateRegTypeParam >(paramptr);//Should not be NULL
if(param!=NULL){
//Transfer all parameters from param to this class
cout<<"Created registration type for template"<<endl;
}
else
cerr<<"ndtd2d registrator has NULL parameters"<<endl;
}
TemplateRegType::~TemplateRegType(){}
bool TemplateRegType::Register(MapTypePtr maptype, Eigen::Affine3d &Tnow, pcl::PointCloud<pcl::PointXYZ> &cloud, Matrix6d cov) {
if(!enableRegistration_||!maptype->Initialized()){
cout<<"Registration disabled - motion based on odometry"<<endl;
return false;
}
else{
TemplateMapTypePtr MapPtr = boost::dynamic_pointer_cast< TemplateMapType >(maptype);
//Perform registration based on prediction "Tinit", your map "MapPtr" and the "cloud"
cout<<"please fill in code for registration- uintil then, registration is disabled"<<endl;
}
return false;//remove this when registration code has been implemented
}
/* ----------- Parameters ------------*/
TemplateRegTypeParam::~TemplateRegTypeParam(){}
TemplateRegTypeParam::TemplateRegTypeParam():registrationParameters(){
}
void TemplateRegTypeParam::GetParametersFromRos(){
registrationParameters::GetParametersFromRos();
ros::NodeHandle nh("~");//base class parameters
nh.param<std::string>("super_important_parameter",super_important_parameter_,"default string");
}
}
}//end namespace
| 30.236364 | 128 | 0.753458 | lllray |
12e25565aaabdbbac82dba56bd2b87404038bb9a | 7,145 | cpp | C++ | Panorama/Panorama.cpp | AmineKheldouni/3D-Computer-Vision | cb84ec0914137cf03136ad315e7682b065fdbe22 | [
"MIT"
] | null | null | null | Panorama/Panorama.cpp | AmineKheldouni/3D-Computer-Vision | cb84ec0914137cf03136ad315e7682b065fdbe22 | [
"MIT"
] | null | null | null | Panorama/Panorama.cpp | AmineKheldouni/3D-Computer-Vision | cb84ec0914137cf03136ad315e7682b065fdbe22 | [
"MIT"
] | 1 | 2020-11-16T19:46:33.000Z | 2020-11-16T19:46:33.000Z | // Imagine++ project
// Project: Panorama
// Author: Pascal Monasse
// Date: 2018/10/09
#include <Imagine/Graphics.h>
#include <Imagine/Images.h>
#include <Imagine/LinAlg.h>
using namespace Imagine;
using namespace std;
// Record clicks in two images, until right button click
void getClicks(Window w1, Window w2,
vector<IntPoint2> &pts1, vector<IntPoint2> &pts2) {
int button;
IntPoint2 click_position;
// Selecting points on the first window
cout << "Click points of interest in the first window... Click on the right button when done." << endl;
setActiveWindow(w1);
int counter = 0;
do {
button = getMouse(click_position);
if (button == 1) {
pts1.push_back(click_position);
drawCircle(click_position, 4, RED, 2);
counter++;
cout << "Number of points clicked : " << counter << endl;
}
} while (button != 3);
// Selecting points on the second window
cout << "Click the matching points in the second window... Click in the right button when done." << endl;
setActiveWindow(w2);
counter = 0;
do {
button = getMouse(click_position);
if (button == 1) {
pts2.push_back(click_position);
drawCircle(click_position, 4, RED, 2);
counter++;
cout << "Number of points clicked : " << counter << endl;
}
} while (button != 3);
cout << "Points have been collected successfully !" << endl;
}
// Return homography compatible with point matches
Matrix<float> getHomography(const vector<IntPoint2> &pts1,
const vector<IntPoint2> &pts2) {
size_t n = min(pts1.size(), pts2.size());
if (n < 4) {
cout << "Not enough correspondences: " << n << endl;
return Matrix<float>::Identity(3);
}
Matrix<float> A((int) (2 * n), 8);
Vector<float> B(2 * n);
for (size_t i = 0; i < n; i++) {
A((int) (2 * i), 0) = pts1[i].x();
A((int) (2 * i), 1) = pts1[i].y();
A((int) (2 * i), 2) = 1;
A((int) (2 * i), 3) = 0;
A((int) (2 * i), 4) = 0;
A((int) (2 * i), 5) = 0;
A((int) (2 * i), 6) = -pts1[i].x() * pts2[i].x();
A((int) (2 * i), 7) = -pts2[i].x() * pts1[i].y();
B[2 * i] = pts2[i].x();
A((int) (2 * i + 1), 0) = 0;
A((int) (2 * i + 1), 1) = 0;
A((int) (2 * i + 1), 2) = 0;
A((int) (2 * i + 1), 3) = pts1[i].x();
A((int) (2 * i + 1), 4) = pts1[i].y();
A((int) (2 * i + 1), 5) = 1;
A((int) (2 * i + 1), 6) = -pts1[i].x() * pts2[i].y();
A((int) (2 * i + 1), 7) = -pts2[i].y() * pts1[i].y();
B[2 * i + 1] = pts2[i].y();
}
B = linSolve(A, B);
Matrix<float> H(3, 3);
H(0, 0) = B[0];
H(0, 1) = B[1];
H(0, 2) = B[2];
H(1, 0) = B[3];
H(1, 1) = B[4];
H(1, 2) = B[5];
H(2, 0) = B[6];
H(2, 1) = B[7];
H(2, 2) = 1;
// Sanity check
for (size_t i = 0; i < n; i++) {
float v1[] = {(float) pts1[i].x(), (float) pts1[i].y(), 1.0f};
float v2[] = {(float) pts2[i].x(), (float) pts2[i].y(), 1.0f};
Vector<float> x1(v1, 3);
Vector<float> x2(v2, 3);
x1 = H * x1;
cout << "(x'^(Hx))_" << i << "= " << x1[1] * x2[2] - x1[2] * x2[1] << ' '
<< x1[2] * x2[0] - x1[0] * x2[2] << ' '
<< x1[0] * x2[1] - x1[1] * x2[0] << endl;
}
return H;
}
// Grow rectangle of corners (x0,y0) and (x1,y1) to include (x,y)
void growTo(float &x0, float &y0, float &x1, float &y1, float x, float y) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
// Panorama construction
void panorama(const Image<Color, 2> &I1, const Image<Color, 2> &I2,
Matrix<float> H) {
Vector<float> v(3);
float x0 = 0, y0 = 0, x1 = I2.width(), y1 = I2.height();
// Construct the box for panoramic image
v[0] = 0;
v[1] = 0;
v[2] = 1;
v = H * v;
v /= v[2];
growTo(x0, y0, x1, y1, v[0], v[1]);
v[0] = I1.width();
v[1] = 0;
v[2] = 1;
v = H * v;
v /= v[2];
growTo(x0, y0, x1, y1, v[0], v[1]);
v[0] = I1.width();
v[1] = I1.height();
v[2] = 1;
v = H * v;
v /= v[2];
growTo(x0, y0, x1, y1, v[0], v[1]);
v[0] = 0;
v[1] = I1.height();
v[2] = 1;
v = H * v;
v /= v[2];
growTo(x0, y0, x1, y1, v[0], v[1]);
cout << "x0 x1 y0 y1=" << x0 << ' ' << x1 << ' ' << y0 << ' ' << y1 << endl;
Image<Color> I(int(x1 - x0), int(y1 - y0));
int overlap;
// Filling the panorama with pixels
for (int i = 0; i < I.width(); i++) {
for (int j = 0; j < I.height(); j++) {
overlap = 0;
v[0] = i + x0;
v[1] = j + y0;
v[2] = 1;
// If we are on the right side, we take pixels from the second image
if (v[0] >= 0 && v[0] < I2.width() && v[1] >= 0 && v[1] < I2.height()) {
overlap++;
I(i, j) = I2((int) v[0], (int) v[1]);
}
// Pull pixels from original image by interpolation
v = inverse(H) * v;
v /= v[2];
// If we are on the left side
if (v[0] >= 0 && v[1] >= 0 && v[0] < I1.width() && v[1] < I1.height()) {
overlap++;
// If we are on the overlapping area we average the values from both images
if (overlap == 2) {
I(i, j) = I(i, j) / 2 + I1((int) v[0], (int) v[1]) / 2;
} else {
I(i, j) = I1((int) v[0], (int) v[1]);
}
}
}
}
setActiveWindow(openWindow(I.width(), I.height()));
display(I, 0, 0);
}
// Main function
int main(int argc, char *argv[]) {
const char *s1 = argc > 1 ? argv[1] : srcPath("image0006.jpg");
const char *s2 = argc > 2 ? argv[2] : srcPath("image0007.jpg");
// Load and display images
Image<Color> I1, I2;
if (!load(I1, s1) ||
!load(I2, s2)) {
cerr << "Unable to load the images" << endl;
return 1;
}
Window w1 = openWindow(I1.width(), I1.height(), s1);
display(I1, 0, 0);
Window w2 = openWindow(I2.width(), I2.height(), s2);
setActiveWindow(w2);
display(I2, 0, 0);
// Get user's clicks in images
vector<IntPoint2> pts1, pts2;
getClicks(w1, w2, pts1, pts2);
// Show points
vector<IntPoint2>::const_iterator it;
cout << "pts1=" << endl;
for (it = pts1.begin(); it != pts1.end(); it++)
cout << *it << endl;
cout << "pts2=" << endl;
for (it = pts2.begin(); it != pts2.end(); it++)
cout << *it << endl;
// Compute homography
Matrix<float> H = getHomography(pts1, pts2);
cout << "H=" << H / H(2, 2);
// Apply homography
panorama(I1, I2, H);
endGraphics();
return 0;
} | 31.337719 | 110 | 0.447306 | AmineKheldouni |
12e6c2e4c800db0f43c8e684214f56283e2a5c1b | 84 | hpp | C++ | tests/wf/operators/shift_equal_continuation.hpp | GuillaumeDua/CppShelf | fc559010a5e38cecfd1967ebbbba21fd4b38e5ee | [
"MIT"
] | 3 | 2021-12-09T20:02:51.000Z | 2022-03-23T09:22:58.000Z | tests/wf/operators/shift_equal_continuation.hpp | GuillaumeDua/CppShelf | fc559010a5e38cecfd1967ebbbba21fd4b38e5ee | [
"MIT"
] | 31 | 2021-08-11T16:14:43.000Z | 2022-03-31T11:45:24.000Z | tests/wf/operators/shift_equal_continuation.hpp | GuillaumeDua/CppShelf | fc559010a5e38cecfd1967ebbbba21fd4b38e5ee | [
"MIT"
] | null | null | null | #pragma once
#include <csl/wf.hpp>
namespace test::wf::operators::shift_equal {
}
| 12 | 44 | 0.714286 | GuillaumeDua |
12e704d2048d8696df6c3977c76a7d017c261b4e | 1,740 | cpp | C++ | graphs/prims.cpp | sumanbanerjee1/Algorithms-and-data-structures | 0bc61036c398bd3cea5f7ddf80535520de3a33fa | [
"Apache-2.0"
] | null | null | null | graphs/prims.cpp | sumanbanerjee1/Algorithms-and-data-structures | 0bc61036c398bd3cea5f7ddf80535520de3a33fa | [
"Apache-2.0"
] | null | null | null | graphs/prims.cpp | sumanbanerjee1/Algorithms-and-data-structures | 0bc61036c398bd3cea5f7ddf80535520de3a33fa | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<bits/stdc++.h>
# define inf INT_MAX
using namespace std;
typedef pair<int,int> iPair;
class Graph{
int v;
list< pair<int,int> > *adj;
public:
Graph(int vert)
{
v=vert;
adj = new list< pair<int,int> > [vert];
}
void addEdge(int u,int v,int w)
{
adj[u].push_back(make_pair(w,v));
adj[v].push_back(make_pair(w,u));
}
void disp()
{
for(int i=0;i<v;i++)
{
cout<<i<<"->";
list < pair<int,int> > :: iterator j;
for(j = adj[i].begin();j!=adj[i].end();j++)
cout<<"("<<(*j).second<<","<<(*j).first<<")->";
cout<<endl;
}
}
long int prims(int s)
{
priority_queue <iPair , vector<iPair>, greater<iPair> > pq;
vector<int> dist(v,inf);
dist[s]=0;
pq.push(make_pair(0,s));
vector<bool> inMST(v,false);
inMST[s] = true;
vector<int> parent(v,-1);
while(!pq.empty())
{
int u=pq.top().second;
pq.pop();
inMST[u] = true;
for(list< pair<int,int> > :: iterator j = adj[u].begin(); j!=adj[u].end(); j++)
{
int node = (*j).second;
if(inMST[node]==false and dist[node]>(*j).first)
{
dist[node] = (*j).first;
pq.push(make_pair(dist[node],node));
parent[node] = u;
}
}
}
long int sum=0;
for(int i=0;i<v;i++)
sum+= dist[i];
return sum;
}
};
int main()
{
Graph *g = new Graph(9);
g->addEdge(0, 1, 4);
g->addEdge(0, 7, 8);
g->addEdge(1, 2, 8);
g->addEdge(1, 7, 11);
g->addEdge(2, 3, 7);
g->addEdge(2, 8, 2);
g->addEdge(2, 5, 4);
g->addEdge(3, 4, 9);
g->addEdge(3, 5, 14);
g->addEdge(4, 5, 10);
g->addEdge(5, 6, 2);
g->addEdge(6, 7, 1);
g->addEdge(6, 8, 6);
g->addEdge(7, 8, 7);
//g->disp();
cout<<g->prims(0);
return 1;
} | 16.571429 | 82 | 0.518966 | sumanbanerjee1 |
12ea2d804ede4cec09704ec28598eeb24492f26f | 4,479 | hpp | C++ | dakota-6.3.0.Windows.x86/include/HOPSPACK_utils.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/HOPSPACK_utils.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | null | null | null | dakota-6.3.0.Windows.x86/include/HOPSPACK_utils.hpp | seakers/ExtUtils | b0186098063c39bd410d9decc2a765f24d631b25 | [
"BSD-2-Clause"
] | 1 | 2022-03-18T14:13:14.000Z | 2022-03-18T14:13:14.000Z | // $Id: HOPSPACK_utils.hpp 203 2012-05-14 22:27:30Z tplante $
// $URL: https://software.sandia.gov/svn/hopspack/tags/dakota-6.3/src/src-shared/HOPSPACK_utils.hpp $
//@HEADER
// ************************************************************************
//
// HOPSPACK: Hybrid Optimization Parallel Search Package
// Copyright 2009 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// This file is part of HOPSPACK.
//
// HOPSPACK is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library. If not, see http://www.gnu.org/licenses/.
//
// Questions? Contact Tammy Kolda (tgkolda@sandia.gov)
// or Todd Plantenga (tplante@sandia.gov)
//
// ************************************************************************
//@HEADER
/*!
\file HOPSPACK_utils.hpp
\brief No classes - declare utility functions in the HOPSPACK namespace.
*/
#ifndef HOPSPACK_UTILS_HPP
#define HOPSPACK_UTILS_HPP
#include "HOPSPACK_common.hpp"
#include "HOPSPACK_ParameterList.hpp"
namespace HOPSPACK
{
/*! Get the next string on the given line, starting at
position pos.
\param line - Line of text from which to read
\param pos - On input, the starting position in the line. On output,
the next position after the string (which may be
std::string::npos). If there is any sort of error, this is set to
std::string::npos upon return.
\param value - On output, filled in with the next string (i.e., the
next contiguous block of non-space characters). This is an empty
string if no string is found.
\retval Returns true if the string is successfully found,
false otherwise.
*/
bool getNextString(const string& line, string::size_type& pos, string& value);
/*! Get the next string on the given line, starting at
position pos, and convert it to a double.
\param line - Line of text from which to read
\param pos - On input, the starting position in the line. On output,
the next position after the string (which may be
std::string::npos). If there is any sort of error in reading the
next string, this is set to std::string::npos upon return.
\param value - On output, filled in with the double value constrained
in the next string (i.e., the next contiguous block of non-space
characters).
\retval Returns true if the next string contains a double,
false otherwise.
*/
bool getNextDouble(const string& line, string::size_type& pos, double& value);
/*! Get the next string on the given line, starting at
position pos, and convert it to a int.
\param[in] line - Line of text from which to read
\param[in,out] pos - On input, the starting position in the line. On output,
the next position after the string (which may be
std::string::npos). If there is any sort of error in reading the
next string, this is set to std::string::npos upon return.
\param[out] value - On output, filled in with the int value constrained
in the next string (i.e., the next contguous block of non-space
characters).
\retval Returns true if the next string contains an integer, false otherwise.
*/
bool getNextInt(const string& line, string::size_type& pos, int& value);
/*!
\brief Helper function for parseTextInputFile.
*/
bool processTextInputFileLine(const string& line,
ParameterList& params,
ParameterList*& subPtr,
ifstream &fin);
/*!
\brief Parse an HOPSPACK input file and store the data in the given parameter list.
\param filename - The file name.
\param params - The parameter list that is to be filled in by this
function
\return Returns false if there are any problems parsing the input
file, true otherwise.
*/
bool parseTextInputFile(const string filename, ParameterList& params);
}
#endif
| 32.693431 | 102 | 0.686314 | seakers |
12ebbe81215360c5ec694657e40dc4aa19622a20 | 9,527 | cpp | C++ | test/OpenDDLExportTest.cpp | lerppana/openddl-parser | a9bc8a5dee880d546136e33a5977d7a0a28eaa20 | [
"MIT"
] | 24 | 2015-02-08T23:16:05.000Z | 2021-07-15T07:31:08.000Z | test/OpenDDLExportTest.cpp | lerppana/openddl-parser | a9bc8a5dee880d546136e33a5977d7a0a28eaa20 | [
"MIT"
] | 64 | 2015-01-28T21:42:06.000Z | 2021-11-01T07:49:24.000Z | test/OpenDDLExportTest.cpp | lerppana/openddl-parser | a9bc8a5dee880d546136e33a5977d7a0a28eaa20 | [
"MIT"
] | 10 | 2015-11-17T09:18:57.000Z | 2021-10-06T18:59:05.000Z | /*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014-2020 Kim Kulling
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 "gtest/gtest.h"
#include "UnitTestCommon.h"
#include <openddlparser/DDLNode.h>
#include <openddlparser/OpenDDLExport.h>
#include <openddlparser/Value.h>
BEGIN_ODDLPARSER_NS
class OpenDDLExportMock : public OpenDDLExport {
public:
OpenDDLExportMock() :
OpenDDLExport() {
// empty
}
virtual ~OpenDDLExportMock() {
// empty
}
virtual bool writeNodeHeaderTester(DDLNode *node, std::string &statement) {
return writeNodeHeader(node, statement);
}
virtual bool writePropertiesTester(DDLNode *node, std::string &statement) {
return writeProperties(node, statement);
}
virtual bool writeValueTypeTester(Value::ValueType type, size_t numItems, std::string &statement) {
return writeValueType(type, numItems, statement);
}
virtual bool writeValueTester(Value *val, std::string &statement) {
return writeValue(val, statement);
}
virtual bool writeValueArrayTester(DataArrayList *al, std::string &statement) {
return writeValueArray(al, statement);
}
};
class OpenDDLExportTest : public testing::Test {
public:
DDLNode *m_root;
protected:
void SetUp() override {
m_root = createNodeHierarchy();
}
void TearDown() override {
delete m_root;
m_root = nullptr;
}
DDLNode *createNodeHierarchy() {
DDLNode *root = DDLNode::create("test", "root");
for (uint32 i = 0; i < 10; i++) {
DDLNode *node(DDLNode::create("test", "child"));
node->attachParent(root);
}
return root;
}
Property *createProperties(size_t numProps) {
if (0 == numProps) {
return nullptr;
}
Property *prop(nullptr), *first(nullptr), *prev(nullptr);
for (size_t i = 0; i < numProps; i++) {
static const size_t Size = 256;
char buffer[Size];
::memset(buffer, 0, Size);
sprintf(buffer, "id.%d", static_cast<int>(i));
Text *id = new Text(buffer, strlen(buffer));
Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32);
v->setInt32(static_cast<int>(i));
prop = new Property(id);
prop->m_value = v;
if (nullptr == first) {
first = prop;
}
if (nullptr != prev) {
prev->m_next = prop;
}
prev = prop;
}
return first;
}
};
TEST_F(OpenDDLExportTest, createTest) {
bool ok(true);
try {
OpenDDLExport myExport;
} catch (...) {
ok = false;
}
EXPECT_TRUE(ok);
}
TEST_F(OpenDDLExportTest, handleNodeTest) {
OpenDDLExport myExport;
bool success(true);
success = myExport.handleNode(m_root);
EXPECT_TRUE(success);
}
TEST_F(OpenDDLExportTest, writeNodeHeaderTest) {
OpenDDLExportMock myExport;
bool ok(true);
std::string statement;
ok = myExport.writeNodeHeaderTester(nullptr, statement);
EXPECT_FALSE(ok);
DDLNode *node(DDLNode::create("test", ""));
node->attachParent(m_root);
ok = myExport.writeNodeHeaderTester(node, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("test", statement);
statement.clear();
ok = myExport.writeNodeHeaderTester(m_root, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("test $root", statement);
}
TEST_F(OpenDDLExportTest, writeBoolTest) {
OpenDDLExportMock myExport;
Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_bool);
v->setBool(true);
std::string statement;
bool ok(true);
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("true", statement);
v->setBool(false);
statement.clear();
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("false", statement);
ValueAllocator::releasePrimData(&v);
}
TEST_F(OpenDDLExportTest, writeIntegerTest) {
OpenDDLExportMock myExport;
Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int8);
v->setInt8(10);
bool ok(true);
std::string statement;
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("10", statement);
ValueAllocator::releasePrimData(&v);
statement.clear();
v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int16);
v->setInt16(655);
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("655", statement);
ValueAllocator::releasePrimData(&v);
statement.clear();
v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32);
v->setInt32(65501);
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("65501", statement);
ValueAllocator::releasePrimData(&v);
statement.clear();
v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int64);
v->setInt64(65502);
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("65502", statement);
ValueAllocator::releasePrimData(&v);
}
TEST_F(OpenDDLExportTest, writeFloatTest) {
OpenDDLExportMock myExport;
Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_float);
v->setFloat(1.1f);
bool ok(true);
std::string statement;
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("1.1", statement);
ValueAllocator::releasePrimData(&v);
}
TEST_F(OpenDDLExportTest, writeStringTest) {
OpenDDLExportMock myExport;
char tempString[] = "huhu";
Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_string, sizeof(tempString));
v->setString(tempString);
bool ok(true);
std::string statement;
ok = myExport.writeValueTester(v, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("\"huhu\"", statement);
ValueAllocator::releasePrimData(&v);
}
TEST_F(OpenDDLExportTest, writeValueTypeTest) {
OpenDDLExportMock myExporter;
bool ok(true);
std::string statement;
ok = myExporter.writeValueTypeTester(Value::ValueType::ddl_types_max, 1, statement);
EXPECT_FALSE(ok);
EXPECT_TRUE(statement.empty());
Value *v_int32 = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32);
ok = myExporter.writeValueTypeTester(v_int32->m_type, 1, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("int32", statement);
statement.clear();
delete v_int32;
Value *v_int32_array = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32);
ok = myExporter.writeValueTypeTester(v_int32_array->m_type, 10, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("int32[10]", statement);
delete v_int32_array;
}
TEST_F(OpenDDLExportTest, writePropertiesTest) {
OpenDDLExportMock myExporter;
bool ok(true);
std::string statement;
ok = myExporter.writePropertiesTester(nullptr, statement);
EXPECT_FALSE(ok);
Property *prop(createProperties(1));
m_root->setProperties(prop);
ok = myExporter.writePropertiesTester(m_root, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("(id.0 = 0)", statement);
statement.clear();
Property *prop2(createProperties(2));
m_root->setProperties(prop2);
ok = myExporter.writePropertiesTester(m_root, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("(id.0 = 0, id.1 = 1)", statement);
}
TEST_F(OpenDDLExportTest, writeValueArrayTest) {
OpenDDLExportMock myExporter;
bool ok(true);
std::string statement;
ok = myExporter.writeValueArrayTester(nullptr, statement);
EXPECT_FALSE(ok);
EXPECT_TRUE(statement.empty());
char token[] =
"float[ 3 ]\n"
"{\n"
" {1, 2, 3}\n"
"}\n";
size_t len(0);
char *end = findEnd(token, len);
DataArrayList *dataArrayList = nullptr;
Value::ValueType type;
char *in = OpenDDLParser::parsePrimitiveDataType(token, end, type, len);
ASSERT_EQ(Value::ValueType::ddl_float, type);
ASSERT_EQ(3U, len);
in = OpenDDLParser::parseDataArrayList(in, end, type, &dataArrayList);
ASSERT_FALSE(nullptr == dataArrayList);
ok = myExporter.writeValueArrayTester(dataArrayList, statement);
EXPECT_TRUE(ok);
EXPECT_EQ("{ 1, 2, 3 }", statement);
delete dataArrayList;
}
END_ODDLPARSER_NS
| 30.4377 | 103 | 0.65771 | lerppana |
12eea4cf8d075f0f2846a72b60c340db33b652de | 4,856 | cpp | C++ | files/soko1/qutim_0.1.1/protocol/oscar/icq/multiplesending.cpp | truebsdorg/truebsdorg.github.io | 8663d8f6fae3b1bb1e2fb29614677f2863521951 | [
"BSD-4-Clause-UC"
] | null | null | null | files/soko1/qutim_0.1.1/protocol/oscar/icq/multiplesending.cpp | truebsdorg/truebsdorg.github.io | 8663d8f6fae3b1bb1e2fb29614677f2863521951 | [
"BSD-4-Clause-UC"
] | null | null | null | files/soko1/qutim_0.1.1/protocol/oscar/icq/multiplesending.cpp | truebsdorg/truebsdorg.github.io | 8663d8f6fae3b1bb1e2fb29614677f2863521951 | [
"BSD-4-Clause-UC"
] | null | null | null | /*
multipleSending
Copyright (c) 2008 by Rustam Chakin <qutim.develop@gmail.com>
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
*/
#include "treegroupitem.h"
#include "treebuddyitem.h"
#include "icqmessage.h"
#include "multiplesending.h"
multipleSending::multipleSending(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
setWindowTitle(tr("Send multiple"));
setWindowIcon(QIcon(":/icons/crystal_project/multiple.png"));
move(desktopCenter());
ui.contactListWidget->header()->hide();
QList<int> listSize;
listSize.append(408);
listSize.append(156);
ui.splitter->setSizes(listSize);
sendTimer = new QTimer(this);
connect(sendTimer, SIGNAL(timeout()), this, SLOT(sendMessage()));
}
multipleSending::~multipleSending()
{
}
void multipleSending::rellocateDialogToCenter(QWidget *widget)
{
QDesktopWidget desktop;
// Get current screen num
int curScreen = desktop.screenNumber(widget);
// Get available geometry of the screen
QRect screenGeom = desktop.availableGeometry(curScreen);
// Let's calculate point to move dialog
QPoint moveTo(screenGeom.left(), screenGeom.top());
moveTo.setX(moveTo.x() + screenGeom.width() / 2);
moveTo.setY(moveTo.y() + screenGeom.height() / 2);
moveTo.setX(moveTo.x() - this->size().width() / 2);
moveTo.setY(moveTo.y() - this->size().height() / 2);
this->move(moveTo);
}
void multipleSending::setTreeModel(const QString &uin, const QHash<quint16, treeGroupItem *> *groupList, const QHash<QString, treeBuddyItem *> *buddyList)
{
rootItem = new QTreeWidgetItem(ui.contactListWidget);
rootItem->setText(0, uin);
rootItem->setFlags(rootItem->flags() | Qt::ItemIsUserCheckable);
rootItem->setCheckState(0, Qt::Unchecked);
foreach(treeGroupItem *getgroup, *groupList)
{
QTreeWidgetItem *group = new QTreeWidgetItem(rootItem);
group->setText(0,getgroup->name);
group->setFlags(group->flags() | Qt::ItemIsUserCheckable);
group->setCheckState(0, Qt::Unchecked);
foreach(treeBuddyItem *getbuddy, *buddyList)
{
if ( getbuddy->groupName == getgroup->name)
{
QTreeWidgetItem *buddy = new QTreeWidgetItem(group);
buddy->setText(0,getbuddy->getName());
buddy->setIcon(0, getbuddy->icon(0));
buddy->setFlags(buddy->flags() | Qt::ItemIsUserCheckable);
buddy->setCheckState(0, Qt::Unchecked);
buddy->setToolTip(0,getbuddy->getUin());
}
}
if ( group->childCount() )
group->setExpanded(true);
}
if ( rootItem->childCount() )
rootItem->setExpanded(true);
}
void multipleSending::on_contactListWidget_itemChanged(QTreeWidgetItem *item, int )
{
if ( item->childCount() )
{
Qt::CheckState checkState = item->checkState(0);
for ( int i = 0; i < item->childCount(); i++)
{
item->child(i)->setCheckState(0,checkState);
}
}
}
QPoint multipleSending::desktopCenter()
{
QDesktopWidget desktop;
return QPoint(desktop.width() / 2 - size().width() / 2, desktop.height() / 2 - size().height() / 2);
}
void multipleSending::on_sendButton_clicked()
{
if ( !ui.messageEdit->toPlainText().isEmpty())
{
ui.sendButton->setEnabled(false);
ui.stopButton->setEnabled(true);
for( int i = 0; i < rootItem->childCount(); i++)
{
QTreeWidgetItem *group = rootItem->child(i);
for ( int j = 0; j < group->childCount(); j++)
{
if ( !group->child(j)->toolTip(0).isEmpty() && group->child(j)->checkState(0))
sendToList<<group->child(j)->toolTip(0);
}
}
barInterval = sendToList.count();
if (barInterval)
{
sendMessage();
}
else
on_stopButton_clicked();
}
}
void multipleSending::on_stopButton_clicked()
{
ui.sendButton->setEnabled(true);
ui.stopButton->setEnabled(false);
sendToList.clear();
sendTimer->stop();
ui.progressBar->setValue(0);
}
void multipleSending::sendMessage()
{
if ( !ui.messageEdit->toPlainText().isEmpty())
{
if ( sendToList.count() )
{
messageFormat msg;
msg.date = QDateTime::currentDateTime();
msg.fromUin = sendToList.at(0);
msg.message = ui.messageEdit->toPlainText();
emit sendMessageToContact(msg);
sendToList.removeAt(0);
sendTimer->start(2000);
ui.progressBar->setValue(ui.progressBar->value() + 100 / barInterval );
if ( !sendToList.count() )
on_stopButton_clicked();
} else
on_stopButton_clicked();
} else
on_stopButton_clicked();
}
| 27.280899 | 154 | 0.644563 | truebsdorg |
12f00818638db4fb4442d04bef80cc851d808e1c | 1,926 | cpp | C++ | Game/ui/documentmenu.cpp | da3m0nsec/OpenGothic | af30c52309cb84ff338d42554610679e0e245f91 | [
"MIT"
] | null | null | null | Game/ui/documentmenu.cpp | da3m0nsec/OpenGothic | af30c52309cb84ff338d42554610679e0e245f91 | [
"MIT"
] | null | null | null | Game/ui/documentmenu.cpp | da3m0nsec/OpenGothic | af30c52309cb84ff338d42554610679e0e245f91 | [
"MIT"
] | null | null | null | #include "documentmenu.h"
#include "utils/gthfont.h"
#include "gothic.h"
using namespace Tempest;
DocumentMenu::DocumentMenu(Gothic& gothic)
:gothic(gothic) {
}
void DocumentMenu::show(const DocumentMenu::Show &doc) {
document = doc;
active = true;
update();
}
void DocumentMenu::close() {
if(!active)
return;
active=false;
if(auto pl = gothic.player())
pl->setInteraction(nullptr);
}
void DocumentMenu::keyDownEvent(KeyEvent &e) {
if(!active){
e.ignore();
return;
}
if(e.key!=Event::K_ESCAPE){
e.ignore();
return;
}
close();
}
void DocumentMenu::keyUpEvent(KeyEvent&) {
}
void DocumentMenu::paintEvent(PaintEvent &e) {
if(!active)
return;
float mw = 0, mh = 0;
for(auto& i:document.pages){
auto back = Resources::loadTexture((i.flg&F_Backgr) ? i.img : document.img);
if(!back)
continue;
mw += float(back->w());
mh = std::max(mh,float(back->h()));
}
float k = std::min(1.f,float(800+document.margins.xMargin())/std::max(mw,1.f));
int x=(w()-int(k*mw))/2, y = (h()-int(mh))/2;
Painter p(e);
for(auto& i:document.pages){
const GthFont* fnt = nullptr;
if(i.flg&F_Font)
fnt = &Resources::font(i.font.c_str()); else
fnt = &Resources::font(document.font.c_str());
if(fnt==nullptr)
fnt = &Resources::font();
auto back = Resources::loadTexture((i.flg&F_Backgr) ? i.img : document.img);
if(!back)
continue;
auto& mgr = (i.flg&F_Margin) ? i.margins : document.margins;
const int w = int(k*float(back->w()));
p.setBrush(*back);
p.drawRect(x,y,w,back->h(),
0,0,back->w(),back->h());
p.setBrush(Color(0.04f,0.04f,0.04f,1));
fnt->drawText(p,x+mgr.left,
y+mgr.top,
w - mgr.xMargin(),
back->h() - mgr.yMargin(),
i.text, Tempest::AlignLeft);
x+=w;
}
}
| 21.640449 | 81 | 0.573209 | da3m0nsec |
12f31d7d66104c07eb40b842fac64512ce7d4837 | 1,017 | cpp | C++ | Engine/src/DebugPass.cpp | Swizzman/DV1573_Stort_Spel | 77ed6524988b0b501d9b556c487a36d929a20313 | [
"MIT"
] | 3 | 2022-01-29T12:05:53.000Z | 2022-02-20T16:00:26.000Z | Engine/src/DebugPass.cpp | Swizzman/Homehearth | 77ed6524988b0b501d9b556c487a36d929a20313 | [
"MIT"
] | null | null | null | Engine/src/DebugPass.cpp | Swizzman/Homehearth | 77ed6524988b0b501d9b556c487a36d929a20313 | [
"MIT"
] | null | null | null | #include "EnginePCH.h"
#include "BasePass.h"
void DebugPass::PreRender(Camera* pCam, ID3D11DeviceContext* pDeviceContext)
{
DC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
DC->IASetInputLayout(PM->m_defaultInputLayout.Get());
DC->VSSetShader(PM->m_defaultVertexShader.Get(), nullptr, 0);
DC->PSSetShader(PM->m_debugPixelShader.Get(), nullptr, 0);
DC->VSSetConstantBuffers(1, 1, pCam->m_viewConstantBuffer.GetAddressOf());
DC->RSSetViewports(1, &PM->m_viewport);
DC->RSSetState(PM->m_rasterStateWireframe.Get());
DC->OMSetRenderTargets(1, PM->m_backBuffer.GetAddressOf(), PM->m_debugDepthStencilView.Get());
//DC->OMSetDepthStencilState(PM->m_depthStencilStateEqualAndDisableDepthWrite.Get(), 0);
}
void DebugPass::Render(Scene* pScene)
{
pScene->RenderDebug();
}
void DebugPass::PostRender(ID3D11DeviceContext* pDeviceContext)
{
// Cleanup.
//ID3D11ShaderResourceView* nullSRV[] = { nullptr };
//DC->PSSetShaderResources(0, 1, nullSRV);
}
| 31.78125 | 98 | 0.73648 | Swizzman |
12f336ca54ddf12ba3c8afa32ed6fbf1c4610928 | 410 | cpp | C++ | Practise/0-1背包.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | Practise/0-1背包.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | Practise/0-1背包.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int m,n;
cin>>n>>m;
int a[5001],b[5001];
int dp[501][501];
for(int i=1;i<=n;i++)
cin>>b[i];
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++)
{
for(int j=m;j>0;j--)
{
if(a[i]<=j)
dp[i][j]=max(dp[i-1][j],dp[i-1][j-a[i]]+b[i]);
else dp[i][j]=dp[i-1][j];
}
}
cout<<dp[n][m]<<endl;
}
| 17.083333 | 48 | 0.436585 | windcry1 |
12f9ed1bfd569b99c78754fff91318080f6565de | 1,115 | cc | C++ | day06/main.cc | HappyCerberus/moderncpp-aoc-2021 | 0973201f2e1c2c6c2900162e3829a68477818ced | [
"MIT"
] | 20 | 2021-12-04T04:53:22.000Z | 2022-02-24T23:37:31.000Z | day06/main.cc | HappyCerberus/moderncpp-aoc-2021 | 0973201f2e1c2c6c2900162e3829a68477818ced | [
"MIT"
] | null | null | null | day06/main.cc | HappyCerberus/moderncpp-aoc-2021 | 0973201f2e1c2c6c2900162e3829a68477818ced | [
"MIT"
] | 1 | 2022-01-04T22:12:05.000Z | 2022-01-04T22:12:05.000Z | #include "lanternfish.h"
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "This program expects one parameter that is the input file to read.\n";
return 1;
}
std::ifstream input(argv[1]);
if (!input.is_open()) {
std::cerr << "Failed to open file.\n";
return 1;
}
std::string starting_pop;
if (!getline(input, starting_pop))
throw std::runtime_error("Failed to read input.");
constexpr const uint32_t days_part1 = 80;
{
Population pop;
init_population(pop, starting_pop);
for (uint32_t i = 0; i < days_part1; i++)
simulate_day(pop);
std::cout << "Simulated population size of lanternfish after " << days_part1 << " is " << total_pop_count(pop) << "\n";
}
constexpr const uint32_t days_part2 = 256;
{
Population pop;
init_population(pop, starting_pop);
for (uint32_t i = 0; i < days_part2; i++)
simulate_day(pop);
std::cout << "Simulated population size of lanternfish after " << days_part2 << " is " << total_pop_count(pop) << "\n";
}
return 0;
} | 27.875 | 123 | 0.636771 | HappyCerberus |
12fe5a69ec6ca62a21385ca1c1c89d205758bd44 | 7,569 | cpp | C++ | Samples/RnD/DDGI/SVGFPass.cpp | guoxx/DDGI | cc8b6b8194ff4473cdf21f72754a103cd6f8526d | [
"BSD-3-Clause"
] | 15 | 2019-11-12T21:45:58.000Z | 2022-02-08T07:07:06.000Z | Samples/RnD/DDGI/SVGFPass.cpp | guoxx/DDGI | cc8b6b8194ff4473cdf21f72754a103cd6f8526d | [
"BSD-3-Clause"
] | 1 | 2020-01-16T07:21:23.000Z | 2020-02-07T02:39:27.000Z | Samples/RnD/DDGI/SVGFPass.cpp | guoxx/DDGI | cc8b6b8194ff4473cdf21f72754a103cd6f8526d | [
"BSD-3-Clause"
] | 3 | 2020-05-16T12:35:34.000Z | 2022-01-23T07:30:47.000Z | #include "SVGFPass.h"
using namespace Falcor;
SVGFPass::SharedPtr SVGFPass::create(uint32_t width, uint32_t height)
{
return std::make_shared<SVGFPass>(width, height);
}
SVGFPass::SVGFPass(uint32_t width, uint32_t height)
: mAtrousIterations(4),
mFeedbackTap(1),
mAtrousRadius(2),
mAlpha(0.15f),
mMomentsAlpha(0.2f),
mPhiColor(10.0f),
mPhiNormal(128.0f),
mEnableTemporalReprojection(true),
mEnableSpatialVarianceEstimation(true)
{
Fbo::Desc reprojFboDesc;
reprojFboDesc.setColorTarget(0, ResourceFormat::RGBA16Float); // Input signal, variance
reprojFboDesc.setColorTarget(1, ResourceFormat::RG16Float); // 1st and 2nd Moments
reprojFboDesc.setColorTarget(2, ResourceFormat::R16Float); // History length
mCurrReprojFbo = FboHelper::create2D(width, height, reprojFboDesc);
mPrevReprojFbo = FboHelper::create2D(width, height, reprojFboDesc);
Fbo::Desc atrousFboDesc;
atrousFboDesc.setColorTarget(0, ResourceFormat::RGBA16Float); // Input signal, variance
mOutputFbo = FboHelper::create2D(width, height, atrousFboDesc);
mLastFilteredFbo = FboHelper::create2D(width, height, atrousFboDesc);
mAtrousPingFbo = FboHelper::create2D(width, height, atrousFboDesc);
mAtrousPongFbo = FboHelper::create2D(width, height, atrousFboDesc);
mPrevLinearZTexture = Texture::create2D(width, height, ResourceFormat::RGBA32Float, 1, 1, nullptr, ResourceBindFlags::ShaderResource | ResourceBindFlags::RenderTarget);
mReprojectionPass = FullScreenPass::create("SVGF_Reprojection.slang");
mReprojectionVars = GraphicsVars::create(mReprojectionPass->getProgram()->getReflector());
mReprojectionState = GraphicsState::create();
mVarianceEstimationPass = FullScreenPass::create("SVGF_VarianceEstimation.slang");
mVarianceEstimationVars = GraphicsVars::create(mVarianceEstimationPass->getProgram()->getReflector());
mVarianceEstimationState = GraphicsState::create();
mAtrousPass = FullScreenPass::create("SVGF_Atrous.slang");
mAtrousPass->getProgram()->addDefine("ATROUS_RADIUS", std::to_string(mAtrousRadius));
mAtrousVars = GraphicsVars::create(mAtrousPass->getProgram()->getReflector());
mAtrousState = GraphicsState::create();
}
SVGFPass::~SVGFPass()
{
}
Texture::SharedPtr SVGFPass::Execute(
RenderContext* renderContext,
Texture::SharedPtr inputSignal,
Texture::SharedPtr motionVec,
Texture::SharedPtr linearZ,
Texture::SharedPtr normalDepth)
{
GPU_EVENT(renderContext, "SVGF");
mGBufferInput.inputSignal = inputSignal;
mGBufferInput.linearZ = linearZ;
mGBufferInput.motionVec = motionVec;
mGBufferInput.compactNormalDepth = normalDepth;
TemporalReprojection(renderContext);
SpatialVarianceEstimation(renderContext);
for (uint32_t i = 0; i < mAtrousIterations; ++i)
{
Fbo::SharedPtr output = (i == mAtrousIterations - 1) ? mOutputFbo : mAtrousPongFbo;
AtrousFilter(renderContext, i, mAtrousPingFbo, output);
if (i == std::min(mFeedbackTap, mAtrousIterations-1))
{
renderContext->blit(output->getColorTexture(0)->getSRV(), mLastFilteredFbo->getColorTexture(0)->getRTV(), uvec4(-1), uvec4(-1), Sampler::Filter::Point);
}
std::swap(mAtrousPingFbo, mAtrousPongFbo);
}
std::swap(mCurrReprojFbo, mPrevReprojFbo);
renderContext->blit(mGBufferInput.linearZ->getSRV(), mPrevLinearZTexture->getRTV(), uvec4(-1), uvec4(-1), Sampler::Filter::Point);
return mOutputFbo->getColorTexture(0);
}
void SVGFPass::TemporalReprojection(RenderContext* renderContext)
{
GPU_EVENT(renderContext, "TemporalReprojection");
mReprojectionVars->setTexture("gInputSignal", mGBufferInput.inputSignal);
mReprojectionVars->setTexture("gLinearZ", mGBufferInput.linearZ);
mReprojectionVars->setTexture("gMotion", mGBufferInput.motionVec);
mReprojectionVars->setTexture("gPrevLinearZ", mPrevLinearZTexture);
mReprojectionVars->setTexture("gPrevInputSignal", mLastFilteredFbo->getColorTexture(0));
mReprojectionVars->setTexture("gPrevMoments", mPrevReprojFbo->getColorTexture(1));
mReprojectionVars->setTexture("gHistoryLength", mPrevReprojFbo->getColorTexture(2));
mReprojectionVars["PerPassCB"]["gAlpha"] = mAlpha;
mReprojectionVars["PerPassCB"]["gMomentsAlpha"] = mMomentsAlpha;
mReprojectionVars["PerPassCB"]["gEnableTemporalReprojection"] = mEnableTemporalReprojection;
mReprojectionState->setFbo(mCurrReprojFbo);
renderContext->pushGraphicsState(mReprojectionState);
renderContext->pushGraphicsVars(mReprojectionVars);
mReprojectionPass->execute(renderContext);
renderContext->popGraphicsVars();
renderContext->popGraphicsState();
}
void SVGFPass::SpatialVarianceEstimation(RenderContext* renderContext)
{
GPU_EVENT(renderContext, "SpatialVarianceEstimation");
mVarianceEstimationVars->setTexture("gCompactNormDepth", mGBufferInput.compactNormalDepth);
mVarianceEstimationVars->setTexture("gInputSignal", mCurrReprojFbo->getColorTexture(0));
mVarianceEstimationVars->setTexture("gMoments", mCurrReprojFbo->getColorTexture(1));
mVarianceEstimationVars->setTexture("gHistoryLength", mCurrReprojFbo->getColorTexture(2));
mVarianceEstimationVars["PerPassCB"]["gPhiColor"] = mPhiColor;
mVarianceEstimationVars["PerPassCB"]["gPhiNormal"] = mPhiNormal;
mVarianceEstimationVars["PerPassCB"]["gEnableSpatialVarianceEstimation"] = mEnableSpatialVarianceEstimation;
mVarianceEstimationState->setFbo(mAtrousPingFbo);
renderContext->pushGraphicsState(mVarianceEstimationState);
renderContext->pushGraphicsVars(mVarianceEstimationVars);
mVarianceEstimationPass->execute(renderContext);
renderContext->popGraphicsVars();
renderContext->popGraphicsState();
}
void SVGFPass::AtrousFilter(RenderContext* renderContext, uint32_t iteration, Fbo::SharedPtr input, Fbo::SharedPtr output)
{
GPU_EVENT(renderContext, "AtrousFilter");
mAtrousVars->setTexture("gCompactNormDepth", mGBufferInput.compactNormalDepth);
mAtrousVars->setTexture("gInputSignal", input->getColorTexture(0));
mAtrousVars["PerPassCB"]["gStepSize"] = 1u << iteration;
mAtrousVars["PerPassCB"]["gPhiColor"] = mPhiColor;
mAtrousVars["PerPassCB"]["gPhiNormal"] = mPhiNormal;
mAtrousState->setFbo(output);
renderContext->pushGraphicsState(mAtrousState);
renderContext->pushGraphicsVars(mAtrousVars);
mAtrousPass->execute(renderContext);
renderContext->popGraphicsVars();
renderContext->popGraphicsState();
}
void SVGFPass::RenderGui(Gui* gui, const char* group)
{
if (gui->beginGroup(group))
{
gui->addCheckBox("Temporal Reprojection", mEnableTemporalReprojection);
gui->addCheckBox("Spatial Variance Estimation", mEnableSpatialVarianceEstimation);
gui->addFloatSlider("Color Alpha", mAlpha, 0.0f, 1.0f);
gui->addFloatSlider("Moments Alpha", mMomentsAlpha, 0.0f, 1.0f);
gui->addFloatSlider("Phi Color", mPhiColor, 0.0f, 64.0f);
gui->addFloatSlider("Phi Normal", mPhiNormal, 1.0f, 256.0f);
gui->addIntSlider("Atrous Iterations", *reinterpret_cast<int32_t*>(&mAtrousIterations), 1, 5);
gui->addIntSlider("Feedback Tap", *reinterpret_cast<int32_t*>(&mFeedbackTap), 1, 5);
if (gui->addIntSlider("Atrous Radius", *reinterpret_cast<int32_t*>(&mAtrousRadius), 1, 2))
{
mAtrousPass->getProgram()->addDefine("ATROUS_RADIUS", std::to_string(mAtrousRadius));
}
gui->endGroup();
}
}
| 41.81768 | 172 | 0.742767 | guoxx |
12fec15170acfc423d45b41856c648420d8cd3c6 | 1,900 | cpp | C++ | tests/test_lfringbuffer.cpp | zxjcarrot/iris | ec9dbb0b41895a41fe259c777ec79bfff353f96f | [
"MIT"
] | 3 | 2020-12-28T08:36:17.000Z | 2022-01-03T14:08:37.000Z | tests/test_lfringbuffer.cpp | zxjcarrot/iris | ec9dbb0b41895a41fe259c777ec79bfff353f96f | [
"MIT"
] | null | null | null | tests/test_lfringbuffer.cpp | zxjcarrot/iris | ec9dbb0b41895a41fe259c777ec79bfff353f96f | [
"MIT"
] | 1 | 2018-02-09T03:19:39.000Z | 2018-02-09T03:19:39.000Z | #include <thread>
#include <string>
#include <assert.h>
#include <lfringbuffer.h>
#include <sslfqueue.h>
#include <define.h>
using namespace iris;
#define ITERATIONS (int)1e7
lfringbuffer rbuf(1024);
struct buffer_t {
char * b;
int size;
int alloc_size;
int data;
};
sslfqueue<buffer_t> q;
void recyle() {
int i = 1;
while (i <= ITERATIONS) {
buffer_t b;
while (!q.poll(b))
std::this_thread::yield();
assert(std::stoi(std::string(b.b, b.b + b.size)) == b.data);
rbuf.release(b.alloc_size);
++i;
}
}
int main(int argc, char const *argv[]) {
char *p1;
char *p2;
char *p3;
assert(512 == rbuf.acquire(512, p1));
assert(p1);
assert(256 == rbuf.acquire(256, p2));
assert(p2);
assert(p2 - p1 == 512);
assert(0 == rbuf.acquire(512, p1));
assert(rbuf.freespace() == 256);
assert(0 == rbuf.acquire(512, p3));
rbuf.release(512);
assert(768 == rbuf.acquire(512, p3));
printf("rbuf.freespace(): %lu\n", rbuf.freespace());
assert(rbuf.freespace() == 0);
rbuf.release(256);
printf("rbuf.freespace(): %lu\n", rbuf.freespace());
assert(256 == rbuf.freespace());
rbuf.release(768);
printf("rbuf.freespace(): %lu\n", rbuf.freespace());
assert(1024 == rbuf.freespace());
std::thread recyler(recyle);
int i = 1;
while (i <= ITERATIONS) {
std::string s(std::to_string(i));
buffer_t b;
char *ptr;
int size;
while (!(size = rbuf.acquire(s.size(), ptr)))
std::this_thread::yield();
b.b = ptr;
memcpy(b.b, s.c_str(), s.size());
b.size = s.size();
b.alloc_size = size;
b.data = i;
while (!q.offer(b))
std::this_thread::yield();
++i;
}
recyler.join();
printf("passed\n");
return 0;
}
| 20 | 68 | 0.540526 | zxjcarrot |
4203d42f2e3627f188b6bdb185210525479f5d7c | 5,986 | cpp | C++ | src/app/main.cpp | balintfodor/Build3D | b735129e380a414d62a1d91556f5f52674f1f6f9 | [
"MIT"
] | null | null | null | src/app/main.cpp | balintfodor/Build3D | b735129e380a414d62a1d91556f5f52674f1f6f9 | [
"MIT"
] | 5 | 2021-03-19T09:28:07.000Z | 2022-03-12T00:09:14.000Z | src/app/main.cpp | balintfodor/Build3D | b735129e380a414d62a1d91556f5f52674f1f6f9 | [
"MIT"
] | 1 | 2019-12-23T16:44:49.000Z | 2019-12-23T16:44:49.000Z | #include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <QApplication>
#include <QtGlobal>
#include <QOpenGLContext>
#include <QQmlApplicationEngine>
#include <QFontDatabase>
#include <QStyleFactory>
#include <QCommandLineParser>
#include <QDir>
// #include "client/crashpad_client.h"
// #include "client/crash_report_database.h"
// #include "client/settings.h"
#include "version.h"
#include "LogCollector.h"
#include "VolumeData.h"
#include "VolumeTexture.h"
#include "TurnTableCameraController.h"
#include "BackendStore.h"
#include "BackendOutput.h"
#include "GlobalSettings.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
using namespace std;
// using namespace crashpad;
// static bool startCrashHandler()
// {
// map<string, string> annotations;
// vector<string> arguments;
// CrashpadClient client;
// bool rc;
// #ifdef _WIN32
// wchar_t exePathChar[2048];
// wstring exePath(exePathChar, GetModuleFileName(NULL, exePathChar, 2048));
// exePath = exePath.substr(0, exePath.rfind('\\'));
// // TODO: change it to AppData since Program Files is readonly for the application
// wstring db_path(exePath + L"\\crashes");
// wstring handler_path(exePath + L"\\crashpad_handler.exe");
// wcout << handler_path << endl;
// #else
// string db_path("crashes/");
// string handler_path("./crashpad_handler");
// #endif
// string url("https://a3dc.sp.backtrace.io:6098");
// annotations["token"] = "e8c10c5d9cd420229c8d21a7d6c365ea88a4dae0d79bc2cc8c4623b851d8bf02";
// annotations["format"] = "minidump";
// base::FilePath db(db_path);
// base::FilePath handler(handler_path);
// arguments.push_back("--no-rate-limit");
// unique_ptr<CrashReportDatabase> database =
// crashpad::CrashReportDatabase::Initialize(db);
// if (database == nullptr || database->GetSettings() == NULL)
// return false;
// database->GetSettings()->SetUploadsEnabled(true);
// rc = client.StartHandler(handler, db, db, url, annotations, arguments, true, false);
// return rc;
// }
void setSurfaceFormat()
{
QSurfaceFormat format;
if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) {
format.setVersion(3, 2);
format.setProfile(QSurfaceFormat::CoreProfile);
}
format.setDepthBufferSize(24);
format.setSamples(0);
format.setStencilBufferSize(8);
QSurfaceFormat::setDefaultFormat(format);
}
int main(int argc, char* argv[])
{
// ensure logging is alive from the first moment
LogCollector::instance();
// FIXME: trial period has expired at bactrace.io so no minidump upload can be done
// if (startCrashHandler() == false) {
// cout << "crash reporter could not start" << endl;
// return -1;
// }
qputenv("QT_STYLE_OVERRIDE", "Material");
QApplication::setStyle(QStyleFactory::create("Material"));
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
app.setOrganizationName("MTA KOKI KatonaLab");
app.setOrganizationDomain("koki.hu");
app.setApplicationName("A3DC (" + QString(_A3DC_BUILD_GIT_SHA) + QString(_A3DC_BUILD_PLATFORM) + ")");
// TODO: call setApplicationVersion
QCommandLineParser parser;
QCommandLineOption pythonHomeOption("python-home", "sets PYTHONHOME", "PY_HOME");
parser.addOption(pythonHomeOption);
QCommandLineOption modulePathOption("module-path", "sets the module path", "MODULE_PATH");
parser.addOption(modulePathOption);
QCommandLineOption editorOption("editor", "opens the program in editor mode");
parser.addOption(editorOption);
parser.process(app);
QString pythonHome = parser.value(pythonHomeOption);
QString modulePath = parser.value(modulePathOption);
GlobalSettings::editorMode = parser.isSet(editorOption);
if (pythonHome.isEmpty()) {
QByteArray venv = qgetenv("VIRTUAL_ENV");
if (venv.isEmpty()) {
pythonHome = QString("virtualenv");
}
else {
pythonHome = QString::fromLocal8Bit(venv);
}
}
qputenv("PYTHONHOME", pythonHome.toLocal8Bit());
if (!modulePath.isEmpty()) {
GlobalSettings::modulePath = modulePath;
}
else {
GlobalSettings::modulePath = QString("modules");
}
QString pythonPath = QString::fromLocal8Bit(qgetenv("PYTHONPATH"));
QDir d = GlobalSettings::modulePath;
d.cdUp();
if (pythonPath.isEmpty()) {
pythonPath = d.absolutePath();
}
else {
const QString envPathSep(QDir::listSeparator());
pythonPath = d.absolutePath() + envPathSep + pythonPath;
}
qputenv("PYTHONPATH", pythonPath.toLocal8Bit());
qInfo() << "PYTHONHOME:" << pythonHome;
qInfo() << "PYTHONPATH:" << pythonPath;
qInfo() << "module path:" << GlobalSettings::modulePath.absolutePath();
if (GlobalSettings::editorMode) {
qInfo() << "editor mode";
}
setSurfaceFormat();
qmlRegisterInterface<ImageOutputValue>("ImageOutputValue");
qmlRegisterType<VolumeTexture>("koki.katonalab.a3dc", 1, 0, "VolumeTexture");
qmlRegisterType<TurnTableCameraController>("koki.katonalab.a3dc", 1, 0, "TurnTableCameraController");
qmlRegisterSingletonType<A3DCVersion>("koki.katonalab.a3dc", 1, 0, "A3DCVersion", singletonA3DCVersionProvider);
// NOTE: it will initialize LogCollector and routes the all qDebug/qInfo... log through this instance
// see LogCollector.cpp for details
qmlRegisterSingletonType<LogCollector>("koki.katonalab.a3dc", 1, 0, "LogCollector", singletonLogCollectorProvider);
qmlRegisterInterface<BackendStoreItem>("BackendStoreItem");
qmlRegisterType<BackendStore>("koki.katonalab.a3dc", 1, 0, "BackendStore");
qmlRegisterType<BackendStoreFilter>("koki.katonalab.a3dc", 1, 0, "BackendStoreFilter");
if (QFontDatabase::addApplicationFont(":/assets/fonts/fontello.ttf") == -1) {
qWarning() << "Failed to load fontello.ttf";
}
QQmlApplicationEngine engine;
engine.load(QUrl("qrc:/qml/main.qml"));
return app.exec();
}
| 31.671958 | 119 | 0.705647 | balintfodor |
420584dddf7ea9ffe6fa2caa0c549145b39c5be7 | 1,011 | hpp | C++ | Engine/Code/Engine/Renderer/SpriteAnimDefinition.hpp | sam830917/TenNenDemon | a5f60007b73cccc6af8675c7f3dec597008dfdb4 | [
"MIT"
] | null | null | null | Engine/Code/Engine/Renderer/SpriteAnimDefinition.hpp | sam830917/TenNenDemon | a5f60007b73cccc6af8675c7f3dec597008dfdb4 | [
"MIT"
] | null | null | null | Engine/Code/Engine/Renderer/SpriteAnimDefinition.hpp | sam830917/TenNenDemon | a5f60007b73cccc6af8675c7f3dec597008dfdb4 | [
"MIT"
] | null | null | null | #pragma once
#include "SpriteSheet.hpp"
enum class SpriteAnimPlaybackType
{
ONCE, // for 5-frame anim, plays 0,1,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4...
LOOP, // for 5-frame anim, plays 0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0...
PINGPONG // for 5-frame anim, plays 0,1,2,3,4,3,2,1,0,1,2,3,4,3,2,1,0,1,2,3,4,3,2,1,0,1...
};
class SpriteAnimDefinition
{
public:
SpriteAnimDefinition( const SpriteSheet& sheet, int startSpriteIndex, int endSpriteIndex,
float durationSeconds, SpriteAnimPlaybackType playbackType = SpriteAnimPlaybackType::LOOP );
SpriteAnimDefinition( const SpriteSheet& sheet, const std::vector<int>& spriteIndexs,
float durationSeconds, SpriteAnimPlaybackType playbackType = SpriteAnimPlaybackType::LOOP );
const SpriteDefinition& GetSpriteDefAtTime( float seconds ) const;
private:
const SpriteSheet& m_spriteSheet;
float m_durationSeconds = 1.f;
SpriteAnimPlaybackType m_playbackType = SpriteAnimPlaybackType::LOOP;
std::vector<int> m_spriteIndexes;
};
| 37.444444 | 94 | 0.740851 | sam830917 |
42075bf31ee80b30fb7175f179f7b56b5a476549 | 339 | cpp | C++ | src/xgdial.cpp | msperl/Period | da4b4364e8228852cc2b82639470dab0b3579055 | [
"MIT"
] | 1 | 2019-12-10T20:13:11.000Z | 2019-12-10T20:13:11.000Z | src/xgdial.cpp | msperl/Period | da4b4364e8228852cc2b82639470dab0b3579055 | [
"MIT"
] | null | null | null | src/xgdial.cpp | msperl/Period | da4b4364e8228852cc2b82639470dab0b3579055 | [
"MIT"
] | null | null | null | /*
* Program: Period98
*
* File: xgdial.h
* Purpose: Implementation-file for
* ?
* Author: Martin Sperl
* Created: 1996
* Copyright: (c) 1996-1998, Martin Sperl
*/
#include "xgdial.h"
Bool myDialogBox::OnClose(void)
{
int result=wxDialogBox::OnClose();
Show(FALSE);
return result;
}
| 16.95 | 43 | 0.587021 | msperl |
420b724ad3961986b054359d68284129eee05771 | 645 | cpp | C++ | test/linux/router/service.cpp | justinc1/IncludeOS | 2ce07b04e7a35c8d96e773f041db32a4593ca3d0 | [
"Apache-2.0"
] | null | null | null | test/linux/router/service.cpp | justinc1/IncludeOS | 2ce07b04e7a35c8d96e773f041db32a4593ca3d0 | [
"Apache-2.0"
] | null | null | null | test/linux/router/service.cpp | justinc1/IncludeOS | 2ce07b04e7a35c8d96e773f041db32a4593ca3d0 | [
"Apache-2.0"
] | null | null | null | #include <service>
#include "async_device.hpp"
static std::unique_ptr<Async_device> dev2;
void Service::start()
{
extern void create_network_device(int N, const char* route, const char* ip);
create_network_device(0, "10.0.0.0/24", "10.0.0.1");
// Get the first IP stack configured from config.json
auto& inet = net::Super_stack::get<net::IP4>(0);
inet.network_config({10,0,0,42}, {255,255,255,0}, {10,0,0,1});
dev2 = std::make_unique<Async_device> (1500);
dev2->set_transmit(
[] (net::Packet_ptr) {
printf("Inside network dropping packet\n");
});
extern void register_plugin_nacl();
register_plugin_nacl();
}
| 28.043478 | 78 | 0.683721 | justinc1 |
420c3c03afaad46519b0bd79063348d7c72dbb6a | 10,468 | cpp | C++ | opcodes/dxil/dxil_compute.cpp | HansKristian-Work/DXIL2SPIRV | ea9ac33ae88c9efb0f864d473eb22c3c04d166a5 | [
"MIT"
] | 5 | 2019-11-07T13:14:56.000Z | 2019-12-09T20:01:47.000Z | opcodes/dxil/dxil_compute.cpp | HansKristian-Work/DXIL2SPIRV | ea9ac33ae88c9efb0f864d473eb22c3c04d166a5 | [
"MIT"
] | null | null | null | opcodes/dxil/dxil_compute.cpp | HansKristian-Work/DXIL2SPIRV | ea9ac33ae88c9efb0f864d473eb22c3c04d166a5 | [
"MIT"
] | null | null | null | /* Copyright (c) 2019-2022 Hans-Kristian Arntzen for Valve Corporation
*
* SPDX-License-Identifier: MIT
*
* 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 "dxil_compute.hpp"
#include "dxil_common.hpp"
#include "opcodes/converter_impl.hpp"
#include "spirv_module.hpp"
namespace dxil_spv
{
bool emit_barrier_instruction(Converter::Impl &impl, const llvm::CallInst *instruction)
{
auto &builder = impl.builder();
uint32_t operation;
if (!get_constant_operand(instruction, 1, &operation))
return false;
// Match DXC SPIR-V output here.
Operation *op = nullptr;
switch (static_cast<DXIL::BarrierMode>(operation))
{
case DXIL::BarrierMode::DeviceMemoryBarrierWithGroupSync:
op = impl.allocate(spv::OpControlBarrier);
op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup));
op->add_id(builder.makeUintConstant(spv::ScopeDevice));
op->add_id(
builder.makeUintConstant(spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsUniformMemoryMask |
spv::MemorySemanticsAcquireReleaseMask));
break;
case DXIL::BarrierMode::GroupMemoryBarrierWithGroupSync:
op = impl.allocate(spv::OpControlBarrier);
op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup));
op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup));
op->add_id(
builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask));
break;
case DXIL::BarrierMode::AllMemoryBarrierWithGroupSync:
op = impl.allocate(spv::OpControlBarrier);
op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup));
op->add_id(builder.makeUintConstant(spv::ScopeDevice));
op->add_id(
builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsImageMemoryMask |
spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask));
break;
case DXIL::BarrierMode::DeviceMemoryBarrier:
op = impl.allocate(spv::OpMemoryBarrier);
op->add_id(builder.makeUintConstant(spv::ScopeDevice));
op->add_id(
builder.makeUintConstant(spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsUniformMemoryMask |
spv::MemorySemanticsAcquireReleaseMask));
break;
case DXIL::BarrierMode::GroupMemoryBarrier:
op = impl.allocate(spv::OpMemoryBarrier);
op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup));
op->add_id(
builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask));
break;
case DXIL::BarrierMode::AllMemoryBarrier:
op = impl.allocate(spv::OpMemoryBarrier);
op->add_id(builder.makeUintConstant(spv::ScopeDevice));
op->add_id(
builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsImageMemoryMask |
spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask));
break;
default:
return false;
}
impl.add(op);
return true;
}
static bool emit_thread_2d_quad_fixup_instruction(spv::BuiltIn builtin, Converter::Impl &impl,
const llvm::CallInst *instruction, uint32_t component)
{
// We have to compute everything from scratch. Sigh ... <_>
auto &builder = impl.builder();
spv::Id local_thread_id = impl.spirv_module.get_builtin_shader_input(spv::BuiltInLocalInvocationId);
{
auto *load_op = impl.allocate(spv::OpLoad, builder.makeVectorType(builder.makeUintType(32), 3));
load_op->add_id(local_thread_id);
impl.add(load_op);
local_thread_id = load_op->id;
}
spv::Id comp_ids[3] = {};
const bool require[3] = {
true,
component >= 1 || builtin == spv::BuiltInLocalInvocationIndex,
builtin == spv::BuiltInLocalInvocationIndex
};
for (unsigned i = 0; i < 3; i++)
{
if (require[i])
{
auto *extract_op = impl.allocate(spv::OpCompositeExtract, builder.makeUintType(32));
extract_op->add_id(local_thread_id);
extract_op->add_literal(i);
impl.add(extract_op);
comp_ids[i] = extract_op->id;
}
}
if (require[1])
{
// Y * 2 + ((X >> 1) & 1).
auto *x_part = impl.allocate(spv::OpBitFieldUExtract, builder.makeUintType(32));
x_part->add_id(comp_ids[0]);
x_part->add_id(builder.makeUintConstant(1));
x_part->add_id(builder.makeUintConstant(1));
impl.add(x_part);
auto *y_part = impl.allocate(spv::OpIMul, builder.makeUintType(32));
y_part->add_id(comp_ids[1]);
y_part->add_id(builder.makeUintConstant(2));
impl.add(y_part);
auto *add_part = impl.allocate(spv::OpIAdd, builder.makeUintType(32));
add_part->add_id(x_part->id);
add_part->add_id(y_part->id);
impl.add(add_part);
comp_ids[1] = add_part->id;
}
{
// Reconstruct X. In a group of 4 threads, we should see [0, 1, 0, 1], but for different Ys.
auto *and_op = impl.allocate(spv::OpBitwiseAnd, builder.makeUintType(32));
and_op->add_id(comp_ids[0]);
and_op->add_id(builder.makeUintConstant(1));
impl.add(and_op);
auto *shift_down = impl.allocate(spv::OpShiftRightLogical, builder.makeUintType(32));
shift_down->add_id(comp_ids[0]);
shift_down->add_id(builder.makeUintConstant(2));
impl.add(shift_down);
auto *shift_up = impl.allocate(spv::OpShiftLeftLogical, builder.makeUintType(32));
shift_up->add_id(shift_down->id);
shift_up->add_id(builder.makeUintConstant(1));
impl.add(shift_up);
auto *or_op = impl.allocate(spv::OpBitwiseOr, builder.makeUintType(32));
or_op->add_id(and_op->id);
or_op->add_id(shift_up->id);
impl.add(or_op);
comp_ids[0] = or_op->id;
}
// Reconstruct the flattened index.
if (builtin == spv::BuiltInLocalInvocationIndex)
{
auto *y_base_op = impl.allocate(spv::OpIMul, builder.makeUintType(32));
y_base_op->add_id(comp_ids[1]);
y_base_op->add_id(builder.makeUintConstant(impl.execution_mode_meta.workgroup_threads[0] / 2));
impl.add(y_base_op);
auto *z_base_op = impl.allocate(spv::OpIMul, builder.makeUintType(32));
z_base_op->add_id(comp_ids[2]);
z_base_op->add_id(builder.makeUintConstant(
impl.execution_mode_meta.workgroup_threads[0] * impl.execution_mode_meta.workgroup_threads[1]));
impl.add(z_base_op);
auto *add_op = impl.allocate(spv::OpIAdd, builder.makeUintType(32));
add_op->add_id(y_base_op->id);
add_op->add_id(z_base_op->id);
impl.add(add_op);
auto *final_add_op = impl.allocate(spv::OpIAdd, instruction);
final_add_op->add_id(add_op->id);
final_add_op->add_id(comp_ids[0]);
impl.add(final_add_op);
}
else if (builtin == spv::BuiltInLocalInvocationId)
{
impl.rewrite_value(instruction, comp_ids[component]);
}
else
{
spv::Id wg_id = impl.spirv_module.get_builtin_shader_input(spv::BuiltInWorkgroupId);
auto *ptr_wg = impl.allocate(spv::OpAccessChain,
builder.makePointer(spv::StorageClassInput, builder.makeUintType(32)));
ptr_wg->add_id(wg_id);
ptr_wg->add_id(builder.makeUintConstant(component));
impl.add(ptr_wg);
auto *load_wg = impl.allocate(spv::OpLoad, builder.makeUintType(32));
load_wg->add_id(ptr_wg->id);
impl.add(load_wg);
auto *base_thread = impl.allocate(spv::OpIMul, builder.makeUintType(32));
base_thread->add_id(load_wg->id);
if (component == 0)
base_thread->add_id(builder.makeUintConstant(impl.execution_mode_meta.workgroup_threads[component] / 2));
else // if (component == 1)
base_thread->add_id(builder.makeUintConstant(impl.execution_mode_meta.workgroup_threads[component] * 2));
impl.add(base_thread);
auto *final_add = impl.allocate(spv::OpIAdd, instruction);
final_add->add_id(base_thread->id);
final_add->add_id(comp_ids[component]);
impl.add(final_add);
}
return true;
}
bool emit_thread_id_load_instruction(spv::BuiltIn builtin, Converter::Impl &impl, const llvm::CallInst *instruction)
{
// This appears to always be constant, not unlike all other input loading instructions.
// Any attempt to dynamically index forces alloca.
uint32_t component = 0;
if (builtin != spv::BuiltInLocalInvocationIndex && !get_constant_operand(instruction, 1, &component))
return false;
// Querying Z component for ThreadId or ThreadIdInGroup doesn't change with 2D quad fixup, just use normal path.
// Need to consider ThreadId.xy, ThreadIdInGroup.xy and FlattenedThreadIdInGroup.
if (builtin != spv::BuiltInWorkgroupId && impl.execution_mode_meta.synthesize_2d_quad_dispatch && component <= 1)
return emit_thread_2d_quad_fixup_instruction(builtin, impl, instruction, component);
// Awkward NVIDIA workaround. If loading LocalInvocationId, check if we can return constant 0.
// This is key to avoid some particular shader compiler bugs.
if (builtin == spv::BuiltInLocalInvocationId)
{
if (component <= 2 && impl.execution_mode_meta.workgroup_threads[component] == 1)
{
spv::Id const_zero = impl.builder().makeUintConstant(0);
impl.rewrite_value(instruction, const_zero);
return true;
}
}
spv::Id var_id = impl.spirv_module.get_builtin_shader_input(builtin);
if (builtin != spv::BuiltInLocalInvocationIndex)
{
Operation *op =
impl.allocate(spv::OpAccessChain,
impl.builder().makePointer(spv::StorageClassInput, impl.get_type_id(instruction->getType())));
op->add_id(var_id);
op->add_id(impl.get_id_for_value(instruction->getOperand(1)));
impl.add(op);
var_id = op->id;
}
Operation *op = impl.allocate(spv::OpLoad, instruction);
op->add_id(var_id);
impl.add(op);
return true;
}
} // namespace dxil_spv
| 36.729825 | 116 | 0.734142 | HansKristian-Work |
420e527ead4e3ab10222a979e049da424ac337a7 | 9,252 | cpp | C++ | Sources/Elastos/Frameworks/Droid/DevSamples/bak/DownloadDemo/CActivityOne.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/DevSamples/bak/DownloadDemo/CActivityOne.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/DevSamples/bak/DownloadDemo/CActivityOne.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z |
#include "CActivityOne.h"
#include "R.h"
#include <elastos/utility/logging/Slogger.h>
using Elastos::Core::CStringWrapper;
using Elastos::Core::EIID_IRunnable;
using Elastos::Utility::Logging::Slogger;
using Elastos::Droid::App::CDownloadManagerRequest;
using Elastos::Droid::Content::CIntentFilter;
using Elastos::Droid::Net::CUriHelper;
using Elastos::Droid::Net::IUriHelper;
using Elastos::Droid::Os::IEnvironment;
using Elastos::Droid::Provider::IDownloadsImpl;
using Elastos::Droid::View::EIID_IViewOnClickListener;
using Elastos::Droid::Widget::IToast;
using Elastos::Droid::Widget::CToastHelper;
using Elastos::Droid::Widget::IToastHelper;
namespace Elastos {
namespace Droid {
namespace DevSamples {
namespace DownloadDemo {
CActivityOne::MyListener::MyListener(
/* [in] */ CActivityOne* host)
: mHost(host)
{
}
PInterface CActivityOne::MyListener::Probe(
/* [in] */ REIID riid)
{
if (riid == EIID_IInterface) {
return (PInterface)(IViewOnClickListener*)this;
}
else if (riid == EIID_IViewOnClickListener) {
return (IViewOnClickListener*)this;
}
return NULL;
}
UInt32 CActivityOne::MyListener::AddRef()
{
return ElRefBase::AddRef();
}
UInt32 CActivityOne::MyListener::Release()
{
return ElRefBase::Release();
}
ECode CActivityOne::MyListener::GetInterfaceID(
/* [in] */ IInterface *pObject,
/* [out] */ InterfaceID *pIID)
{
if (pIID == NULL) {
return E_INVALID_ARGUMENT;
}
if (pObject == (IInterface*)(IViewOnClickListener*)this) {
*pIID = EIID_IViewOnClickListener;
}
else {
return E_INVALID_ARGUMENT;
}
return NOERROR;
}
ECode CActivityOne::MyListener::OnClick(
/* [in] */ IView* v)
{
Slogger::E("CActivityOne", __FUNCTION__);
// AutoPtr<ICharSequence> text;
// mHost->mText->GetText((ICharSequence**)&text);
String textStr("http://down10.zol.com.cn/zoldown/wrar501@89734@.exe");
// String textStr("http://f.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=eb86871cb21c8701d6e3bae0174fb217/d53f8794a4c27d1e17ee023c1ad5ad6edcc43879.jpg");
// String textStr;
// text->ToString(&textStr);
AutoPtr<IUriHelper> helper;
CUriHelper::AcquireSingleton((IUriHelper**)&helper);
AutoPtr<IUri> uri;
helper->Parse(textStr, (IUri**)&uri);
AutoPtr<IDownloadManagerRequest> request;
CDownloadManagerRequest::New(uri, (IDownloadManagerRequest**)&request);
request->SetAllowedNetworkTypes(IDownloadManagerRequest::NETWORK_MOBILE | IDownloadManagerRequest::NETWORK_WIFI);
AutoPtr<ICharSequence> cs;
CStringWrapper::New(String("Updating"), (ICharSequence**)&cs);
request->SetTitle(cs);
cs = NULL;
CStringWrapper::New(String("Downloading file"), (ICharSequence**)&cs);
request->SetDescription(cs);
request->SetDestinationInExternalPublicDir(IEnvironment::DIRECTORY_DOWNLOADS, String("rar.exe"));
Int32 id;
v->GetId(&id);
switch (id) {
case R::id::download: {
Slogger::E("CActivityOne", "click download");
mHost->mDownloadManager->Enqueue(request, &mHost->mDownloadId);
Boolean result;
mHost->mHandler->PostDelayed(mHost->mRunnable, 1000, &result);
break;
}
case R::id::rm: {
Slogger::E("CActivityOne", "click remove");
AutoPtr<ArrayOf<Int64> > idArray = ArrayOf<Int64>::Alloc(1);
idArray->Set(0, mHost->mDownloadId);
Int32 result;
mHost->mDownloadManager->Remove(idArray, &result);
break;
}
}
return NOERROR;
}
CAR_INTERFACE_IMPL(CActivityOne::MyRunnable, IRunnable);
ECode CActivityOne::MyRunnable::Run()
{
Int32 status = 0;
AutoPtr<IDownloadManagerQuery> query;
CDownloadManagerQuery::New((IDownloadManagerQuery**)&query);
AutoPtr<ArrayOf<Int64> > idArray = ArrayOf<Int64>::Alloc(1);
idArray->Set(0, mHost->mDownloadId);
query->SetFilterById(idArray);
AutoPtr<ICursor> cursor;
mHost->mDownloadManager->Query(query, (ICursor**)&cursor);
Slogger::E("CActivityOne", "the cursor: %p", cursor.Get());
Int32 count;
cursor->GetCount(&count);
if (count > 0) {
Boolean tofirst;
cursor->MoveToFirst(&tofirst);
Boolean afterLast;
cursor->IsAfterLast(&afterLast);
while (!afterLast) {
Int32 index;
cursor->GetColumnIndex(IDownloadManager::COLUMN_STATUS, &index);
cursor->GetInt32(index, &status);
Slogger::E("CActivityOne", "the status: %d", status);
if (status == IDownloadManager::STATUS_RUNNING) {
Slogger::E("CActivityOne", "the download is running");
Boolean result;
mHost->mHandler->PostDelayed(mHost->mRunnable, 1000, &result);
} else if (status == IDownloadManager::STATUS_PAUSED) {
Slogger::E("CActivityOne", "the download is paused");
} else if (status == IDownloadManager::STATUS_SUCCESSFUL) {
Slogger::E("CActivityOne", "the download is successful");
} else if (status == IDownloadManager::STATUS_FAILED) {
Slogger::E("CActivityOne", "the download is failed");
} else if (status == IDownloadManager::STATUS_PENDING) {
Slogger::E("CActivityOne", "the downlod is pending");
}
Boolean hasNext;
cursor->MoveToNext(&hasNext);
cursor->IsAfterLast(&afterLast);
}
}
if (cursor != NULL) cursor->Close();
return NOERROR;
}
ECode CActivityOne::MyReceiver::OnReceive(
/* [in] */ IContext* context,
/* [in] */ IIntent* intent)
{
Slogger::E("CActivityOne", __FUNCTION__);
String action;
intent->GetAction(&action);
if (IDownloadManager::ACTION_DOWNLOAD_COMPLETE.Equals(action)) {
Slogger::E("CActivityOne", "recevice the action ACTION_DOWNLOAD_COMPLETE");
Int64 downloadId;
intent->GetInt64Extra(IDownloadManager::EXTRA_DOWNLOAD_ID, 0, &downloadId);
AutoPtr<IDownloadManagerQuery> query;
CDownloadManagerQuery::New((IDownloadManagerQuery**)&query);
AutoPtr<ArrayOf<Int64> > idArray = ArrayOf<Int64>::Alloc(1);
idArray->Set(0, downloadId);
query->SetFilterById(idArray);
AutoPtr<ICursor> c;
mHost->mDownloadManager->Query(query, (ICursor**)&c);
Boolean first;
c->MoveToFirst(&first);
if (first) {
Int32 columnIndex;
c->GetColumnIndex(IDownloadManager::COLUMN_STATUS, &columnIndex);
Int32 status;
c->GetInt32(columnIndex, &status);
if (IDownloadManager::STATUS_SUCCESSFUL == status) {
c->GetColumnIndex(IDownloadManager::COLUMN_LOCAL_URI, &columnIndex);
String uriString;
c->GetString(columnIndex, &uriString);
Slogger::E("CActivityOne", "the local uri: %s", uriString.string());
AutoPtr<IToastHelper> thelper;
CToastHelper::AcquireSingleton((IToastHelper**)&thelper);
AutoPtr<ICharSequence> cs;
CStringWrapper::New(String("get file complete: ") + uriString, (ICharSequence**)&cs);
AutoPtr<IToast> toast;
thelper->MakeText(IContext::Probe(this),
cs, 0, (IToast**)&toast);
toast->Show();
}
}
if (c != NULL) c->Close();
} else if (IDownloadsImpl::ACTION_DOWNLOAD_COMPLETED.Equals(action)) {
Slogger::E("CActivityOne", "recevice the action ACTION_DOWNLOAD_COMPLETED");
}
return NOERROR;
}
ECode CActivityOne::OnCreate(
/* [in] */ IBundle* savedInstanceState)
{
Activity::OnCreate(savedInstanceState);
SetContentView(R::layout::main);
CHandler::New((IHandler**)&mHandler);
mRunnable = new MyRunnable(this);
AutoPtr<IView> view = FindViewById(R::id::download);
mDBt = IButton::Probe(view);
view = NULL;
view = FindViewById(R::id::rm);
mRBt = IButton::Probe(view);
// get download service and set request
AutoPtr<IInterface> service;
GetSystemService(IContext::DOWNLOAD_SERVICE, (IInterface**)&service);
mDownloadManager = IDownloadManager::Probe(service);
// set listener
AutoPtr<MyListener> l = new MyListener(this);
mDBt->SetOnClickListener(l);
mRBt->SetOnClickListener(l);
return NOERROR;
}
ECode CActivityOne::OnStart()
{
return Activity::OnStart();
}
ECode CActivityOne::OnResume()
{
AutoPtr<IIntentFilter> filter;
CIntentFilter::New(IDownloadManager::ACTION_DOWNLOAD_COMPLETE, (IIntentFilter**)&filter);
filter->AddAction(IDownloadsImpl::ACTION_DOWNLOAD_COMPLETED);
mReceiver = new MyReceiver(this);
AutoPtr<IIntent> intent;
RegisterReceiver(mReceiver, filter, (IIntent**)&intent);
return Activity::OnResume();
}
ECode CActivityOne::OnPause()
{
UnregisterReceiver(mReceiver);
return Activity::OnPause();
}
ECode CActivityOne::OnStop()
{
return Activity::OnStop();
}
ECode CActivityOne::OnDestroy()
{
return Activity::OnDestroy();
}
} // namespace DownloadDemo
} // namespace DevSamples
} // namespace Droid
} // namespace Elastos
| 32.808511 | 158 | 0.647752 | jingcao80 |
4210c2aaf8f2187a480a4b39fb5310b42836d22a | 772 | hpp | C++ | pal/src/include/pal/handleapi.hpp | Taritsyn/ChakraCore | b6042191545a823fcf9d53df2b09d160d5808f51 | [
"MIT"
] | 8,664 | 2016-01-13T17:33:19.000Z | 2019-05-06T19:55:36.000Z | pal/src/include/pal/handleapi.hpp | Taritsyn/ChakraCore | b6042191545a823fcf9d53df2b09d160d5808f51 | [
"MIT"
] | 5,058 | 2016-01-13T17:57:02.000Z | 2019-05-04T15:41:54.000Z | pal/src/include/pal/handleapi.hpp | Taritsyn/ChakraCore | b6042191545a823fcf9d53df2b09d160d5808f51 | [
"MIT"
] | 1,367 | 2016-01-13T17:54:57.000Z | 2019-04-29T18:16:27.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*++
Module Name:
handleapi.hpp
Abstract:
Declaration of the handle management APIs
--*/
#ifndef _HANDLEAPI_HPP
#define _HANDLEAPI_HPP
#include "corunix.hpp"
namespace CorUnix
{
PAL_ERROR
InternalDuplicateHandle(
CPalThread *pThread,
HANDLE hSourceProcess,
HANDLE hSource,
HANDLE hTargetProcess,
LPHANDLE phDuplicate,
DWORD dwDesiredAccess,
BOOL bInheritHandle,
DWORD dwOptions
);
PAL_ERROR
InternalCloseHandle(
CPalThread *pThread,
HANDLE hObject
);
}
#endif // _HANDLEAPI_HPP
| 15.44 | 102 | 0.65544 | Taritsyn |
4210f672c013214c16e1dc820db8b5711539fa04 | 1,288 | hpp | C++ | typed_python/PyPythonObjectOfTypeInstance.hpp | npang1/nativepython | df311a5614a9660c15a8183b2dc606ff3e4600df | [
"Apache-2.0"
] | null | null | null | typed_python/PyPythonObjectOfTypeInstance.hpp | npang1/nativepython | df311a5614a9660c15a8183b2dc606ff3e4600df | [
"Apache-2.0"
] | null | null | null | typed_python/PyPythonObjectOfTypeInstance.hpp | npang1/nativepython | df311a5614a9660c15a8183b2dc606ff3e4600df | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "PyInstance.hpp"
class PyPythonObjectOfTypeInstance : public PyInstance {
public:
typedef PythonObjectOfType modeled_type;
static void copyConstructFromPythonInstanceConcrete(PythonObjectOfType* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) {
int isinst = PyObject_IsInstance(pyRepresentation, (PyObject*)eltType->pyType());
if (isinst == -1) {
isinst = 0;
PyErr_Clear();
}
if (!isinst) {
throw std::logic_error("Object of type " + std::string(pyRepresentation->ob_type->tp_name) +
" is not an instance of " + ((PythonObjectOfType*)eltType)->pyType()->tp_name);
}
Py_INCREF(pyRepresentation);
((PyObject**)tgt)[0] = pyRepresentation;
return;
}
static bool pyValCouldBeOfTypeConcrete(modeled_type* type, PyObject* pyRepresentation) {
int isinst = PyObject_IsInstance(pyRepresentation, (PyObject*)type->pyType());
if (isinst == -1) {
isinst = 0;
PyErr_Clear();
}
return isinst > 0;
}
static PyObject* extractPythonObjectConcrete(PythonObjectOfType* valueType, instance_ptr data) {
return incref(*(PyObject**)data);
}
};
| 30.666667 | 149 | 0.63587 | npang1 |
4216d37a7ec815a46ba620348eafdf13133dc2ef | 2,103 | cpp | C++ | codes/HDU/hdu5402.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/HDU/hdu5402.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/HDU/hdu5402.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 105;
const int dir[2][4][2] = { {{0, -1}, {-1, 0}, {1, 0}, {0, 1}}, {{-1, 0}, {0, 1}, {0, -1}, {1, 0}} };
const char sig[2][5] = {"LUDR", "URLD"};
int N, M, A[maxn][maxn], V[maxn][maxn];
char str[maxn * maxn];
int build (const int d[4][2], const char* t) {
int x = 1, y = 1, n = 0; V[1][1] = 1;
while (true) {
bool flag = true;
for (int i = 0; i < 4 && flag; i++) {
int p = x + d[i][0];
int q = y + d[i][1];
if (p <= 0 || p > N || q <= 0 || q > M || V[p][q])
continue;
str[n++] = t[i]; V[p][q] = 1;
x = p, y = q, flag = false;
}
if (flag) break;
}
str[n] = '\0';
if (x == N && y == M)
return n;
return 0;
}
void build2 (const int d[4][2], const char* t, int& x, int &y, int& n, int l, int r) {
V[x][y] = 1;
while (true) {
// printf("%d %d\n", x, y);
bool flag = true;
for (int i = 0; i < 4 && flag; i++) {
int p = x + d[i][0];
int q = y + d[i][1];
if (p <= 0 || p > N || q <= l || q > r || V[p][q])
continue;
str[n++] = t[i]; V[p][q] = 1;
x = p, y = q, flag = false;
}
if (flag) break;;
}
// printf("end:%d %d\n", x, y);
}
int main () {
while (scanf("%d%d", &N, &M) == 2) {
memset(V, 0, sizeof(V));
int k = 1e4 + 5, rx, ry, s = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
scanf("%d", &A[i][j]);
s += A[i][j];
if (A[i][j] < k && ((i+j)&1)) {
k = A[i][j];
rx = i, ry = j;
}
}
}
int end = N * M - 1;
if ((N&1) == 0 && (M&1) == 0) {
s -= k;
int x = 1, y = 1, n = 0;
memset(V, 0, sizeof(V));
V[rx][ry] = 1;
for (int i = 1; i <= M; i += 2) {
if (i == ry || i + 1 == ry)
build2(dir[1], sig[1], x, y, n, y - 1, y + 1);
else
build2(dir[0], sig[0], x, y, n, y - 1, y + 1);
y++;
str[n++] = 'R';
}
str[n-1] = '\0';
} else {
memset(V, 0, sizeof(V));
int n = build(dir[0], sig[0]);
if (n != end) {
memset(V, 0, sizeof(V));
int n = build(dir[1], sig[1]);
}
}
printf("%d\n%s\n", s, str);
}
return 0;
}
| 21.03 | 100 | 0.406087 | JeraKrs |
421c63e7851ba31fb469dacf5023e6b3a74f3ca8 | 3,790 | cpp | C++ | RegionGrowingColor/prova.cpp | OttoBismark/DigitalImageProcessing | 83ecbe64efe8acb6ce6aea020125b2eba2569f30 | [
"MIT"
] | null | null | null | RegionGrowingColor/prova.cpp | OttoBismark/DigitalImageProcessing | 83ecbe64efe8acb6ce6aea020125b2eba2569f30 | [
"MIT"
] | null | null | null | RegionGrowingColor/prova.cpp | OttoBismark/DigitalImageProcessing | 83ecbe64efe8acb6ce6aea020125b2eba2569f30 | [
"MIT"
] | null | null | null | /*
Region Growing a colori
*/
#include <cstdlib>
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/video.hpp>
#include <iostream>
#include <stdio.h>
#include <opencv2/core/core.hpp>
#include <math.h>
#include <unistd.h>
#include <vector>
#include <iterator>
using namespace std;
using namespace cv;
void regionGrowingColorIterative(Mat img, vector<Point> vecPoint, Vec3b pixel, int T, Mat mask, Mat toModify)
{
while(!vecPoint.empty())
{
Point P = vecPoint.back();
int x = P.x;
int y = P.y;
vecPoint.pop_back();
for(int i=-1; i<=1; i++)
{
for(int j=-1; j<=1; j++)
{
if((x+i>=0) && (x+i<img.rows))
{
if((y+j>=0) && (y+j<img.cols))
{
int dist = sqrt(pow(pixel.val[0]-img.at<Vec3b>(x+i,y+j).val[0],2)+
pow(pixel.val[1]-img.at<Vec3b>(x+i,y+j).val[1],2)+
pow(pixel.val[2]-img.at<Vec3b>(x+i,y+j).val[2],2));
if(dist < T && mask.at<uchar>(x+i,y+j)==0)
{
mask.at<uchar>(x+i,y+j) = 1;
toModify.at<Vec3b>(x+i,y+j) = pixel;
vecPoint.push_back(Point(x+i,y+j));
}
}
}
}
}
}
}
void regionGrowingColor(Mat img,int x, int y, Vec3b pixel, int T, Mat mask, Mat toModify)
{
for(int i=-1; i<=1; i++)
{
for(int j=-1; j<=1; j++)
{
if((x+i>=0) && (x+i<img.rows))
{
if((y+j>=0) && (y+j<img.cols))
{
int dist = sqrt(pow(pixel.val[0]-img.at<Vec3b>(x+i,y+j).val[0],2)+
pow(pixel.val[1]-img.at<Vec3b>(x+i,y+j).val[1],2)+
pow(pixel.val[2]-img.at<Vec3b>(x+i,y+j).val[2],2));
if(dist < T && mask.at<uchar>(x+i,y+j)==0)
{
mask.at<uchar>(x+i,y+j) = 1;
toModify.at<Vec3b>(x+i,y+j) = pixel;
regionGrowingColor(img,x+i,y+j,pixel,T,mask,toModify);
}
}
}
}
}
}
int main(int argc, char **argv)
{
if(argv[1] == nullptr && argv[2] == nullptr)
{
cerr << "Inserire due argomenti da passare al main" << endl;
exit(-1);
}
Mat image = imread(argv[1], 1);
Mat outputImage = Mat::zeros(image.size(),image.type());
Mat mask = Mat::zeros(image.size(),image.type());
int xPixel,yPixel,range=10;
Vec3b pixel;
vector<Point> vecPoint;
if(!image.data)
{
cout << "Impossibile leggere l'immagine!\n" << endl;
exit(0);
}
for(int i=0; i<atoi(argv[2]); i++)
{
xPixel = rand()%image.rows;
yPixel = rand()%image.cols;
if(mask.at<uchar>(xPixel,yPixel) == 0)
{
mask.at<uchar>(xPixel,yPixel) = 1;
outputImage.at<Vec3b>(xPixel,yPixel) = image.at<Vec3b>(xPixel,yPixel);
pixel = image.at<Vec3b>(xPixel,yPixel);
vecPoint.clear();
vecPoint.push_back(Point(xPixel,yPixel));
//regionGrowingColor(image,xPixel,yPixel,pixel,range,mask,outputImage);
regionGrowingColorIterative(image,vecPoint,pixel,range,mask,outputImage);
}
else
{
i--;
}
}
namedWindow("Original",0);
imshow("Original",image);
namedWindow("RegionGrowing",0);
imshow("RegionGrowing",outputImage);
waitKey();
return 0;
}
| 28.712121 | 109 | 0.466755 | OttoBismark |
421ec7da40ccd4ce7e985263c3617f6c3beafa54 | 1,670 | hpp | C++ | lib/models/customer.hpp | lacriment/Hayyam | 488f274944df61562e19b02145a6fdbcf7dc88b1 | [
"MIT"
] | 2 | 2016-05-03T07:38:34.000Z | 2020-12-13T22:31:32.000Z | lib/models/customer.hpp | lacriment/Hayyam | 488f274944df61562e19b02145a6fdbcf7dc88b1 | [
"MIT"
] | null | null | null | lib/models/customer.hpp | lacriment/Hayyam | 488f274944df61562e19b02145a6fdbcf7dc88b1 | [
"MIT"
] | null | null | null | #ifndef CUSTOMER_HPP
#define CUSTOMER_HPP
#include <QObject>
#include <QString>
#include "city.hpp"
class Customer : public QObject
{
Q_OBJECT
private:
int m_Id;
QString m_tc;
QString m_name;
QString m_surname;
QString m_phone;
City *m_city;
QString m_address;
public:
explicit Customer(QObject *parent = 0);
Q_PROPERTY(int id READ getId WRITE setId NOTIFY idChanged)
Q_PROPERTY(QString tc READ getTc WRITE setTc NOTIFY tcChanged)
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged)
Q_PROPERTY(QString surname READ getSurname WRITE setSurname NOTIFY surnameChanged)
Q_PROPERTY(QString phone READ getPhone WRITE setPhone NOTIFY phoneChanged)
Q_PROPERTY(City* city READ getCity WRITE setCity NOTIFY cityChanged)
Q_PROPERTY(QString address READ getAddress WRITE setAddress NOTIFY addressChanged)
int getId() const;
QString getTc() const;
QString getName() const;
QString getSurname() const;
QString getPhone() const;
City *getCity() const;
QString getAddress() const;
signals:
void idChanged(int newId);
void tcChanged(QString newTc);
void nameChanged(QString newName);
void surnameChanged(QString newSurname);
void phoneChanged(QString newPhone);
void cityChanged(City *newCity);
void addressChanged(QString newAddress);
public slots:
void setId(int value);
void setTc(const QString &value);
void setName(const QString &value);
void setSurname(const QString &value);
void setPhone(const QString &value);
void setCity(City *city);
void setAddress(const QString &value);
};
#endif // CUSTOMER_HPP
| 27.377049 | 86 | 0.731138 | lacriment |
4220ddf754aceabd1d3f24bd1b872703805eeb7b | 278 | hh | C++ | netcode/detail/visibility.hh | ahamez/netcode | aee7eeca8081831574dfb82edf3450ee03be36a1 | [
"BSD-2-Clause"
] | 7 | 2016-10-11T12:12:42.000Z | 2022-02-16T09:54:05.000Z | netcode/detail/visibility.hh | ahamez/netcode | aee7eeca8081831574dfb82edf3450ee03be36a1 | [
"BSD-2-Clause"
] | 1 | 2021-01-13T17:31:11.000Z | 2021-01-13T17:32:16.000Z | netcode/detail/visibility.hh | ahamez/netcode | aee7eeca8081831574dfb82edf3450ee03be36a1 | [
"BSD-2-Clause"
] | 4 | 2016-04-25T21:26:18.000Z | 2020-11-20T21:31:38.000Z | #pragma once
/*------------------------------------------------------------------------------------------------*/
#define NTC_PUBLIC __attribute__ ((visibility ("default")))
/*------------------------------------------------------------------------------------------------*/
| 34.75 | 100 | 0.201439 | ahamez |
422465eb7bab342d3f42586d18b9683dfdefef45 | 1,706 | cpp | C++ | src/providers/mpi/connection.cpp | PeterJGeorg/pmr | e3022da0027313f947b0778188fad1a863fd7dbf | [
"Apache-2.0"
] | 6 | 2017-01-31T10:39:36.000Z | 2020-08-15T12:40:21.000Z | src/providers/mpi/connection.cpp | pjgeorg/pMR | e3022da0027313f947b0778188fad1a863fd7dbf | [
"Apache-2.0"
] | null | null | null | src/providers/mpi/connection.cpp | pjgeorg/pMR | e3022da0027313f947b0778188fad1a863fd7dbf | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 Peter Georg
//
// 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 "connection.hpp"
#include "../../backends/backend.hpp"
#include "../../backends/mpi/target.hpp"
#include "../../backends/mpi/threadsupport.hpp"
pMR::MPI::Connection::Connection(Target const &target)
: mCommunicator{target.getMPICommunicator()}
, mTargetRank{target.getTargetRank()}
, mThreadLevel{Backend::ThreadSupport().getLevel()}
{
mSendTag = {static_cast<int>(reinterpret_cast<std::intptr_t>(this) %
#ifdef MPI_TAG_NARROW
std::numeric_limits<std::uint16_t>::max())};
#else
std::numeric_limits<int>::max())};
#endif // MPI_TAG_NARROW
// Exchange a (hopefully) unique message tag with remote
Backend::exchange(target, mSendTag, mRecvTag);
}
MPI_Comm pMR::MPI::Connection::getCommunicator() const
{
return {mCommunicator};
}
int pMR::MPI::Connection::getTargetRank() const
{
return {mTargetRank};
}
int pMR::MPI::Connection::getSendTag() const
{
return {mSendTag};
}
int pMR::MPI::Connection::getRecvTag() const
{
return {mRecvTag};
}
enum pMR::ThreadLevel pMR::MPI::Connection::getThreadLevel() const
{
return {mThreadLevel};
}
| 28.433333 | 76 | 0.708675 | PeterJGeorg |
4228967ffd0e8e7f8735a54c212d0a7bffced7e9 | 64 | cpp | C++ | 3DEngine/Physics/OBB.cpp | EricDDK/3DEngineEEE | cf7832e69ba03111d54093b1f797eaabab3455e1 | [
"MIT"
] | 5 | 2019-07-23T03:21:04.000Z | 2020-08-28T09:09:08.000Z | 3DEngine/Physics/OBB.cpp | EricDDK/3DEngineEEE | cf7832e69ba03111d54093b1f797eaabab3455e1 | [
"MIT"
] | null | null | null | 3DEngine/Physics/OBB.cpp | EricDDK/3DEngineEEE | cf7832e69ba03111d54093b1f797eaabab3455e1 | [
"MIT"
] | 3 | 2019-07-25T01:36:02.000Z | 2020-02-15T08:11:19.000Z | #include "OBB.h"
ENGINE_NAMESPACE_START
ENGINE_NAMESPACE_END | 9.142857 | 22 | 0.828125 | EricDDK |
422a01aaedf0b837d43481314c423a82d9598ce4 | 428 | cpp | C++ | test/src/dummy.cpp | WojciechMigda/TCO-Ringbeller | 8447e6ff44bba84b85250bdd3905180fcf1a96aa | [
"MIT"
] | null | null | null | test/src/dummy.cpp | WojciechMigda/TCO-Ringbeller | 8447e6ff44bba84b85250bdd3905180fcf1a96aa | [
"MIT"
] | null | null | null | test/src/dummy.cpp | WojciechMigda/TCO-Ringbeller | 8447e6ff44bba84b85250bdd3905180fcf1a96aa | [
"MIT"
] | null | null | null | /*
* This file exists to satisfy modern CMake practices, as conveniently
* described here: https://github.com/Bagira80/More-Modern-CMake/
*
* I have decided not to go with the most modern CMake versions, as some
* linux distributions are still using rather dated CMake release packages.
*
* Hence, using less-than-latest CMake, with the rationale described in the
* quoted URL, requires presence of this dummy file.
*/
| 38.909091 | 75 | 0.754673 | WojciechMigda |
422d7cfc53b6ef303711742d998a759c59689269 | 2,935 | cpp | C++ | src/Canvas/NumberPadCanvas.cpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | 2 | 2020-10-23T19:53:56.000Z | 2020-11-06T08:59:48.000Z | src/Canvas/NumberPadCanvas.cpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | src/Canvas/NumberPadCanvas.cpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | #include "NumberPadCanvas.hpp"
NumberPadCanvas::NumberPadCanvas(Canvas * canvas, uint16_t id) : Canvas(canvas, id) {
for (uint8_t i=0;i<12;i++) {
char text[10];
snprintf(text, sizeof(text), "%d", i+1);
numberButtonsCanvas[i] = new TextCanvas(this, i);
numberButtonsCanvas[i]->setText(text);
numberButtonsCanvas[i]->onTouch([i, this](Canvas* canvas, TouchEvent event, TouchEventData)->bool{
if (isEventLosely(event, TouchEvent::TouchActionPressed)) {
if ((i < 9 && !this->isNumbersDisabled()) ||
(i == 9 && !this->isLeftButtonDisabled()) ||
(i == 11 && !this->isRightButtonDisabled()) ||
(i == 10 && !this->isNumbersDisabled())) {
canvas->setBgColor(this->pressedColor);
}
} else if (isEventLosely(event, TouchEvent::TouchActionTapped)) {
canvas->setBgColor(this->bgColor);
if (i<9) {
if (this->isNumbersDisabled()) {
return false;
}
return pressCallback(this, i+1);
} else if (i == 9) {
if (this->isLeftButtonDisabled()) {
return false;
}
return pressCallback(this, 10);
} else if (i == 10) {
if (this->isNumbersDisabled()) {
return false;
}
return pressCallback(this, 0);
} else {
if (this->isRightButtonDisabled()) {
return false;
}
return pressCallback(this, 11);
}
} else {
canvas->setBgColor(this->bgColor);
return false;
}
return false;
});
}
numberButtonsCanvas[9]->setText("");
numberButtonsCanvas[10]->setText("0");
numberButtonsCanvas[11]->setText("");
pressCallback = [](NumberPadCanvas*, uint8_t)->bool{return false;};
}
void NumberPadCanvas::resetLayout() {
uint16_t size = (this->width/3>this->height/4)?this->height/4:this->width/3;
uint16_t xOffset = getButtonX();
uint16_t yOffset = getButtonY();
for (uint8_t i=0;i<12;i++) {
numberButtonsCanvas[i]->setWidth(size);
numberButtonsCanvas[i]->setHeight(size);
numberButtonsCanvas[i]->setHAlign(ALIGN_CENTER);
numberButtonsCanvas[i]->setVAlign(ALIGN_MIDDLE);
uint8_t gridX = ((i)%3)*size;
uint8_t gridY = ((i)/3)*size;
numberButtonsCanvas[i]->setX(xOffset + gridX);
numberButtonsCanvas[i]->setY(yOffset + gridY);
}
} | 43.80597 | 106 | 0.479727 | RobinSinghNanda |
422f0cadcc4cba747dcf7969fa31b9c9316afcd1 | 2,286 | cpp | C++ | monad_test.cpp | XzoRit/cpp_monad | 9777f14d38c0df62cdaecfb286ae4d2f52777927 | [
"BSL-1.0"
] | null | null | null | monad_test.cpp | XzoRit/cpp_monad | 9777f14d38c0df62cdaecfb286ae4d2f52777927 | [
"BSL-1.0"
] | null | null | null | monad_test.cpp | XzoRit/cpp_monad | 9777f14d38c0df62cdaecfb286ae4d2f52777927 | [
"BSL-1.0"
] | null | null | null | #include "monad.hpp"
#include <boost/test/unit_test.hpp>
#include <cctype>
#include <iostream>
#include <variant>
namespace std
{
ostream& boost_test_print_type(ostream& ostr, monostate const& right)
{
ostr << "monostate";
return ostr;
}
}
struct init
{
init() { BOOST_TEST_MESSAGE("init"); }
~init() { BOOST_TEST_MESSAGE("~init"); }
};
using namespace std;
string str_toupper(string a)
{
transform(
a.begin(), a.end(), a.begin(), [](unsigned char c) { return toupper(c); });
return a;
}
BOOST_AUTO_TEST_SUITE(monad)
BOOST_FIXTURE_TEST_CASE(monad_lazy_value, init)
{
using namespace monad;
const auto a = lazy_value{ []() { return 2374; } };
BOOST_TEST(a() == 2374);
BOOST_TEST(a() == 2374);
}
BOOST_FIXTURE_TEST_CASE(monad_io_monostate, init)
{
const auto a = monad::io::make_action([]() { return monostate{}; });
BOOST_TEST(a() == monostate{});
}
BOOST_FIXTURE_TEST_CASE(monad_io_bind, init)
{
const auto a = monad::io::make_action([]() { return 1; })
.bind([](const auto& a) {
return monad::io::make_action([a]() { return a + 2; });
})
.bind([](const auto& a) {
return monad::io::make_action([a]() { return a + 3; });
});
BOOST_TEST(a() == 6);
const auto b = monad::io::make_action([]() { return string{ "1" }; }) |
[](const auto& a) {
return monad::io::make_action([a]() { return a + "2"; });
} |
[](const auto& a) {
return monad::io::make_action([a]() { return a + "3"; });
};
BOOST_TEST(b() == "123");
}
BOOST_FIXTURE_TEST_CASE(monad_io_fmap, init)
{
const auto a = monad::io::make_action([]() { return string{ "a" }; })
.fmap([](const auto& a) { return a + "b"; })
.fmap([](const auto& a) { return a + "c"; })
.fmap(str_toupper);
BOOST_TEST(a() == "ABC");
const auto b = monad::io::make_action([]() { return string{ "a" }; }) >
[](const auto& a) { return a + "b"; } > [](const auto& a) { return a + "c"; } > str_toupper;
BOOST_TEST(b() == "ABC");
}
BOOST_FIXTURE_TEST_CASE(monad_io_pure, init)
{
const auto a = monad::io::pure(string{ "abc" });
BOOST_TEST(a() == "abc");
}
BOOST_AUTO_TEST_SUITE_END()
| 23.326531 | 96 | 0.561242 | XzoRit |
4231df6f009026d47fff53a263e67666fce71ee6 | 3,125 | cpp | C++ | lang/codeGen/types/CodeGenArrayComplexType.cpp | zippy1978/stark | 62607d606fc5fe1addea4bd433b4d8dba9d4f3b1 | [
"MIT"
] | null | null | null | lang/codeGen/types/CodeGenArrayComplexType.cpp | zippy1978/stark | 62607d606fc5fe1addea4bd433b4d8dba9d4f3b1 | [
"MIT"
] | null | null | null | lang/codeGen/types/CodeGenArrayComplexType.cpp | zippy1978/stark | 62607d606fc5fe1addea4bd433b4d8dba9d4f3b1 | [
"MIT"
] | null | null | null | #include <vector>
#include <llvm/IR/Constant.h>
#include <llvm/IR/IRBuilder.h>
#include "../CodeGenFileContext.h"
#include "CodeGenComplexType.h"
using namespace llvm;
using namespace std;
namespace stark
{
CodeGenArrayComplexType::CodeGenArrayComplexType(std::string typeName, CodeGenFileContext *context) : CodeGenComplexType(formatv("array.{0}", typeName), context, true)
{
Type *t = context->getType(typeName);
addMember("elements", typeName, t->getPointerTo());
addMember("len", "int", context->getPrimaryType("int")->getType());
}
void CodeGenArrayComplexType::defineConstructor()
{
// Array constructor is not supported
}
Value *CodeGenArrayComplexType::createDefaultValue()
{
std::vector<Value *> values;
return create(values);
}
Value *CodeGenArrayComplexType::create(std::vector<Value *> values)
{
// Get array element type
Type *elementType = this->members[0]->type->getPointerElementType();
IRBuilder<> Builder(context->getLlvmContext());
Builder.SetInsertPoint(context->getCurrentBlock());
// Alloc inner array
// If element type is a complex type : it is a pointer
Type *innerArrayType = ArrayType::get(elementType, values.size());
Value* innerArrayAllocSize = ConstantExpr::getSizeOf(innerArrayType);
Value *innerArrayAlloc = context->createMemoryAllocation(innerArrayType, innerArrayAllocSize, context->getCurrentBlock());
// Initialize inner array with elements
// TODO : there is probably a way to write the whole content in a single instruction !!!
long index = 0;
for (auto it = values.begin(); it != values.end(); it++)
{
std::vector<llvm::Value *> indices;
indices.push_back(ConstantInt::get(context->getLlvmContext(), APInt(32, 0, true)));
indices.push_back(ConstantInt::get(context->getLlvmContext(), APInt(32, index, true)));
Value *elementVarValue = Builder.CreateInBoundsGEP(innerArrayAlloc, indices, "elementptr");
Builder.CreateStore(*it, elementVarValue);
index++;
}
// Create array
Type *arrayType = context->getArrayComplexType(context->getTypeName(elementType))->getType();
Constant* arrayAllocSize = ConstantExpr::getSizeOf(arrayType);
Value *arrayAlloc = context->createMemoryAllocation(arrayType, arrayAllocSize, context->getCurrentBlock());
// Set len member
Value *lenMember = Builder.CreateStructGEP(arrayAlloc, 1, "arrayleninit");
Builder.CreateStore(ConstantInt::get(context->getPrimaryType("int")->getType(), values.size(), true), lenMember);
// Set elements member with inner array
Value *elementsMemberPointer = Builder.CreateStructGEP(arrayAlloc, 0, "arrayeleminit");
Builder.CreateStore(new BitCastInst(innerArrayAlloc, elementType->getPointerTo(), "", context->getCurrentBlock()), elementsMemberPointer);
// Return new instance
return arrayAlloc;
}
} // namespace stark | 40.584416 | 171 | 0.67104 | zippy1978 |
423537413507863635dc62c08b62af1a6dd04a29 | 1,219 | cpp | C++ | test/cpp/misc_tests/url-1.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | test/cpp/misc_tests/url-1.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | test/cpp/misc_tests/url-1.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | //
// Copyright (c) 2008 João Abecasis
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <saga/saga.hpp>
#include <iostream>
int main()
{
saga::url u1("http://example.com"), u2 = u1, u3;
std::cout << "u1: " << u1 << std::endl;
std::cout << "u2: " << u2 << std::endl;
std::cout << "u3: " << u3 << std::endl;
std::cout << "Resetting u2." << std::endl;
u2 = "condor://localhost";
std::cout << "u1: " << u1 << std::endl;
std::cout << "u2: " << u2 << std::endl;
std::cout << "u3: " << u3 << std::endl;
std::cout << "u1.get_host(): " << u1.get_host() << std::endl;
std::cout << "u2.get_host(): " << u2.get_host() << std::endl;
std::cout << "u3.get_host(): " << u3.get_host() << std::endl;
std::cout << "Resetting all hosts to localhost." << std::endl;
u1.set_host("localhost");
u2.set_host("localhost");
u3.set_host("localhost");
std::cout << "u1.get_host(): " << u1.get_host() << std::endl;
std::cout << "u2.get_host(): " << u2.get_host() << std::endl;
std::cout << "u3.get_host(): " << u3.get_host() << std::endl;
}
| 29.731707 | 80 | 0.546349 | saga-project |
4237709d2596784d4f7ba3af9705c389b7d0c391 | 1,375 | cpp | C++ | src/ui/main.cpp | mario-martinez-proyecto1/arbol-b | 832371749cfa192f3b32873b0a55e99936f5ab6a | [
"MIT"
] | null | null | null | src/ui/main.cpp | mario-martinez-proyecto1/arbol-b | 832371749cfa192f3b32873b0a55e99936f5ab6a | [
"MIT"
] | null | null | null | src/ui/main.cpp | mario-martinez-proyecto1/arbol-b | 832371749cfa192f3b32873b0a55e99936f5ab6a | [
"MIT"
] | null | null | null | #include <iostream>
#include "../tl/Gestor.h"
#include "utilitario/Validar.h"
Gestor gestor;
Validar validar;
using namespace std;
void menu();
void procesarMenu(int &, bool &);
int ingresarNum(string);
int main() {
menu();
return 0;
}
void menu() {
bool salir;
string valor;
int opcion = 0;
do {
cout << "\nMenú Árbol\n\nElija una opción\n" <<
"01 Agregar elemento\n" <<
"02 Buscar elemento\n" <<
"03 Número primo menor que ...\n" <<
"04 Salir\n";
cin >> valor;
opcion = validar.ingresarInt(valor);
procesarMenu(opcion, salir);
} while (!salir);
}
void procesarMenu(int & pOpcion, bool & salir) {
switch (pOpcion) {
case 1:
// addValores();
break;
case 2:
// buscarValores();
break;
case 3:
// nPrimoMenorQue();
break;
case 4:
salir = true;
break;
default:
cout << "Opción inválida\n";
}
}
int ingresarNum(string msg){
int num;
string valor;
do {
cout << msg << endl;
cin >> valor;
num = validar.ingresarInt(valor);
if (num == -1){
cout << "El valor ingresado es incorrecto\nVuelva a intentarlo\n";
}
} while (num == -1);
return num;
} | 22.540984 | 78 | 0.506182 | mario-martinez-proyecto1 |
423b4bfc1e4fa564a57f5197c188b4c0856bd2ce | 947 | cpp | C++ | SmallestGoodBase.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | 3 | 2017-11-27T03:01:50.000Z | 2021-03-13T08:14:00.000Z | SmallestGoodBase.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | null | null | null | SmallestGoodBase.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | null | null | null | // log * log * log
class Solution {
public:
unsigned long long calc(int d, int k) {;
unsigned long long x = 1;
unsigned long long sum = 0;
for (int i = 0; i < d; i++) {
sum += x;
x *= k;
}
return sum;
}
string smallestGoodBase(string n) {
unsigned long long m = stoull(n);
for (int d = 62; d >= 2; d--) {
if ((1 << d) - 1 <= m) {
int L = 2, R = pow(m, 1.0 / (d - 1)) + 1.0;
while (L <= R) {
int mid = (L + R) / 2;
long long x = calc(d, mid);
if (x == m) {
return to_string(mid);
} else if (x > m) {
R = mid - 1;
} else {
L = mid + 1;
}
}
}
}
return to_string(m - 1);
}
}; | 28.69697 | 59 | 0.317846 | yplusplus |
423e08911ac1f9242f73e8f9d47878398b5b69b1 | 7,499 | hh | C++ | src/sound/YM2413Burczynski.hh | lutris/openmsx | 91ed35400c7b4c8c460004710736af9abc4dde29 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5 | 2015-02-27T21:42:28.000Z | 2021-10-10T23:36:08.000Z | src/sound/YM2413Burczynski.hh | lutris/openmsx | 91ed35400c7b4c8c460004710736af9abc4dde29 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/sound/YM2413Burczynski.hh | lutris/openmsx | 91ed35400c7b4c8c460004710736af9abc4dde29 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2015-06-15T09:57:56.000Z | 2017-05-14T01:11:48.000Z | #ifndef YM2413BURCZYNSKI_HH
#define YM2413BURCZYNSKI_HH
#include "YM2413Core.hh"
#include "FixedPoint.hh"
#include "serialize_meta.hh"
namespace openmsx {
namespace YM2413Burczynski {
class Channel;
/** 16.16 fixed point type for frequency calculations.
*/
typedef FixedPoint<16> FreqIndex;
class Slot
{
public:
Slot();
void resetOperators();
/** Update phase increment counter of operator.
* Also updates the EG rates if necessary.
*/
void updateGenerators(Channel& channel);
inline int calcOutput(Channel& channel, unsigned eg_cnt, bool carrier,
unsigned lfo_am, int phase);
inline int calc_slot_mod(Channel& channel, unsigned eg_cnt, bool carrier,
unsigned lfo_pm, unsigned lfo_am);
inline int calc_envelope(Channel& channel, unsigned eg_cnt, bool carrier);
inline int calc_phase(Channel& channel, unsigned lfo_pm);
enum KeyPart { KEY_MAIN = 1, KEY_RHYTHM = 2 };
void setKeyOn(KeyPart part);
void setKeyOff(KeyPart part);
void setKeyOnOff(KeyPart part, bool enabled);
/** Does this slot currently produce an output signal?
*/
bool isActive() const;
/** Sets the frequency multiplier [0..15].
*/
void setFrequencyMultiplier(byte value);
/** Sets the key scale rate: true->0, false->2.
*/
void setKeyScaleRate(bool value);
/** Sets the envelope type of the current instrument.
* @param value true->sustained, false->percussive.
*/
void setEnvelopeSustained(bool value);
/** Enables (true) or disables (false) vibrato.
*/
void setVibrato(bool value);
/** Enables (true) or disables (false) amplitude modulation.
*/
void setAmplitudeModulation(bool value);
/** Sets the total level: [0..63].
*/
void setTotalLevel(Channel& channel, byte value);
/** Sets the key scale level: 0->0 / 1->1.5 / 2->3.0 / 3->6.0 dB/OCT.
*/
void setKeyScaleLevel(Channel& channel, byte value);
/** Sets the waveform: 0 = sinus, 1 = half sinus, half silence.
*/
void setWaveform(byte value);
/** Sets the amount of feedback [0..7].
*/
void setFeedbackShift(byte value);
/** Sets the attack rate [0..15].
*/
void setAttackRate(const Channel& channel, byte value);
/** Sets the decay rate [0..15].
*/
void setDecayRate(const Channel& channel, byte value);
/** Sets the release rate [0..15].
*/
void setReleaseRate(const Channel& channel, byte value);
/** Sets the sustain level [0..15].
*/
void setSustainLevel(byte value);
/** Called by Channel when block_fnum changes.
*/
void updateFrequency(Channel& channel);
template<typename Archive>
void serialize(Archive& ar, unsigned version);
public: // public for serialization, otherwise could be private
/** Envelope Generator phases
* Note: These are ordered: phase constants are compared in the code.
*/
enum EnvelopeState {
EG_DUMP, EG_ATTACK, EG_DECAY, EG_SUSTAIN, EG_RELEASE, EG_OFF
};
private:
/** Change envelope state
*/
void setEnvelopeState(EnvelopeState state);
inline void updateTotalLevel(Channel& channel);
inline void updateAttackRate(int kcodeScaled);
inline void updateDecayRate(int kcodeScaled);
inline void updateReleaseRate(int kcodeScaled);
unsigned* wavetable; // waveform select
// Phase Generator
FreqIndex phase; // frequency counter
FreqIndex freq; // frequency counter step
// Envelope Generator
int TL; // total level: TL << 2
int TLL; // adjusted now TL
int egout; // envelope counter
int sl; // sustain level: sl_tab[SL]
EnvelopeState state;
int op1_out[2]; // MOD output for feedback
bool eg_sustain;// percussive/nonpercussive mode
byte fb_shift; // feedback shift value
byte key; // 0 = KEY OFF, >0 = KEY ON
const byte* eg_sel_dp;
const byte* eg_sel_ar;
const byte* eg_sel_dr;
const byte* eg_sel_rr;
const byte* eg_sel_rs;
unsigned eg_mask_dp; // == (1 << eg_sh_dp) - 1
unsigned eg_mask_ar; // == (1 << eg_sh_ar) - 1
unsigned eg_mask_dr; // == (1 << eg_sh_dr) - 1
unsigned eg_mask_rr; // == (1 << eg_sh_rr) - 1
unsigned eg_mask_rs; // == (1 << eg_sh_rs) - 1
byte eg_sh_dp; // (dump state)
byte eg_sh_ar; // (attack state)
byte eg_sh_dr; // (decay state)
byte eg_sh_rr; // (release state for non-perc.)
byte eg_sh_rs; // (release state for perc.mode)
byte ar; // attack rate: AR<<2
byte dr; // decay rate: DR<<2
byte rr; // release rate:RR<<2
byte KSR; // key scale rate
byte ksl; // keyscale level
byte mul; // multiple: mul_tab[ML]
// LFO
byte AMmask; // LFO Amplitude Modulation enable mask
byte vib; // LFO Phase Modulation enable flag (active high)
};
class Channel
{
public:
Channel();
/** Calculate the value of the current sample produced by this channel.
*/
inline int calcOutput(unsigned eg_cnt, unsigned lfo_pm, unsigned lfo_am, int fm);
/** Sets the frequency for this channel.
*/
void setFrequency(int block_fnum);
/** Changes the lower 8 bits of the frequency for this channel.
*/
void setFrequencyLow(byte value);
/** Changes the higher 4 bits of the frequency for this channel.
*/
void setFrequencyHigh(byte value);
/** Sets some synthesis parameters as specified by the instrument.
* @param part Part [0..7] of the instrument.
* @param value New value for this part.
*/
void updateInstrumentPart(int part, byte value);
/** Sets all synthesis parameters as specified by the instrument.
* @param inst Instrument data.
*/
void updateInstrument(const byte* inst);
int getBlockFNum() const;
FreqIndex getFrequencyIncrement() const;
int getKeyScaleLevelBase() const;
byte getKeyCode() const;
bool isSustained() const;
void setSustain(bool sustained);
template<typename Archive>
void serialize(Archive& ar, unsigned version);
Slot mod;
Slot car;
private:
// phase generator state
int block_fnum; // block+fnum
FreqIndex fc; // Freq. freqement base
int ksl_base; // KeyScaleLevel Base step
bool sus; // sus on/off (release speed in percussive mode)
};
class YM2413 : public YM2413Core
{
public:
YM2413();
template<typename Archive>
void serialize(Archive& ar, unsigned version);
private:
// YM2413Core
virtual void reset();
virtual void writeReg(byte reg, byte value);
virtual byte peekReg(byte reg) const;
virtual void generateChannels(int* bufs[9 + 5], unsigned num);
virtual int getAmplificationFactor() const;
/** Reset operator parameters.
*/
void resetOperators();
inline bool isRhythm() const;
Channel& getChannelForReg(byte reg);
/** Called when the custom instrument (instrument 0) has changed.
* @param part Part [0..7] of the instrument.
* @param value The new value.
*/
void updateCustomInstrument(int part, byte value);
void setRhythmFlags(byte old);
/** OPLL chips have 9 channels. */
Channel channels[9];
/** Global envelope generator counter. */
unsigned eg_cnt;
/** Random generator for noise: 23 bit shift register. */
int noise_rng;
/** Number of samples the output was completely silent. */
unsigned idleSamples;
typedef FixedPoint< 6> LFOAMIndex;
typedef FixedPoint<10> LFOPMIndex;
LFOAMIndex lfo_am_cnt;
LFOPMIndex lfo_pm_cnt;
/** Instrument settings:
* 0 - user instrument
* 1-15 - fixed instruments
* 16 - bass drum settings
* 17-18 - other percussion instruments
*/
byte inst_tab[19][8];
/** Registers */
byte reg[0x40];
};
} // namespace YM2413Burczynski
SERIALIZE_CLASS_VERSION(YM2413Burczynski::YM2413, 3);
SERIALIZE_CLASS_VERSION(YM2413Burczynski::Channel, 3);
SERIALIZE_CLASS_VERSION(YM2413Burczynski::Slot, 2);
} // namespace openmsx
#endif
| 25.593857 | 82 | 0.709428 | lutris |
423e5287e968b03a7a40b8153df367c9f0f61624 | 2,306 | cpp | C++ | tests/hull/hullTest.cpp | Yattabyte/TestProject | 21a1e047dd03f90087e2738c7d90545a067e8375 | [
"BSD-3-Clause"
] | 1 | 2020-03-02T21:56:42.000Z | 2020-03-02T21:56:42.000Z | tests/hull/hullTest.cpp | Yattabyte/TestProject | 21a1e047dd03f90087e2738c7d90545a067e8375 | [
"BSD-3-Clause"
] | null | null | null | tests/hull/hullTest.cpp | Yattabyte/TestProject | 21a1e047dd03f90087e2738c7d90545a067e8375 | [
"BSD-3-Clause"
] | null | null | null | #include "hull.hpp"
#include <cassert>
#include <iostream>
#include <limits>
#include <string>
//////////////////////////////////////////////////////////////////////
/// Use the shared mini namespace
using namespace mini;
// Constant variables for this test
constexpr auto scale(10.0F);
constexpr auto pointCount(16384ULL);
constexpr auto seed(1234567890U);
void cloudTest(const std::vector<vec3>& pointCloud);
void hullTest(const std::vector<vec3>& pointCloud);
int main() {
// Generate a point cloud given the above variables
std::cout << "Generating point cloud given:\n"
<< "\t-scale: " << std::to_string(scale) << "\n"
<< "\t-count: " << std::to_string(pointCount) << "\n"
<< "\t-seed: " << std::to_string(seed) << std::endl;
const auto pointCloud(Hull::generate_point_cloud(scale, pointCount, seed));
// Test the point cloud for accuracy
cloudTest(pointCloud);
// Test the convex hull for accuracy
hullTest(pointCloud);
exit(0);
}
void cloudTest(const std::vector<vec3>& pointCloud) {
// Ensure number of points match
assert(pointCloud.size() == pointCount);
// Ensure scale is accurate
vec3 max(std::numeric_limits<float>::min());
vec3 min(std::numeric_limits<float>::max());
for (const auto& point : pointCloud) {
if (max.x() < point.x())
max.x() = point.x();
if (max.y() < point.y())
max.y() = point.y();
if (max.z() < point.z())
max.z() = point.z();
if (min.x() > point.x())
min.x() = point.x();
if (min.y() > point.y())
min.y() = point.y();
if (min.z() > point.z())
min.z() = point.z();
}
[[maybe_unused]] const auto delta = max - min;
assert(ceilf((delta.x() + delta.y() + delta.z()) / 6.0F) == ceilf(scale));
// Ensure deterministic point cloud
assert(
pointCloud[0].x() == 2.37589645F && pointCloud[0].y() == -3.18982124F &&
pointCloud[0].z() == 1.83247185F);
}
void hullTest(const std::vector<vec3>& pointCloud) {
// Attempt to generate a convex hull
[[maybe_unused]] const auto convexHull(
Hull::generate_convex_hull(pointCloud));
// Ensure we have actually have a hull
assert(!convexHull.empty());
} | 31.589041 | 80 | 0.573287 | Yattabyte |
4244bf1064c76dbcfe7a5c0983dc66ab07321ab2 | 1,247 | cc | C++ | Codeforces/311 Division 2/Problem A/A.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/311 Division 2/Problem A/A.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/311 Division 2/Problem A/A.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<vector>
#include<utility>
#include<queue>
#include<stack>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);
#define tr(x) cout<<x<<endl;
#define tr2(x,y) cout<<x<<" "<<y<<endl;
#define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl;
#define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
int n;
int x1, x2, x3, x4, x5, x6;
int main(){
cin >> n;
sd2(x1,x2);
sd2(x3,x4);
sd2(x5,x6);
int a = x1, b = x3, c = x5;
n -= (x1+x3+x5);
if(n >= x2-x1){
n -= x2-x1;
a = x2;
}
else{
a += n;
n = 0;
}
if(n >= x4-x3){
n -= x4-x3;
b = x4;
}
else{
b += n;
n = 0;
}
if(n >= x6-x5){
n -= x6-x5;
c = x6;
}
else{
c += n;
n = 0;
}
tr3(a,b,c);
return 0;
}
| 17.082192 | 79 | 0.55413 | VastoLorde95 |
4248f17545d2945270c98c53ced6fcf8158a8c88 | 509 | cxx | C++ | Tracing/MDL/MDLIntroPage.cxx | tostathaina/farsight | 7e9d6d15688735f34f7ca272e4e715acd11473ff | [
"Apache-2.0"
] | 8 | 2016-07-22T11:24:19.000Z | 2021-04-10T04:22:31.000Z | Tracing/MDL/MDLIntroPage.cxx | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | null | null | null | Tracing/MDL/MDLIntroPage.cxx | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | 7 | 2016-07-21T07:39:17.000Z | 2020-01-29T02:03:27.000Z | #include "MDLIntroPage.h"
#include "MDLWizard.h"
#include <iostream>
using std::cout;
using std::endl;
MDLIntroPage::MDLIntroPage(QWidget *parent)
{
}
bool MDLIntroPage::isComplete() const
{
MDLWizard *wiz = static_cast<MDLWizard*>(this->wizard());
if(wiz->InputImageLabel->text() != "" &&
wiz->BackboneOutputLabel->text() != "" &&
wiz->SpinesOutputLabel->text() != "")
{
return true;
}
return false;
}
void MDLIntroPage::CheckIfComplete()
{
emit this->completeChanged();
}
| 17.551724 | 59 | 0.658153 | tostathaina |
424a1938b3dfb575afc3d89a653c01ec8e2da0c7 | 748 | cpp | C++ | 2265/9284084_AC_0MS_956K.cpp | vandreas19/POJ_sol | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 18 | 2017-08-14T07:34:42.000Z | 2022-01-29T14:20:29.000Z | 2265/9284084_AC_0MS_956K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | null | null | null | 2265/9284084_AC_0MS_956K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 14 | 2016-12-21T23:37:22.000Z | 2021-07-24T09:38:57.000Z | #define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
const int ID_MAX=100000;
int x[ID_MAX]={0},y[ID_MAX]={0};
int main(){
for(int id=0;id+1<ID_MAX;id++){
if(x[id]>=0 && x[id]+y[id]<0){
x[id+1]=x[id]+1;
y[id+1]=y[id];
}
else if(y[id]<=0 && x[id]+y[id]>=0){
x[id+1]=x[id];
y[id+1]=y[id]+1;
}
else if(x[id]>0 && y[id]>0){
x[id+1]=x[id]-1;
y[id+1]=y[id]+1;
}
else if(x[id]<=0 && x[id]+y[id]>0){
x[id+1]=x[id]-1;
y[id+1]=y[id];
}
else if(y[id]>0 && x[id]+y[id]<=0){
x[id+1]=x[id];
y[id+1]=y[id]-1;
}
else if(x[id]<0 && y[id]<=0){
x[id+1]=x[id]+1;
y[id+1]=y[id]-1;
}
}
int id;
while(scanf("%d",&id)!=EOF)
printf("%d %d\n",x[id-1],y[id-1]);
return 0;
} | 19.684211 | 39 | 0.450535 | vandreas19 |
424b3a4833b296d05cea1a528f1ec30ad7101f12 | 1,241 | cpp | C++ | UVA/11462 - Age Sort.cpp | Mhmd-Hisham/Problem-Solving | 7ce0955b697e735c5ccb37347d9bec83e57339b5 | [
"MIT"
] | null | null | null | UVA/11462 - Age Sort.cpp | Mhmd-Hisham/Problem-Solving | 7ce0955b697e735c5ccb37347d9bec83e57339b5 | [
"MIT"
] | null | null | null | UVA/11462 - Age Sort.cpp | Mhmd-Hisham/Problem-Solving | 7ce0955b697e735c5ccb37347d9bec83e57339b5 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
/*
Problem: 11462 - Age Sort
Link : https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2457
Solution by: Mohamed Hisham El-Banna
Gmail : Mohamed00Hisham@Gmail.com
Github : www.github.com/Mhmd-Hisham
LinkedIn: www.linkedin.com/in/Mhmd-Hisham
*/
using namespace std;
int N, age, age_freq[2000002];
set<int> ages;
set<int> ::iterator it;
int main () {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
while ( cin >> N && N ){
int left = N; // numbers left to print
for (int i = 0; i < N; i++){
cin >> age;
age_freq[age]++;
ages.insert(age);
}
it = ages.begin();
while (it != ages.end()){
while (age_freq[*it]){
cout << *it;
cout << ( (left == 1)? "" : " ");
age_freq[*it]--;
left--;
}
it++;
}
cout << '\n';
ages.clear();
}
return 0;
}
/*
Sample input:-
-----------------
5
3 4 2 1 5
5
2 3 2 3 1
0
Sample output:-
-----------------
1 2 3 4 5
1 2 2 3 3
Resources:-
-------------
Explanation:
---------------
*/
| 17.478873 | 109 | 0.475423 | Mhmd-Hisham |
424c3492be6bec6e38bb392610a3d35089e7011a | 27,536 | cc | C++ | modules/devapi/mod_mysqlx_schema.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 119 | 2016-04-14T14:16:22.000Z | 2022-03-08T20:24:38.000Z | modules/devapi/mod_mysqlx_schema.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 9 | 2017-04-26T20:48:42.000Z | 2021-09-07T01:52:44.000Z | modules/devapi/mod_mysqlx_schema.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 51 | 2016-07-20T05:06:48.000Z | 2022-03-09T01:20:53.000Z | /*
* Copyright (c) 2014, 2020, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "modules/devapi/mod_mysqlx_schema.h"
#include <mysqld_error.h>
#include <memory>
#include <string>
#include <vector>
#include "scripting/lang_base.h"
#include "scripting/object_factory.h"
#include "shellcore/base_shell.h"
#include "shellcore/shell_core.h"
#include "scripting/proxy_object.h"
#include "modules/devapi/mod_mysqlx_collection.h"
#include "modules/devapi/mod_mysqlx_resultset.h"
#include "modules/devapi/mod_mysqlx_session.h"
#include "modules/devapi/mod_mysqlx_table.h"
#include "mysqlshdk/include/scripting/type_info/custom.h"
#include "mysqlshdk/include/scripting/type_info/generic.h"
#include "mysqlshdk/libs/db/mysqlx/xpl_error.h"
#include "mysqlshdk/libs/utils/logger.h"
#include "shellcore/utils_help.h"
#include "utils/utils_general.h"
#include "utils/utils_sqlstring.h"
#include "utils/utils_string.h"
using namespace mysqlsh;
using namespace mysqlsh::mysqlx;
using namespace shcore;
// Documentation of Schema class
REGISTER_HELP_SUB_CLASS(Schema, mysqlx, DatabaseObject);
REGISTER_HELP(SCHEMA_GLOBAL_BRIEF,
"Used to work with database schema objects.");
REGISTER_HELP(SCHEMA_BRIEF,
"Represents a Schema as retrieved from a session created using "
"the X Protocol.");
REGISTER_HELP(SCHEMA_DETAIL, "<b>View Support</b>");
REGISTER_HELP(
SCHEMA_DETAIL1,
"MySQL Views are stored queries that when executed produce a result set.");
REGISTER_HELP(SCHEMA_DETAIL2,
"MySQL supports the concept of Updatable Views: in specific "
"conditions are met, "
"Views can be used not only to retrieve data from them but also "
"to update, add and delete records.");
REGISTER_HELP(SCHEMA_DETAIL3,
"For the purpose of this API, Views behave similar to a Table, "
"and so they are treated as Tables.");
REGISTER_HELP(SCHEMA_DETAIL4, "<b>Tables and Collections as Properties</b>");
REGISTER_HELP(SCHEMA_DETAIL5, "${DYNAMIC_PROPERTIES}");
REGISTER_HELP_TOPIC(Dynamic Properties, TOPIC, DYNAMIC_PROPERTIES, Schema,
SCRIPTING);
REGISTER_HELP_TOPIC_TEXT(DYNAMIC_PROPERTIES, R"*(
A Schema object may expose tables and collections as properties, this way they
can be accessed as:
@li schema.@<collection_name@>
@li schema.@<table_name@>
This handy way of accessing tables and collections is available if they met the
following conditions:
@li They existed at the moment the Schema object was retrieved from the session.
@li The name is a valid identifier.
@li The name is different from any other property or function on the Schema
object.
If any of the conditions is not met, the way to access the table or collection
is by using the standard DevAPI functions:
@li schema.<<<getTable>>>(@<name@>)
@li schema.<<<getCollection>>>(@<name@>)
)*");
REGISTER_HELP(SCHEMA_PROPERTIES_CLOSING_DESC,
"Some tables and collections are also exposed as properties of "
"the Schema object. For details look at 'Tables and Collections "
"as Properties' on the DETAILS section.");
Schema::Schema(std::shared_ptr<Session> session, const std::string &schema)
: DatabaseObject(session, std::shared_ptr<DatabaseObject>(), schema) {
init();
}
Schema::~Schema() {}
void Schema::init() {
add_method("getTables", std::bind(&Schema::get_tables, this, _1));
add_method("getCollections", std::bind(&Schema::get_collections, this, _1));
add_method("getTable", std::bind(&Schema::get_table, this, _1), "name",
shcore::String);
add_method("getCollection", std::bind(&Schema::get_collection, this, _1),
"name", shcore::String);
add_method("getCollectionAsTable",
std::bind(&Schema::get_collection_as_table, this, _1), "name",
shcore::String);
expose("createCollection", &Schema::create_collection, "name", "?options");
expose("modifyCollection", &Schema::modify_collection, "name", "options");
add_method("dropCollection",
std::bind(&Schema::drop_schema_object, this, _1, "Collection"),
"name", shcore::String);
// Note: If properties are added uncomment this
// _base_property_count = _properties.size();
_tables = Value::new_map().as_map();
_views = Value::new_map().as_map();
_collections = Value::new_map().as_map();
// Setups the cache handlers
auto table_generator = [this](const std::string &name) {
return shcore::Value::wrap<Table>(
new Table(shared_from_this(), name, false));
};
auto view_generator = [this](const std::string &name) {
return shcore::Value::wrap<Table>(
new Table(shared_from_this(), name, true));
};
auto collection_generator = [this](const std::string &name) {
return shcore::Value::wrap<Collection>(
new Collection(shared_from_this(), name));
};
update_table_cache = [table_generator, this](const std::string &name,
bool exists) {
DatabaseObject::update_cache(name, table_generator, exists, _tables,
use_object_handles() ? this : nullptr);
};
update_view_cache = [view_generator, this](const std::string &name,
bool exists) {
DatabaseObject::update_cache(name, view_generator, exists, _views,
use_object_handles() ? this : nullptr);
};
update_collection_cache = [collection_generator, this](
const std::string &name, bool exists) {
DatabaseObject::update_cache(name, collection_generator, exists,
_collections,
use_object_handles() ? this : nullptr);
};
update_full_table_cache = [table_generator,
this](const std::vector<std::string> &names) {
_using_object_handles = true;
DatabaseObject::update_cache(names, table_generator, _tables, this);
};
update_full_view_cache = [view_generator,
this](const std::vector<std::string> &names) {
_using_object_handles = true;
DatabaseObject::update_cache(names, view_generator, _views, this);
};
update_full_collection_cache = [collection_generator,
this](const std::vector<std::string> &names) {
_using_object_handles = true;
DatabaseObject::update_cache(names, collection_generator, _collections,
this);
};
}
void Schema::update_cache() {
try {
std::shared_ptr<Session> sess(
std::static_pointer_cast<Session>(_session.lock()));
if (sess) {
std::vector<std::string> tables;
std::vector<std::string> collections;
std::vector<std::string> views;
std::vector<std::string> others;
{
shcore::Dictionary_t args = shcore::make_dict();
(*args)["schema"] = Value(_name);
auto result = sess->execute_mysqlx_stmt("list_objects", args);
while (auto row = result->fetch_one()) {
std::string object_name = row->get_string(0);
std::string object_type = row->get_string(1);
if (object_type == "TABLE")
tables.push_back(object_name);
else if (object_type == "VIEW")
views.push_back(object_name);
else if (object_type == "COLLECTION")
collections.push_back(object_name);
else
others.push_back(str_format(
"Unexpected Object Retrieved from Database: %s of type %s",
object_name.c_str(), object_type.c_str()));
}
// Updates the cache
update_full_table_cache(tables);
update_full_view_cache(views);
update_full_collection_cache(collections);
// Log errors about unexpected object type
if (others.size()) {
for (size_t index = 0; index < others.size(); index++)
log_error("%s", others[index].c_str());
}
}
}
}
CATCH_AND_TRANSLATE();
}
void Schema::_remove_object(const std::string &name, const std::string &type) {
if (type == "View") {
if (_views->count(name)) _views->erase(name);
} else if (type == "Table") {
if (_tables->count(name)) _tables->erase(name);
} else if (type == "Collection") {
if (_collections->count(name)) _collections->erase(name);
}
}
bool Schema::use_object_handles() const {
return current_shell_options()->get().devapi_schema_object_handles;
}
std::vector<std::string> Schema::get_members() const {
// Flush the cache if we have it populated but it got disabled
if (!use_object_handles() && _using_object_handles) {
_using_object_handles = false;
flush_cache(_views, const_cast<Schema *>(this));
flush_cache(_tables, const_cast<Schema *>(this));
flush_cache(_collections, const_cast<Schema *>(this));
}
return DatabaseObject::get_members();
}
Value Schema::get_member(const std::string &prop) const {
Value ret_val;
// Only checks the cache if the requested member is not a base one
if (!is_base_member(prop) && use_object_handles()) {
// Searches prop as a table
ret_val = find_in_cache(prop, _tables);
// Searches prop as a collection
if (!ret_val) ret_val = find_in_cache(prop, _collections);
// Searches prop as a view
if (!ret_val) ret_val = find_in_cache(prop, _views);
}
if (!ret_val) {
if (prop == "schema")
ret_val = Value(std::const_pointer_cast<Schema>(shared_from_this()));
else
ret_val = DatabaseObject::get_member(prop);
}
return ret_val;
}
// Documentation of getTables function
REGISTER_HELP_FUNCTION(getTables, Schema);
REGISTER_HELP(SCHEMA_GETTABLES_BRIEF,
"Returns a list of Tables for this Schema.");
REGISTER_HELP(
SCHEMA_GETTABLES_RETURNS,
"@returns A List containing the Table objects available for the Schema.");
REGISTER_HELP(
SCHEMA_GETTABLES_DETAIL,
"Pulls from the database the available Tables, Views and Collections.");
REGISTER_HELP(
SCHEMA_GETTABLES_DETAIL1,
"Does a full refresh of the Tables, Views and Collections cache.");
REGISTER_HELP(SCHEMA_GETTABLES_DETAIL2,
"Returns a List of available Table objects.");
/**
* $(SCHEMA_GETTABLES_BRIEF)
*
* \sa Table
*
* $(SCHEMA_GETTABLES_RETURNS)
*
* $(SCHEMA_GETTABLES_DETAIL)
*
* $(SCHEMA_GETTABLES_DETAIL1)
*
* $(SCHEMA_GETTABLES_DETAIL2)
*/
#if DOXYGEN_JS
List Schema::getTables() {}
#elif DOXYGEN_PY
list Schema::get_tables() {}
#endif
shcore::Value Schema::get_tables(const shcore::Argument_list &args) {
args.ensure_count(0, get_function_name("getTables").c_str());
if (use_object_handles()) update_cache();
shcore::Value::Array_type_ref list(new shcore::Value::Array_type);
get_object_list(_tables, list);
get_object_list(_views, list);
return shcore::Value(list);
}
// Documentation of getCollections function
REGISTER_HELP_FUNCTION(getCollections, Schema);
REGISTER_HELP(SCHEMA_GETCOLLECTIONS_BRIEF,
"Returns a list of Collections for this Schema.");
REGISTER_HELP(SCHEMA_GETCOLLECTIONS_RETURNS,
"@returns A List containing the Collection objects available for "
"the Schema.");
REGISTER_HELP(
SCHEMA_GETCOLLECTIONS_DETAIL,
"Pulls from the database the available Tables, Views and Collections.");
REGISTER_HELP(
SCHEMA_GETCOLLECTIONS_DETAIL1,
"Does a full refresh of the Tables, Views and Collections cache.");
REGISTER_HELP(SCHEMA_GETCOLLECTIONS_DETAIL2,
"Returns a List of available Collection objects.");
/**
* $(SCHEMA_GETCOLLECTIONS_BRIEF)
*
* \sa Collection
*
* $(SCHEMA_GETCOLLECTIONS_RETURNS)
*
* $(SCHEMA_GETCOLLECTIONS_DETAIL)
*
* $(SCHEMA_GETCOLLECTIONS_DETAIL1)
*
* $(SCHEMA_GETCOLLECTIONS_DETAIL2)
*/
#if DOXYGEN_JS
List Schema::getCollections() {}
#elif DOXYGEN_PY
list Schema::get_collections() {}
#endif
shcore::Value Schema::get_collections(const shcore::Argument_list &args) {
args.ensure_count(0, get_function_name("getCollections").c_str());
if (use_object_handles()) update_cache();
shcore::Value::Array_type_ref list(new shcore::Value::Array_type);
get_object_list(_collections, list);
return shcore::Value(list);
}
// Documentation of getTable function
REGISTER_HELP_FUNCTION(getTable, Schema);
REGISTER_HELP(SCHEMA_GETTABLE_BRIEF,
"Returns the Table of the given name for this schema.");
REGISTER_HELP(SCHEMA_GETTABLE_PARAM,
"@param name the name of the Table to look for.");
REGISTER_HELP(SCHEMA_GETTABLE_RETURNS,
"@returns the Table object matching the name.");
REGISTER_HELP(SCHEMA_GETTABLE_DETAIL,
"Verifies if the requested Table exist on the database, if "
"exists, returns the corresponding Table object.");
REGISTER_HELP(SCHEMA_GETTABLE_DETAIL1, "Updates the Tables cache.");
/**
* $(SCHEMA_GETTABLE_BRIEF)
*
* $(SCHEMA_GETTABLE_PARAM)
*
* $(SCHEMA_GETTABLE_RETURNS)
*
* $(SCHEMA_GETTABLE_DETAIL)
*
* $(SCHEMA_GETTABLE_DETAIL1)
*
* \sa Table
*/
#if DOXYGEN_JS
Table Schema::getTable(String name) {}
#elif DOXYGEN_PY
Table Schema::get_table(str name) {}
#endif
shcore::Value Schema::get_table(const shcore::Argument_list &args) {
args.ensure_count(1, get_function_name("getTable").c_str());
std::string name = args.string_at(0);
shcore::Value ret_val;
try {
if (!name.empty()) {
std::string found_type;
std::string real_name;
auto session = _session.lock();
if (session)
real_name = session->db_object_exists(found_type, name, _name);
else
throw shcore::Exception::logic_error("Unable to get table '" + name +
"', no Session available");
bool exists = false;
if (!real_name.empty()) {
if (found_type == "TABLE") {
exists = true;
// Updates the cache
update_table_cache(real_name, exists);
ret_val = (*_tables)[real_name];
} else if (found_type == "VIEW") {
exists = true;
// Updates the cache
update_view_cache(real_name, exists);
ret_val = (*_views)[real_name];
}
}
if (!exists)
throw shcore::Exception::runtime_error("The table " + _name + "." +
name + " does not exist");
} else
throw shcore::Exception::argument_error(
"An empty name is invalid for a table");
}
CATCH_AND_TRANSLATE_FUNCTION_EXCEPTION(get_function_name("getTable"));
return ret_val;
}
// Documentation of getCollection function
REGISTER_HELP_FUNCTION(getCollection, Schema);
REGISTER_HELP(SCHEMA_GETCOLLECTION_BRIEF,
"Returns the Collection of the given name for this schema.");
REGISTER_HELP(SCHEMA_GETCOLLECTION_PARAM,
"@param name the name of the Collection to look for.");
REGISTER_HELP(SCHEMA_GETCOLLECTION_RETURNS,
"@returns the Collection object matching the name.");
REGISTER_HELP(
SCHEMA_GETCOLLECTION_DETAIL,
"Verifies if the requested Collection exist on the database, if exists, "
"returns the corresponding Collection object.");
REGISTER_HELP(SCHEMA_GETCOLLECTION_DETAIL1, "Updates the Collections cache.");
/**
* $(SCHEMA_GETCOLLECTION_BRIEF)
*
* $(SCHEMA_GETCOLLECTION_PARAM)
*
* $(SCHEMA_GETCOLLECTION_RETURNS)
*
* $(SCHEMA_GETCOLLECTION_DETAIL)
*
* $(SCHEMA_GETCOLLECTION_DETAIL1)
*
* \sa Collection
*/
#if DOXYGEN_JS
Collection Schema::getCollection(String name) {}
#elif DOXYGEN_PY
Collection Schema::get_collection(str name) {}
#endif
shcore::Value Schema::get_collection(const shcore::Argument_list &args) {
args.ensure_count(1, get_function_name("getCollection").c_str());
std::string name = args.string_at(0);
shcore::Value ret_val;
try {
if (!name.empty()) {
std::string found_type;
std::string real_name;
auto session = _session.lock();
if (session)
real_name = session->db_object_exists(found_type, name, _name);
else
throw shcore::Exception::logic_error("Unable to retrieve collection '" +
name + "', no Session available");
bool exists = false;
if (!real_name.empty() && found_type == "COLLECTION") exists = true;
// Updates the cache
update_collection_cache(real_name, exists);
if (exists)
ret_val = (*_collections)[real_name];
else
throw shcore::Exception::runtime_error("The collection " + _name + "." +
name + " does not exist");
} else
throw shcore::Exception::argument_error(
"An empty name is invalid for a collection");
}
CATCH_AND_TRANSLATE_FUNCTION_EXCEPTION(get_function_name("getCollection"));
return ret_val;
}
// Documentation of getCollectionAsTable function
REGISTER_HELP_FUNCTION(getCollectionAsTable, Schema);
REGISTER_HELP(
SCHEMA_GETCOLLECTIONASTABLE_BRIEF,
"Returns a Table object representing a Collection on the database.");
REGISTER_HELP(
SCHEMA_GETCOLLECTIONASTABLE_PARAM,
"@param name the name of the collection to be retrieved as a table.");
REGISTER_HELP(
SCHEMA_GETCOLLECTIONASTABLE_RETURNS,
"@returns the Table object representing the collection or undefined.");
/**
* $(SCHEMA_GETCOLLECTIONASTABLE_BRIEF)
*
* $(SCHEMA_GETCOLLECTIONASTABLE_PARAM)
*
* $(SCHEMA_GETCOLLECTIONASTABLE_RETURNS)
*/
#if DOXYGEN_JS
Collection Schema::getCollectionAsTable(String name) {}
#elif DOXYGEN_PY
Collection Schema::get_collection_as_table(str name) {}
#endif
shcore::Value Schema::get_collection_as_table(
const shcore::Argument_list &args) {
args.ensure_count(1, get_function_name("getCollectionAsTable").c_str());
Value ret_val = get_collection(args);
if (ret_val) {
std::shared_ptr<Table> table(
new Table(shared_from_this(), args.string_at(0)));
ret_val = Value(std::static_pointer_cast<Object_bridge>(table));
}
return ret_val;
}
// Documentation of createCollection function
REGISTER_HELP_FUNCTION(createCollection, Schema);
REGISTER_HELP_FUNCTION_TEXT(SCHEMA_CREATECOLLECTION, R"*(
Creates in the current schema a new collection with the specified name and
retrieves an object representing the new collection created.
@param name the name of the collection.
@param options optional dictionary with options.
@returns the new created collection.
To specify a name for a collection, follow the naming conventions in MySQL.
The options dictionary may contain the following attributes:
@li reuseExistingObject: boolean, indicating if the call should succeed when
collection with the same name already exists.
@li validation: object defining JSON schema validation for the collection.
The validation object allows the following attributes:
@li level: which can be either 'strict' or 'off'.
@li schema: a JSON schema specification as described at json-schema.org.
)*");
/**
* $(SCHEMA_CREATECOLLECTION_BRIEF)
*
* $(SCHEMA_CREATECOLLECTION)
*/
#if DOXYGEN_JS
Collection Schema::createCollection(String name, Dictionary options) {}
#elif DOXYGEN_PY
Collection Schema::create_collection(str name, dict options) {}
#endif
shcore::Value Schema::create_collection(const std::string &name,
const shcore::Dictionary_t &opts) {
Value ret_val;
// Creates the collection on the server
shcore::Dictionary_t options = shcore::make_dict();
options->set("schema", Value(_name));
options->set("name", Value(name));
if (opts && !opts->empty()) {
shcore::Dictionary_t validation;
mysqlshdk::utils::nullable<bool> reuse;
shcore::Option_unpacker{opts}
.optional("validation", &validation)
.optional("reuseExistingObject", &reuse)
.end("in create collection options dictionary");
if (reuse) {
opts->erase("reuseExistingObject");
opts->emplace("reuse_existing", *reuse);
}
options->set("options", Value(opts));
}
std::shared_ptr<Session> sess(
std::static_pointer_cast<Session>(_session.lock()));
try {
if (sess) {
sess->execute_mysqlx_stmt("create_collection", options);
// If this is reached it implies all went OK on the previous operation
update_collection_cache(name, true);
ret_val = (*_collections)[name];
} else {
throw shcore::Exception::logic_error("Unable to create collection '" +
name + "', no Session available");
}
} catch (const mysqlshdk::db::Error &e) {
if (opts && !opts->empty()) {
std::string err_msg;
switch (e.code()) {
case ER_X_CMD_NUM_ARGUMENTS:
if (strstr(e.what(), "Invalid number of arguments") != nullptr)
err_msg =
"The target MySQL server does not support options in the "
"<<<createCollection>>> function";
break;
case ER_X_CMD_INVALID_ARGUMENT:
if (strstr(e.what(), "reuse_existing") != nullptr)
err_msg =
"The target MySQL server does not support the "
"reuseExistingObject attribute";
else if (strstr(e.what(), "field for create_collection command"))
err_msg = shcore::str_replace(
e.what(), "field for create_collection command", "option");
break;
case ER_X_INVALID_VALIDATION_SCHEMA:
err_msg = std::string("The provided validation schema is invalid (") +
e.what() + ").";
break;
}
if (!err_msg.empty()) {
log_error("%s", e.what());
throw mysqlshdk::db::Error(err_msg, e.code());
}
}
throw;
}
return ret_val;
}
REGISTER_HELP_FUNCTION(modifyCollection, Schema);
REGISTER_HELP_FUNCTION_TEXT(SCHEMA_MODIFYCOLLECTION, R"*(
Modifies the schema validation of a collection.
@param name the name of the collection.
@param options dictionary with options.
The options dictionary may contain the following attributes:
@li validation: object defining JSON schema validation for the collection.
The validation object allows the following attributes:
@li level: which can be either 'strict' or 'off'.
@li schema: a JSON schema specification as described at json-schema.org.
)*");
/**
* $(SCHEMA_MODIFYCOLLECTION_BRIEF)
*
* $(SCHEMA_MODIFYCOLLECTION)
*/
#if DOXYGEN_JS
Undefined Schema::modifyCollection(String name, Dictionary options) {}
#elif DOXYGEN_PY
None Schema::modify_collection(str name, dict options) {}
#endif
void Schema::modify_collection(const std::string &name,
const shcore::Dictionary_t &opts) {
if (!opts)
throw Exception::argument_error(
"The options dictionary needs to be specified");
// Modifies collection on the server
shcore::Dictionary_t options = shcore::make_dict();
options->set("schema", Value(_name));
options->set("name", Value(name));
shcore::Argument_map(*opts).ensure_keys({"validation"}, {},
"modify collection options", true);
if (opts->get_type("validation") != Value_type::Map ||
opts->get_map("validation")->size() == 0)
throw Exception::argument_error(
"validation option's value needs to be a non empty map");
options->set("options", Value(opts));
std::shared_ptr<Session> sess(
std::static_pointer_cast<Session>(_session.lock()));
try {
if (sess)
sess->execute_mysqlx_stmt("modify_collection_options", options);
else
throw shcore::Exception::logic_error("Unable to create collection '" +
name + "', no Session available");
} catch (const mysqlshdk::db::Error &e) {
std::string err_msg;
switch (e.code()) {
case ER_X_INVALID_ADMIN_COMMAND:
err_msg =
"The target MySQL server does not support the requested operation.";
break;
case ER_X_CMD_INVALID_ARGUMENT:
if (strstr(e.what(), "field for modify_collection_options command"))
err_msg = shcore::str_replace(
e.what(), "field for modify_collection_options command",
"option");
break;
case ER_X_INVALID_VALIDATION_SCHEMA:
err_msg = std::string("The provided validation schema is invalid (") +
e.what() + ").";
break;
}
if (!err_msg.empty()) {
log_error("%s", e.what());
throw mysqlshdk::db::Error(err_msg, e.code());
}
throw;
}
}
// Documentation of dropCollection function
REGISTER_HELP_FUNCTION(dropCollection, Schema);
REGISTER_HELP(SCHEMA_DROPCOLLECTION_BRIEF, "Drops the specified collection.");
REGISTER_HELP(SCHEMA_DROPCOLLECTION_RETURNS, "@returns Nothing.");
/**
* $(SCHEMA_DROPCOLLECTION_BRIEF)
*
* $(SCHEMA_DROPCOLLECTION_RETURNS)
*/
#if DOXYGEN_JS
Undefined Schema::dropCollection(String name) {}
#elif DOXYGEN_PY
None Schema::drop_collection(str name) {}
#endif
shcore::Value Schema::drop_schema_object(const shcore::Argument_list &args,
const std::string &type) {
std::string function = get_function_name("drop" + type);
args.ensure_count(1, function.c_str());
if (args[0].type != shcore::String)
throw shcore::Exception::type_error(
function + ": Argument #1 is expected to be a string");
Value schema = this->get_member("name");
std::string name = args[0].get_string();
try {
if (type == "View") {
std::shared_ptr<Session> sess(
std::static_pointer_cast<Session>(_session.lock()));
sess->execute_sql(sqlstring("drop view if exists !.!", 0)
<< schema.get_string() << name);
} else {
if ((type == "Table") || (type == "Collection")) {
auto command_args = shcore::make_dict();
command_args->emplace("name", name);
command_args->emplace("schema", schema);
std::shared_ptr<Session> sess(
std::static_pointer_cast<Session>(_session.lock()));
try {
sess->execute_mysqlx_stmt("drop_collection", command_args);
} catch (const mysqlshdk::db::Error &e) {
if (e.code() != ER_BAD_TABLE_ERROR) throw;
}
}
}
}
CATCH_AND_TRANSLATE_FUNCTION_EXCEPTION(get_function_name("drop" + type));
this->_remove_object(name, type);
return shcore::Value();
}
| 34.079208 | 80 | 0.671485 | mueller |
42521aa4b8951f72b588c6847e0e199be7d2a4bb | 1,169 | cc | C++ | src/rocksdb2/util/concurrent_arena.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 5 | 2019-01-23T04:36:03.000Z | 2020-02-04T07:10:39.000Z | src/rocksdb2/util/concurrent_arena.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | null | null | null | src/rocksdb2/util/concurrent_arena.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 2 | 2019-05-14T07:26:59.000Z | 2020-06-15T07:25:01.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2011至今,Facebook,Inc.保留所有权利。
//此源代码在两个gplv2下都获得了许可(在
//复制根目录中的文件)和Apache2.0许可证
//(在根目录的license.apache文件中找到)。
//
//版权所有(c)2011 LevelDB作者。版权所有。
//此源代码的使用受可以
//在许可证文件中找到。有关参与者的名称,请参阅作者文件。
#include "util/concurrent_arena.h"
#include <thread>
#include "port/port.h"
#include "util/random.h"
namespace rocksdb {
#ifdef ROCKSDB_SUPPORT_THREAD_LOCAL
__thread size_t ConcurrentArena::tls_cpuid = 0;
#endif
ConcurrentArena::ConcurrentArena(size_t block_size, AllocTracker* tracker,
size_t huge_page_size)
: shard_block_size_(block_size / 8),
shards_(),
arena_(block_size, tracker, huge_page_size) {
Fixup();
}
ConcurrentArena::Shard* ConcurrentArena::Repick() {
auto shard_and_index = shards_.AccessElementAndIndex();
#ifdef ROCKSDB_SUPPORT_THREAD_LOCAL
//即使我们是CPU 0,也要使用非零的tls_cpuid,这样我们就可以告诉我们
//重选
tls_cpuid = shard_and_index.second | shards_.Size();
#endif
return shard_and_index.first;
}
} //命名空间rocksdb
| 24.354167 | 74 | 0.753636 | yinchengtsinghua |
4252f86f3a4026b5ede0f41551da91c9d9d87eaf | 19,861 | hpp | C++ | blast/include/objtools/data_loaders/genbank/impl/info_cache.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objtools/data_loaders/genbank/impl/info_cache.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objtools/data_loaders/genbank/impl/info_cache.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | #ifndef GENBANK_IMPL_INFO_CACHE
#define GENBANK_IMPL_INFO_CACHE
/* $Id: info_cache.hpp 497447 2016-04-06 18:19:05Z vasilche $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description:
* GenBank data loader in-memory cache
*
* ===========================================================================
*/
#include <corelib/ncbistd.hpp>
#include <corelib/ncbimtx.hpp>
#include <corelib/ncbiobj.hpp>
#include <corelib/ncbitime.hpp>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
BEGIN_SCOPE(GBL)
#define USE_MAIN_MUTEX_IN_CACHE 0
#define USE_MAIN_MUTEX_FOR_DATA 0
class CInfo_Base;
class CInfoLock_Base;
class CInfoCache_Base;
class CInfoManager;
class CInfoRequestor;
class CInfoRequestorLock;
class INoCopying
{
public:
INoCopying() {}
private:
// prevent copying
INoCopying(const INoCopying&);
void operator=(const INoCopying&);
};
enum EDoNotWait {
eAllowWaiting,
eDoNotWait
};
enum EExpirationType {
eExpire_normal,
eExpire_fast
};
class CLoadMutex : public CObject, public CMutex // CFastMutex
{
public:
CLoadMutex(void)
: m_LoadingRequestor(0)
{
}
bool IsLoading(void) const
{
return m_LoadingRequestor != 0;
}
protected:
friend class CInfoManager;
friend class CInfoRequestor;
friend class CInfoRequestorLock;
CInfoRequestor* volatile m_LoadingRequestor;
};
class CInfo_Base : public CObject, INoCopying
{
public:
typedef Uint4 TExpirationTime; // UTC time, seconds since epoch (1970)
typedef int TUseCounter;
typedef list< CRef<CInfo_Base> > TGCQueue;
explicit CInfo_Base(TGCQueue& gc_queue);
virtual ~CInfo_Base(void);
bool IsLoaded(TExpirationTime expiration_time) const;
bool IsLoaded(CInfoRequestor& requestor) const;
TExpirationTime GetExpirationTime(void) const
{
return m_ExpirationTime;
}
protected:
friend class CInfoRequestorLock;
friend class CInfoCache_Base;
friend class CInfoManager;
friend class CInfoRequestor;
// info usage counter for garbage collector
TUseCounter m_UseCounter;
// info expiration UTC time, seconds is actual until this time
volatile TExpirationTime m_ExpirationTime;
CRef<CLoadMutex> m_LoadMutex; // mutex for loading info
TGCQueue::iterator m_GCQueuePos; // pos in GC queue if info is not used
};
// CInfoRequestorLock is a lock within a single requesting thread.
// There is no MT-safety required when operating on the CInfoRequestorLock.
// It holds MT-lock for the loaded info object.
class CInfoRequestorLock : public CObject, INoCopying
{
public:
CInfoRequestorLock(CInfoRequestor& requestor, CInfo_Base& info);
~CInfoRequestorLock(void);
protected:
friend class CInfoLock_Base;
friend class CInfoCache_Base;
friend class CInfoRequestor;
friend class CInfoManager;
typedef CInfo_Base::TExpirationTime TExpirationTime;
CInfo_Base& GetInfo(void) const
{
return m_Info.GetNCObject();
}
CInfoRequestor& GetRequestor(void) const
{
return m_Requestor;
}
TExpirationTime GetNewExpirationTime(EExpirationType type) const;
CInfoManager& GetManager(void) const;
bool IsLocked(void) const
{
return m_Mutex.NotNull();
}
bool IsLoaded(void) const;
bool SetLoadedFor(TExpirationTime new_expiration_time);
bool SetLoaded(EExpirationType type);
TExpirationTime GetExpirationTime(void) const
{
return GetInfo().GetExpirationTime();
}
typedef CMutex TMainMutex; // CFastMutex
bool x_SetLoadedFor(TMainMutex::TWriteLockGuard& guard,
TExpirationTime new_expiration_time);
bool x_SetLoaded(TMainMutex::TWriteLockGuard& guard,
EExpirationType type);
CInfoRequestor& m_Requestor;
CRef<CInfo_Base> m_Info;
CRef<CLoadMutex> m_Mutex;
};
class CInfoManager : public CObject, INoCopying
{
public:
CInfoManager(void);
virtual ~CInfoManager(void);
typedef CMutex TMainMutex; // CFastMutex
TMainMutex& GetMainMutex(void)
{
return m_MainMutex;
}
void ReleaseAllLoadLocks(CInfoRequestor& requestor);
void ReleaseLoadLock(CInfoRequestorLock& lock);
protected:
friend class CInfoRequestor;
friend class CInfoRequestorLock;
friend class CInfoCache_Base;
bool x_WaitForOtherLoader(TMainMutex::TWriteLockGuard& guard,
CInfoRequestorLock& lock);
bool x_DeadLock(const CInfoRequestor& requestor,
const CInfo_Base& info) const;
void x_AssignLoadMutex(CRef<CLoadMutex>& mutex);
void x_ReleaseLoadMutex(CRef<CLoadMutex>& mutex);
void x_AssignLoadMutex(CInfo_Base& info);
void x_ReleaseLoadMutex(CInfo_Base& info);
void x_LockInfoMutex(CInfoRequestorLock& lock);
void x_UnlockInfoMutex(CInfoRequestorLock& lock);
void x_ReleaseLoadLock(CInfoRequestorLock& lock);
void x_AcquireLoadLock(TMainMutex::TWriteLockGuard& guard,
CInfoRequestorLock& lock,
EDoNotWait do_not_wait);
void x_AcquireLoadLock(CInfoRequestorLock& lock,
EDoNotWait do_not_wait);
typedef vector< CRef<CLoadMutex> > TLoadMutexPool;
TMainMutex m_MainMutex;
TLoadMutexPool m_LoadMutexPool;
};
class CInfoRequestor : INoCopying
{
public:
explicit CInfoRequestor(CInfoManager& manager);
virtual ~CInfoRequestor(void);
void ReleaseAllLoadLocks(void)
{
GetManager().ReleaseAllLoadLocks(*this);
}
typedef CInfo_Base::TExpirationTime TExpirationTime;
virtual TExpirationTime GetRequestTime(void) const = 0;
virtual TExpirationTime GetNewExpirationTime(EExpirationType type) const = 0;
protected:
friend class CInfoManager;
friend class CInfoRequestorLock;
friend class CInfoCache_Base;
CInfoManager& GetManager(void) const
{
return m_Manager.GetNCObject();
}
void ReleaseAllUsedInfos(void);
void ReleaseLoadLock(CInfoRequestorLock& lock)
{
GetManager().ReleaseLoadLock(lock);
}
CRef<CInfoRequestorLock> x_GetLock(CInfoCache_Base& cache,
CInfo_Base& info);
struct PtrHash {
size_t operator()(const void* ptr) const {
return size_t(ptr)>>3;
}
};
typedef unordered_map<CInfo_Base*, CRef<CInfoRequestorLock>, PtrHash> TLockMap;
typedef unordered_map<CInfoCache_Base*, vector<CInfo_Base*>, PtrHash> TCacheMap;
CRef<CInfoManager> m_Manager;
TLockMap m_LockMap; // map from CInfo_Base -> CInfoRequestorLock
TCacheMap m_CacheMap; // map of used infos
//set< CRef<CInfo_Base> > m_LockedInfos;
CRef<CInfo_Base> m_WaitingForInfo;
};
inline
bool CInfo_Base::IsLoaded(TExpirationTime expiration_time) const
{
return GetExpirationTime() >= expiration_time;
}
inline
bool CInfo_Base::IsLoaded(CInfoRequestor& requestor) const
{
return IsLoaded(requestor.GetRequestTime());
}
inline
bool CInfoRequestorLock::IsLoaded(void) const
{
return GetInfo().IsLoaded(GetRequestor());
}
inline
CInfoRequestorLock::TExpirationTime
CInfoRequestorLock::GetNewExpirationTime(EExpirationType type) const
{
return GetRequestor().GetNewExpirationTime(type);
}
inline
bool CInfoRequestorLock::SetLoaded(EExpirationType type)
{
return SetLoadedFor(GetNewExpirationTime(type));
}
inline
bool CInfoRequestorLock::x_SetLoaded(TMainMutex::TWriteLockGuard& guard,
EExpirationType type)
{
return x_SetLoadedFor(guard, GetNewExpirationTime(type));
}
inline
CInfoManager& CInfoRequestorLock::GetManager(void) const
{
return GetRequestor().GetManager();
}
class CInfoLock_Base
{
public:
typedef CInfo_Base::TExpirationTime TExpirationTime;
bool IsLocked(void) const
{
return m_Lock->IsLocked();
}
bool IsLoaded(void) const
{
return m_Lock->IsLoaded();
}
bool SetLoadedFor(TExpirationTime expiration_time)
{
return m_Lock->SetLoadedFor(expiration_time);
}
bool SetLoaded(EExpirationType type)
{
return m_Lock->SetLoaded(type);
}
TExpirationTime GetExpirationTime(void) const
{
return m_Lock->GetExpirationTime();
}
TExpirationTime GetNewExpirationTime(EExpirationType type) const
{
return m_Lock->GetNewExpirationTime(type);
}
CInfoRequestor& GetRequestor(void) const
{
return m_Lock->GetRequestor();
}
DECLARE_OPERATOR_BOOL_REF(m_Lock);
protected:
friend class CInfoManager;
friend class CInfoCache_Base;
#if USE_MAIN_MUTEX_FOR_DATA
typedef CInfoManager::TMainMutex TDataMutex;
TDataMutex& GetDataLock(void) const
{
return m_Lock->GetManager().GetMainMutex();
}
bool x_SetLoadedFor(TDataMutex::TWriteLockGuard& guard,
TExpirationTime expiration_time)
{
return m_Lock->x_SetLoadedFor(guard, expiration_time);
}
bool x_SetLoaded(TDataMutex::TWriteLockGuard& guard,
EExpirationType type)
{
return m_Lock->x_SetLoaded(guard, type);
}
#else
typedef CMutex TDataMutex; // CFastMutex
DECLARE_CLASS_STATIC_MUTEX(sm_DataMutex);
SSystemMutex& GetDataLock(void) const
{
return sm_DataMutex;
}
bool x_SetLoadedFor(TDataMutex::TWriteLockGuard& /*guard*/,
TExpirationTime expiration_time)
{
return m_Lock->SetLoadedFor(expiration_time);
}
bool x_SetLoaded(TDataMutex::TWriteLockGuard& /*guard*/,
EExpirationType type)
{
return m_Lock->SetLoaded(type);
}
#endif
CInfo_Base& GetInfo(void) const
{
return m_Lock->GetInfo();
}
CRef<CInfoRequestorLock> m_Lock;
};
class CInfoCache_Base : INoCopying
{
public:
enum {
kDefaultMaxSize = 10240
};
explicit CInfoCache_Base(CInfoManager::TMainMutex& mutex);
CInfoCache_Base(CInfoManager::TMainMutex& mutex, size_t max_size);
virtual ~CInfoCache_Base(void);
size_t GetMaxGCQueueSize(void) const
{
return m_MaxGCQueueSize;
}
void SetMaxGCQueueSize(size_t max_size);
protected:
friend class CInfoLock_Base;
friend class CInfoManager;
friend class CInfoRequestor;
typedef CInfoManager::TMainMutex TMainMutex;
#if USE_MAIN_MUTEX_IN_CACHE
typedef TMainMutex TCacheMutex;
TCacheMutex& m_CacheMutex;
#else
typedef CMutex TCacheMutex; // CFastMutex
TCacheMutex m_CacheMutex;
#endif
// mark info as used and set it into CInfoLock_Base
void x_SetInfo(CInfoLock_Base& lock,
CInfoRequestor& requestor,
CInfo_Base& info);
// try to acquire lock or leave it unlocked if deadlock is possible
#if USE_MAIN_MUTEX_IN_CACHE
void x_AcquireLoadLock(TMainMutex::TWriteLockGuard& guard,
CInfoRequestorLock& lock,
EDoNotWait do_not_wait)
{
lock.GetManager().x_AcquireLoadLock(guard, lock, do_not_wait);
}
#else
void x_AcquireLoadLock(TCacheMutex::TWriteLockGuard& guard,
CInfoRequestorLock& lock,
EDoNotWait do_not_wait)
{
guard.Release();
lock.GetManager().x_AcquireLoadLock(lock, do_not_wait);
}
#endif
void x_AcquireLoadLock(TMainMutex::TWriteLockGuard& guard,
CInfoLock_Base& lock,
EDoNotWait do_not_wait)
{
x_AcquireLoadLock(guard, *lock.m_Lock, do_not_wait);
}
bool x_Check(const vector<const CInfo_Base*>& infos) const;
void ReleaseInfos(const vector<CInfo_Base*>& infos);
void x_SetUsed(CInfo_Base& info);
void x_SetUnused(CInfo_Base& info);
void x_RemoveFromGCQueue(CInfo_Base& info);
void x_AddToGCQueue(CInfo_Base& info);
void x_GC(void);
virtual void x_ForgetInfo(CInfo_Base& info) = 0;
typedef CInfo_Base::TGCQueue TGCQueue;
size_t m_MaxGCQueueSize, m_MinGCQueueSize, m_CurGCQueueSize;
TGCQueue m_GCQueue;
};
template<class DataType> class CInfoLock;
template<class DataType>
class CInfo_DataBase : public CInfo_Base
{
public:
typedef DataType TData;
protected:
friend class CInfoLock<TData>;
explicit CInfo_DataBase(typename CInfo_Base::TGCQueue& gc_queue)
: CInfo_Base(gc_queue)
{
}
TData m_Data;
};
template<class DataType>
class CInfoLock : public CInfoLock_Base
{
public:
typedef CInfo_DataBase<DataType> TInfo;
typedef DataType TData;
TData GetData(void) const
{
TDataMutex::TReadLockGuard guard(GetDataLock());
return GetInfo().m_Data;
}
bool SetLoaded(const TData& data, EExpirationType type)
{
TDataMutex::TWriteLockGuard guard(GetDataLock());
bool changed = x_SetLoaded(guard, type);
if ( changed ) {
GetInfo().m_Data = data;
}
return changed;
}
bool SetLoadedFor(const TData& data, TExpirationTime expiration_time)
{
TDataMutex::TWriteLockGuard guard(GetDataLock());
bool changed = x_SetLoadedFor(guard, expiration_time);
if ( changed ) {
GetInfo().m_Data = data;
}
return changed;
}
protected:
TInfo& GetInfo(void) const
{
return static_cast<TInfo&>(CInfoLock_Base::GetInfo());
}
};
template<class KeyType, class DataType>
class CInfoCache : public CInfoCache_Base
{
public:
typedef KeyType key_type;
typedef DataType data_type;
typedef CInfo_Base::TExpirationTime TExpirationTime;
explicit CInfoCache(CInfoManager::TMainMutex& mutex)
: CInfoCache_Base(mutex)
{
}
CInfoCache(CInfoManager::TMainMutex& mutex, size_t max_size)
: CInfoCache_Base(mutex, max_size)
{
}
~CInfoCache(void)
{
}
class CInfo : public CInfo_DataBase<DataType>
{
public:
typedef KeyType TKey;
const TKey& GetKey(void) const
{
return m_Key;
}
protected:
friend class CInfoCache;
CInfo(typename CInfo_Base::TGCQueue& gc_queue, const TKey& key)
: CInfo_DataBase<DataType>(gc_queue),
m_Key(key)
{
}
TKey m_Key;
};
typedef CInfo TInfo;
typedef CInfoLock<DataType> TInfoLock;
bool IsLoaded(CInfoRequestor& requestor,
const key_type& key)
{
TCacheMutex::TReadLockGuard guard(m_CacheMutex);
_ASSERT(x_Check());
typename TIndex::iterator iter = m_Index.find(key);
return iter != m_Index.end() && iter->second->IsLoaded(requestor);
}
bool MarkLoading(CInfoRequestor& requestor,
const key_type& key)
{
return !GetLoadLock(requestor, key).IsLoaded();
}
TInfoLock GetLoadLock(CInfoRequestor& requestor,
const key_type& key,
EDoNotWait do_not_wait = eAllowWaiting)
{
TInfoLock lock;
_ASSERT(x_Check());
TCacheMutex::TWriteLockGuard guard(m_CacheMutex);
CRef<CInfo>& slot = m_Index[key];
if ( !slot ) {
// new slot
slot = new CInfo(m_GCQueue, key);
}
x_SetInfo(lock, requestor, *slot);
x_AcquireLoadLock(guard, lock, do_not_wait);
_ASSERT(x_Check());
return lock;
}
bool SetLoaded(CInfoRequestor& requestor,
const key_type& key,
const data_type& value,
EExpirationType type)
{
TCacheMutex::TWriteLockGuard guard(m_CacheMutex);
_ASSERT(x_Check());
CRef<CInfo>& slot = m_Index[key];
if ( !slot ) {
// new slot
slot = new CInfo(m_GCQueue, key);
}
TInfoLock lock;
x_SetInfo(lock, requestor, *slot);
_ASSERT(x_Check());
return lock.SetLoaded(value, type);
}
bool SetLoadedFor(CInfoRequestor& requestor,
const key_type& key,
const data_type& value,
TExpirationTime expiration_time)
{
TCacheMutex::TWriteLockGuard guard(m_CacheMutex);
_ASSERT(x_Check());
CRef<CInfo>& slot = m_Index[key];
if ( !slot ) {
// new slot
slot = new CInfo(m_GCQueue, key);
}
TInfoLock lock;
x_SetInfo(lock, requestor, *slot);
_ASSERT(x_Check());
return lock.SetLoadedFor(value, expiration_time);
}
TInfoLock GetLoaded(CInfoRequestor& requestor,
const key_type& key)
{
TInfoLock lock;
TCacheMutex::TWriteLockGuard guard(m_CacheMutex);
_ASSERT(x_Check());
typename TIndex::iterator iter = m_Index.find(key);
if ( iter != m_Index.end() &&
iter->second->IsLoaded(requestor) ) {
x_SetInfo(lock, requestor, *iter->second);
}
_ASSERT(x_Check());
return lock;
}
protected:
friend class CInfoLock_Base;
bool x_Check(void) const
{
return true;
vector<const CInfo_Base*> infos;
ITERATE ( typename TIndex, it, m_Index ) {
infos.push_back(it->second);
}
return CInfoCache_Base::x_Check(infos);
}
virtual void x_ForgetInfo(CInfo_Base& info_base)
{
_ASSERT(dynamic_cast<TInfo*>(&info_base));
_VERIFY(m_Index.erase(static_cast<TInfo&>(info_base).GetKey()));
}
private:
typedef map<key_type, CRef<TInfo> > TIndex;
TIndex m_Index;
};
END_SCOPE(GBL)
END_SCOPE(objects)
END_NCBI_SCOPE
#endif // GENBANK_IMPL_INFO_CACHE
| 27.394483 | 84 | 0.632345 | mycolab |
425971bfbfba9c353863dbd86bee053dd268e749 | 7,120 | cc | C++ | zircon/system/ulib/kernel-mexec/kernel-mexec_test.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | zircon/system/ulib/kernel-mexec/kernel-mexec_test.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | zircon/system/ulib/kernel-mexec/kernel-mexec_test.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | #include <zxtest/zxtest.h>
#include <vector>
#include <lib/kernel-mexec/kernel-mexec.h>
#include <fuchsia/device/manager/c/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <zircon/assert.h>
#include <lib/fidl-async/bind.h>
#include <lib/svc/outgoing.h>
#include <lib/zx/vmar.h>
#include <libzbi/zbi-cpp.h>
namespace {
class FakeSysCalls {
public:
FakeSysCalls() : zbi(zbi_data, kZbiSize) {}
internal::MexecSysCalls Interface() {
return {
.mexec =
[this](zx_handle_t root, zx_handle_t kernel, zx_handle_t bootdata) {
size_t kernel_size = 0;
auto status = zx_vmo_get_size(kernel, &kernel_size);
if (status != ZX_OK)
return status;
received_kernel.resize(kernel_size);
status = zx_vmo_read(kernel, received_kernel.data(), 0, kernel_size);
if (status != ZX_OK)
return status;
size_t bootdata_size = 0;
status = zx_vmo_get_size(bootdata, &bootdata_size);
if (status != ZX_OK)
return status;
received_bootdata.resize(bootdata_size);
status = zx_vmo_read(bootdata, received_bootdata.data(), 0, bootdata_size);
if (status != ZX_OK)
return status;
return ZX_OK;
},
.mexec_payload_get =
[this](zx_handle_t root, void* data, size_t size) {
memcpy(data, zbi_data, std::min(size, kZbiSize));
return ZX_OK;
},
};
}
std::vector<uint8_t> received_kernel;
std::vector<uint8_t> received_bootdata;
static constexpr size_t kZbiSize = 512;
uint8_t zbi_data[kZbiSize];
zbi::Zbi zbi;
};
class MexecTest : public zxtest::Test {
public:
MexecTest() {
ops_.Suspend = [](void* ctx, uint32_t flags, fidl_txn_t* txn) {
return fuchsia_device_manager_AdministratorSuspend_reply(
txn, reinterpret_cast<MexecTest*>(ctx)->suspend_callback_(flags));
};
}
static void SetUpTestCase() {
loop_ = std::make_unique<async::Loop>(&kAsyncLoopConfigNoAttachToCurrentThread);
ZX_ASSERT(ZX_OK == loop_->StartThread("MexecTestLoop"));
}
static void TearDownTestCase() { loop_ = nullptr; }
protected:
void SetUp() override {
outgoing_ = std::make_unique<svc::Outgoing>(loop_->dispatcher());
ASSERT_OK(zx::vmo::create(1024, 0, &kernel_));
ASSERT_OK(zx::vmo::create(1024, 0, &bootdata_));
ASSERT_EQ(ZBI_RESULT_OK, sys_calls_.zbi.Reset());
ASSERT_EQ(ZBI_RESULT_OK, sys_calls_.zbi.Check(nullptr));
ASSERT_OK(bootdata_.write(sys_calls_.zbi_data, 0, 512));
zx::channel listening;
ASSERT_OK(zx::channel::create(0, &suspend_service_, &listening));
context_.devmgr_channel = zx::unowned_channel(suspend_service_);
const auto service = [this](zx::channel request) {
return fidl_bind(
loop_->dispatcher(), request.release(),
reinterpret_cast<fidl_dispatch_t*>(fuchsia_device_manager_Administrator_dispatch), this,
&ops_);
};
outgoing_->root_dir()->AddEntry(fuchsia_device_manager_Administrator_Name,
fbl::MakeRefCounted<fs::Service>(service));
outgoing_->Serve(std::move(listening));
}
KernelMexecContext context_;
FakeSysCalls sys_calls_;
zx::channel suspend_service_;
std::function<zx_status_t(uint32_t)> suspend_callback_ = [](uint32_t) { return ZX_OK; };
fuchsia_device_manager_Administrator_ops_t ops_;
std::unique_ptr<svc::Outgoing> outgoing_;
zx::vmo kernel_;
zx::vmo bootdata_;
static std::unique_ptr<async::Loop> loop_;
};
std::unique_ptr<async::Loop> MexecTest::loop_;
static const std::string kKernelText("I'M A KERNEL!");
struct CheckConditions {
bool has_crash_log = false;
bool has_others = false;
};
} // namespace
TEST_F(MexecTest, Success) {
void* data = nullptr;
ASSERT_EQ(ZBI_RESULT_OK, sys_calls_.zbi.CreateSection(50, ZBI_TYPE_CRASHLOG, 0, 0, &data));
ASSERT_OK(kernel_.write(kKernelText.c_str(), 0, kKernelText.length()));
auto status = internal::PerformMexec(static_cast<void*>(&context_), kernel_.get(),
bootdata_.get(), sys_calls_.Interface());
// BAD_STATE is expected. Normally the mexec syscall should not return so
// this method should never return.
ASSERT_EQ(ZX_ERR_BAD_STATE, status);
// Ensure the kernel VMO still has the same kernel data.
ASSERT_GE(sys_calls_.received_kernel.size(), kKernelText.length());
ASSERT_BYTES_EQ(kKernelText.c_str(), sys_calls_.received_kernel.data(), kKernelText.length());
// Ensure the bootdata is still valid and has the zbi from mexec_payload_get
// added to it.
zbi::Zbi received_zbi(sys_calls_.received_bootdata.data());
ASSERT_EQ(ZBI_RESULT_OK, received_zbi.Check(nullptr));
CheckConditions conditions;
ASSERT_EQ(ZBI_RESULT_OK, received_zbi.ForEach(
[](zbi_header_t* hdr, void*, void* ctx) {
auto* conditions = reinterpret_cast<CheckConditions*>(ctx);
if (hdr->type == ZBI_TYPE_CRASHLOG) {
conditions->has_crash_log = true;
} else {
fprintf(stderr, "Found other zbi entry: %d\n", hdr->type);
conditions->has_others = true;
}
return ZBI_RESULT_OK;
},
static_cast<void*>(&conditions)));
ASSERT_EQ(true, conditions.has_crash_log);
ASSERT_EQ(false, conditions.has_others);
}
TEST_F(MexecTest, SuspendFail) {
// Use an error that is unlikely to occur otherwise.
const auto error = ZX_ERR_ADDRESS_UNREACHABLE;
suspend_callback_ = [](uint32_t) { return error; };
auto status = internal::PerformMexec(static_cast<void*>(&context_), kernel_.get(),
bootdata_.get(), sys_calls_.Interface());
ASSERT_EQ(error, status);
}
TEST_F(MexecTest, MexecPayloadFail) {
// Use an error that is unlikely to occur otherwise.
const auto error = ZX_ERR_ADDRESS_UNREACHABLE;
auto sys_calls = sys_calls_.Interface();
sys_calls.mexec_payload_get = [](zx_handle_t, void* buffer, size_t size) { return error; };
auto status = internal::PerformMexec(static_cast<void*>(&context_), kernel_.get(),
bootdata_.get(), sys_calls);
ASSERT_EQ(error, status);
}
TEST_F(MexecTest, MexecPayloadJunk) {
auto sys_calls = sys_calls_.Interface();
sys_calls.mexec_payload_get = [](zx_handle_t, void* buffer, size_t size) {
char* char_buffer = static_cast<char*>(buffer);
for (size_t i = 0; i < size; i++) {
*(char_buffer++) = 0xA;
}
return ZX_OK;
};
auto status = internal::PerformMexec(static_cast<void*>(&context_), kernel_.get(),
bootdata_.get(), sys_calls);
ASSERT_NE(ZX_ERR_BAD_STATE, status);
}
| 33.42723 | 98 | 0.63427 | opensource-assist |
425ad57f0ec487f910bb9d842de40c70bfe72c4e | 9,890 | cpp | C++ | TRANSmission/Intermediate/Build/Win64/UE4Editor/Inc/TRANSmission/Vibrator.gen.cpp | daff0111/GGJ2018 | 2d14edb4f1ba6a281985c758961939294cdeda9a | [
"MIT"
] | null | null | null | TRANSmission/Intermediate/Build/Win64/UE4Editor/Inc/TRANSmission/Vibrator.gen.cpp | daff0111/GGJ2018 | 2d14edb4f1ba6a281985c758961939294cdeda9a | [
"MIT"
] | null | null | null | TRANSmission/Intermediate/Build/Win64/UE4Editor/Inc/TRANSmission/Vibrator.gen.cpp | daff0111/GGJ2018 | 2d14edb4f1ba6a281985c758961939294cdeda9a | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "Vibrator.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeVibrator() {}
// Cross Module References
TRANSMISSION_API UEnum* Z_Construct_UEnum_TRANSmission_EController();
UPackage* Z_Construct_UPackage__Script_TRANSmission();
TRANSMISSION_API UEnum* Z_Construct_UEnum_TRANSmission_EMorseInput();
TRANSMISSION_API UClass* Z_Construct_UClass_AVibrator_NoRegister();
TRANSMISSION_API UClass* Z_Construct_UClass_AVibrator();
ENGINE_API UClass* Z_Construct_UClass_AActor();
ENGINE_API UClass* Z_Construct_UClass_UForceFeedbackEffect_NoRegister();
// End Cross Module References
static UEnum* EController_StaticEnum()
{
static UEnum* Singleton = nullptr;
if (!Singleton)
{
Singleton = GetStaticEnum(Z_Construct_UEnum_TRANSmission_EController, Z_Construct_UPackage__Script_TRANSmission(), TEXT("EController"));
}
return Singleton;
}
static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_EController(EController_StaticEnum, TEXT("/Script/TRANSmission"), TEXT("EController"), false, nullptr, nullptr);
uint32 Get_Z_Construct_UEnum_TRANSmission_EController_CRC() { return 4001267138U; }
UEnum* Z_Construct_UEnum_TRANSmission_EController()
{
#if WITH_HOT_RELOAD
UPackage* Outer = Z_Construct_UPackage__Script_TRANSmission();
static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("EController"), 0, Get_Z_Construct_UEnum_TRANSmission_EController_CRC(), false);
#else
static UEnum* ReturnEnum = nullptr;
#endif // WITH_HOT_RELOAD
if (!ReturnEnum)
{
static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = {
{ "EController::Player1", (int64)EController::Player1 },
{ "EController::Player2", (int64)EController::Player2 },
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "ModuleRelativePath", "Vibrator.h" },
};
#endif
static const UE4CodeGen_Private::FEnumParams EnumParams = {
(UObject*(*)())Z_Construct_UPackage__Script_TRANSmission,
UE4CodeGen_Private::EDynamicType::NotDynamic,
"EController",
RF_Public|RF_Transient|RF_MarkAsNative,
nullptr,
(uint8)UEnum::ECppForm::EnumClass,
"EController",
Enumerators,
ARRAY_COUNT(Enumerators),
METADATA_PARAMS(Enum_MetaDataParams, ARRAY_COUNT(Enum_MetaDataParams))
};
UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams);
}
return ReturnEnum;
}
static UEnum* EMorseInput_StaticEnum()
{
static UEnum* Singleton = nullptr;
if (!Singleton)
{
Singleton = GetStaticEnum(Z_Construct_UEnum_TRANSmission_EMorseInput, Z_Construct_UPackage__Script_TRANSmission(), TEXT("EMorseInput"));
}
return Singleton;
}
static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_EMorseInput(EMorseInput_StaticEnum, TEXT("/Script/TRANSmission"), TEXT("EMorseInput"), false, nullptr, nullptr);
uint32 Get_Z_Construct_UEnum_TRANSmission_EMorseInput_CRC() { return 797329059U; }
UEnum* Z_Construct_UEnum_TRANSmission_EMorseInput()
{
#if WITH_HOT_RELOAD
UPackage* Outer = Z_Construct_UPackage__Script_TRANSmission();
static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("EMorseInput"), 0, Get_Z_Construct_UEnum_TRANSmission_EMorseInput_CRC(), false);
#else
static UEnum* ReturnEnum = nullptr;
#endif // WITH_HOT_RELOAD
if (!ReturnEnum)
{
static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = {
{ "EMorseInput::A", (int64)EMorseInput::A },
{ "EMorseInput::B", (int64)EMorseInput::B },
{ "EMorseInput::X", (int64)EMorseInput::X },
{ "EMorseInput::Y", (int64)EMorseInput::Y },
{ "EMorseInput::S", (int64)EMorseInput::S },
{ "EMorseInput::U", (int64)EMorseInput::U },
{ "EMorseInput::C", (int64)EMorseInput::C },
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "ModuleRelativePath", "Vibrator.h" },
};
#endif
static const UE4CodeGen_Private::FEnumParams EnumParams = {
(UObject*(*)())Z_Construct_UPackage__Script_TRANSmission,
UE4CodeGen_Private::EDynamicType::NotDynamic,
"EMorseInput",
RF_Public|RF_Transient|RF_MarkAsNative,
nullptr,
(uint8)UEnum::ECppForm::EnumClass,
"EMorseInput",
Enumerators,
ARRAY_COUNT(Enumerators),
METADATA_PARAMS(Enum_MetaDataParams, ARRAY_COUNT(Enum_MetaDataParams))
};
UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams);
}
return ReturnEnum;
}
void AVibrator::StaticRegisterNativesAVibrator()
{
}
UClass* Z_Construct_UClass_AVibrator_NoRegister()
{
return AVibrator::StaticClass();
}
UClass* Z_Construct_UClass_AVibrator()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
static UObject* (*const DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_AActor,
(UObject* (*)())Z_Construct_UPackage__Script_TRANSmission,
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = {
{ "IncludePath", "Vibrator.h" },
{ "ModuleRelativePath", "Vibrator.h" },
};
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DashHapticFeedback_MetaData[] = {
{ "Category", "Vibrator" },
{ "ModuleRelativePath", "Vibrator.h" },
};
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_DashHapticFeedback = { UE4CodeGen_Private::EPropertyClass::Object, "DashHapticFeedback", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AVibrator, DashHapticFeedback), Z_Construct_UClass_UForceFeedbackEffect_NoRegister, METADATA_PARAMS(NewProp_DashHapticFeedback_MetaData, ARRAY_COUNT(NewProp_DashHapticFeedback_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DotHapticFeedback_MetaData[] = {
{ "Category", "Vibrator" },
{ "ModuleRelativePath", "Vibrator.h" },
};
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_DotHapticFeedback = { UE4CodeGen_Private::EPropertyClass::Object, "DotHapticFeedback", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AVibrator, DotHapticFeedback), Z_Construct_UClass_UForceFeedbackEffect_NoRegister, METADATA_PARAMS(NewProp_DotHapticFeedback_MetaData, ARRAY_COUNT(NewProp_DotHapticFeedback_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SignalToPlay_MetaData[] = {
{ "Category", "Vibrator" },
{ "ModuleRelativePath", "Vibrator.h" },
};
#endif
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_SignalToPlay = { UE4CodeGen_Private::EPropertyClass::Enum, "SignalToPlay", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AVibrator, SignalToPlay), Z_Construct_UEnum_TRANSmission_EMorseInput, METADATA_PARAMS(NewProp_SignalToPlay_MetaData, ARRAY_COUNT(NewProp_SignalToPlay_MetaData)) };
static const UE4CodeGen_Private::FBytePropertyParams NewProp_SignalToPlay_Underlying = { UE4CodeGen_Private::EPropertyClass::Byte, "UnderlyingType", RF_Public|RF_Transient|RF_MarkAsNative, 0x0000000000000000, 1, nullptr, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PlaySignal_MetaData[] = {
{ "Category", "Vibrator" },
{ "ModuleRelativePath", "Vibrator.h" },
{ "ToolTip", "Test" },
};
#endif
auto NewProp_PlaySignal_SetBit = [](void* Obj){ ((AVibrator*)Obj)->PlaySignal = 1; };
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_PlaySignal = { UE4CodeGen_Private::EPropertyClass::Bool, "PlaySignal", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(AVibrator), &UE4CodeGen_Private::TBoolSetBitWrapper<decltype(NewProp_PlaySignal_SetBit)>::SetBit, METADATA_PARAMS(NewProp_PlaySignal_MetaData, ARRAY_COUNT(NewProp_PlaySignal_MetaData)) };
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_DashHapticFeedback,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_DotHapticFeedback,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_SignalToPlay,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_SignalToPlay_Underlying,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_PlaySignal,
};
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = {
TCppClassTypeTraits<AVibrator>::IsAbstract,
};
static const UE4CodeGen_Private::FClassParams ClassParams = {
&AVibrator::StaticClass,
DependentSingletons, ARRAY_COUNT(DependentSingletons),
0x00900080u,
nullptr, 0,
PropPointers, ARRAY_COUNT(PropPointers),
nullptr,
&StaticCppClassTypeInfo,
nullptr, 0,
METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams))
};
UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AVibrator, 3214353239);
static FCompiledInDefer Z_CompiledInDefer_UClass_AVibrator(Z_Construct_UClass_AVibrator, &AVibrator::StaticClass, TEXT("/Script/TRANSmission"), TEXT("AVibrator"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AVibrator);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 47.548077 | 456 | 0.768959 | daff0111 |