text
string
size
int64
token_count
int64
//===----------------------------------------------------------------------===// // // This file is part of the Noxoscope project // // Copyright (c) 2016 Niklas Helmertz // //===----------------------------------------------------------------------===// #include "TestShared.h" #include <Logging.h> #include <GeometryMath.h> TEST_CASE("Example test") { REQUIRE(1 + 1 == 2); } TEST_CASE("Test converting spherical and back") { using namespace glm; rc::prop("", []() { float radius = floatInRange(0.01f, 100.0f); float inclination = floatInRange(0.0f, PI_F); float azimuth = floatInRange(0.0f, 2.0f * PI_F); vec3 cartesian = sphericalToCartesian(radius, inclination, azimuth); vec3 sphericalRes = cartesianToSpherical(cartesian); float resRadius = sphericalRes.x; float resInclination = sphericalRes.y; float resAzimuth = fmod(sphericalRes.z + 2.0f * PI_F, 2.0f * PI_F); // Convert from [-pi,pi] to [0,2*pi] RC_ASSERT(approxEqual(radius, resRadius)); RC_ASSERT(approxEqual(inclination, resInclination)); // If inclination is either straight up or down, any azimuth would be valid if (!approxEqual(inclination, 0.0f) && !approxEqual(inclination, PI_F)) { RC_ASSERT(approxEqual(azimuth, resAzimuth)); } }); }
1,247
470
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cuml/fil/fnv_hash.h> #include <gtest/gtest.h> #include <raft/error.hpp> struct fnv_vec_t { std::vector<char> input; unsigned long long correct_64bit; uint32_t correct_32bit; }; class FNVHashTest : public testing::TestWithParam<fnv_vec_t> { protected: void SetUp() override { param = GetParam(); } void check() { unsigned long long hash_64bit = fowler_noll_vo_fingerprint64(param.input.begin(), param.input.end()); ASSERT(hash_64bit == param.correct_64bit, "Wrong hash computed"); unsigned long hash_32bit = fowler_noll_vo_fingerprint64_32(param.input.begin(), param.input.end()); ASSERT(hash_32bit == param.correct_32bit, "Wrong xor-folded hash computed"); } fnv_vec_t param; }; std::vector<fnv_vec_t> fnv_vecs = { {{}, 14695981039346656037ull, 0xcbf29ce4 ^ 0x84222325}, // test #0 // 32-bit output is xor-folded 64-bit output. The format below makes this obvious. {{0}, 0xaf63bd4c8601b7df, 0xaf63bd4c ^ 0x8601b7df}, {{1}, 0xaf63bd4c8601b7de, 0xaf63bd4c ^ 0x8601b7de}, {{2}, 0xaf63bd4c8601b7dd, 0xaf63bd4c ^ 0x8601b7dd}, {{3}, 0xaf63bd4c8601b7dc, 0xaf63bd4c ^ 0x8601b7dc}, {{1, 2}, 0x08328707b4eb6e38, 0x08328707 ^ 0xb4eb6e38}, // test #5 {{2, 1}, 0x08328607b4eb6c86, 0x08328607 ^ 0xb4eb6c86}, {{1, 2, 3}, 0xd949aa186c0c492b, 0xd949aa18 ^ 0x6c0c492b}, {{1, 3, 2}, 0xd949ab186c0c4ad9, 0xd949ab18 ^ 0x6c0c4ad9}, {{2, 1, 3}, 0xd94645186c0967b1, 0xd9464518 ^ 0x6c0967b1}, {{2, 3, 1}, 0xd94643186c09644d, 0xd9464318 ^ 0x6c09644d}, // test #10 {{3, 1, 2}, 0xd942e1186c0687ed, 0xd942e118 ^ 0x6c0687ed}, {{3, 2, 1}, 0xd942e2186c0689a3, 0xd942e218 ^ 0x6c0689a3}, }; TEST_P(FNVHashTest, Import) { check(); } INSTANTIATE_TEST_CASE_P(FilTests, FNVHashTest, testing::ValuesIn(fnv_vecs));
2,376
1,232
#include "GamePCH.h" #include "GameObjects/GameObject.h" #include "Trainer.h" #include "Controllers/PlayerController.h" #include "Sprites/AnimatedSprite.h" #include "GameplayHelpers/ResourceManager.h" #include "GameplayHelpers/TileMap.h" #include "Mesh/Mesh.h" #include "GameplayHelpers/SceneManager.h" #include "Scenes/Scene.h" #include "Scenes/OakLab.h" #include "Scenes/PalletTown.h" Trainer::Trainer(ResourceManager * aResourceManager, GameCore * myGame, Mesh * myMesh, GLuint aTexture) :GameObject(myGame, myMesh, aTexture) { myDirection = SpriteWalkDown; myResourceManager = aResourceManager; m_pMesh->GenerateFrameMesh(); //Initialize the animated sprites for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i] = new AnimatedSprite(myResourceManager, myGame, myMesh, 2, aTexture); m_Animations[i]->AddFrame(AnimationKeys[i] + "1.png"); m_Animations[i]->AddFrame(AnimationKeys[i] + "2.png"); m_Animations[i]->AddFrame(AnimationKeys[i] + "1.png"); m_Animations[i]->AddFrame(AnimationKeys[i] + "3.png"); m_Animations[i]->SetFrameSpeed(6.0f); m_Animations[i]->SetLoop(true); m_Animations[i]->SetPosition(m_Position); } m_Stop = false; m_InTransition = false; } Trainer::~Trainer() { for (int i = 0; i < NUM_DIRECTIONS; i++) { delete m_Animations[i]; m_Animations[i] = nullptr; } myResourceManager = nullptr; } void Trainer::Update(float deltatime) { Pause(); if (m_InTransition == false) { if (myController) { if (m_Stop == false) { if (myController->IsForwardHeld()) { Move(SpriteWalkUp, deltatime); } if (myController->IsReverseHeld()) { Move(SpriteWalkDown, deltatime); } if (myController->IsTurnRightHeld()) { Move(SpriteWalkRight, deltatime); } if (myController->IsTurnLeftHeld()) { Move(SpriteWalkLeft, deltatime); } if (myController->IsInputReleased()) { for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->SetFrameIndex(0); } } } } } if (m_InTransition == true) { if (myDirection == SpriteWalkUp || myDirection == SpriteWalkRight) { if (m_Position.y < aTransitionDestination.y) { Move(myDirection, deltatime); } else if (m_Position.x < aTransitionDestination.x) { Move(myDirection, deltatime); } else { m_InTransition = false; } } if (myDirection == SpriteWalkDown || myDirection == SpriteWalkLeft) { if (m_Position.y > aTransitionDestination.y) { Move(myDirection, deltatime); } else if (m_Position.x > aTransitionDestination.x) { Move(myDirection, deltatime); } else { m_InTransition = false; } } } for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->SetPosition(GetPosition()); m_Animations[i]->Update(deltatime); } } void Trainer::Draw(vec2 camPos, vec2 projecScale) { m_Animations[myDirection]->Draw(camPos, projecScale); } void Trainer::Move(SpriteDirection dir, float deltatime) { NewPosition = m_Position; Resume(); if (myDirection != dir) { myDirection = dir; } vec2 velocity = DIRECTIONVECTOR[dir] * PLAYER_SPEED; NewPosition += velocity * deltatime; if (m_InTransition == false) { if (CheckForCollision(NewPosition) == true) { SetPosition(NewPosition); } } else { SetPosition(NewPosition); } } void Trainer::Pause() { for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->Pause(); } } void Trainer::Resume() { for (int i = 0; i < NUM_DIRECTIONS; i++) { m_Animations[i]->Resume(); } } void Trainer::SetStop(bool StopPlayer) { if (m_Stop != StopPlayer) { m_Stop = StopPlayer; } } void Trainer::OnEvent(Event * anEvent) { DoorEvent* e = (DoorEvent*)anEvent; if (e->GetDoorType() == 11) { myDirection = SpriteWalkUp; SetPosition(m_pGame->GetSceneManager()->GetActiveScene()->GetPlayerStart()); PlayerTransition(); } if (e->GetDoorType() == 10) { myDirection = SpriteWalkDown; SetPosition(m_pGame->GetSceneManager()->GetActiveScene()->GetPlayerStart()); PlayerTransition(); } } void Trainer::PlayerTransition() { m_InTransition = true; aTransitionDestination = GetPosition() + vec2(DIRECTIONVECTOR[myDirection] * (TILESIZE / 4)); } SpriteDirection Trainer::GetMyDirection() { return myDirection; } bool Trainer::CheckForCollision(vec2 playerNewPosition) { //Get the location of each point of collision on the player and then truncate it to a row and column ivec2 OriginIndex = ivec2((playerNewPosition.x / TILESIZE), ((playerNewPosition.y - 0.3f) / TILESIZE)); ivec2 TopLeftIndex = ivec2((playerNewPosition.x / TILESIZE), (((playerNewPosition.y - 0.5f) + (TILESIZE / 2)) / TILESIZE)); ivec2 TopRightIndex = ivec2(((playerNewPosition.x + (TILESIZE / 2)) / TILESIZE), (((playerNewPosition.y - 0.5f) + (TILESIZE / 2)) / TILESIZE)); ivec2 BottomRightIndex = ivec2(((playerNewPosition.x + (TILESIZE / 2)) / TILESIZE), ((playerNewPosition.y - 0.3f) / TILESIZE)); //Check each index for whether the tile it lands on is walkable bool CheckOrigin = m_pGame->GetTileMap()->GetTileAtPlayer(OriginIndex); bool CheckTopLeft = m_pGame->GetTileMap()->GetTileAtPlayer(TopLeftIndex); bool CheckTopRight = m_pGame->GetTileMap()->GetTileAtPlayer(TopRightIndex); bool CheckBottomRight = m_pGame->GetTileMap()->GetTileAtPlayer(BottomRightIndex); //If all the point land on walkable tile return true else return false bool Collision = (CheckOrigin && CheckTopLeft && CheckTopRight && CheckBottomRight); return Collision; }
5,506
2,321
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDUshortInfo.cxx 27946 2008-08-13 15:26:24Z cblume $ */ /////////////////////////////////////////////////////////////////////////////// // // // Calibration base class for a single ROC // // Contains one UShort_t value per pad // // However, values are set and get as float, there are stored internally as // // (UShort_t) value * 10000 // // // /////////////////////////////////////////////////////////////////////////////// #include "AliTRDUshortInfo.h" ClassImp(AliTRDUshortInfo) //_____________________________________________________________________________ AliTRDUshortInfo::AliTRDUshortInfo() :TObject() ,fSize(0) ,fData(0) { // // Default constructor // } //_____________________________________________________________________________ AliTRDUshortInfo::AliTRDUshortInfo(Int_t n) :TObject() ,fSize(n) ,fData(0) { // // Constructor that initializes a given size // fData = new UShort_t[fSize]; for(Int_t k = 0; k < fSize; k++){ fData[k] = 0; } } //_____________________________________________________________________________ AliTRDUshortInfo::AliTRDUshortInfo(const AliTRDUshortInfo &c) :TObject(c) ,fSize(c.fSize) ,fData(0) { // // AliTRDUshortInfo copy constructor // Int_t iBin = 0; fData = new UShort_t[fSize]; for (iBin = 0; iBin < fSize; iBin++) { fData[iBin] = ((AliTRDUshortInfo &) c).fData[iBin]; } } //_____________________________________________________________________________ AliTRDUshortInfo::~AliTRDUshortInfo() { // // AliTRDUshortInfo destructor // if (fData) { delete [] fData; fData = 0; } } //_____________________________________________________________________________ AliTRDUshortInfo &AliTRDUshortInfo::operator=(const AliTRDUshortInfo &c) { // // Assignment operator // if (this == &c) { return *this; } fSize = c.fSize; if (fData) { delete [] fData; } fData = new UShort_t[fSize]; for (Int_t iBin = 0; iBin < fSize; iBin++) { fData[iBin] = c.fData[iBin]; } return *this; } //_____________________________________________________________________________ void AliTRDUshortInfo::Copy(TObject &c) const { // // Copy function // Int_t iBin = 0; ((AliTRDUshortInfo &) c).fSize = fSize; if (((AliTRDUshortInfo &) c).fData) delete [] ((AliTRDUshortInfo &) c).fData; ((AliTRDUshortInfo &) c).fData = new UShort_t[fSize]; for (iBin = 0; iBin < fSize; iBin++) { ((AliTRDUshortInfo &) c).fData[iBin] = fData[iBin]; } TObject::Copy(c); } //_____________________________________________________________________________ void AliTRDUshortInfo::SetSize(Int_t n) { // // Set the size // if(fData) delete [] fData; fData = new UShort_t[n]; fSize = n; }
4,104
1,269
#pragma once #include <cstdint> #include <vector> #include <gmock/gmock.h> namespace ipmiblob { class CrcInterface { public: virtual ~CrcInterface() = default; virtual std::uint16_t generateCrc(const std::vector<std::uint8_t>& data) const = 0; }; class CrcMock : public CrcInterface { public: virtual ~CrcMock() = default; MOCK_METHOD(std::uint16_t, generateCrc, (const std::vector<std::uint8_t>&), (const, override)); }; } // namespace ipmiblob
497
184
#include <iostream> #include <vector> #include <fstream> #include <sstream> #include <string> int main() { std::vector<std::vector<double>> arr; std::string str; std::ifstream in; in.open("april.txt"); while(std::getline(in, str)) { std::stringstream ss(str); int index=0;double n; std::vector<double> arr1; while(ss>>n) arr1.emplace_back(n); arr.emplace_back(arr1); } in.close(); for(auto& i:arr) { for(auto& j:i) std::cout<<j<<" "; std::cout<<"\n"; } }
574
211
/************************************************************************ > File Name: variable_v1.cpp > Author: deqi > Mail: deqi_tang@163.com > Created Time: Sat 30 Jan 2021 01:11:54 PM CST ************************************************************************/ //#include "atomsciflow/abinit/utils.h" #include "atomsciflow/abinit/variable_v1.h" #include <string> //#include <vector> namespace atomsciflow { using namespace utils; // inline functions // inline std::string to_string_same_line(const AbinitVariableV1& var, std::string indent, int n) { if (false == var.status) { return ""; } std::string out = ""; if (0 == var.value.size()) { return out + var.key; } if (1 == var.value.size()) { if (1 == var.value[0].size()) { out += indent + var.key + n_to_string(n) + " " + var.value[0][0]; } else { out += indent + var.key + n_to_string(n); for (auto item : var.value[0]) { out += " " + item; } } } else { out += indent + var.key + n_to_string(n); for (auto val : var.value[0]) { out += " " + val; } out += "\n"; for (int row = 1; row < var.value.size() - 1; ++row) { out += indent; for (auto val : var.value[row]) { out += " " + val; } out += "\n"; } out += indent; for (auto val : var.value[var.value.size()-1]) { out += " " + val; } } return out; } inline std::string to_string_second_line(const AbinitVariableV1& var, std::string indent, int n) { if (false == var.status) { return ""; } std::string out = ""; if (0 == var.value.size()) { return out + var.key; } if (1 == var.value.size()) { if (1 == var.value[0].size()) { out += indent + var.key + n_to_string(n) + " " + var.value[0][0]; } else { out += indent + var.key + n_to_string(n) + "\n"; out += indent; for (auto item : var.value[0]) { out += " " + item; } } } else { out += indent + var.key + n_to_string(n) + "\n"; for (auto row : var.value) { out += indent; for (auto val : row) { out += " " + val; } out += "\n"; } } return out; } void AbinitVariableV1::set(std::string key, int value) { this->key = key; this->value.clear(); this->value.push_back(std::vector<std::string>{std::to_string(value)}); } void AbinitVariableV1::set(std::string key, double value) { this->key = key; this->value.clear(); this->value.push_back(std::vector<std::string>{std::to_string(value)}); } void AbinitVariableV1::set(std::string key, std::string value) { this->key = key; this->value.clear(); this->value.push_back(std::vector<std::string>{value}); } void AbinitVariableV1::set(std::string key, std::vector<int> value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& i : value) { vec_str.push_back(std::to_string(i)); } this->value.push_back(vec_str); } void AbinitVariableV1::set(std::string key, std::vector<double> value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& i : value) { vec_str.push_back(std::to_string(i)); } this->value.push_back(vec_str); } void AbinitVariableV1::set(std::string key, std::vector<std::string> value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& val : value) { vec_str.push_back(val); } this->value.push_back(vec_str); } void AbinitVariableV1::set(std::string key, std::vector<std::vector<int> > value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& row : value) { vec_str.clear(); for (auto& val : row) { vec_str.push_back(std::to_string(val)); } this->value.push_back(vec_str); } } void AbinitVariableV1::set(std::string key, std::vector<std::vector<double> > value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& row : value) { vec_str.clear(); for (auto& val : row) { vec_str.push_back(std::to_string(val)); } this->value.push_back(vec_str); } } void AbinitVariableV1::set(std::string key, std::vector<std::vector<std::string> > value) { this->key = key; this->value.clear(); std::vector<std::string> vec_str; for (auto& row : value) { vec_str.clear(); for (auto& val : row) { vec_str.push_back(val); } this->value.push_back(vec_str); } } void AbinitVariableV1::to(int& value) { value = std::atoi(this->value[0][0].c_str()); } void AbinitVariableV1::to(double& value) { value = std::atof(this->value[0][0].c_str()); } void AbinitVariableV1::to(std::string& value) { value = this->value[0][0]; } void AbinitVariableV1::to(std::vector<int>& value) { value.clear(); for (auto& val : this->value[0]) { value.push_back(std::atoi(val.c_str())); } } void AbinitVariableV1::to(std::vector<double>& value) { value.clear(); for (auto& val : this->value[0]) { value.push_back(std::atof(val.c_str())); } } void AbinitVariableV1::to(std::vector<std::string>& value) { value.clear(); //for (auto& val : this->value[0]) { // value.push_back(val); //} value = this->value[0]; } void AbinitVariableV1::to(std::vector<std::vector<int>>& value) { value.clear(); std::vector<int> vec_int; for (auto& row : this->value) { vec_int.clear(); for (auto& val : row) { vec_int.push_back(std::atoi(val.c_str())); } value.push_back(vec_int); } } void AbinitVariableV1::to(std::vector<std::vector<double>>& value) { value.clear(); std::vector<double> vec_double; for (auto& row : this->value) { vec_double.clear(); for (auto& val : row) { vec_double.push_back(std::atof(val.c_str())); } value.push_back(vec_double); } } void AbinitVariableV1::to(std::vector<std::vector<std::string>>& value) { value.clear(); //std::vector<std::string> vec_str; //for (auto& row : this->value) { // vec_double.clear(); // for (auto& val : row) { // vec_double.push_back(val); // } // value.push_back(vec_str); //} value = this->value; } std::string AbinitVariableV1::to_string() { if (false == this->status) { return ""; } return this->to_string(0); } std::string AbinitVariableV1::to_string(int n) { if (false == this->status) { return ""; } std::string out = ""; if (9 == this->value.size()) { return out + this->key; } if (this->value.size() == 1) { if (this->value[0].size() == 1) { out += this->key + n_to_string(n) + " " + this->value[0][0]; } else { out += this->key + n_to_string(n) + "\n"; for (auto item : this->value[0]) { out += " " + item; } } } else { out += this->key + n_to_string(n) + "\n"; for (auto row : this->value) { for (auto val : row) { out += " " + val; } out += "\n"; } } return out; } std::string AbinitVariableV1::to_string(std::string layout, std::string indent) { if (false == this->status) { return ""; } return this->to_string(layout, indent, 0); } std::string AbinitVariableV1::to_string(std::string layout, std::string indent, int n) { /* * layout: * "same-line"; * "second-line"'' */ if (false == this->status) { return ""; } if ("same-line" == layout) { return to_string_same_line(*this, indent, n); } else if ("second-line" == layout) { return to_string_second_line(*this, indent, n); } else { return to_string(n); } } // } // namespace atomsciflow
9,458
2,986
#include <iostream> #include <vector> #include <string> #include <string> #include <iomanip> #include <cmath> #include <map> #include <set> using std::cout; using std::endl; using std::vector; using std::set; using std::cin; using std::string; using std::map; #define PI 3.14159265359 #define N 1000 #define M 2*N+1 int fact2_min_dp[N][N]; int fact5_min_dp[N][N]; typedef struct Point { int x, y; }; // p is prime int fact(int v, int p) { int c = 0; while ( v % p == 0 ) { v = v / p; c += 1; } return c; } int fact5(int v) { return fact(v, 5); } int fact2(int v) { return fact(v, 2); } int calcFact(int A[N][N], int n, int dp[N][N], int prime) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if (i == 0 && j == 0) { dp[i][j] = fact(A[i][j], prime); } else if (i == 0) { dp[i][j] = fact(A[i][j], prime) + dp[i][j-1]; } else if (j == 0) { dp[i][j] = fact(A[i][j], prime) + dp[i-1][j]; } else { dp[i][j] = fact(A[i][j], prime) + std::min(dp[i][j-1], dp[i-1][j]); } } } return dp[n-1][n-1]; } void lookForPath(int dp[N][N], int n, char *path) { // look for path int x = n-1, y = n-1; int path_k = 2*n-3; // 2(n-1) elements + \0 path[path_k+1] = '\0'; while (x > 0 && y > 0) { //cout << x << " " << y << " " << dp[x-1][y] << " " << dp[x][y-1] << " "; if (dp[y-1][x] < dp[y][x-1]) { path[path_k] = 'D'; path_k -= 1; y = y-1; } else { path[path_k] = 'R'; path_k -= 1; x = x - 1; } //cout << path[path_k+1] << " " << endl; } while (x > 0) { path[path_k] = 'R'; path_k -= 1; x -= 1; } while (y > 0) { path[path_k] = 'D'; path_k -= 1; y -= 1; } } int calcFactBy2Min(int A[N][N], int n, int dp[N][N]) { return calcFact(A, n, dp, 2); } int calcFactBy5Min(int A[N][N], int n, int dp[N][N]) { return calcFact(A, n, dp, 5); } void pathThroughZero(const Point &zero_pos, int n, char *path) { int path_k = 0; for(int i = 0; i < zero_pos.x; i++) { path[path_k] = 'R'; path_k += 1; } for(int i = 0; i < n-1; i++) { path[path_k] = 'D'; path_k += 1; } for(int i = zero_pos.x; i < n-1; i++) { path[path_k] = 'R'; path_k += 1; } path[path_k] = '\0'; } void print_dp(int dp[][N], int n) { for(int i = 0 ; i < n ;i++) { for(int j = 0 ; j < n ;j++) { cout << dp[i][j] << " "; } cout << endl; } } void solve(int A[N][N], int n, bool has_zero, const Point &zero_pos) { //char fact2_min_path[M], fact5_min_path[M]; char path[M]; int least_trailing_zero_num; //cout << endl; calcFactBy2Min(A, n, fact2_min_dp); //print_dp(fact2_min_dp, n); //cout << endl; calcFactBy5Min(A, n, fact5_min_dp); /*print_dp(fact5_min_dp, n); cout << endl;*/ if (fact2_min_dp[n-1][n-1] < fact5_min_dp[n-1][n-1]) { lookForPath(fact2_min_dp, n, path); least_trailing_zero_num = fact2_min_dp[n-1][n-1]; } else { lookForPath(fact5_min_dp, n, path); least_trailing_zero_num = fact5_min_dp[n-1][n-1]; } if (has_zero && least_trailing_zero_num > 1) { pathThroughZero(zero_pos, n, path); cout << 1 << "\n" << path << endl; } else { cout << least_trailing_zero_num << "\n" << path << endl; } } int main(int argc, const char *argv[]) { int A[N][N]; int n; cin >> n; bool has_zero = false; Point zero_pos; // ---> x(j:0->n); // | // | // | // V y (i:0->n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cin >> A[i][j]; if (A[i][j] == 0) { A[i][j] = 10; has_zero = true; zero_pos.x = j; zero_pos.y = i; } } } solve(A, n, has_zero, zero_pos); return 0; }
3,744
1,826
/** * @file: InSpeciesTypeBond.cpp * @brief: Implementation of the InSpeciesTypeBond class * @author: SBMLTeam * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2020 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * 3. University College London, London, UK * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * This library 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. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ------------------------------------------------------------------------ --> */ #include <sbml/packages/multi/sbml/InSpeciesTypeBond.h> #include <sbml/packages/multi/validator/MultiSBMLError.h> using namespace std; #ifdef __cplusplus LIBSBML_CPP_NAMESPACE_BEGIN /* * Creates a new InSpeciesTypeBond with the given level, version, and package version. */ InSpeciesTypeBond::InSpeciesTypeBond (unsigned int level, unsigned int version, unsigned int pkgVersion) : SBase(level, version) //// ,mId ("") //// ,mName ("") ,mBindingSite1 ("") ,mBindingSite2 ("") { // set an SBMLNamespaces derived object of this package setSBMLNamespacesAndOwn(new MultiPkgNamespaces(level, version, pkgVersion)); } /* * Creates a new InSpeciesTypeBond with the given MultiPkgNamespaces object. */ InSpeciesTypeBond::InSpeciesTypeBond (MultiPkgNamespaces* multins) : SBase(multins) //// ,mId ("") //// ,mName ("") ,mBindingSite1 ("") ,mBindingSite2 ("") { // set the element namespace of this object setElementNamespace(multins->getURI()); // load package extensions bound with this object (if any) loadPlugins(multins); } /* * Copy constructor for InSpeciesTypeBond. */ InSpeciesTypeBond::InSpeciesTypeBond (const InSpeciesTypeBond& orig) : SBase(orig) // , mId ( orig.mId) // , mName ( orig.mName) , mBindingSite1 ( orig.mBindingSite1) , mBindingSite2 ( orig.mBindingSite2) { } /* * Assignment for InSpeciesTypeBond. */ InSpeciesTypeBond& InSpeciesTypeBond::operator=(const InSpeciesTypeBond& rhs) { if (&rhs != this) { SBase::operator=(rhs); mId = rhs.mId; mName = rhs.mName; mBindingSite1 = rhs.mBindingSite1; mBindingSite2 = rhs.mBindingSite2; } return *this; } /* * Clone for InSpeciesTypeBond. */ InSpeciesTypeBond* InSpeciesTypeBond::clone () const { return new InSpeciesTypeBond(*this); } /* * Destructor for InSpeciesTypeBond. */ InSpeciesTypeBond::~InSpeciesTypeBond () { } /* * Returns the value of the "id" attribute of this InSpeciesTypeBond. */ const std::string& InSpeciesTypeBond::getId() const { return mId; } /* * Returns the value of the "name" attribute of this InSpeciesTypeBond. */ const std::string& InSpeciesTypeBond::getName() const { return mName; } /* * Returns the value of the "bindingSite1" attribute of this InSpeciesTypeBond. */ const std::string& InSpeciesTypeBond::getBindingSite1() const { return mBindingSite1; } /* * Returns the value of the "bindingSite2" attribute of this InSpeciesTypeBond. */ const std::string& InSpeciesTypeBond::getBindingSite2() const { return mBindingSite2; } /* * Returns true/false if id is set. */ bool InSpeciesTypeBond::isSetId() const { return (mId.empty() == false); } /* * Returns true/false if name is set. */ bool InSpeciesTypeBond::isSetName() const { return (mName.empty() == false); } /* * Returns true/false if bindingSite1 is set. */ bool InSpeciesTypeBond::isSetBindingSite1() const { return (mBindingSite1.empty() == false); } /* * Returns true/false if bindingSite2 is set. */ bool InSpeciesTypeBond::isSetBindingSite2() const { return (mBindingSite2.empty() == false); } /* * Sets id and returns value indicating success. */ int InSpeciesTypeBond::setId(const std::string& id) { return SyntaxChecker::checkAndSetSId(id, mId); } /* * Sets name and returns value indicating success. */ int InSpeciesTypeBond::setName(const std::string& name) { mName = name; return LIBSBML_OPERATION_SUCCESS; } /* * Sets bindingSite1 and returns value indicating success. */ int InSpeciesTypeBond::setBindingSite1(const std::string& bindingSite1) { if (!(SyntaxChecker::isValidInternalSId(bindingSite1))) { return LIBSBML_INVALID_ATTRIBUTE_VALUE; } else { mBindingSite1 = bindingSite1; return LIBSBML_OPERATION_SUCCESS; } } /* * Sets bindingSite2 and returns value indicating success. */ int InSpeciesTypeBond::setBindingSite2(const std::string& bindingSite2) { if (!(SyntaxChecker::isValidInternalSId(bindingSite2))) { return LIBSBML_INVALID_ATTRIBUTE_VALUE; } else { mBindingSite2 = bindingSite2; return LIBSBML_OPERATION_SUCCESS; } } /* * Unsets id and returns value indicating success. */ int InSpeciesTypeBond::unsetId() { mId.erase(); if (mId.empty() == true) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * Unsets name and returns value indicating success. */ int InSpeciesTypeBond::unsetName() { mName.erase(); if (mName.empty() == true) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * Unsets bindingSite1 and returns value indicating success. */ int InSpeciesTypeBond::unsetBindingSite1() { mBindingSite1.erase(); if (mBindingSite1.empty() == true) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * Unsets bindingSite2 and returns value indicating success. */ int InSpeciesTypeBond::unsetBindingSite2() { mBindingSite2.erase(); if (mBindingSite2.empty() == true) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * rename attributes that are SIdRefs or instances in math */ void InSpeciesTypeBond::renameSIdRefs(const std::string& oldid, const std::string& newid) { SBase::renameSIdRefs(oldid, newid); if (isSetBindingSite1() == true && mBindingSite1 == oldid) { setBindingSite1(newid); } if (isSetBindingSite2() == true && mBindingSite2 == oldid) { setBindingSite2(newid); } } /* * Returns the XML element name of this object */ const std::string& InSpeciesTypeBond::getElementName () const { static const string name = "inSpeciesTypeBond"; return name; } /* * Returns the libSBML type code for this SBML object. */ int InSpeciesTypeBond::getTypeCode () const { return SBML_MULTI_IN_SPECIES_TYPE_BOND; } /* * check if all the required attributes are set */ bool InSpeciesTypeBond::hasRequiredAttributes () const { bool allPresent = true; if (isSetBindingSite1() == false) allPresent = false; if (isSetBindingSite2() == false) allPresent = false; return allPresent; } /** @cond doxygenLibsbmlInternal */ /* * write contained elements */ void InSpeciesTypeBond::writeElements (XMLOutputStream& stream) const { SBase::writeElements(stream); SBase::writeExtensionElements(stream); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Accepts the given SBMLVisitor. */ bool InSpeciesTypeBond::accept (SBMLVisitor& v) const { return v.visit(*this); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Sets the parent SBMLDocument. */ void InSpeciesTypeBond::setSBMLDocument (SBMLDocument* d) { SBase::setSBMLDocument(d); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Enables/Disables the given package with this element. */ void InSpeciesTypeBond::enablePackageInternal(const std::string& pkgURI, const std::string& pkgPrefix, bool flag) { SBase::enablePackageInternal(pkgURI, pkgPrefix, flag); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Get the list of expected attributes for this element. */ void InSpeciesTypeBond::addExpectedAttributes(ExpectedAttributes& attributes) { SBase::addExpectedAttributes(attributes); attributes.add("id"); attributes.add("name"); attributes.add("bindingSite1"); attributes.add("bindingSite2"); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Read values from the given XMLAttributes set into their specific fields. */ void InSpeciesTypeBond::readAttributes (const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes) { const unsigned int sbmlLevel = getLevel (); const unsigned int sbmlVersion = getVersion(); unsigned int numErrs; /* look to see whether an unknown attribute error was logged * during the read of the listOfInSpeciesTypeBonds - which will have * happened immediately prior to this read */ ListOfInSpeciesTypeBonds * parentListOf = static_cast<ListOfInSpeciesTypeBonds*>(getParentSBMLObject()); if (getErrorLog() != NULL && parentListOf->size() < 2) { numErrs = getErrorLog()->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (getErrorLog()->getError(n)->getErrorId() == UnknownPackageAttribute) { const std::string details = getErrorLog()->getError(n)->getMessage(); getErrorLog()->remove(UnknownPackageAttribute); getErrorLog()->logPackageError("multi", MultiLofInSptBnds_AllowedAtts, getPackageVersion(), sbmlLevel, sbmlVersion, details, parentListOf->getLine(), parentListOf->getColumn()); } else if (getErrorLog()->getError(n)->getErrorId() == UnknownCoreAttribute) { const std::string details = getErrorLog()->getError(n)->getMessage(); getErrorLog()->remove(UnknownCoreAttribute); getErrorLog()->logPackageError("multi", MultiLofInSptBnds_AllowedAtts, getPackageVersion(), sbmlLevel, sbmlVersion, details, parentListOf->getLine(), parentListOf->getColumn()); } } } SBase::readAttributes(attributes, expectedAttributes); // look to see whether an unknown attribute error was logged if (getErrorLog() != NULL) { numErrs = getErrorLog()->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (getErrorLog()->getError(n)->getErrorId() == UnknownPackageAttribute) { const std::string details = getErrorLog()->getError(n)->getMessage(); getErrorLog()->remove(UnknownPackageAttribute); getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedMultiAtts, getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn()); } else if (getErrorLog()->getError(n)->getErrorId() == UnknownCoreAttribute) { const std::string details = getErrorLog()->getError(n)->getMessage(); getErrorLog()->remove(UnknownCoreAttribute); getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedCoreAtts, getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn()); } } } bool assigned = false; // // id SId ( use = "optional" ) // assigned = attributes.readInto("id", mId); if (assigned == true) { // check string is not empty and correct syntax if (mId.empty() == true) { logEmptyString(mId, getLevel(), getVersion(), "<InSpeciesTypeBond>"); } else if (SyntaxChecker::isValidSBMLSId(mId) == false && getErrorLog() != NULL) { std::string details = "The syntax of the attribute id='" + mId + "' does not conform."; getErrorLog()->logPackageError("multi", MultiInvSIdSyn, getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn()); } } // // name string ( use = "optional" ) // assigned = attributes.readInto("name", mName); if (assigned == true) { // check string is not empty if (mName.empty() == true) { logEmptyString(mName, getLevel(), getVersion(), "<InSpeciesTypeBond>"); } } // // bindingSite1 SIdRef ( use = "required" ) // assigned = attributes.readInto("bindingSite1", mBindingSite1); if (assigned == true) { // check string is not empty and correct syntax if (mBindingSite1.empty() == true) { logEmptyString(mBindingSite1, getLevel(), getVersion(), "<InSpeciesTypeBond>"); } else if (SyntaxChecker::isValidSBMLSId(mBindingSite1) == false && getErrorLog() != NULL) { std::string details = "The syntax of the attribute bindingSite1='" + mBindingSite1 + "' does not conform."; getErrorLog()->logPackageError("multi", MultiInvSIdSyn, getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn()); } } else { std::string message = "Multi attribute 'bindingSite1' is missing."; getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedMultiAtts, getPackageVersion(), sbmlLevel, sbmlVersion, message, getLine(), getColumn()); } // // bindingSite2 SIdRef ( use = "required" ) // assigned = attributes.readInto("bindingSite2", mBindingSite2); if (assigned == true) { // check string is not empty and correct syntax if (mBindingSite2.empty() == true) { logEmptyString(mBindingSite2, getLevel(), getVersion(), "<InSpeciesTypeBond>"); } else if (SyntaxChecker::isValidSBMLSId(mBindingSite2) == false && getErrorLog() != NULL) { std::string details = "The syntax of the attribute bindingSite2='" + mBindingSite2 + "' does not conform."; getErrorLog()->logPackageError("multi", MultiInvSIdSyn, getPackageVersion(), sbmlLevel, sbmlVersion, details, getLine(), getColumn()); } } else { std::string message = "Multi attribute 'bindingSite2' is missing."; getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedMultiAtts, getPackageVersion(), sbmlLevel, sbmlVersion, message, getLine(), getColumn()); } } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Write values of XMLAttributes to the output stream. */ void InSpeciesTypeBond::writeAttributes (XMLOutputStream& stream) const { SBase::writeAttributes(stream); if (isSetId() == true) stream.writeAttribute("id", getPrefix(), mId); if (isSetName() == true) stream.writeAttribute("name", getPrefix(), mName); if (isSetBindingSite1() == true) stream.writeAttribute("bindingSite1", getPrefix(), mBindingSite1); if (isSetBindingSite2() == true) stream.writeAttribute("bindingSite2", getPrefix(), mBindingSite2); SBase::writeExtensionAttributes(stream); } /** @endcond */ /* * Constructor */ ListOfInSpeciesTypeBonds::ListOfInSpeciesTypeBonds(unsigned int level, unsigned int version, unsigned int pkgVersion) : ListOf(level, version) { setSBMLNamespacesAndOwn(new MultiPkgNamespaces(level, version, pkgVersion)); } /* * Constructor */ ListOfInSpeciesTypeBonds::ListOfInSpeciesTypeBonds(MultiPkgNamespaces* multins) : ListOf(multins) { setElementNamespace(multins->getURI()); } /* * Returns a deep copy of this ListOfInSpeciesTypeBonds */ ListOfInSpeciesTypeBonds* ListOfInSpeciesTypeBonds::clone () const { return new ListOfInSpeciesTypeBonds(*this); } /* * Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by index. */ InSpeciesTypeBond* ListOfInSpeciesTypeBonds::get(unsigned int n) { return static_cast<InSpeciesTypeBond*>(ListOf::get(n)); } /* * Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by index. */ const InSpeciesTypeBond* ListOfInSpeciesTypeBonds::get(unsigned int n) const { return static_cast<const InSpeciesTypeBond*>(ListOf::get(n)); } /* * Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by id. */ InSpeciesTypeBond* ListOfInSpeciesTypeBonds::get(const std::string& sid) { return const_cast<InSpeciesTypeBond*>( static_cast<const ListOfInSpeciesTypeBonds&>(*this).get(sid)); } /* * Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by id. */ const InSpeciesTypeBond* ListOfInSpeciesTypeBonds::get(const std::string& sid) const { vector<SBase*>::const_iterator result; result = find_if( mItems.begin(), mItems.end(), IdEq<InSpeciesTypeBond>(sid) ); return (result == mItems.end()) ? 0 : static_cast <InSpeciesTypeBond*> (*result); } /* * Removes the nth InSpeciesTypeBond from this ListOfInSpeciesTypeBonds */ InSpeciesTypeBond* ListOfInSpeciesTypeBonds::remove(unsigned int n) { return static_cast<InSpeciesTypeBond*>(ListOf::remove(n)); } /* * Removes the InSpeciesTypeBond from this ListOfInSpeciesTypeBonds with the given identifier */ InSpeciesTypeBond* ListOfInSpeciesTypeBonds::remove(const std::string& sid) { SBase* item = NULL; vector<SBase*>::iterator result; result = find_if( mItems.begin(), mItems.end(), IdEq<InSpeciesTypeBond>(sid) ); if (result != mItems.end()) { item = *result; mItems.erase(result); } return static_cast <InSpeciesTypeBond*> (item); } /* * Returns the XML element name of this object */ const std::string& ListOfInSpeciesTypeBonds::getElementName () const { static const string name = "listOfInSpeciesTypeBonds"; return name; } /* * Returns the libSBML type code for this SBML object. */ int ListOfInSpeciesTypeBonds::getTypeCode () const { return SBML_LIST_OF; } /* * Returns the libSBML type code for the objects in this LIST_OF. */ int ListOfInSpeciesTypeBonds::getItemTypeCode () const { return SBML_MULTI_IN_SPECIES_TYPE_BOND; } /** @cond doxygenLibsbmlInternal */ /* * Creates a new InSpeciesTypeBond in this ListOfInSpeciesTypeBonds */ SBase* ListOfInSpeciesTypeBonds::createObject(XMLInputStream& stream) { const std::string& name = stream.peek().getName(); SBase* object = NULL; if (name == "inSpeciesTypeBond") { MULTI_CREATE_NS(multins, getSBMLNamespaces()); object = new InSpeciesTypeBond(multins); appendAndOwn(object); delete multins; } return object; } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Write the namespace for the Multi package. */ void ListOfInSpeciesTypeBonds::writeXMLNS(XMLOutputStream& stream) const { XMLNamespaces xmlns; std::string prefix = getPrefix(); if (prefix.empty()) { XMLNamespaces* thisxmlns = getNamespaces(); if (thisxmlns && thisxmlns->hasURI(MultiExtension::getXmlnsL3V1V1())) { xmlns.add(MultiExtension::getXmlnsL3V1V1(),prefix); } } stream << xmlns; } /** @endcond */ LIBSBML_EXTERN InSpeciesTypeBond_t * InSpeciesTypeBond_create(unsigned int level, unsigned int version, unsigned int pkgVersion) { return new InSpeciesTypeBond(level, version, pkgVersion); } LIBSBML_EXTERN void InSpeciesTypeBond_free(InSpeciesTypeBond_t * istb) { if (istb != NULL) delete istb; } LIBSBML_EXTERN InSpeciesTypeBond_t * InSpeciesTypeBond_clone(InSpeciesTypeBond_t * istb) { if (istb != NULL) { return static_cast<InSpeciesTypeBond_t*>(istb->clone()); } else { return NULL; } } LIBSBML_EXTERN char * InSpeciesTypeBond_getId(InSpeciesTypeBond_t * istb) { if (istb == NULL) return NULL; return istb->getId().empty() ? NULL : safe_strdup(istb->getId().c_str()); } LIBSBML_EXTERN char * InSpeciesTypeBond_getName(InSpeciesTypeBond_t * istb) { if (istb == NULL) return NULL; return istb->getName().empty() ? NULL : safe_strdup(istb->getName().c_str()); } LIBSBML_EXTERN char * InSpeciesTypeBond_getBindingSite1(InSpeciesTypeBond_t * istb) { if (istb == NULL) return NULL; return istb->getBindingSite1().empty() ? NULL : safe_strdup(istb->getBindingSite1().c_str()); } LIBSBML_EXTERN char * InSpeciesTypeBond_getBindingSite2(InSpeciesTypeBond_t * istb) { if (istb == NULL) return NULL; return istb->getBindingSite2().empty() ? NULL : safe_strdup(istb->getBindingSite2().c_str()); } LIBSBML_EXTERN int InSpeciesTypeBond_isSetId(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? static_cast<int>(istb->isSetId()) : 0; } LIBSBML_EXTERN int InSpeciesTypeBond_isSetName(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? static_cast<int>(istb->isSetName()) : 0; } LIBSBML_EXTERN int InSpeciesTypeBond_isSetBindingSite1(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? static_cast<int>(istb->isSetBindingSite1()) : 0; } LIBSBML_EXTERN int InSpeciesTypeBond_isSetBindingSite2(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? static_cast<int>(istb->isSetBindingSite2()) : 0; } LIBSBML_EXTERN int InSpeciesTypeBond_setId(InSpeciesTypeBond_t * istb, const char * id) { return (istb != NULL) ? istb->setId(id) : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_setName(InSpeciesTypeBond_t * istb, const char * name) { return (istb != NULL) ? istb->setName(name) : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_setBindingSite1(InSpeciesTypeBond_t * istb, const char * bindingSite1) { return (istb != NULL) ? istb->setBindingSite1(bindingSite1) : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_setBindingSite2(InSpeciesTypeBond_t * istb, const char * bindingSite2) { return (istb != NULL) ? istb->setBindingSite2(bindingSite2) : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_unsetId(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? istb->unsetId() : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_unsetName(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? istb->unsetName() : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_unsetBindingSite1(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? istb->unsetBindingSite1() : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_unsetBindingSite2(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? istb->unsetBindingSite2() : LIBSBML_INVALID_OBJECT; } LIBSBML_EXTERN int InSpeciesTypeBond_hasRequiredAttributes(InSpeciesTypeBond_t * istb) { return (istb != NULL) ? static_cast<int>(istb->hasRequiredAttributes()) : 0; } LIBSBML_EXTERN InSpeciesTypeBond_t * ListOfInSpeciesTypeBonds_getById(ListOf_t * lo, const char * sid) { if (lo == NULL) return NULL; return (sid != NULL) ? static_cast <ListOfInSpeciesTypeBonds *>(lo)->get(sid) : NULL; } LIBSBML_EXTERN InSpeciesTypeBond_t * ListOfInSpeciesTypeBonds_removeById(ListOf_t * lo, const char * sid) { if (lo == NULL) return NULL; return (sid != NULL) ? static_cast <ListOfInSpeciesTypeBonds *>(lo)->remove(sid) : NULL; } LIBSBML_CPP_NAMESPACE_END #endif /*__cplusplus */
23,649
8,303
// A C++ Program to implement A* Search Algorithm #include <bits/stdc++.h> using namespace std; #define ROW 9 #define COL 10 // Creating a shortcut for int, int pair type typedef pair<int, int> Pair; // Creating a shortcut for pair<int, pair<int, int>> type typedef pair<double, pair<int, int>> pPair; // A structure to hold the neccesary parameters struct cell { // Row and Column index of its parent // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 int parent_i, parent_j; // f = g + h double f, g, h; }; // A Utility Function to check whether given cell (row, col) // is a valid cell or not. bool isValid(int row, int col) { // Returns true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL); } // A Utility Function to check whether the given cell is // blocked or not bool isUnBlocked(int grid[][COL], int row, int col) { // Returns true if the cell is not blocked else false if (grid[row][col] == 1) return (true); else return (false); } // A Utility Function to check whether destination cell has // been reached or not bool isDestination(int row, int col, Pair dest) { if (row == dest.first && col == dest.second) return (true); else return (false); } // A Utility Function to calculate the 'h' heuristics. double calculateHValue(int row, int col, Pair dest) { // Return using the distance formula return ((double)sqrt ((row-dest.first)*(row-dest.first) + (col-dest.second)*(col-dest.second))); } // A Utility Function to trace the path from the source // to destination void tracePath(cell cellDetails[][COL], Pair dest) { printf ("\nThe Path is "); int row = dest.first; int col = dest.second; stack<Pair> Path; while (!(cellDetails[row][col].parent_i == row && cellDetails[row][col].parent_j == col )) { Path.push (make_pair (row, col)); int temp_row = cellDetails[row][col].parent_i; int temp_col = cellDetails[row][col].parent_j; row = temp_row; col = temp_col; } Path.push (make_pair (row, col)); while (!Path.empty()) { pair<int,int> p = Path.top(); Path.pop(); printf("-> (%d,%d) ",p.first,p.second); } return; } // A Function to find the shortest path between // a given source cell to a destination cell according // to A* Search Algorithm void aStarSearch(int grid[][COL], Pair src, Pair dest) { // If the source is out of range if (isValid (src.first, src.second) == false) { printf ("Source is invalid\n"); return; } // If the destination is out of range if (isValid (dest.first, dest.second) == false) { printf ("Destination is invalid\n"); return; } // Either the source or the destination is blocked if (isUnBlocked(grid, src.first, src.second) == false || isUnBlocked(grid, dest.first, dest.second) == false) { printf ("Source or the destination is blocked\n"); return; } // If the destination cell is the same as source cell if (isDestination(src.first, src.second, dest) == true) { printf ("We are already at the destination\n"); return; } // Create a closed list and initialise it to false which means // that no cell has been included yet // This closed list is implemented as a boolean 2D array bool closedList[ROW][COL]; memset(closedList, false, sizeof (closedList)); // Declare a 2D array of structure to hold the details //of that cell cell cellDetails[ROW][COL]; int i, j; for (i=0; i<ROW; i++) { for (j=0; j<COL; j++) { cellDetails[i][j].f = FLT_MAX; cellDetails[i][j].g = FLT_MAX; cellDetails[i][j].h = FLT_MAX; cellDetails[i][j].parent_i = -1; cellDetails[i][j].parent_j = -1; } } // Initialising the parameters of the starting node i = src.first, j = src.second; cellDetails[i][j].f = 0.0; cellDetails[i][j].g = 0.0; cellDetails[i][j].h = 0.0; cellDetails[i][j].parent_i = i; cellDetails[i][j].parent_j = j; /* Create an open list having information as- <f, <i, j>> where f = g + h, and i, j are the row and column index of that cell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implenented as a set of pair of pair.*/ set<pPair> openList; // Put the starting cell on the open list and set its // 'f' as 0 openList.insert(make_pair (0.0, make_pair (i, j))); // We set this boolean value as false as initially // the destination is not reached. bool foundDest = false; while (!openList.empty()) { pPair p = *openList.begin(); // Remove this vertex from the open list openList.erase(openList.begin()); // Add this vertex to the open list i = p.second.first; j = p.second.second; closedList[i][j] = true; /* Generating all the 8 successor of this cell N.W N N.E \ | / \ | / W----Cell----E / | \ / | \ S.W S S.E Cell-->Popped Cell (i, j) N --> North (i-1, j) S --> South (i+1, j) E --> East (i, j+1) W --> West (i, j-1) N.E--> North-East (i-1, j+1) N.W--> North-West (i-1, j-1) S.E--> South-East (i+1, j+1) S.W--> South-West (i+1, j-1)*/ // To store the 'g', 'h' and 'f' of the 8 successors double gNew, hNew, fNew; //----------- 1st Successor (North) ------------ // Only process this cell if this is a valid one if (isValid(i-1, j) == true) { // If the destination cell is the same as the // current successor if (isDestination(i-1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i-1][j].parent_i = i; cellDetails[i-1][j].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i-1][j] == false && isUnBlocked(grid, i-1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue (i-1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i-1][j].f == FLT_MAX || cellDetails[i-1][j].f > fNew) { openList.insert( make_pair(fNew, make_pair(i-1, j))); // Update the details of this cell cellDetails[i-1][j].f = fNew; cellDetails[i-1][j].g = gNew; cellDetails[i-1][j].h = hNew; cellDetails[i-1][j].parent_i = i; cellDetails[i-1][j].parent_j = j; } } } //----------- 2nd Successor (South) ------------ // Only process this cell if this is a valid one if (isValid(i+1, j) == true) { // If the destination cell is the same as the // current successor if (isDestination(i+1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i+1][j].parent_i = i; cellDetails[i+1][j].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i+1][j] == false && isUnBlocked(grid, i+1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i+1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i+1][j].f == FLT_MAX || cellDetails[i+1][j].f > fNew) { openList.insert( make_pair (fNew, make_pair (i+1, j))); // Update the details of this cell cellDetails[i+1][j].f = fNew; cellDetails[i+1][j].g = gNew; cellDetails[i+1][j].h = hNew; cellDetails[i+1][j].parent_i = i; cellDetails[i+1][j].parent_j = j; } } } //----------- 3rd Successor (East) ------------ // Only process this cell if this is a valid one if (isValid (i, j+1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j+1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j+1].parent_i = i; cellDetails[i][j+1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i][j+1] == false && isUnBlocked (grid, i, j+1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue (i, j+1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i][j+1].f == FLT_MAX || cellDetails[i][j+1].f > fNew) { openList.insert( make_pair(fNew, make_pair (i, j+1))); // Update the details of this cell cellDetails[i][j+1].f = fNew; cellDetails[i][j+1].g = gNew; cellDetails[i][j+1].h = hNew; cellDetails[i][j+1].parent_i = i; cellDetails[i][j+1].parent_j = j; } } } //----------- 4th Successor (West) ------------ // Only process this cell if this is a valid one if (isValid(i, j-1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j-1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j-1].parent_i = i; cellDetails[i][j-1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i][j-1] == false && isUnBlocked(grid, i, j-1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i, j-1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i][j-1].f == FLT_MAX || cellDetails[i][j-1].f > fNew) { openList.insert( make_pair (fNew, make_pair (i, j-1))); // Update the details of this cell cellDetails[i][j-1].f = fNew; cellDetails[i][j-1].g = gNew; cellDetails[i][j-1].h = hNew; cellDetails[i][j-1].parent_i = i; cellDetails[i][j-1].parent_j = j; } } } //----------- 5th Successor (North-East) ------------ // Only process this cell if this is a valid one if (isValid(i-1, j+1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i-1, j+1, dest) == true) { // Set the Parent of the destination cell cellDetails[i-1][j+1].parent_i = i; cellDetails[i-1][j+1].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i-1][j+1] == false && isUnBlocked(grid, i-1, j+1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i-1, j+1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i-1][j+1].f == FLT_MAX || cellDetails[i-1][j+1].f > fNew) { openList.insert( make_pair (fNew, make_pair(i-1, j+1))); // Update the details of this cell cellDetails[i-1][j+1].f = fNew; cellDetails[i-1][j+1].g = gNew; cellDetails[i-1][j+1].h = hNew; cellDetails[i-1][j+1].parent_i = i; cellDetails[i-1][j+1].parent_j = j; } } } //----------- 6th Successor (North-West) ------------ // Only process this cell if this is a valid one if (isValid (i-1, j-1) == true) { // If the destination cell is the same as the // current successor if (isDestination (i-1, j-1, dest) == true) { // Set the Parent of the destination cell cellDetails[i-1][j-1].parent_i = i; cellDetails[i-1][j-1].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i-1][j-1] == false && isUnBlocked(grid, i-1, j-1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i-1, j-1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i-1][j-1].f == FLT_MAX || cellDetails[i-1][j-1].f > fNew) { openList.insert( make_pair (fNew, make_pair (i-1, j-1))); // Update the details of this cell cellDetails[i-1][j-1].f = fNew; cellDetails[i-1][j-1].g = gNew; cellDetails[i-1][j-1].h = hNew; cellDetails[i-1][j-1].parent_i = i; cellDetails[i-1][j-1].parent_j = j; } } } //----------- 7th Successor (South-East) ------------ // Only process this cell if this is a valid one if (isValid(i+1, j+1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i+1, j+1, dest) == true) { // Set the Parent of the destination cell cellDetails[i+1][j+1].parent_i = i; cellDetails[i+1][j+1].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i+1][j+1] == false && isUnBlocked(grid, i+1, j+1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i+1, j+1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i+1][j+1].f == FLT_MAX || cellDetails[i+1][j+1].f > fNew) { openList.insert(make_pair(fNew, make_pair (i+1, j+1))); // Update the details of this cell cellDetails[i+1][j+1].f = fNew; cellDetails[i+1][j+1].g = gNew; cellDetails[i+1][j+1].h = hNew; cellDetails[i+1][j+1].parent_i = i; cellDetails[i+1][j+1].parent_j = j; } } } //----------- 8th Successor (South-West) ------------ // Only process this cell if this is a valid one if (isValid (i+1, j-1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i+1, j-1, dest) == true) { // Set the Parent of the destination cell cellDetails[i+1][j-1].parent_i = i; cellDetails[i+1][j-1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i+1][j-1] == false && isUnBlocked(grid, i+1, j-1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i+1, j-1, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. if (cellDetails[i+1][j-1].f == FLT_MAX || cellDetails[i+1][j-1].f > fNew) { openList.insert(make_pair(fNew, make_pair(i+1, j-1))); // Update the details of this cell cellDetails[i+1][j-1].f = fNew; cellDetails[i+1][j-1].g = gNew; cellDetails[i+1][j-1].h = hNew; cellDetails[i+1][j-1].parent_i = i; cellDetails[i+1][j-1].parent_j = j; } } } } // When the destination cell is not found and the open // list is empty, then we conclude that we failed to // reach the destiantion cell. This may happen when the // there is no way to destination cell (due to blockages) if (foundDest == false) printf("Failed to find the Destination Cell\n"); return; } // Driver program to test above function int main() { /* Description of the Grid- 1--> The cell is not blocked 0--> The cell is blocked */ int grid[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } }; // Source is the left-most bottom-most corner Pair src = make_pair(8, 0); // Destination is the left-most top-most corner Pair dest = make_pair(0, 0); aStarSearch(grid, src, dest); return(0); }
23,992
7,138
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "pch.h" #include "stdafx.h" #include "EffectPlayer.h" #include <ICryAnimation.h> #include <IEntitySystem.h> namespace CharacterTool { EffectPlayer::EffectPlayer() : m_pSkeleton2(0) , m_pSkeletonPose(0) , m_pIDefaultSkeleton(0) { GetIEditor()->RegisterNotifyListener(this); } EffectPlayer::~EffectPlayer() { KillAllEffects(); GetIEditor()->UnregisterNotifyListener(this); } void EffectPlayer::SetSkeleton(ISkeletonAnim* pSkeletonAnim, ISkeletonPose* pSkeletonPose, IDefaultSkeleton* pIDefaultSkeleton) { m_pSkeleton2 = pSkeletonAnim; m_pSkeletonPose = pSkeletonPose; m_pIDefaultSkeleton = pIDefaultSkeleton; } void EffectPlayer::Update(const QuatT& rPhysEntity) { for (int i = 0; i < m_effects.size(); ) { EffectEntry& entry = m_effects[i]; // If the animation has stopped, kill the effect. bool effectStillPlaying = (entry.pEmitter ? entry.pEmitter->IsAlive() : false); bool animStillPlaying = IsPlayingAnimation(entry.animID); if (animStillPlaying && effectStillPlaying) { // Update the effect position. Matrix34 tm; GetEffectTM(tm, entry.boneID, entry.offset, entry.dir); if (entry.pEmitter) { entry.pEmitter->SetMatrix(Matrix34(rPhysEntity) * tm); } ++i; } else { if (m_effects[i].pEmitter) { m_effects[i].pEmitter->Activate(false); } m_effects.erase(m_effects.begin() + i); } } } void EffectPlayer::KillAllEffects() { for (int i = 0, count = m_effects.size(); i < count; ++i) { if (m_effects[i].pEmitter) { m_effects[i].pEmitter->Activate(false); } } m_effects.clear(); } void EffectPlayer::SpawnEffect(int animID, const char* animName, const char* effectName, const char* boneName, const Vec3& offset, const Vec3& dir) { // Check whether we are already playing this effect, and if so dont restart it. bool alreadyPlayingEffect = false; if (!gEnv->pConsole->GetCVar("ca_AllowMultipleEffectsOfSameName")->GetIVal()) { alreadyPlayingEffect = IsPlayingEffect(effectName); } if (!alreadyPlayingEffect) { IParticleEffect* pEffect = gEnv->pParticleManager->FindEffect(effectName); if (!pEffect) { CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, "Anim events cannot find effect \"%s\", requested by animation \"%s\".", (effectName ? effectName : "<MISSING EFFECT NAME>"), (animName ? animName : "<MISSING ANIM NAME>")); } int boneID = (boneName && boneName[0] && m_pIDefaultSkeleton ? m_pIDefaultSkeleton->GetJointIDByName(boneName) : -1); boneID = (boneID == -1 ? 0 : boneID); Matrix34 tm; GetEffectTM(tm, boneID, offset, dir); IParticleEmitter* pEmitter = (pEffect ? pEffect->Spawn(tm, ePEF_Nowhere) : 0); if (pEffect && pEmitter) { // Make sure the emitter is not rendered in the game. m_effects.push_back(EffectEntry(pEffect, pEmitter, boneID, offset, dir, animID)); } } } void EffectPlayer::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) { case eNotify_OnCloseScene: KillAllEffects(); break; } } EffectPlayer::EffectEntry::EffectEntry(const _smart_ptr<IParticleEffect>& pEffect, const _smart_ptr<IParticleEmitter>& pEmitter, int boneID, const Vec3& offset, const Vec3& dir, int animID) : pEffect(pEffect) , pEmitter(pEmitter) , boneID(boneID) , offset(offset) , dir(dir) , animID(animID) { } EffectPlayer::EffectEntry::~EffectEntry() { } void EffectPlayer::GetEffectTM(Matrix34& tm, int boneID, const Vec3& offset, const Vec3& dir) { if (dir.len2() > 0) { tm = Matrix33::CreateRotationXYZ(Ang3(dir * 3.14159f / 180.0f)); } else { tm.SetIdentity(); } tm.AddTranslation(offset); if (m_pSkeletonPose) { tm = Matrix34(m_pSkeletonPose->GetAbsJointByID(boneID)) * tm; } } bool EffectPlayer::IsPlayingAnimation(int animID) { enum { NUM_LAYERS = 4 }; // Check whether the animation has stopped. bool animPlaying = false; for (int layer = 0; layer < NUM_LAYERS; ++layer) { for (int animIndex = 0, animCount = (m_pSkeleton2 ? m_pSkeleton2->GetNumAnimsInFIFO(layer) : 0); animIndex < animCount; ++animIndex) { CAnimation& anim = m_pSkeleton2->GetAnimFromFIFO(layer, animIndex); animPlaying = animPlaying || (anim.GetAnimationId() == animID); } } return animPlaying; } bool EffectPlayer::IsPlayingEffect(const char* effectName) { bool isPlaying = false; for (int effectIndex = 0, effectCount = m_effects.size(); effectIndex < effectCount; ++effectIndex) { IParticleEffect* pEffect = m_effects[effectIndex].pEffect; if (pEffect && azstricmp(pEffect->GetName(), effectName) == 0) { isPlaying = true; } } return isPlaying; } void EffectPlayer::Render(SRendParams& params, const SRenderingPassInfo& passInfo) { for (int effectIndex = 0, effectCount = m_effects.size(); effectIndex < effectCount; ++effectIndex) { IParticleEmitter* pEmitter = m_effects[effectIndex].pEmitter; if (pEmitter) { pEmitter->Update(); pEmitter->Render(params, passInfo); } } } }
6,824
2,168
#include "editoroptions.h" #include "loading.h" #include "colors.h" #include "definitions.h" EditorOptions::EditorOptions() { free(); } EditorOptions::~EditorOptions() { free(); } void EditorOptions::free() { if (!keytextvec.empty()) { for (auto &it : keytextvec) { delete it; it = nullptr; } keytextvec.clear(); } if (!infotextvec.empty()) { for (auto &it : infotextvec) { delete it; it = nullptr; } infotextvec.clear(); } reset(); lastPage = 3; } void EditorOptions::reset() { currPage = 0; active = false; } void EditorOptions::load(const float& screen_w, const float& screen_h) { free(); float scale_x = screen_w / 1920; if (scale_x > 1.0f) scale_x = 1; float scale_y = screen_h / 1080; if (scale_y > 1.0f) scale_y = 1; // Set button. button.load("images/buttons/settings.png"); if (Loading::isError()) return; button.setVolume(MIN_SOUND_VOLUME); // muted button.setScale(screen_w / 2560, screen_h / 1440); button.setPosition(screen_w - (screen_w / 256 + button.getWidth()) * 4, screen_h / 144); // Set button label. Loading::add(label.setFont(cmm::JCANDLE_FONT_PATH)); if (Loading::isError()) return; label.setText("options"); label.setAlpha(MAX_ALPHA); label.setPosition(button.getLeft() + button.getWidth() / 2 - label.getWidth() / 2.5, button.getBot() + screen_w / 300.0f); label.setSize(screen_w / 60); // Set board. Loading::add(plank.load("images/other/plank.png")); if (Loading::isError()) return; plank.setScale(scale_x, scale_y); plank.center(screen_w / 2, screen_h / 2); // Set black layer. blackLayer.setFillColor(sf::Color(0, 0, 0, 140)); blackLayer.setSize(sf::Vector2f(screen_w, screen_h)); blackLayer.setPosition(0, 0); // Set left/right buttons. Loading::add(leftbutton.load("images/icons/lefticon.png")); Loading::add(rightbutton.load("images/icons/righticon.png")); if (Loading::isError()) return; float factor = 0.9f; leftbutton.setScale(scale_x * factor, scale_y * factor); rightbutton.setScale(scale_x * factor, scale_y * factor); leftbutton.setPosition(plank.getLeft() + screen_w / 128, plank.getTop() + plank.getHeight() / 2 - leftbutton.getHeight() / 2); rightbutton.setPosition((plank.getRight() - screen_w / 128) - rightbutton.getWidth(), leftbutton.getY()); leftbutton.setAlpha(MAX_ALPHA / 1.5); rightbutton.setAlpha(MAX_ALPHA / 1.5); // Set texts. for (int i = 0; i < LABELS::AMOUNT; ++i) { keytextvec.push_back(new cmm::Text); infotextvec.push_back(new cmm::Text); Loading::add(keytextvec.back()->setFont(cmm::JAPOKKI_FONT_PATH)); Loading::add(infotextvec.back()->setFont(cmm::JAPOKKI_FONT_PATH)); if (Loading::isError()) return; keytextvec.back()->setSize(plank.getWidth() / 25); infotextvec.back()->setSize(plank.getWidth() / 25); keytextvec.back()->setFillColor(cmm::DULL_IRON_COLOR); infotextvec.back()->setFillColor(cmm::WHITISH_COLOR); keytextvec.back()->setAlpha(MAX_ALPHA); infotextvec.back()->setAlpha(MAX_ALPHA); } keytextvec[ESCAPE]->setText("[ESC]"); keytextvec[ENTER]->setText("[ENTER]"); keytextvec[CTRL_Z]->setText("[CTRL+Z]"); keytextvec[SPACE]->setText("[SPACE]"); keytextvec[LCTRL]->setText("[LCTRL]"); keytextvec[LSHIFT]->setText("[LSHIFT]"); keytextvec[A]->setText("[A]\t\t"); keytextvec[S]->setText("[S]\t\t"); keytextvec[D]->setText("[D]\t\t"); keytextvec[Z]->setText("[Z]\t\t"); keytextvec[X]->setText("[X]\t\t"); keytextvec[C]->setText("[C]\t\t"); keytextvec[LEFT]->setText("[LEFT]"); keytextvec[RIGHT]->setText("[RIGHT]"); keytextvec[UP]->setText("[UP]"); keytextvec[DOWN]->setText("[DOWN]"); keytextvec[LEFTMOUSE]->setText("[LEFT MOUSE BUTTON]"); keytextvec[RIGHTMOUSE]->setText("[RIGHT MOUSE BUTTON]"); keytextvec[SCROLLMOUSE]->setText("[MOUSE SCROLL]"); infotextvec[ESCAPE]->setText("Closes current open window. Turns off\ncurrent active mode.\nResets group and chosen entity from group.\n"); infotextvec[ENTER]->setText("Agrees with current decision in message log.\nApproves choice yes/ok.\n"); infotextvec[CTRL_Z]->setText("Undo. Back to previous world state.\nDetermines current state then goes back to\nthe previous.\n"); infotextvec[SPACE]->setText("Temporary quick mode. Does actions like\nput (place) or remove. Based on current\nmode it deletes or puts entity very fast.\n"); infotextvec[LCTRL]->setText("Temporary delete mode. Enables user to\nremove entity that mouse is pointing at.\n"); infotextvec[LSHIFT]->setText("Temporary whole collision mode. This mode\nis very useful while placing tiles.\nTurnt on checks the whole rect occupied by\nentity.\n\n"); infotextvec[A]->setText("Moves to the previous group of entities."); infotextvec[S]->setText("Reset the chosen group to none."); infotextvec[D]->setText("Moves to the succeding group of entities.\n"); infotextvec[Z]->setText("Goes to previous entity from the group."); infotextvec[X]->setText("Goes to nearest middle one from the group."); infotextvec[C]->setText("Goes to next entity from the group.\n"); infotextvec[LEFT]->setText("Moves current world content's position\nleftward (it does not change entities position).\n"); infotextvec[RIGHT]->setText("Moves current world content's position\nrightward (same as above).\n"); infotextvec[UP]->setText("Moves current world content's position upward\n(same as above).\n"); infotextvec[DOWN]->setText("Moves current world content's position\ndownward (same as above).\n"); infotextvec[LEFTMOUSE]->setText("Puts entity or removes\n(depends on current mode).\n\n"); infotextvec[RIGHTMOUSE]->setText("If mouse cursor is hovered\nabove the entity it opens\nthe options of a group.\n\n\n"); infotextvec[SCROLLMOUSE]->setText("Changes entity of chosen group\nto upward or downward one."); // Set page text. Loading::add(pageText.setFont(cmm::JCANDLE_FONT_PATH)); if (Loading::isError()) return; pageText.setAlpha(MAX_ALPHA); pageText.setSize(plank.getWidth() / 20); setPageText(); } void EditorOptions::handle(const sf::Event &event) { if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { float x = (float)event.mouseButton.x; float y = (float)event.mouseButton.y; if (!active && button.handle(event)) { active = button.isActive(); if (active) setText(); return; } if (!active) return; if (leftbutton.checkCollision(x, y)) { if (isAbleToGoLeft()) { --currPage; setText(); } } else if (rightbutton.checkCollision(x, y)) { if (isAbleToGoRight()) { ++currPage; setText(); } } else if (!plank.checkCollision(x, y)) { active = false; button.setActive(false); reset(); } } } if (!active) return; if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) { active = false; button.setActive(false); reset(); return; } } // hovering... if (event.type == sf::Event::MouseMoved) { leftbutton.setAlpha(MAX_ALPHA / 1.5); rightbutton.setAlpha(MAX_ALPHA / 1.5); float x = (float)event.mouseMove.x; float y = (float)event.mouseMove.y; if (isAbleToGoLeft() && leftbutton.checkCollision(x, y)) leftbutton.setAlpha(MAX_ALPHA); else if (isAbleToGoRight() &&rightbutton.checkCollision(x, y)) rightbutton.setAlpha(MAX_ALPHA); } } void EditorOptions::drawButton(sf::RenderWindow* &window) { // Draw button and label always. button.draw(window); window->draw(label); } void EditorOptions::draw(sf::RenderWindow* &window) { if (!active) return; window->draw(blackLayer); window->draw(plank); // Draw descriptions / texts. for (int i = first; i <= last; ++i) { window->draw(*keytextvec[i]); window->draw(*infotextvec[i]); } // Draw left/right buttons. if (currPage != 0) window->draw(leftbutton); if (currPage != lastPage) window->draw(rightbutton); window->draw(pageText); } void EditorOptions::setText() { setPageText(); setBorders(); // set position of current scope keytextvec[first]->setPosition(plank.getX() + plank.getWidth() / 64, plank.getY() + plank.getHeight() / 64); infotextvec[first]->setPosition(keytextvec[first]->getX() + keytextvec[first]->getWidth() + plank.getWidth() / 64, keytextvec[first]->getY()); for (int i = first + 1; i <= last; ++i) { keytextvec[i]->setPosition(keytextvec[first]->getX(), infotextvec[i - 1]->getBot()); infotextvec[i]->setPosition(keytextvec[i]->getX() + keytextvec[i]->getWidth() + plank.getWidth() / 64, infotextvec[i - 1]->getBot()); } } void EditorOptions::setPageText() { pageText.setText(std::to_string(currPage) + "/" + std::to_string(lastPage)); pageText.setPosition(plank.getLeft() + plank.getWidth() - pageText.getWidth() * 1.2, plank.getTop() + plank.getHeight() - plank.getWidth() / 15); } void EditorOptions::setBorders() { if (currPage == 0) { first = 0; last = SPACE; } else if (currPage == 1) { first = LCTRL; last = C; } else if (currPage == lastPage - 1) { first = LEFT; last = DOWN; } else { first = LEFTMOUSE; last = SCROLLMOUSE; } } bool EditorOptions::isAbleToGoLeft() { return currPage > 0; } bool EditorOptions::isAbleToGoRight() { return currPage < lastPage; }
9,190
3,727
#include <Eigen/Dense> #include <iostream> #include <iomanip> #include <cmath> //! \brief One step of autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method //! Use SDIRK method for first order ode z' = f(z). Steps of size h. //! \tparam StateType type of solution space y and initial data y0 //! \param[in] z0 initial data z(0) //! \param[in] h size of the step //! \param[in] gamma parameter //! \return next step z1 template <class StateType> StateType sdirkStep(const StateType & z0, double h, double gamma) { // Matrix A for evaluation of f Eigen::Matrix2d A; A << 0.,1.,-1.,-1.; // Reuse factorization auto A_lu = (Eigen::Matrix2d::Identity()-h*gamma*A).partialPivLu(); Eigen::Vector2d az = A*z0; // Increments Eigen::Vector2d k1 = A_lu.solve(az); Eigen::Vector2d k2 = A_lu.solve(az + h*(1-2*gamma)*A*k1); // Next step return z0 + h*0.5*(k1 + k2); } //! \brief Solve autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method //! Use SDIRK method for first order ode z' = f(z), with N equidistant steps //! \tparam StateType type of solution space z = [y,y']! and initial data z0 = [y(0), y'(0)] //! \param[in] z0 initial data z(0) //! \param[in] N number of equidistant steps //! \param[in] T final time of simulation //! \param[in] gamma parameter //! \return vector containing each step of z_k (y and y') template <class StateType> std::vector<StateType> sdirkSolve(const StateType & z0, unsigned int N, double T, double gamma) { // Solution vector std::vector<StateType> res(N+1); // Equidistant step size const double h = T/N; // Push initial data res.at(0) = z0; // Main loop for(unsigned int i = 1; i <= N; ++i) { res.at(i) = sdirkStep(res.at(i-1), h, gamma); } return res; } int main() { // Initial data z0 = [y(0), y'(0)] Eigen::Vector2d z0; z0 << 1,0; // Final time const double T = 10; // Parameter const double gamma = (3.+std::sqrt(3.)) / 6.; // Mesh sizes std::vector<int> N = {20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240}; // Exact solution (only y(t)) given z0 = [y(0), y'(0)] and t auto yex = [&z0] (double t) { return 1./3.*std::exp(-t/2.) * ( 3.*z0(0) * std::cos( std::sqrt(3.)*t/2. ) + std::sqrt(3.)*z0(0) * std::sin( std::sqrt(3.)*t/2. ) + 2.*std::sqrt(3.)*z0(1) * std::sin( std::sqrt(3.)*t/2. ) ); }; // Store old error for rate computation double errold = 0; std::cout << std::setw(15) << "n" << std::setw(15) << "maxerr" << std::setw(15) << "rate" << std::endl; // Loop over all meshes for(unsigned int i = 0; i < N.size(); ++i) { int n = N.at(i); // Get solution auto sol = sdirkSolve(z0, n, T, gamma); // Compute error double err = std::abs(sol.back()(0) - yex(T)); // I/O std::cout << std::setw(15) << n << std::setw(15) << err; if(i > 0) std::cout << std::setw(15) << std::log2(errold /err); std::cout << std::endl; // Store old error errold = err; } }
3,160
1,291
/* * src/c_dd.cc * * This work was supported by the Director, Office of Science, Division * of Mathematical, Information, and Computational Sciences of the * U.S. Department of Energy under contract number DE-AC03-76SF00098. * * Copyright (c) 2000-2001 * * Contains the C wrapper functions for double-double precision arithmetic. * This can be used from Fortran code. */ #include <cstring> #include "config.h" #include <qd/dd_real.h> #include <qd/c_dd.h> #define TO_DOUBLE_PTR(a, ptr) ptr[0] = a.x[0]; ptr[1] = a.x[1]; extern "C" { /* add */ void c_dd_add(const double *a, const double *b, double *c) { dd_real cc; cc = dd_real(a) + dd_real(b); TO_DOUBLE_PTR(cc, c); } void c_dd_add_dd_d(const double *a, double b, double *c) { dd_real cc; cc = dd_real(a) + b; TO_DOUBLE_PTR(cc, c); } void c_dd_add_d_dd(double a, const double *b, double *c) { dd_real cc; cc = a + dd_real(b); TO_DOUBLE_PTR(cc, c); } /* sub */ void c_dd_sub(const double *a, const double *b, double *c) { dd_real cc; cc = dd_real(a) - dd_real(b); TO_DOUBLE_PTR(cc, c); } void c_dd_sub_dd_d(const double *a, double b, double *c) { dd_real cc; cc = dd_real(a) - b; TO_DOUBLE_PTR(cc, c); } void c_dd_sub_d_dd(double a, const double *b, double *c) { dd_real cc; cc = a - dd_real(b); TO_DOUBLE_PTR(cc, c); } /* mul */ void c_dd_mul(const double *a, const double *b, double *c) { dd_real cc; cc = dd_real(a) * dd_real(b); TO_DOUBLE_PTR(cc, c); } void c_dd_mul_dd_d(const double *a, double b, double *c) { dd_real cc; cc = dd_real(a) * b; TO_DOUBLE_PTR(cc, c); } void c_dd_mul_d_dd(double a, const double *b, double *c) { dd_real cc; cc = a * dd_real(b); TO_DOUBLE_PTR(cc, c); } /* div */ void c_dd_div(const double *a, const double *b, double *c) { dd_real cc; cc = dd_real(a) / dd_real(b); TO_DOUBLE_PTR(cc, c); } void c_dd_div_dd_d(const double *a, double b, double *c) { dd_real cc; cc = dd_real(a) / b; TO_DOUBLE_PTR(cc, c); } void c_dd_div_d_dd(double a, const double *b, double *c) { dd_real cc; cc = a / dd_real(b); TO_DOUBLE_PTR(cc, c); } /* copy */ void c_dd_copy(const double *a, double *b) { b[0] = a[0]; b[1] = a[1]; } void c_dd_copy_d(double a, double *b) { b[0] = a; b[1] = 0.0; } void c_dd_sqrt(const double *a, double *b) { dd_real bb; bb = std::sqrt(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_sqr(const double *a, double *b) { dd_real bb; bb = sqr(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_abs(const double *a, double *b) { dd_real bb; bb = std::abs(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_npwr(const double *a, int n, double *b) { dd_real bb; bb = npwr(dd_real(a), n); TO_DOUBLE_PTR(bb, b); } void c_dd_nroot(const double *a, int n, double *b) { dd_real bb; bb = nroot(dd_real(a), n); TO_DOUBLE_PTR(bb, b); } void c_dd_nint(const double *a, double *b) { dd_real bb; bb = nint(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_aint(const double *a, double *b) { dd_real bb; bb = aint(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_floor(const double *a, double *b) { dd_real bb; bb = std::floor(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_ceil(const double *a, double *b) { dd_real bb; bb = std::ceil(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_log(const double *a, double *b) { dd_real bb; bb = std::log(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_log10(const double *a, double *b) { dd_real bb; bb = std::log10(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_exp(const double *a, double *b) { dd_real bb; bb = std::exp(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_sin(const double *a, double *b) { dd_real bb; bb = std::sin(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_cos(const double *a, double *b) { dd_real bb; bb = std::cos(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_tan(const double *a, double *b) { dd_real bb; bb = std::tan(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_asin(const double *a, double *b) { dd_real bb; bb = std::asin(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_acos(const double *a, double *b) { dd_real bb; bb = std::acos(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_atan(const double *a, double *b) { dd_real bb; bb = std::atan(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_atan2(const double *a, const double *b, double *c) { dd_real cc; cc = std::atan2(dd_real(a), dd_real(b)); TO_DOUBLE_PTR(cc, c); } void c_dd_sinh(const double *a, double *b) { dd_real bb; bb = std::sinh(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_cosh(const double *a, double *b) { dd_real bb; bb = std::cosh(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_tanh(const double *a, double *b) { dd_real bb; bb = std::tanh(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_asinh(const double *a, double *b) { dd_real bb; bb = std::asinh(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_acosh(const double *a, double *b) { dd_real bb; bb = std::acosh(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_atanh(const double *a, double *b) { dd_real bb; bb = std::atanh(dd_real(a)); TO_DOUBLE_PTR(bb, b); } void c_dd_sincos(const double *a, double *s, double *c) { dd_real ss, cc; sincos(dd_real(a), ss, cc); TO_DOUBLE_PTR(ss, s); TO_DOUBLE_PTR(cc, c); } void c_dd_sincosh(const double *a, double *s, double *c) { dd_real ss, cc; sincosh(dd_real(a), ss, cc); TO_DOUBLE_PTR(ss, s); TO_DOUBLE_PTR(cc, c); } void c_dd_read(const char *s, double *a) { dd_real aa(s); TO_DOUBLE_PTR(aa, a); } void c_dd_swrite(const double *a, int precision, char *s, int len) { dd_real(a).write(s, len, precision); } void c_dd_write(const double *a) { std::cout << dd_real(a).to_string(dd_real::_ndigits()) << std::endl; } void c_dd_neg(const double *a, double *b) { b[0] = -a[0]; b[1] = -a[1]; } void c_dd_rand(double *a) { dd_real aa; aa = ddrand(); TO_DOUBLE_PTR(aa, a); } void c_dd_comp(const double *a, const double *b, int *result) { dd_real aa(a), bb(b); if (aa < bb) *result = -1; else if (aa > bb) *result = 1; else *result = 0; } void c_dd_comp_dd_d(const double *a, double b, int *result) { dd_real aa(a), bb(b); if (aa < bb) *result = -1; else if (aa > bb) *result = 1; else *result = 0; } void c_dd_comp_d_dd(double a, const double *b, int *result) { dd_real aa(a), bb(b); if (aa < bb) *result = -1; else if (aa > bb) *result = 1; else *result = 0; } void c_dd_pi(double *a) { TO_DOUBLE_PTR(dd_real::_pi(), a); } }
6,580
3,267
/* * ModDocTemplate.cpp * ------------------ * Purpose: CDocTemplate and CModDocManager specialization for CModDoc. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "FolderScanner.h" #include "Mainfrm.h" #include "Moddoc.h" #include "ModDocTemplate.h" #include "Reporting.h" #include "SelectPluginDialog.h" #include "../soundlib/plugins/PluginManager.h" OPENMPT_NAMESPACE_BEGIN #ifdef MPT_ALL_LOGGING #define DDEDEBUG #endif CDocument *CModDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL addToMru, BOOL makeVisible) { const mpt::PathString filename = (lpszPathName ? mpt::PathString::FromCString(lpszPathName) : mpt::PathString()); // First, remove document from MRU list. if(addToMru) { theApp.RemoveMruItem(filename); } CDocument *pDoc = CMultiDocTemplate::OpenDocumentFile(filename.empty() ? nullptr : filename.ToCString().GetString(), addToMru, makeVisible); if(pDoc) { CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); if (pMainFrm) pMainFrm->OnDocumentCreated(static_cast<CModDoc *>(pDoc)); } else if(!filename.empty() && CMainFrame::GetMainFrame() && addToMru) { // Opening the document failed CMainFrame::GetMainFrame()->UpdateMRUList(); } return pDoc; } CDocument *CModDocTemplate::OpenTemplateFile(const mpt::PathString &filename, bool isExampleTune) { CDocument *doc = OpenDocumentFile(filename.ToCString(), isExampleTune ? TRUE : FALSE, TRUE); if(doc) { CModDoc *modDoc = static_cast<CModDoc *>(doc); // Clear path so that saving will not take place in templates/examples folder. modDoc->ClearFilePath(); if(!isExampleTune) { CMultiDocTemplate::SetDefaultTitle(modDoc); m_nUntitledCount++; // Name has changed... CMainFrame::GetMainFrame()->UpdateTree(modDoc, GeneralHint().General()); // Reset edit history for template files CSoundFile &sndFile = modDoc->GetSoundFile(); sndFile.GetFileHistory().clear(); sndFile.m_dwCreatedWithVersion = Version::Current(); sndFile.m_dwLastSavedWithVersion = Version(); sndFile.m_modFormat = ModFormatDetails(); sndFile.m_songArtist = TrackerSettings::Instance().defaultArtist; if(sndFile.GetType() != MOD_TYPE_MPT) { // Always enforce most compatible playback for legacy module types sndFile.m_playBehaviour = sndFile.GetDefaultPlaybackBehaviour(sndFile.GetType()); } doc->UpdateAllViews(nullptr, UpdateHint().ModType().AsLPARAM()); } else { // Remove extension from title, so that saving the file will not suggest a filename like e.g. "example.it.it". const CString title = modDoc->GetTitle(); const int dotPos = title.ReverseFind(_T('.')); if(dotPos >= 0) { modDoc->SetTitle(title.Left(dotPos)); } } } return doc; } void CModDocTemplate::AddDocument(CDocument *doc) { CMultiDocTemplate::AddDocument(doc); m_documents.insert(static_cast<CModDoc *>(doc)); } void CModDocTemplate::RemoveDocument(CDocument *doc) { CMultiDocTemplate::RemoveDocument(doc); m_documents.erase(static_cast<CModDoc *>(doc)); } bool CModDocTemplate::DocumentExists(const CModDoc *doc) const { return m_documents.count(const_cast<CModDoc *>(doc)) != 0; } CDocument *CModDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU) { const mpt::PathString filename = (lpszFileName ? mpt::PathString::FromCString(lpszFileName) : mpt::PathString()); if(filename.IsDirectory()) { FolderScanner scanner(filename, FolderScanner::kOnlyFiles | FolderScanner::kFindInSubDirectories); mpt::PathString file; CDocument *pDoc = nullptr; while(scanner.Next(file)) { pDoc = OpenDocumentFile(file.ToCString(), bAddToMRU); } return pDoc; } if(const auto fileExt = filename.GetFileExt(); !mpt::PathString::CompareNoCase(fileExt, P_(".dll")) || !mpt::PathString::CompareNoCase(fileExt, P_(".vst3"))) { if(auto plugManager = theApp.GetPluginManager(); plugManager != nullptr) { if(auto plugLib = plugManager->AddPlugin(filename, TrackerSettings::Instance().BrokenPluginsWorkaroundVSTMaskAllCrashes); plugLib != nullptr) { if(!CSelectPluginDlg::VerifyPlugin(plugLib, nullptr)) { plugManager->RemovePlugin(plugLib); } return nullptr; } } } CDocument *pDoc = CDocManager::OpenDocumentFile(lpszFileName, bAddToMRU); if(pDoc == nullptr && !filename.empty()) { if(!filename.IsFile()) { Reporting::Error(MPT_CFORMAT("Unable to open \"{}\": file does not exist.")(filename.ToCString())); theApp.RemoveMruItem(filename); CMainFrame::GetMainFrame()->UpdateMRUList(); } else { // Case: Valid path but opening failed. const int numDocs = theApp.GetOpenDocumentCount(); Reporting::Notification(MPT_CFORMAT("Opening \"{}\" failed. This can happen if " "no more modules can be opened or if the file type was not " "recognised (currently there {} {} document{} open).")( filename.ToCString(), (numDocs == 1) ? CString(_T("is")) : CString(_T("are")), numDocs, (numDocs == 1) ? CString(_T("")) : CString(_T("s")))); } } return pDoc; } BOOL CModDocManager::OnDDECommand(LPTSTR lpszCommand) { BOOL bResult, bActivate; #ifdef DDEDEBUG MPT_LOG_GLOBAL(LogDebug, "DDE", U_("OnDDECommand: ") + mpt::ToUnicode(mpt::winstring(lpszCommand))); #endif // Handle any DDE commands recognized by your application // and return TRUE. See implementation of CWinApp::OnDDEComand // for example of parsing the DDE command string. bResult = FALSE; bActivate = FALSE; if ((lpszCommand) && lpszCommand[0] && (theApp.m_pMainWnd)) { std::size_t len = _tcslen(lpszCommand); std::vector<TCHAR> s(lpszCommand, lpszCommand + len + 1); len--; while((len > 0) && _tcschr(_T("(){}[]\'\" "), s[len])) { s[len--] = 0; } TCHAR *pszCmd = s.data(); while (pszCmd[0] == _T('[')) pszCmd++; TCHAR *pszData = pszCmd; while ((pszData[0] != _T('(')) && (pszData[0])) { if (((BYTE)pszData[0]) <= (BYTE)' ') *pszData = 0; pszData++; } while ((*pszData) && (_tcschr(_T("(){}[]\'\" "), *pszData))) { *pszData = 0; pszData++; } // Edit/Open if ((!lstrcmpi(pszCmd, _T("Edit"))) || (!lstrcmpi(pszCmd, _T("Open")))) { if (pszData[0]) { bResult = TRUE; bActivate = TRUE; OpenDocumentFile(pszData); } } else // New if (!lstrcmpi(pszCmd, _T("New"))) { OpenDocumentFile(_T("")); bResult = TRUE; bActivate = TRUE; } #ifdef DDEDEBUG MPT_LOG_GLOBAL(LogDebug, "DDE", MPT_UFORMAT("{}({})")(mpt::winstring(pszCmd), mpt::winstring(pszData))); #endif if ((bActivate) && (theApp.m_pMainWnd->m_hWnd)) { if (theApp.m_pMainWnd->IsIconic()) theApp.m_pMainWnd->ShowWindow(SW_RESTORE); theApp.m_pMainWnd->SetActiveWindow(); } } // Return FALSE for any DDE commands you do not handle. #ifdef DDEDEBUG if (!bResult) { MPT_LOG_GLOBAL(LogDebug, "DDE", U_("WARNING: failure in CModDocManager::OnDDECommand()")); } #endif return bResult; } OPENMPT_NAMESPACE_END
7,007
2,816
@interface CocoaViewport : NSView { @public phoenix::Viewport* viewport; } -(id) initWith:(phoenix::Viewport&)viewport; -(void) drawRect:(NSRect)rect; -(BOOL) acceptsFirstResponder; -(NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender; -(BOOL) performDragOperation:(id<NSDraggingInfo>)sender; -(void) keyDown:(NSEvent*)event; -(void) keyUp:(NSEvent*)event; @end namespace phoenix { struct pViewport : public pWidget { Viewport& viewport; CocoaViewport* cocoaViewport = nullptr; uintptr_t handle(); void setDroppable(bool droppable); pViewport(Viewport& viewport) : pWidget(viewport), viewport(viewport) {} void constructor(); void destructor(); }; }
680
240
// Copyright Carl Philipp Reh 2009 - 2018. // 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 FCPPT_TIME_OUTPUT_TM_HPP_INCLUDED #define FCPPT_TIME_OUTPUT_TM_HPP_INCLUDED #include <fcppt/detail/symbol.hpp> #include <fcppt/io/ostream_fwd.hpp> #include <fcppt/config/external_begin.hpp> #include <ctime> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace time { /** \brief Outputs an <code>%std::tm</code> to a stream \ingroup fcppttime Outputs \a tm to \a stream using the <code>std::time_put</code> locale facet, obtained from the locale of \a stream. Example: \snippet output_tm.cpp output_tm \param stream The stream to output to \param tm The time struct to output \return \a stream */ FCPPT_DETAIL_SYMBOL fcppt::io::ostream & output_tm( fcppt::io::ostream &stream, std::tm const &tm ); } } #endif
967
389
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/output/delegating_renderer.h" #include "cc/output/gl_renderer.h" #include "cc/output/output_surface.h" #include "cc/test/fake_output_surface_client.h" #include "cc/test/fake_renderer_client.h" #include "cc/test/fake_resource_provider.h" #include "cc/test/test_context_provider.h" #include "cc/test/test_web_graphics_context_3d.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace cc { namespace { class TestOutputSurface : public OutputSurface { public: explicit TestOutputSurface(scoped_refptr<ContextProvider> context_provider); ~TestOutputSurface() override; // OutputSurface implementation void SwapBuffers(CompositorFrame* frame) override; }; TestOutputSurface::TestOutputSurface( scoped_refptr<ContextProvider> context_provider) : OutputSurface(std::move(context_provider)) {} TestOutputSurface::~TestOutputSurface() { } void TestOutputSurface::SwapBuffers(CompositorFrame* frame) { client_->DidSwapBuffers(); client_->DidSwapBuffersComplete(); } class MockContextProvider : public TestContextProvider { public: explicit MockContextProvider( std::unique_ptr<TestWebGraphicsContext3D> context) : TestContextProvider(std::move(context)) {} MOCK_METHOD0(DeleteCachedResources, void()); protected: ~MockContextProvider() {} }; template <class T> std::unique_ptr<Renderer> CreateRenderer(RendererClient* client, const RendererSettings* settings, OutputSurface* output_surface, ResourceProvider* resource_provider); template <> std::unique_ptr<Renderer> CreateRenderer<DelegatingRenderer>( RendererClient* client, const RendererSettings* settings, OutputSurface* output_surface, ResourceProvider* resource_provider) { return DelegatingRenderer::Create( client, settings, output_surface, resource_provider); } template <> std::unique_ptr<Renderer> CreateRenderer<GLRenderer>( RendererClient* client, const RendererSettings* settings, OutputSurface* output_surface, ResourceProvider* resource_provider) { return GLRenderer::Create( client, settings, output_surface, resource_provider, NULL, 0); } template <typename T> class RendererTest : public ::testing::Test { protected: virtual void SetUp() { context_provider_ = new MockContextProvider(TestWebGraphicsContext3D::Create()); output_surface_.reset(new TestOutputSurface(context_provider_)); output_surface_->BindToClient(&output_surface_client_); resource_provider_ = FakeResourceProvider::Create(output_surface_.get(), nullptr); renderer_ = CreateRenderer<T>(&renderer_client_, &tree_settings_, output_surface_.get(), resource_provider_.get()); } FakeRendererClient renderer_client_; RendererSettings tree_settings_; FakeOutputSurfaceClient output_surface_client_; scoped_refptr<MockContextProvider> context_provider_; std::unique_ptr<OutputSurface> output_surface_; std::unique_ptr<ResourceProvider> resource_provider_; std::unique_ptr<Renderer> renderer_; }; typedef ::testing::Types<DelegatingRenderer, GLRenderer> RendererTypes; TYPED_TEST_CASE(RendererTest, RendererTypes); TYPED_TEST(RendererTest, ContextPurgedWhenRendererBecomesInvisible) { EXPECT_CALL(*(this->context_provider_.get()), DeleteCachedResources()) .Times(1); EXPECT_TRUE(this->renderer_->visible()); this->renderer_->SetVisible(false); EXPECT_FALSE(this->renderer_->visible()); } } // namespace } // namespace cc
3,873
1,154
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** test01.cpp -- Demo "new" dynamic method support. See the README file for a description of these capabilities. This demo excercises all of the major capabilities. Original Author: Stuart Swan, Cadence Design Systems, Inc., 2002-10-22 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Andy Goodrich, Forte Design Systems, 30 July 03 Description of Modification: Converted thread demo to method demo. *****************************************************************************/ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> int test_function(double d) { cout << endl << "Test_function sees " << d << endl; return int(d); } void void_function(double d) { cout << endl << "void_function sees " << d << endl; } int ref_function(const double& d) { cout << endl << "ref_function sees " << d << endl; return int(d); } class top : public sc_module { public: SC_HAS_PROCESS(top); top(sc_module_name name) : sc_module(name) { SC_THREAD(main); } void main() { sc_event e1, e2, e3, e4; sc_spawn_options options1, options2, options3, options4; int r; cout << endl; e1.notify(100, SC_NS); // Spawn several methods that co-operatively execute in round robin order options1.spawn_method(); options1.dont_initialize(); options1.set_sensitivity(&e1); sc_spawn(&r, sc_bind(&top::round_robin, this, "1", sc_ref(e1), sc_ref(e2), 3), "1", &options1 ); options2.spawn_method(); options2.dont_initialize(); options2.set_sensitivity(&e2); sc_spawn(&r, sc_bind(&top::round_robin, this, "2", sc_ref(e2), sc_ref(e3), 3), "2", &options2 ); options3.spawn_method(); options3.dont_initialize(); options3.set_sensitivity(&e3); sc_spawn(&r, sc_bind(&top::round_robin, this, "3", sc_ref(e3), sc_ref(e4), 3), "3", &options3 ); options4.spawn_method(); options4.dont_initialize(); options4.set_sensitivity(&e4); sc_spawn(&r, sc_bind(&top::round_robin, this, "4", sc_ref(e4), sc_ref(e1), 3), "4", &options4 ); wait(295, SC_NS); cout << endl << "Done." << endl; sc_stop(); } int round_robin(const char *str, sc_event& receive, sc_event& send, int cnt) { cout << "Round robin method " << str << " at time " << sc_time_stamp() << endl; next_trigger(receive); send.notify(10, SC_NS); return 0; } }; int sc_main (int argc , char *argv[]) { top top1("Top1"); sc_start(); return 0; }
3,739
1,253
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "display_gralloc_test.h" #include <securec.h> #include "gtest/gtest.h" #include "display_gralloc.h" #include "display_test.h" #include "hi_gbm_internal.h" namespace { const AllocTestPrms GRALLOC_TEST_SETS[] = { { .allocInfo = { .width = 1920, .height = 1080, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBX_8888 }, .expectStride = 1920 * 4, .expectSize = 1920 * 1080 * 4 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBX_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4 }, { .allocInfo = { .width = 1280, .height = 720, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBX_8888 }, .expectStride = 1280 * 4, .expectSize = 1280 * 720 * 4 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBA_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGB_888 }, .expectStride = 1080 * 3, .expectSize = 1080 * 1920 * 3 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGRA_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGRX_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBA_4444 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBX_4444 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGRA_4444 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGRX_4444 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGR_565 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGRA_5551 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_BGRX_5551 }, .expectStride = 1080 * 2, .expectSize = 1080 * 1920 * 2 }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_YCBCR_420_SP }, .expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN), .expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920, }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_YCRCB_420_SP }, .expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN), .expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920, }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_YCBCR_420_P }, .expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN), .expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920, }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_YCRCB_420_P }, .expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN), .expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920, }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA, .format = PIXEL_FMT_RGBX_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4, }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ, .format = PIXEL_FMT_RGBX_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4, }, { .allocInfo = { .width = 1080, .height = 1920, .usage = HBM_USE_MEM_DMA | HBM_USE_CPU_WRITE, .format = PIXEL_FMT_RGBX_8888 }, .expectStride = 1080 * 4, .expectSize = 1080 * 1920 * 4, }, }; static bool CheckBufferHandle(AllocTestPrms &info, BufferHandle &buffer) { if (buffer.stride != (ALIGN_UP(info.expectStride, WIDTH_ALIGN))) { DISPLAY_TEST_LOGE("stride check faild stride %d, expect stride %d ", buffer.stride, info.expectStride); DISPLAY_TEST_LOGE("stride check faild format %d width %d, height %d ", info.allocInfo.format, info.allocInfo.width, info.allocInfo.height); return false; } if (buffer.size != info.expectSize) { DISPLAY_TEST_LOGE("size check faild size %d, expect size %d ", buffer.size, info.expectSize); DISPLAY_TEST_LOGE("stride check faild format %d width %d, height %d ", info.allocInfo.format, info.allocInfo.width, info.allocInfo.height); return false; } return true; } void GrallocAllocTest::SetUp() { if (GrallocInitialize(&mGrallocFuncs) != DISPLAY_SUCCESS) { DISPLAY_TEST_LOGE("DisplayInit failure\n"); ASSERT_TRUE(0); } } void GrallocAllocTest::TearDown() { if (GrallocUninitialize(mGrallocFuncs) != DISPLAY_SUCCESS) { DISPLAY_TEST_LOGE("DisplayUninit failure\n"); ASSERT_TRUE(0); } } int32_t GrallocAllocTest::AllocMemTest(AllocTestPrms &info) { int ret; BufferHandle *buffer = nullptr; const int testCount = 1; // test 40 times for (int i = 0; i < testCount; i++) { ret = mGrallocFuncs->AllocMem(&info.allocInfo, &buffer); if (ret != DISPLAY_SUCCESS) { return ret; } void *vAddr = mGrallocFuncs->Mmap(buffer); if (vAddr == nullptr) { return DISPLAY_FAILURE; } if (info.allocInfo.usage & (HBM_USE_CPU_READ | HBM_USE_CPU_WRITE)) { ret = mGrallocFuncs->InvalidateCache(buffer); if (ret != DISPLAY_SUCCESS) { return ret; } } if (memset_s(vAddr, buffer->size, 0, buffer->size) != EOK) { return DISPLAY_NOMEM; } DISPLAY_TEST_CHK_RETURN(!CheckBufferHandle(info, *buffer), DISPLAY_FAILURE, DISPLAY_TEST_LOGE("buffer check failed")); if (info.allocInfo.usage & (HBM_USE_CPU_READ | HBM_USE_CPU_WRITE)) { ret = mGrallocFuncs->FlushCache(buffer); if (ret != DISPLAY_SUCCESS) { return ret; } } mGrallocFuncs->Unmap((buffer)); mGrallocFuncs->FreeMem(buffer); } return DISPLAY_SUCCESS; } TEST(GrallocAllocTest, NULLPTR) { int ret = GrallocInitialize(nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); GrallocFuncs *grallocFuncs; AllocInfo allocInfo; BufferHandle *hdl; ret = GrallocInitialize(&grallocFuncs); ASSERT_TRUE(ret == DISPLAY_SUCCESS); ret = grallocFuncs->AllocMem(nullptr, nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); ret = grallocFuncs->AllocMem(&allocInfo, nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); ret = grallocFuncs->AllocMem(nullptr, &hdl); ASSERT_TRUE(ret != DISPLAY_SUCCESS); ret = grallocFuncs->InvalidateCache(nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); ret = grallocFuncs->FlushCache(nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); grallocFuncs->FreeMem(nullptr); void *vAddr = grallocFuncs->Mmap(nullptr); ASSERT_TRUE(vAddr == nullptr); ret = grallocFuncs->Unmap(nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); ret = GrallocUninitialize(nullptr); ASSERT_TRUE(ret != DISPLAY_SUCCESS); ret = GrallocUninitialize(grallocFuncs); ASSERT_TRUE(ret == DISPLAY_SUCCESS); } TEST_P(GrallocAllocTest, GrallocAlloc) { AllocTestPrms params = GetParam(); int ret = AllocMemTest(params); ASSERT_TRUE(ret == DISPLAY_SUCCESS); } INSTANTIATE_TEST_CASE_P(AllocTest, GrallocAllocTest, ::testing::ValuesIn(GRALLOC_TEST_SETS)); }
11,379
4,688
/* Copyright 2021 Stanford University * * 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 "pennant.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <map> #include <vector> #include "mappers/default_mapper.h" #include <sys/time.h> #include <sys/resource.h> void print_rusage(const char *message) { struct rusage usage; if (getrusage(RUSAGE_SELF, &usage) != 0) return; printf("%s: %ld MB\n", message, usage.ru_maxrss / 1024); } using namespace Legion; using namespace Legion::Mapping; struct config { int64_t np; int64_t nz; int64_t nzx; int64_t nzy; double lenx; double leny; int64_t numpcx; int64_t numpcy; int64_t npieces; int64_t meshtype; bool compact; int64_t stripsize; int64_t spansize; }; enum { MESH_PIE = 0, MESH_RECT = 1, MESH_HEX = 2, }; /// /// Mesh Generator /// /* * Some portions of the following code are derived from the * open-source release of PENNANT: * * https://github.com/losalamos/PENNANT */ static void generate_mesh_rect(config &conf, std::vector<double> &pointpos_x, std::vector<double> &pointpos_y, std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, std::vector<int64_t> &zonestart, std::vector<int64_t> &zonesize, std::vector<int64_t> &zonepoints, std::vector<int64_t> &zonecolors, std::vector<int64_t> &zxbounds, std::vector<int64_t> &zybounds) { int64_t &nz = conf.nz; int64_t &np = conf.np; nz = conf.nzx * conf.nzy; const int npx = conf.nzx + 1; const int npy = conf.nzy + 1; np = npx * npy; // generate point coordinates pointpos_x.reserve(np); pointpos_y.reserve(np); double dx = conf.lenx / (double) conf.nzx; double dy = conf.leny / (double) conf.nzy; int pcy = 0; for (int j = 0; j < npy; ++j) { if (j >= zybounds[pcy+1]) pcy += 1; double y = dy * (double) j; int pcx = 0; for (int i = 0; i < npx; ++i) { if (i >= zxbounds[pcx+1]) pcx += 1; double x = dx * (double) i; pointpos_x.push_back(x); pointpos_y.push_back(y); int c = pcy * conf.numpcx + pcx; if (i != zxbounds[pcx] && j != zybounds[pcy]) pointcolors.push_back(c); else { int p = pointpos_x.size() - 1; pointcolors.push_back(MULTICOLOR); std::vector<int64_t> &pmc = pointmcolors[p]; if (i == zxbounds[pcx] && j == zybounds[pcy]) pmc.push_back(c - conf.numpcx - 1); if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx); if (i == zxbounds[pcx]) pmc.push_back(c - 1); pmc.push_back(c); } } } // generate zone adjacency lists zonestart.reserve(nz); zonesize.reserve(nz); zonepoints.reserve(4 * nz); zonecolors.reserve(nz); pcy = 0; for (int j = 0; j < conf.nzy; ++j) { if (j >= zybounds[pcy+1]) pcy += 1; int pcx = 0; for (int i = 0; i < conf.nzx; ++i) { if (i >= zxbounds[pcx+1]) pcx += 1; zonestart.push_back(zonepoints.size()); zonesize.push_back(4); int p0 = j * npx + i; zonepoints.push_back(p0); zonepoints.push_back(p0 + 1); zonepoints.push_back(p0 + npx + 1); zonepoints.push_back(p0 + npx); zonecolors.push_back(pcy * conf.numpcx + pcx); } } } static void generate_mesh_pie(config &conf, std::vector<double> &pointpos_x, std::vector<double> &pointpos_y, std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, std::vector<int64_t> &zonestart, std::vector<int64_t> &zonesize, std::vector<int64_t> &zonepoints, std::vector<int64_t> &zonecolors, std::vector<int64_t> &zxbounds, std::vector<int64_t> &zybounds) { int64_t &nz = conf.nz; int64_t &np = conf.np; nz = conf.nzx * conf.nzy; const int npx = conf.nzx + 1; const int npy = conf.nzy + 1; np = npx * (npy - 1) + 1; // generate point coordinates pointpos_x.reserve(np); pointpos_y.reserve(np); double dth = conf.lenx / (double) conf.nzx; double dr = conf.leny / (double) conf.nzy; int pcy = 0; for (int j = 0; j < npy; ++j) { if (j >= zybounds[pcy+1]) pcy += 1; if (j == 0) { // special case: "row" at origin only contains // one point, shared by all pieces in row pointpos_x.push_back(0.); pointpos_y.push_back(0.); if (conf.numpcx == 1) pointcolors.push_back(0); else { pointcolors.push_back(MULTICOLOR); std::vector<int64_t> &pmc = pointmcolors[0]; for (int c = 0; c < conf.numpcx; ++c) pmc.push_back(c); } continue; } double r = dr * (double) j; int pcx = 0; for (int i = 0; i < npx; ++i) { if (i >= zxbounds[pcx+1]) pcx += 1; double th = dth * (double) (conf.nzx - i); double x = r * cos(th); double y = r * sin(th); pointpos_x.push_back(x); pointpos_y.push_back(y); int c = pcy * conf.numpcx + pcx; if (i != zxbounds[pcx] && j != zybounds[pcy]) pointcolors.push_back(c); else { int p = pointpos_x.size() - 1; pointcolors.push_back(MULTICOLOR); std::vector<int64_t> &pmc = pointmcolors[p]; if (i == zxbounds[pcx] && j == zybounds[pcy]) pmc.push_back(c - conf.numpcx - 1); if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx); if (i == zxbounds[pcx]) pmc.push_back(c - 1); pmc.push_back(c); } } } // generate zone adjacency lists zonestart.reserve(nz); zonesize.reserve(nz); zonepoints.reserve(4 * nz); zonecolors.reserve(nz); pcy = 0; for (int j = 0; j < conf.nzy; ++j) { if (j >= zybounds[pcy+1]) pcy += 1; int pcx = 0; for (int i = 0; i < conf.nzx; ++i) { if (i >= zxbounds[pcx+1]) pcx += 1; zonestart.push_back(zonepoints.size()); int p0 = j * npx + i - (npx - 1); if (j == 0) { zonesize.push_back(3); zonepoints.push_back(0); } else { zonesize.push_back(4); zonepoints.push_back(p0); zonepoints.push_back(p0 + 1); } zonepoints.push_back(p0 + npx + 1); zonepoints.push_back(p0 + npx); zonecolors.push_back(pcy * conf.numpcx + pcx); } } } static void generate_mesh_hex(config &conf, std::vector<double> &pointpos_x, std::vector<double> &pointpos_y, std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, std::vector<int64_t> &zonestart, std::vector<int64_t> &zonesize, std::vector<int64_t> &zonepoints, std::vector<int64_t> &zonecolors, std::vector<int64_t> &zxbounds, std::vector<int64_t> &zybounds) { int64_t &nz = conf.nz; int64_t &np = conf.np; nz = conf.nzx * conf.nzy; const int npx = conf.nzx + 1; const int npy = conf.nzy + 1; // generate point coordinates pointpos_x.resize(2 * npx * npy); // upper bound pointpos_y.resize(2 * npx * npy); // upper bound double dx = conf.lenx / (double) (conf.nzx - 1); double dy = conf.leny / (double) (conf.nzy - 1); std::vector<int64_t> pbase(npy); int p = 0; int pcy = 0; for (int j = 0; j < npy; ++j) { if (j >= zybounds[pcy+1]) pcy += 1; pbase[j] = p; double y = dy * ((double) j - 0.5); y = std::max(0., std::min(conf.leny, y)); int pcx = 0; for (int i = 0; i < npx; ++i) { if (i >= zxbounds[pcx+1]) pcx += 1; double x = dx * ((double) i - 0.5); x = std::max(0., std::min(conf.lenx, x)); int c = pcy * conf.numpcx + pcx; if (i == 0 || i == conf.nzx || j == 0 || j == conf.nzy) { pointpos_x[p] = x; pointpos_y[p++] = y; if (i != zxbounds[pcx] && j != zybounds[pcy]) pointcolors.push_back(c); else { int p1 = p - 1; pointcolors.push_back(MULTICOLOR); std::vector<int64_t> &pmc = pointmcolors[p1]; if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx); if (i == zxbounds[pcx]) pmc.push_back(c - 1); pmc.push_back(c); } } else { pointpos_x[p] = x - dx / 6.; pointpos_y[p++] = y + dy / 6.; pointpos_x[p] = x + dx / 6.; pointpos_y[p++] = y - dy / 6.; if (i != zxbounds[pcx] && j != zybounds[pcy]) { pointcolors.push_back(c); pointcolors.push_back(c); } else { int p1 = p - 2; int p2 = p - 1; pointcolors.push_back(MULTICOLOR); pointcolors.push_back(MULTICOLOR); std::vector<int64_t> &pmc1 = pointmcolors[p1]; std::vector<int64_t> &pmc2 = pointmcolors[p2]; if (i == zxbounds[pcx] && j == zybounds[pcy]) { pmc1.push_back(c - conf.numpcx - 1); pmc2.push_back(c - conf.numpcx - 1); pmc1.push_back(c - 1); pmc2.push_back(c - conf.numpcx); } else if (j == zybounds[pcy]) { pmc1.push_back(c - conf.numpcx); pmc2.push_back(c - conf.numpcx); } else { // i == zxbounds[pcx] pmc1.push_back(c - 1); pmc2.push_back(c - 1); } pmc1.push_back(c); pmc2.push_back(c); } } } // for i } // for j np = p; pointpos_x.resize(np); pointpos_y.resize(np); // generate zone adjacency lists zonestart.resize(nz); zonesize.resize(nz); zonepoints.reserve(6 * nz); // upper bound zonecolors.reserve(nz); pcy = 0; for (int j = 0; j < conf.nzy; ++j) { if (j >= zybounds[pcy+1]) pcy += 1; int pbasel = pbase[j]; int pbaseh = pbase[j+1]; int pcx = 0; for (int i = 0; i < conf.nzx; ++i) { if (i >= zxbounds[pcx+1]) pcx += 1; int z = j * conf.nzx + i; std::vector<int64_t> v(6); v[1] = pbasel + 2 * i; v[0] = v[1] - 1; v[2] = v[1] + 1; v[5] = pbaseh + 2 * i; v[4] = v[5] + 1; v[3] = v[4] + 1; if (j == 0) { v[0] = pbasel + i; v[2] = v[0] + 1; if (i == conf.nzx - 1) v.erase(v.begin()+3); v.erase(v.begin()+1); } // if j else if (j == conf.nzy - 1) { v[5] = pbaseh + i; v[3] = v[5] + 1; v.erase(v.begin()+4); if (i == 0) v.erase(v.begin()+0); } // else if j else if (i == 0) v.erase(v.begin()+0); else if (i == conf.nzx - 1) v.erase(v.begin()+3); zonestart[z] = zonepoints.size(); zonesize[z] = v.size(); zonepoints.insert(zonepoints.end(), v.begin(), v.end()); zonecolors.push_back(pcy * conf.numpcx + pcx); } // for i } // for j } static void calc_mesh_num_pieces(config &conf) { // pick numpcx, numpcy such that pieces are as close to square // as possible // we would like: nzx / numpcx == nzy / numpcy, // where numpcx * numpcy = npieces (total number of pieces) // this solves to: numpcx = sqrt(npieces * nzx / nzy) // we compute this, assuming nzx <= nzy (swap if necessary) double nx = static_cast<double>(conf.nzx); double ny = static_cast<double>(conf.nzy); bool swapflag = (nx > ny); if (swapflag) std::swap(nx, ny); double n = sqrt(conf.npieces * nx / ny); // need to constrain n to be an integer with npieces % n == 0 // try rounding n both up and down int n1 = floor(n + 1.e-12); n1 = std::max(n1, 1); while (conf.npieces % n1 != 0) --n1; int n2 = ceil(n - 1.e-12); while (conf.npieces % n2 != 0) ++n2; // pick whichever of n1 and n2 gives blocks closest to square, // i.e. gives the shortest long side double longside1 = std::max(nx / n1, ny / (conf.npieces/n1)); double longside2 = std::max(nx / n2, ny / (conf.npieces/n2)); conf.numpcx = (longside1 <= longside2 ? n1 : n2); conf.numpcy = conf.npieces / conf.numpcx; if (swapflag) std::swap(conf.numpcx, conf.numpcy); } static void generate_mesh(config &conf, std::vector<double> &pointpos_x, std::vector<double> &pointpos_y, std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, std::vector<int64_t> &zonestart, std::vector<int64_t> &zonesize, std::vector<int64_t> &zonepoints, std::vector<int64_t> &zonecolors) { // Do calculations common to all mesh types: std::vector<int64_t> zxbounds; std::vector<int64_t> zybounds; if (conf.numpcx <= 0 || conf.numpcy <= 0) { calc_mesh_num_pieces(conf); } zxbounds.push_back(-1); for (int pcx = 1; pcx < conf.numpcx; ++pcx) zxbounds.push_back(pcx * conf.nzx / conf.numpcx); zxbounds.push_back(conf.nzx + 1); zybounds.push_back(-1); for (int pcy = 1; pcy < conf.numpcy; ++pcy) zybounds.push_back(pcy * conf.nzy / conf.numpcy); zybounds.push_back(0x7FFFFFFF); // Mesh type-specific calculations: if (conf.meshtype == MESH_PIE) { generate_mesh_pie(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors, zonestart, zonesize, zonepoints, zonecolors, zxbounds, zybounds); } else if (conf.meshtype == MESH_RECT) { generate_mesh_rect(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors, zonestart, zonesize, zonepoints, zonecolors, zxbounds, zybounds); } else if (conf.meshtype == MESH_HEX) { generate_mesh_hex(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors, zonestart, zonesize, zonepoints, zonecolors, zxbounds, zybounds); } } static void sort_zones_by_color(const config &conf, const std::vector<int64_t> &zonecolors, std::vector<int64_t> &zones_inverse_map, std::vector<int64_t> &zones_map) { // Sort zones by color. assert(int64_t(zonecolors.size()) == conf.nz); std::map<int64_t, std::vector<int64_t> > zones_by_color; for (int64_t z = 0; z < conf.nz; z++) { zones_by_color[zonecolors[z]].push_back(z); } for (int64_t c = 0; c < conf.npieces; c++) { std::vector<int64_t> &zones = zones_by_color[c]; for (std::vector<int64_t>::iterator zt = zones.begin(), ze = zones.end(); zt != ze; ++zt) { int64_t z = *zt; assert(zones_map[z] == -1ll); zones_map[z] = zones_inverse_map.size(); zones_inverse_map.push_back(z); } } } static std::set<int64_t> zone_point_set( int64_t z, const std::vector<int64_t> &zonestart, const std::vector<int64_t> &zonesize, const std::vector<int64_t> &zonepoints) { std::set<int64_t> points; for (int64_t z_start = zonestart[z], z_size = zonesize[z], z_point = z_start; z_point < z_start + z_size; z_point++) { points.insert(zonepoints[z_point]); } return points; } static void sort_zones_by_color_strip(const config &conf, const std::vector<double> &pointpos_x, const std::vector<double> &pointpos_y, const std::vector<int64_t> &zonestart, const std::vector<int64_t> &zonesize, const std::vector<int64_t> &zonepoints, const std::vector<int64_t> &zonecolors, std::vector<int64_t> &zones_inverse_map, std::vector<int64_t> &zones_map) { int64_t stripsize = conf.stripsize; // Sort zones by color. Within each color, make strips of zones of // size stripsize. std::vector<std::vector<int64_t> > strips; assert(int64_t(zonecolors.size()) == conf.nz); for (int64_t c = 0; c < conf.npieces; c++) { strips.assign(strips.size(), std::vector<int64_t>()); int64_t z_start = -1ll; std::set<int64_t> z_start_points; for (int64_t z = 0; z < conf.nz; z++) { if (zonecolors[z] == c) { if (z_start >= 0) { if (z > z_start + 1) { bool intersect = false; for (int64_t z_start = zonestart[z], z_size = zonesize[z], z_point = z_start; z_point < z_start + z_size; z_point++) { if (z_start_points.count(zonepoints[z_point])) { intersect = true; break; } } if (intersect) { z_start = z; z_start_points = zone_point_set(z_start, zonestart, zonesize, zonepoints); } } } else { z_start = z; z_start_points = zone_point_set(z_start, zonestart, zonesize, zonepoints); } int64_t strip = (z - z_start)/stripsize; if (strip + 1 > int64_t(strips.size())) { strips.resize(strip+1); } strips[strip].push_back(z); } } for (std::vector<std::vector<int64_t> >::iterator st = strips.begin(), se = strips.end(); st != se; ++st) { for (std::vector<int64_t>::iterator zt = st->begin(), ze = st->end(); zt != ze; ++zt) { int64_t z = *zt; assert(zones_map[z] == -1ll); zones_map[z] = zones_inverse_map.size(); zones_inverse_map.push_back(z); } } } } static void sort_points_by_color( const config &conf, const std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, std::vector<int64_t> &points_inverse_map, std::vector<int64_t> &points_map) { // Sort points by color; sort multi-color points by first color. assert(int64_t(pointcolors.size()) == conf.np); std::map<int64_t, std::vector<int64_t> > points_by_color; std::map<int64_t, std::vector<int64_t> > points_by_multicolor; for (int64_t p = 0; p < conf.np; p++) { if (pointcolors[p] == MULTICOLOR) { points_by_multicolor[pointmcolors[p][0]].push_back(p); } else { points_by_color[pointcolors[p]].push_back(p); } } for (int64_t c = 0; c < conf.npieces; c++) { std::vector<int64_t> &points = points_by_multicolor[c]; for (std::vector<int64_t>::iterator pt = points.begin(), pe = points.end(); pt != pe; ++pt) { int64_t p = *pt; assert(points_map[p] == -1ll); points_map[p] = points_inverse_map.size(); points_inverse_map.push_back(p); } } for (int64_t c = 0; c < conf.npieces; c++) { std::vector<int64_t> &points = points_by_color[c]; for (std::vector<int64_t>::iterator pt = points.begin(), pe = points.end(); pt != pe; ++pt) { int64_t p = *pt; assert(points_map[p] == -1ll); points_map[p] = points_inverse_map.size(); points_inverse_map.push_back(p); } } } static void compact_mesh(const config &conf, std::vector<double> &pointpos_x, std::vector<double> &pointpos_y, std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, std::vector<int64_t> &zonestart, std::vector<int64_t> &zonesize, std::vector<int64_t> &zonepoints, std::vector<int64_t> &zonecolors) { // This stage is responsible for compacting the mesh so that each of // the pieces is dense (in the global coordinate space). This // involves sorting the various elements by color and then rewriting // the various pointers to be internally consistent again. // Sort zones by color. std::vector<int64_t> zones_inverse_map; std::vector<int64_t> zones_map(conf.nz, -1ll); if (conf.stripsize > 0) { sort_zones_by_color_strip(conf, pointpos_x, pointpos_y, zonestart, zonesize, zonepoints, zonecolors, zones_inverse_map, zones_map); } else { sort_zones_by_color(conf, zonecolors, zones_inverse_map, zones_map); } assert(int64_t(zones_inverse_map.size()) == conf.nz); // Sort points by color; sort multi-color points by first color. std::vector<int64_t> points_inverse_map; std::vector<int64_t> points_map(conf.np, -1ll); sort_points_by_color(conf, pointcolors, pointmcolors, points_inverse_map, points_map); assert(int64_t(points_inverse_map.size()) == conf.np); // Various sanity checks. #if 0 for (int64_t z = 0; z < conf.nz; z++) { printf("zone old %ld new %ld color %ld\n", z, zones_map[z], zonecolors[z]); } printf("\n"); for (int64_t newz = 0; newz < conf.nz; newz++) { int64_t oldz = zones_inverse_map[newz]; printf("zone new %ld old %ld color %ld\n", newz, oldz, zonecolors[oldz]); } printf("\n"); for (int64_t p = 0; p < conf.np; p++) { printf("point old %ld new %ld color %ld\n", p, points_map[p], pointcolors[p]); } printf("\n"); for (int64_t newp = 0; newp < conf.np; newp++) { int64_t oldp = points_inverse_map[newp]; printf("point new %ld old %ld color %ld\n", newp, oldp, pointcolors[oldp]); } #endif // Project zones through the zones map. { std::vector<int64_t> old_zonestart = zonestart; for (int64_t newz = 0; newz < conf.nz; newz++) { int64_t oldz = zones_inverse_map[newz]; zonestart[newz] = old_zonestart[oldz]; } } { std::vector<int64_t> old_zonesize = zonesize; for (int64_t newz = 0; newz < conf.nz; newz++) { int64_t oldz = zones_inverse_map[newz]; zonesize[newz] = old_zonesize[oldz]; } } { std::vector<int64_t> old_zonepoints = zonepoints; int64_t nzp = zonepoints.size(); for (int64_t zp = 0; zp < nzp; zp++) { zonepoints[zp] = points_map[old_zonepoints[zp]]; } } { std::vector<int64_t> old_zonecolors = zonecolors; for (int64_t newz = 0; newz < conf.nz; newz++) { int64_t oldz = zones_inverse_map[newz]; zonecolors[newz] = old_zonecolors[oldz]; } } // Project points through the points map. { std::vector<double> old_pointpos_x = pointpos_x; for (int64_t newp = 0; newp < conf.np; newp++) { int64_t oldp = points_inverse_map[newp]; pointpos_x[newp] = old_pointpos_x[oldp]; } } { std::vector<double> old_pointpos_y = pointpos_y; for (int64_t newp = 0; newp < conf.np; newp++) { int64_t oldp = points_inverse_map[newp]; pointpos_y[newp] = old_pointpos_y[oldp]; } } { std::vector<int64_t> old_pointcolors = pointcolors; for (int64_t newp = 0; newp < conf.np; newp++) { int64_t oldp = points_inverse_map[newp]; pointcolors[newp] = old_pointcolors[oldp]; } } { std::map<int64_t, std::vector<int64_t> > old_pointmcolors = pointmcolors; for (int64_t newp = 0; newp < conf.np; newp++) { int64_t oldp = points_inverse_map[newp]; pointmcolors[newp] = old_pointmcolors[oldp]; } } } static void color_spans(const config &conf, const std::vector<double> &pointpos_x, const std::vector<double> &pointpos_y, const std::vector<int64_t> &pointcolors, std::map<int64_t, std::vector<int64_t> > &pointmcolors, const std::vector<int64_t> &zonestart, const std::vector<int64_t> &zonesize, const std::vector<int64_t> &zonepoints, const std::vector<int64_t> &zonecolors, std::vector<int64_t> &zonespancolors_vec, std::vector<int64_t> &pointspancolors_vec, int64_t &nspans_zones, int64_t &nspans_points) { { // Compute zone spans. std::vector<std::vector<std::vector<int64_t> > > spans(conf.npieces); std::vector<int64_t> span_size(conf.npieces, conf.spansize); for (int64_t z = 0; z < conf.nz; z++) { int64_t c = zonecolors[z]; if (span_size[c] + zonesize[c] > conf.spansize) { spans[c].resize(spans[c].size() + 1); span_size[c] = 0; } spans[c][spans[c].size() - 1].push_back(z); span_size[c] += zonesize[z]; } // Color zones by span. nspans_zones = 0; zonespancolors_vec.assign(conf.nz, -1ll); for (int64_t c = 0; c < conf.npieces; c++) { std::vector<std::vector<int64_t> > &color_spans = spans[c]; int64_t nspans = color_spans.size(); nspans_zones = std::max(nspans_zones, nspans); for (int64_t ispan = 0; ispan < nspans; ispan++) { std::vector<int64_t> &span = color_spans[ispan]; for (std::vector<int64_t>::iterator zt = span.begin(), ze = span.end(); zt != ze; ++zt) { int64_t z = *zt; zonespancolors_vec[z] = ispan; } } } for (int64_t z = 0; z < conf.nz; z++) { assert(zonespancolors_vec[z] != -1ll); } } { // Compute point spans. std::vector<std::vector<std::vector<int64_t> > > spans(conf.npieces); std::vector<std::vector<std::vector<int64_t> > > mspans(conf.npieces); std::vector<int64_t> span_size(conf.npieces, conf.spansize); std::vector<int64_t> mspan_size(conf.npieces, conf.spansize); for (int64_t p = 0; p < conf.np; p++) { int64_t c = pointcolors[p]; if (c != MULTICOLOR) { if (span_size[c] >= conf.spansize) { spans[c].resize(spans[c].size() + 1); span_size[c] = 0; } spans[c][spans[c].size() - 1].push_back(p); span_size[c]++; } else { c = pointmcolors[p][0]; if (mspan_size[c] >= conf.spansize) { mspans[c].resize(mspans[c].size() + 1); mspan_size[c] = 0; } mspans[c][mspans[c].size() - 1].push_back(p); mspan_size[c]++; } } // Color points by span. nspans_points = 0; pointspancolors_vec.assign(conf.np, -1ll); for (int64_t c = 0; c < conf.npieces; c++) { std::vector<std::vector<int64_t> > &color_spans = spans[c]; int64_t nspans = color_spans.size(); nspans_points = std::max(nspans_points, nspans); for (int64_t ispan = 0; ispan < nspans; ispan++) { std::vector<int64_t> &span = color_spans[ispan]; for (std::vector<int64_t>::iterator pt = span.begin(), pe = span.end(); pt != pe; ++pt) { int64_t p = *pt; pointspancolors_vec[p] = ispan; } } } for (int64_t c = 0; c < conf.npieces; c++) { std::vector<std::vector<int64_t> > &color_spans = mspans[c]; int64_t nspans = color_spans.size(); nspans_points = std::max(nspans_points, nspans); for (int64_t ispan = 0; ispan < nspans; ispan++) { std::vector<int64_t> &span = color_spans[ispan]; for (std::vector<int64_t>::iterator pt = span.begin(), pe = span.end(); pt != pe; ++pt) { int64_t p = *pt; pointspancolors_vec[p] = ispan; } } } for (int64_t p = 0; p < conf.np; p++) { assert(pointspancolors_vec[p] != -1ll); } } } void generate_mesh_raw( int64_t conf_np, int64_t conf_nz, int64_t conf_nzx, int64_t conf_nzy, double conf_lenx, double conf_leny, int64_t conf_numpcx, int64_t conf_numpcy, int64_t conf_npieces, int64_t conf_meshtype, bool conf_compact, int64_t conf_stripsize, int64_t conf_spansize, double *pointpos_x, size_t *pointpos_x_size, double *pointpos_y, size_t *pointpos_y_size, int64_t *pointcolors, size_t *pointcolors_size, uint64_t *pointmcolors, size_t *pointmcolors_size, int64_t *pointspancolors, size_t *pointspancolors_size, int64_t *zonestart, size_t *zonestart_size, int64_t *zonesize, size_t *zonesize_size, int64_t *zonepoints, size_t *zonepoints_size, int64_t *zonecolors, size_t *zonecolors_size, int64_t *zonespancolors, size_t *zonespancolors_size, int64_t *nspans_zones, int64_t *nspans_points) { config conf; conf.np = conf_np; conf.nz = conf_nz; conf.nzx = conf_nzx; conf.nzy = conf_nzy; conf.lenx = conf_lenx; conf.leny = conf_leny; conf.numpcx = conf_numpcx; conf.numpcy = conf_numpcy; conf.npieces = conf_npieces; conf.meshtype = conf_meshtype; conf.compact = conf_compact; conf.stripsize = conf_stripsize; conf.spansize = conf_spansize; std::vector<double> pointpos_x_vec; std::vector<double> pointpos_y_vec; std::vector<int64_t> pointcolors_vec; std::map<int64_t, std::vector<int64_t> > pointmcolors_map; std::vector<int64_t> zonestart_vec; std::vector<int64_t> zonesize_vec; std::vector<int64_t> zonepoints_vec; std::vector<int64_t> zonecolors_vec; generate_mesh(conf, pointpos_x_vec, pointpos_y_vec, pointcolors_vec, pointmcolors_map, zonestart_vec, zonesize_vec, zonepoints_vec, zonecolors_vec); if (conf.compact) { compact_mesh(conf, pointpos_x_vec, pointpos_y_vec, pointcolors_vec, pointmcolors_map, zonestart_vec, zonesize_vec, zonepoints_vec, zonecolors_vec); } std::vector<int64_t> zonespancolors_vec; std::vector<int64_t> pointspancolors_vec; color_spans(conf, pointpos_x_vec, pointpos_y_vec, pointcolors_vec, pointmcolors_map, zonestart_vec, zonesize_vec, zonepoints_vec, zonecolors_vec, zonespancolors_vec, pointspancolors_vec, *nspans_zones, *nspans_points); int64_t color_words = int64_t(ceil(conf_npieces/64.0)); assert(pointpos_x_vec.size() <= *pointpos_x_size); assert(pointpos_y_vec.size() <= *pointpos_y_size); assert(pointcolors_vec.size() <= *pointcolors_size); assert(pointcolors_vec.size()*color_words <= *pointmcolors_size); assert(pointspancolors_vec.size() <= *pointspancolors_size); assert(zonestart_vec.size() <= *zonestart_size); assert(zonesize_vec.size() <= *zonesize_size); assert(zonepoints_vec.size() <= *zonepoints_size); assert(zonecolors_vec.size() <= *zonecolors_size); assert(zonespancolors_vec.size() <= *zonespancolors_size); memcpy(pointpos_x, pointpos_x_vec.data(), pointpos_x_vec.size()*sizeof(double)); memcpy(pointpos_y, pointpos_y_vec.data(), pointpos_y_vec.size()*sizeof(double)); memcpy(pointcolors, pointcolors_vec.data(), pointcolors_vec.size()*sizeof(int64_t)); memcpy(pointspancolors, pointspancolors_vec.data(), pointspancolors_vec.size()*sizeof(int64_t)); memcpy(zonestart, zonestart_vec.data(), zonestart_vec.size()*sizeof(int64_t)); memcpy(zonesize, zonesize_vec.data(), zonesize_vec.size()*sizeof(int64_t)); memcpy(zonepoints, zonepoints_vec.data(), zonepoints_vec.size()*sizeof(int64_t)); memcpy(zonecolors, zonecolors_vec.data(), zonecolors_vec.size()*sizeof(int64_t)); memcpy(zonespancolors, zonespancolors_vec.data(), zonespancolors_vec.size()*sizeof(int64_t)); memset(pointmcolors, 0, (*pointmcolors_size)*sizeof(uint64_t)); for (std::map<int64_t, std::vector<int64_t> >::iterator it = pointmcolors_map.begin(), ie = pointmcolors_map.end(); it != ie; ++it) { int64_t p = it->first; for (std::vector<int64_t>::iterator ct = it->second.begin(), ce = it->second.end(); ct != ce; ++ct) { int64_t word = (*ct) / 64.0; int64_t bit = (*ct) % 64; pointmcolors[p + word] |= (1 << bit); } } *pointpos_x_size = pointpos_x_vec.size(); *pointpos_y_size = pointpos_y_vec.size(); *pointcolors_size = pointcolors_vec.size(); *pointmcolors_size = pointcolors_vec.size()*color_words; *pointspancolors_size = pointspancolors_vec.size(); *zonestart_size = zonestart_vec.size(); *zonesize_size = zonesize_vec.size(); *zonepoints_size = zonepoints_vec.size(); *zonecolors_size = zonecolors_vec.size(); *zonespancolors_size = zonespancolors_vec.size(); } /// /// Mapper /// #define SPMD_SHARD_USE_IO_PROC 0 static LegionRuntime::Logger::Category log_pennant("pennant"); class PennantMapper : public DefaultMapper { public: PennantMapper(MapperRuntime *rt, Machine machine, Processor local, const char *mapper_name, std::vector<Processor>* procs_list, std::vector<Memory>* sysmems_list, std::map<Memory, std::vector<Processor> >* sysmem_local_procs, #if SPMD_SHARD_USE_IO_PROC std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs, #endif std::map<Processor, Memory>* proc_sysmems, std::map<Processor, Memory>* proc_regmems); virtual void default_policy_rank_processor_kinds( MapperContext ctx, const Task &task, std::vector<Processor::Kind> &ranking); virtual Processor default_policy_select_initial_processor( MapperContext ctx, const Task &task); virtual void default_policy_select_target_processors( MapperContext ctx, const Task &task, std::vector<Processor> &target_procs); virtual LogicalRegion default_policy_select_instance_region( MapperContext ctx, Memory target_memory, const RegionRequirement &req, const LayoutConstraintSet &constraints, bool force_new_instances, bool meets_constraints); virtual void map_copy(const MapperContext ctx, const Copy &copy, const MapCopyInput &input, MapCopyOutput &output); virtual void map_must_epoch(const MapperContext ctx, const MapMustEpochInput& input, MapMustEpochOutput& output); template<bool IS_SRC> void pennant_create_copy_instance(MapperContext ctx, const Copy &copy, const RegionRequirement &req, unsigned index, std::vector<PhysicalInstance> &instances); private: std::vector<Processor>& procs_list; std::vector<Memory>& sysmems_list; std::map<Memory, std::vector<Processor> >& sysmem_local_procs; #if SPMD_SHARD_USE_IO_PROC std::map<Memory, std::vector<Processor> >& sysmem_local_io_procs; #endif std::map<Processor, Memory>& proc_sysmems; // std::map<Processor, Memory>& proc_regmems; }; PennantMapper::PennantMapper(MapperRuntime *rt, Machine machine, Processor local, const char *mapper_name, std::vector<Processor>* _procs_list, std::vector<Memory>* _sysmems_list, std::map<Memory, std::vector<Processor> >* _sysmem_local_procs, #if SPMD_SHARD_USE_IO_PROC std::map<Memory, std::vector<Processor> >* _sysmem_local_io_procs, #endif std::map<Processor, Memory>* _proc_sysmems, std::map<Processor, Memory>* _proc_regmems) : DefaultMapper(rt, machine, local, mapper_name), procs_list(*_procs_list), sysmems_list(*_sysmems_list), sysmem_local_procs(*_sysmem_local_procs), #if SPMD_SHARD_USE_IO_PROC sysmem_local_io_procs(*_sysmem_local_io_procs), #endif proc_sysmems(*_proc_sysmems)// , // proc_regmems(*_proc_regmems) { } void PennantMapper::default_policy_rank_processor_kinds(MapperContext ctx, const Task &task, std::vector<Processor::Kind> &ranking) { #if SPMD_SHARD_USE_IO_PROC const char* task_name = task.get_task_name(); const char* prefix = "shard_"; if (strncmp(task_name, prefix, strlen(prefix)) == 0) { // Put shard tasks on IO processors. ranking.resize(5); ranking[0] = Processor::TOC_PROC; ranking[1] = Processor::PROC_SET; ranking[2] = Processor::IO_PROC; ranking[3] = Processor::LOC_PROC; ranking[4] = Processor::PY_PROC; } else { #endif ranking.resize(5); ranking[0] = Processor::TOC_PROC; ranking[1] = Processor::PROC_SET; ranking[2] = Processor::LOC_PROC; ranking[3] = Processor::IO_PROC; ranking[4] = Processor::PY_PROC; #if SPMD_SHARD_USE_IO_PROC } #endif } Processor PennantMapper::default_policy_select_initial_processor( MapperContext ctx, const Task &task) { if (!task.regions.empty()) { if (task.regions[0].handle_type == SINGULAR) { Color index = runtime->get_logical_region_color(ctx, task.regions[0].region); #define NO_SPMD 0 #if NO_SPMD return procs_list[index % procs_list.size()]; #else std::vector<Processor> &local_procs = sysmem_local_procs[proc_sysmems[local_proc]]; if (local_procs.size() > 1) { #define SPMD_RESERVE_SHARD_PROC 0 #if SPMD_RESERVE_SHARD_PROC return local_procs[(index % (local_procs.size() - 1)) + 1]; #else return local_procs[index % local_procs.size()]; #endif } else if (local_procs.size() > 0) { // FIXME: This check seems to be required when using Python processors return local_procs[0]; } #endif } } return DefaultMapper::default_policy_select_initial_processor(ctx, task); } void PennantMapper::default_policy_select_target_processors( MapperContext ctx, const Task &task, std::vector<Processor> &target_procs) { target_procs.push_back(task.target_proc); } LogicalRegion PennantMapper::default_policy_select_instance_region( MapperContext ctx, Memory target_memory, const RegionRequirement &req, const LayoutConstraintSet &layout_constraints, bool force_new_instances, bool meets_constraints) { return req.region; } //-------------------------------------------------------------------------- template<bool IS_SRC> void PennantMapper::pennant_create_copy_instance(MapperContext ctx, const Copy &copy, const RegionRequirement &req, unsigned idx, std::vector<PhysicalInstance> &instances) //-------------------------------------------------------------------------- { // This method is identical to the default version except that it // chooses an intelligent memory based on the destination of the // copy. // See if we have all the fields covered std::set<FieldID> missing_fields = req.privilege_fields; for (std::vector<PhysicalInstance>::const_iterator it = instances.begin(); it != instances.end(); it++) { it->remove_space_fields(missing_fields); if (missing_fields.empty()) break; } if (missing_fields.empty()) return; // If we still have fields, we need to make an instance // We clearly need to take a guess, let's see if we can find // one of our instances to use. // ELLIOTT: Get the remote node here. Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region); // #if SPMD_RESERVE_SHARD_PROC // size_t sysmem_index = index / (std::max(sysmem_local_procs.begin()->second.size() - 1, (size_t)1)); // #else // size_t sysmem_index = index / sysmem_local_procs.begin()->second.size(); // #endif // assert(sysmem_index < sysmems_list.size()); // Memory target_memory = sysmems_list[sysmem_index]; Memory target_memory = default_policy_select_target_memory(ctx, procs_list[index % procs_list.size()], req); log_pennant.spew("Building instance for copy of a region with index %u to be in memory %llx", index, target_memory.id); bool force_new_instances = false; LayoutConstraintID our_layout_id = default_policy_select_layout_constraints(ctx, target_memory, req, COPY_MAPPING, true/*needs check*/, force_new_instances); LayoutConstraintSet creation_constraints = runtime->find_layout_constraints(ctx, our_layout_id); creation_constraints.add_constraint( FieldConstraint(missing_fields, false/*contig*/, false/*inorder*/)); instances.resize(instances.size() + 1); if (!default_make_instance(ctx, target_memory, creation_constraints, instances.back(), COPY_MAPPING, force_new_instances, true/*meets*/, req)) { // If we failed to make it that is bad log_pennant.error("Pennant mapper failed allocation for " "%s region requirement %d of explicit " "region-to-region copy operation in task %s " "(ID %lld) in memory " IDFMT " for processor " IDFMT ". This means the working set of your " "application is too big for the allotted " "capacity of the given memory under the default " "mapper's mapping scheme. You have three " "choices: ask Realm to allocate more memory, " "write a custom mapper to better manage working " "sets, or find a bigger machine. Good luck!", IS_SRC ? "source" : "destination", idx, copy.parent_task->get_task_name(), copy.parent_task->get_unique_id(), target_memory.id, copy.parent_task->current_proc.id); assert(false); } } void PennantMapper::map_copy(const MapperContext ctx, const Copy &copy, const MapCopyInput &input, MapCopyOutput &output) { log_pennant.spew("Pennant mapper map_copy"); for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++) { // Use a virtual instance for the source unless source is // restricted or we'd applying a reduction. output.src_instances[idx].clear(); if (copy.src_requirements[idx].is_restricted()) { // If it's restricted, just take the instance. This will only // happen inside the shard task. output.src_instances[idx] = input.src_instances[idx]; if (!output.src_instances[idx].empty()) runtime->acquire_and_filter_instances(ctx, output.src_instances[idx]); } else if (copy.dst_requirements[idx].privilege == REDUCE) { // Use the default here. This will place the instance on the // current node. default_create_copy_instance<true/*is src*/>(ctx, copy, copy.src_requirements[idx], idx, output.src_instances[idx]); } else { output.src_instances[idx].push_back( PhysicalInstance::get_virtual_instance()); } // Place the destination instance on the remote node. output.dst_instances[idx].clear(); if (!copy.dst_requirements[idx].is_restricted()) { // Call a customized method to create an instance on the desired node. pennant_create_copy_instance<false/*is src*/>(ctx, copy, copy.dst_requirements[idx], idx, output.dst_instances[idx]); } else { // If it's restricted, just take the instance. This will only // happen inside the shard task. output.dst_instances[idx] = input.dst_instances[idx]; if (!output.dst_instances[idx].empty()) runtime->acquire_and_filter_instances(ctx, output.dst_instances[idx]); } } } void PennantMapper::map_must_epoch(const MapperContext ctx, const MapMustEpochInput& input, MapMustEpochOutput& output) { size_t num_nodes = sysmems_list.size(); size_t num_tasks = input.tasks.size(); size_t num_shards_per_node = num_nodes < input.tasks.size() ? (num_tasks + num_nodes - 1) / num_nodes : 1; std::map<const Task*, size_t> task_indices; for (size_t idx = 0; idx < num_tasks; ++idx) { size_t node_idx = idx / num_shards_per_node; size_t proc_idx = idx % num_shards_per_node; assert(node_idx < sysmems_list.size()); #if SPMD_SHARD_USE_IO_PROC assert(proc_idx < sysmem_local_io_procs[sysmems_list[node_idx]].size()); output.task_processors[idx] = sysmem_local_io_procs[sysmems_list[node_idx]][proc_idx]; #else assert(proc_idx < sysmem_local_procs[sysmems_list[node_idx]].size()); output.task_processors[idx] = sysmem_local_procs[sysmems_list[node_idx]][proc_idx]; #endif task_indices[input.tasks[idx]] = node_idx; } for (size_t idx = 0; idx < input.constraints.size(); ++idx) { const MappingConstraint& constraint = input.constraints[idx]; int owner_id = -1; for (unsigned i = 0; i < constraint.constrained_tasks.size(); ++i) { const RegionRequirement& req = constraint.constrained_tasks[i]->regions[ constraint.requirement_indexes[i]]; if (req.is_no_access()) continue; assert(owner_id == -1); owner_id = static_cast<int>(i); } assert(owner_id != -1); const Task* task = constraint.constrained_tasks[owner_id]; const RegionRequirement& req = task->regions[constraint.requirement_indexes[owner_id]]; Memory target_memory = sysmems_list[task_indices[task]]; LayoutConstraintSet layout_constraints; default_policy_select_constraints(ctx, layout_constraints, target_memory, req); layout_constraints.add_constraint( FieldConstraint(req.privilege_fields, false /*!contiguous*/)); PhysicalInstance inst; bool created; bool ok = runtime->find_or_create_physical_instance(ctx, target_memory, layout_constraints, std::vector<LogicalRegion>(1, req.region), inst, created, true /*acquire*/); assert(ok); output.constraint_mappings[idx].push_back(inst); } } static void create_mappers(Machine machine, Runtime *runtime, const std::set<Processor> &local_procs) { std::vector<Processor>* procs_list = new std::vector<Processor>(); std::vector<Memory>* sysmems_list = new std::vector<Memory>(); std::map<Memory, std::vector<Processor> >* sysmem_local_procs = new std::map<Memory, std::vector<Processor> >(); #if SPMD_SHARD_USE_IO_PROC std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs = new std::map<Memory, std::vector<Processor> >(); #endif std::map<Processor, Memory>* proc_sysmems = new std::map<Processor, Memory>(); std::map<Processor, Memory>* proc_regmems = new std::map<Processor, Memory>(); std::vector<Machine::ProcessorMemoryAffinity> proc_mem_affinities; machine.get_proc_mem_affinity(proc_mem_affinities); for (unsigned idx = 0; idx < proc_mem_affinities.size(); ++idx) { Machine::ProcessorMemoryAffinity& affinity = proc_mem_affinities[idx]; if (affinity.p.kind() == Processor::LOC_PROC || affinity.p.kind() == Processor::IO_PROC) { if (affinity.m.kind() == Memory::SYSTEM_MEM) { (*proc_sysmems)[affinity.p] = affinity.m; if (proc_regmems->find(affinity.p) == proc_regmems->end()) (*proc_regmems)[affinity.p] = affinity.m; } else if (affinity.m.kind() == Memory::REGDMA_MEM) (*proc_regmems)[affinity.p] = affinity.m; } } for (std::map<Processor, Memory>::iterator it = proc_sysmems->begin(); it != proc_sysmems->end(); ++it) { if (it->first.kind() == Processor::LOC_PROC) { procs_list->push_back(it->first); (*sysmem_local_procs)[it->second].push_back(it->first); } #if SPMD_SHARD_USE_IO_PROC else if (it->first.kind() == Processor::IO_PROC) { (*sysmem_local_io_procs)[it->second].push_back(it->first); } #endif } for (std::map<Memory, std::vector<Processor> >::iterator it = sysmem_local_procs->begin(); it != sysmem_local_procs->end(); ++it) sysmems_list->push_back(it->first); for (std::set<Processor>::const_iterator it = local_procs.begin(); it != local_procs.end(); it++) { PennantMapper* mapper = new PennantMapper(runtime->get_mapper_runtime(), machine, *it, "pennant_mapper", procs_list, sysmems_list, sysmem_local_procs, #if SPMD_SHARD_USE_IO_PROC sysmem_local_io_procs, #endif proc_sysmems, proc_regmems); runtime->replace_default_mapper(mapper, *it); } } void register_mappers() { Runtime::add_registration_callback(create_mappers); }
50,218
18,293
#include <graphics.h> int main () { initwindow(600,500,"TUTORIAL"); setbkcolor(BLACK); cleardevice(); readimagefile("nyoba.jpg",100,100,300,300); getch(); closegraph(); }
198
99
// Copyright David Abrahams, Daniel Wallin 2003. Use, modification and // distribution is subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/parameter.hpp> #include <boost/parameter/macros.hpp> #include <boost/bind.hpp> #include <boost/static_assert.hpp> #include <boost/ref.hpp> #include <cassert> #include <string.h> #include "basics.hpp" namespace test { BOOST_PARAMETER_FUN(int, f, 2, 4, f_parameters) { p[tester]( p[name] , p[value || boost::bind(&value_default) ] #if BOOST_WORKAROUND(__DECCXX_VER, BOOST_TESTED_AT(60590042)) , p[test::index | 999 ] #else , p[index | 999 ] #endif ); return 1; } } // namespace test int main() { using test::f; using test::name; using test::value; using test::index; using test::tester; f( test::values(S("foo"), S("bar"), S("baz")) , S("foo"), S("bar"), S("baz") ); int x = 56; f( test::values("foo", 666.222, 56) , index = boost::ref(x), name = "foo" ); return boost::report_errors(); }
1,233
497
#pragma once #include "./PKIXCertPathChecker.hpp" class JObject; namespace java::net { class URI; } namespace java::security::cert { class X509Certificate; } namespace java::security::cert { class PKIXRevocationChecker : public java::security::cert::PKIXCertPathChecker { public: // Fields // QJniObject forward template<typename ...Ts> explicit PKIXRevocationChecker(const char *className, const char *sig, Ts...agv) : java::security::cert::PKIXCertPathChecker(className, sig, std::forward<Ts>(agv)...) {} PKIXRevocationChecker(QJniObject obj); // Constructors // Methods java::security::cert::PKIXRevocationChecker clone() const; JObject getOcspExtensions() const; java::net::URI getOcspResponder() const; java::security::cert::X509Certificate getOcspResponderCert() const; JObject getOcspResponses() const; JObject getOptions() const; JObject getSoftFailExceptions() const; void setOcspExtensions(JObject arg0) const; void setOcspResponder(java::net::URI arg0) const; void setOcspResponderCert(java::security::cert::X509Certificate arg0) const; void setOcspResponses(JObject arg0) const; void setOptions(JObject arg0) const; }; } // namespace java::security::cert
1,222
450
#include <stdio.h> #include <math.h> #include <time.h> #ifdef WIN32 #include <windows.h> #include <iostream.h> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <math.h> #include <fstream.h> void SetRandomSeed() { LARGE_INTEGER la; QueryPerformanceCounter( &la ); srand( (unsigned int)la.QuadPart ); } void ShowMessage(char* mess, char* title) { // SDL_WM_SetCaption(mess, 0); // MessageBox(0, mess, title, MB_OK); } double LC_GetCurrentTime() { double val = clock(); return (val / 1000.0); } #define UseMessageBoxForIntro false #else #define UseMessageBoxForIntro false // put the Mac Carbon headers here #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> void SetRandomSeed() { srand( clock() ); } void ConvertCToPascalString(char* from, unsigned char* to) { int i=0; for(i=0; from[i]; i++) { to[i+1] = from[i]; } to[0] = i; } void ShowMessage(char* mess, char* title) { unsigned char buff1[200], buff2[200]; ConvertCToPascalString( ((char*)mess), buff1); ConvertCToPascalString( ((char*)title), buff2); short res; StandardAlert(kAlertNoteAlert, buff2, buff1, 0, &res); } /* void ShowMessage(char* mess, char* title) { printf("\n%s\n", title); for (int i=0; title[i]; i++) printf("-"); printf("\n%s\n\n", mess); } */ double LC_GetCurrentTime() { double val = clock(); return (val / 100.0); } #endif
1,591
674
#ifndef __VSIM_RIGID_BODY_HPP__ #define __VSIM_RIGID_BODY_HPP__ #include <string> #include <vector> #include <memory> #include <Eigen/Core> #include <vsim/env/scene_fwd.hpp> #include <vsim/env/pose.hpp> #include <vsim/env/base_element.hpp> namespace vsim { class RigidBody ; typedef std::shared_ptr<RigidBody> BodyPtr ; // class defining a rigid body class RigidBody: public BaseElement { public: RigidBody() = default ; public: std::vector<CollisionShapePtr> shapes_ ; Pose pose_ ; float mass_ ; Eigen::Vector3f velocity_, angular_velocity_ ; NodePtr visual_ ; }; } #endif
612
246
#define BOOST_TEST_MODULE WeightsTest #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include "sparse_vector.h" using namespace std; BOOST_AUTO_TEST_CASE(Dot) { SparseVector<double> x; SparseVector<double> y; x.set_value(1,0.8); y.set_value(1,5); x.set_value(2,-2); y.set_value(2,1); x.set_value(3,80); BOOST_CHECK_CLOSE(x.dot(y), 2.0, 1e-9); } BOOST_AUTO_TEST_CASE(Equality) { SparseVector<double> x; SparseVector<double> y; x.set_value(1,-1); y.set_value(1,-1); BOOST_CHECK(x == y); } BOOST_AUTO_TEST_CASE(Division) { SparseVector<double> x; SparseVector<double> y; x.set_value(1,1); y.set_value(1,-1); BOOST_CHECK(!(x == y)); x /= -1; BOOST_CHECK(x == y); }
746
364
#include "GameLoader.h" using namespace std; Game* GameLoader::Load(wstring& filePath, int& sizeX, int& sizeY) { Game* game = new Game(); ifstream file(filePath); if (!file.good()) return nullptr; file >> sizeX; file >> sizeY; for (int x = 0; x < sizeX; x++) { game->tiles.push_back(new Tile(x, -1, Tile::Wall, true)); game->tiles.push_back(new Tile(x, sizeY, Tile::Wall, true)); } for (int y = 0; y < sizeY; y++) { game->tiles.push_back(new Tile(-1, y, Tile::Wall, true)); game->tiles.push_back(new Tile(sizeX, y, Tile::Wall, true)); } string line; getline(file, line); for (int y = 0; getline(file, line); y++) { for (int x = 0; x < sizeX;x++) { switch (line[x]) { case 'w': game->tiles.push_back(new Tile(x, y, Tile::Wall, true)); break; case 't': game->tiles.push_back(new Tile(x, y, Tile::Target, false)); break; case 'c': game->tiles.push_back(new Tile(x, y, Tile::Crate, true)); break; case 'p': Tile* player = new Tile(x, y, Tile::Player, true); game->tiles.push_back(player); game->player = player; break; } } } file.close(); return game; }
1,152
555
// Author(s): Bas Ploeger, Carst Tankink, Ruud Koolen // Copyright: see the accompanying file COPYING or copy at // https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING // // 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 "savepicturedialog.h" #include <QImage> #include <QImageWriter> SavePictureDialog::SavePictureDialog(QWidget *parent, LtsCanvas *canvas, QString filename): QDialog(parent), m_canvas(canvas), m_filename(filename), m_inChange(false) { m_ui.setupUi(this); m_width = canvas->viewWidth(); m_height = canvas->viewHeight(); m_ui.width->setValue(m_width); m_ui.height->setValue(m_height); connect(m_ui.width, SIGNAL(valueChanged(int)), this, SLOT(widthChanged(int))); connect(m_ui.height, SIGNAL(valueChanged(int)), this, SLOT(heightChanged(int))); connect(m_ui.buttonBox, SIGNAL(accepted()), this, SLOT(save())); connect(m_ui.buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } void SavePictureDialog::widthChanged(int value) { if (m_inChange) { return; } if (m_ui.maintainAspectRatio->isChecked()) { m_inChange = true; m_ui.height->setValue((int)(value * m_height / m_width)); m_inChange = false; } } void SavePictureDialog::heightChanged(int value) { if (m_inChange) { return; } if (m_ui.maintainAspectRatio->isChecked()) { m_inChange = true; m_ui.height->setValue((int)(value * m_width / m_height)); m_inChange = false; } } void SavePictureDialog::save() { int width = m_ui.width->value(); int height = m_ui.height->value(); QImage image = m_canvas->renderImage(width, height); emit statusMessage("Saving image..."); QImageWriter writer(m_filename); if (writer.write(image)) { emit statusMessage("Done"); } else { emit statusMessage("Saving image failed."); } accept(); }
1,938
730
// HACKERRANK - Halloween Party // https://www.hackerrank.com/challenges/halloween-party #include <iostream> using namespace std; int main (int argc, char *argv[]) { int N; cin >> N; while (N--) { long long input; long long x, y; cin >> input; x = input / 2; y = input - x; cout << x * y << endl; } return 0; }
337
150
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_MULTI_MOVE_COST_HPP_ #define OPTFRAME_MULTI_MOVE_COST_HPP_ #include <cstdlib> #include <iostream> #include <cmath> #include "Component.hpp" #include "BaseConcepts.hpp" #include "Evaluation.hpp" #include "MoveCost.hpp" using namespace std; namespace optframe { //// more than 'objval' we need to ensure arithmetics here... TODO: see that (same as Evaluation) template<optframe::objval ObjType = evtype, XEvaluation XEv = Evaluation<ObjType>> //template<class ObjType = evtype, XEvaluation XEv = Evaluation<ObjType>> class MultiMoveCost: public Component { protected: vector<MoveCost<ObjType, XEv>*> vmc; public: explicit MultiMoveCost(vector<MoveCost<>*> _vmc) : vmc(_vmc) { } MultiMoveCost(const MultiMoveCost<>& mc) : vmc(mc.vmc) { } virtual ~MultiMoveCost() { } int size() const { return vmc.size(); } bool hasCost(int k) const { return vmc[k]; } bool isEstimated(int k) const { return vmc[k]->estimated; } const vector<pair<ObjType, ObjType> >& getAlternativeCosts(int k) const { return vmc[k]->alternatives; } ObjType getObjFunctionCost(int k) const { return vmc[k]->objFunction; } ObjType getInfMeasureCost(int k) const { return vmc[k]->infMeasure; } void addAlternativeCost(const pair<ObjType, ObjType>& alternativeCost, int k) { vmc[k]->alternatives.push_back(alternativeCost); } void setAlternativeCosts(const vector<pair<ObjType, ObjType> >& alternativeCosts, int k) { vmc[k]->alternatives = alternativeCosts; } void setObjFunctionCost(ObjType obj, int k) { vmc[k]->objFunction = obj; } void setInfMeasureCost(ObjType inf, int k) { vmc[k]->infMeasure = inf; } ObjType cost(int k) const { return vmc[k]->cost(); } static string idComponent() { return "OptFrame:MultiMoveCost"; } virtual string id() const { return idComponent(); } virtual void print() const { cout << fixed; // disable scientific notation cout << "MultiMoveCost for " << size() << " objectives:" << endl; for(unsigned i=0; i<vmc.size(); i++) if(vmc[i]) vmc[i]->print(); else cout << "NO COST" << endl; } virtual MultiMoveCost<>& operator=(const MultiMoveCost<>& mmc) { if (&mmc == this) // auto ref check return *this; vmc = mmc.vmc; // TODO fix: this should handle some local instances, for the future... return *this; } virtual MultiMoveCost<>& clone() const { return *new MultiMoveCost<>(*this); } }; #ifndef NDEBUG struct optframe_debug_test_multimove_cost { MultiMoveCost<> testMoveCost; }; #endif } // namespace optframe #endif /*OPTFRAME_MULTI_MOVE_COST_HPP_*/
3,473
1,327
/* Copyright © 2019 Haoran Luo * * 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. */ /** * @file wprofile.hpp * @author Haoran Luo * @brief wdedup Profile header. * * This file describes the profile structures. Profiles are stored in a * (logically) sorted-by-word, FIFO and immutable file. * * According to previous studying of sorted table implementation, multiple * variance of physical implementation is observed, and which one excels * has not been verified. So the profiler file is designed as a virtual * interface, and provided as wdedup::Config item. */ #pragma once #include "wtypes.hpp" #include <string> namespace wdedup { /** * @brief Defines the profile item in profile input and output. * * Various implementation must customize their interfaces to return such * kind of items. */ struct ProfileItem { /// Current recorded word. std::string word; /// Whether this word has been repeated. bool repeated; /// The first occurence of the word. /// If repeated is true, this field should be ignored by the /// scanning algorithms. fileoff_t occur; /// Construct a repeated item. ProfileItem(std::string word) noexcept: word(std::move(word)), repeated(true), occur(0) {} /// Construct a single occurence item. ProfileItem(std::string word, fileoff_t occur) noexcept: word(std::move(word)), repeated(false), occur(occur) {} /// Move constructor of a profile item. ProfileItem(ProfileItem&& item) noexcept: word(std::move(item.word)), repeated(item.repeated), occur(item.occur) {} }; /// @brief Defines the virtual read interface of profile. struct ProfileInput { /// Virtual destructor for pure virtual classes. virtual ~ProfileInput() noexcept {}; /// Test whether there's content in the file. virtual bool empty() const noexcept = 0; /// Peeking the head profileItem from the input table. /// If there's no more content in the table, the content /// returned by the table will be undefined. virtual const ProfileItem& peek() const noexcept = 0; /// Pop the head profileItem from the input table. /// If there's no more content in the table, popping /// from the table will cause exception to be thrown. virtual ProfileItem pop() throw (wdedup::Error) = 0; }; /// @brief Defines the virtual write interface of profile. struct ProfileOutput { /// Virtual destructor for pure virtual classes. virtual ~ProfileOutput() noexcept {}; /// Push content to the profile output. /// Exception will be thrown if there's I/O error on the /// underlying (append-only) files. virtual void push(ProfileItem) throw (wdedup::Error) = 0; /// Indicates that this is the end of profile output. /// The size of the generated file will be collected and /// return to the caller. virtual size_t close() throw (wdedup::Error) = 0; }; } // namespace wdedup
3,871
1,175
#ifndef IRODS_RS_SET_DELAY_SERVER_MIGRATION_INFO_HPP #define IRODS_RS_SET_DELAY_SERVER_MIGRATION_INFO_HPP /// \file #include "irods/plugins/api/delay_server_migration_types.h" struct RsComm; #ifdef __cplusplus extern "C" { #endif /// Atomically sets the leader and successor hostnames for delay server migration in the /// R_GRID_CONFIGURATION table. /// /// The invoking user of this API must be a \p rodsadmin. /// /// This API will verify the following before updating the catalog: /// - Verify that input arguments are not null /// - Verify that hostname requirements imposed by the OS have not been violated /// - Verify that hostnames are not identical /// - Verify that hostnames refer to iRODS servers in the local zone /// /// \param[in] _comm A pointer to a RsComm. /// \param[in] _input \parblock An object holding the new hostname values for the leader and successor. /// /// Although the API allows updating the leader and successor simultaneously, users aren't required to /// do so. Users can choose to skip updating either field. This is achieved by setting the respective /// member variable to the value of \p KW_DELAY_SERVER_MIGRATION_IGNORE. For example: /// \code{.c} /// DelayServerMigrationInput input; /// memset(&input, 0, sizeof(DelayServerMigrationInput)); /// strcpy(input.leader, KW_DELAY_SERVER_MIGRATION_IGNORE); /// \endcode /// \endparblock /// /// \return An integer. /// \retval 0 On success. /// \retval Non-zero On failure. /// /// \since 4.3.0 int rs_set_delay_server_migration_info(RsComm* _comm, const DelayServerMigrationInput* _input); #ifdef __cplusplus } // extern "C" #endif #endif // IRODS_RS_SET_DELAY_SERVER_MIGRATION_INFO_HPP
1,691
546
#include <ghex/transport_layer/callback_communicator.hpp> #include <ghex/transport_layer/mpi/communicator.hpp> #include <iostream> #include <iomanip> #include <gtest/gtest.h> template<typename Comm, typename Alloc> using callback_comm_t = gridtools::ghex::tl::callback_communicator<Comm,Alloc>; //using callback_comm_t = gridtools::ghex::tl::callback_communicator_ts<Comm,Alloc>; const int SIZE = 4000000; int mpi_rank; //#define GHEX_TEST_COUNT_ITERATIONS TEST(transport, send_multi) { { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); EXPECT_EQ(size, 4); } MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); MPI_Barrier(MPI_COMM_WORLD); using comm_type = gridtools::ghex::tl::communicator<gridtools::ghex::tl::mpi_tag>; comm_type comm; using allocator_type = std::allocator<unsigned char>; using smsg_type = gridtools::ghex::tl::shared_message_buffer<allocator_type>; callback_comm_t<comm_type,allocator_type> cb_comm(comm); if (mpi_rank == 0) { smsg_type smsg{SIZE}; int * data = smsg.data<int>(); for (int i = 0; i < SIZE/(int)sizeof(int); ++i) { data[i] = i; } std::array<int, 3> dsts = {1,2,3}; cb_comm.send_multi(smsg, dsts, 42); #ifdef GHEX_TEST_COUNT_ITERATIONS int c = 0; #endif while (cb_comm.progress()) { #ifdef GHEX_TEST_COUNT_ITERATIONS c++; #endif } EXPECT_EQ(smsg.use_count(), 1); #ifdef GHEX_TEST_COUNT_ITERATIONS std::cout << "\n***********\n"; std::cout << "*" << std::setw(8) << c << " *\n"; std::cout << "***********\n"; #endif } else { gridtools::ghex::tl::message_buffer<> rmsg{SIZE}; auto fut = comm.recv(rmsg, 0, 42); fut.wait(); bool ok = true; for (int i = 0; i < (int)rmsg.size()/(int)sizeof(int); ++i) { int * data = rmsg.data<int>(); if ( data[i] != i ) ok = false; } EXPECT_TRUE(ok); } EXPECT_FALSE(cb_comm.progress()); }
2,050
815
/* Copyright (C) 2015 Preet Desai (preet.desai@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef RAINTK_ROW_HPP #define RAINTK_ROW_HPP #include <map> #include <list> #include <raintk/RainTkWidget.hpp> namespace raintk { class Row : public Widget { public: using base_type = raintk::Widget; enum class LayoutDirection { LeftToRight, RightToLeft }; Row(ks::Object::Key const &key, Scene* scene, shared_ptr<Widget> parent); void Init(ks::Object::Key const &, shared_ptr<Row> const &); ~Row(); void AddChild(shared_ptr<Widget> const &child) override; void RemoveChild(shared_ptr<Widget> const &child) override; // Properties Property<float> spacing{ 0.0f }; Property<float> children_width{ 0.0f }; Property<float> children_height{ 0.0f }; Property<LayoutDirection> layout_direction{ LayoutDirection::LeftToRight }; protected: void onSpacingChanged(); void onLayoutDirectionChanged(); void onChildDimsChanged(); Id m_cid_spacing; Id m_cid_layout_direction; private: void update() override; struct Item { Widget* widget; Id cid_width; Id cid_height; }; // TODO replace list if performance is an issue std::list<Item> m_list_items; std::map<Id,std::list<Item>::iterator> m_lkup_id_item_it; }; } #endif // RAINTK_ROW_HPP
2,172
648
/* * PopulationPerPlanningArea.cpp * * Created on: 13 Aug, 2015 * Author: Chetan Rogbeer <chetan.rogbeer@smart.mit.edu> */ #include "database/entity/PopulationPerPlanningArea.hpp" #include <boost/serialization/vector.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> using namespace sim_mob::long_term; PopulationPerPlanningArea::PopulationPerPlanningArea(int planningAreaId, int population, int ethnicityId, int ageCategoryId, double avgIncome, int avgHhSize, int unitType, int floorArea): planningAreaId(planningAreaId), population(population), ethnicityId(ethnicityId), ageCategoryId(ageCategoryId), avgIncome(avgIncome), avgHhSize(avgHhSize), unitType(unitType), floorArea(floorArea){} PopulationPerPlanningArea::~PopulationPerPlanningArea() {} PopulationPerPlanningArea::PopulationPerPlanningArea( const PopulationPerPlanningArea &source) { planningAreaId = source.planningAreaId; population = source.population; ethnicityId = source.ethnicityId; ageCategoryId = source.ageCategoryId; avgIncome = source.avgIncome; avgHhSize = source.avgHhSize; unitType = source.unitType; floorArea = source.floorArea; } PopulationPerPlanningArea& PopulationPerPlanningArea::operator=( const PopulationPerPlanningArea& source) { planningAreaId = source.planningAreaId; population = source.population; ethnicityId = source.ethnicityId; ageCategoryId = source.ageCategoryId; avgIncome = source.avgIncome; avgHhSize = source.avgHhSize; unitType = source.unitType; floorArea = source.floorArea; return *this; } template<class Archive> void PopulationPerPlanningArea::serialize(Archive & ar,const unsigned int version) { ar & planningAreaId; ar & population; ar & ethnicityId ; ar & ethnicityId; ar & ageCategoryId; ar & avgIncome; ar & avgIncome; ar & avgHhSize; ar & unitType; ar & floorArea; } void PopulationPerPlanningArea::saveData(std::vector<PopulationPerPlanningArea*> &s) { // make an archive std::ofstream ofs(filename); boost::archive::binary_oarchive oa(ofs); oa & s; } std::vector<PopulationPerPlanningArea*> PopulationPerPlanningArea::loadSerializedData() { std::vector<PopulationPerPlanningArea*> populationPerPA; // Restore from saved data and print to verify contents std::vector<PopulationPerPlanningArea*> restored_info; { // Create and input archive std::ifstream ifs( "populationPerPlanningArea" ); boost::archive::binary_iarchive ar( ifs ); // Load the data ar & restored_info; } for (auto *itr :restored_info) { PopulationPerPlanningArea *popPerPA = itr; populationPerPA.push_back(popPerPA); } return populationPerPA; } int PopulationPerPlanningArea::getPlanningAreaId() const { return planningAreaId; } int PopulationPerPlanningArea::getPopulation() const { return population; } double PopulationPerPlanningArea::getFloorArea() const { return floorArea; } int PopulationPerPlanningArea::getEthnicityId() const { return ethnicityId; } int PopulationPerPlanningArea::getAgeCategoryId() const { return ageCategoryId; } double PopulationPerPlanningArea::getAvgIncome() const { return avgIncome; } int PopulationPerPlanningArea::getAvgHhSize() const { return avgHhSize; } int PopulationPerPlanningArea::getUnitType() const { return unitType; }
3,662
1,170
// Copyright 2016 the V8 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. #include <memory> #include <string> #include "src/unicode-decoder.h" #include "testing/gtest/include/gtest/gtest.h" namespace v8 { namespace internal { namespace { using Utf8Decoder = unibrow::Utf8Decoder<512>; void Decode(Utf8Decoder* decoder, const std::string& str) { // Put the string in its own buffer on the heap to make sure that // AddressSanitizer's heap-buffer-overflow logic can see what's going on. std::unique_ptr<char[]> buffer(new char[str.length()]); memcpy(buffer.get(), str.data(), str.length()); decoder->Reset(buffer.get(), str.length()); } } // namespace TEST(UnicodeTest, ReadOffEndOfUtf8String) { Utf8Decoder decoder; // Not enough continuation bytes before string ends. Decode(&decoder, "\xE0"); Decode(&decoder, "\xED"); Decode(&decoder, "\xF0"); Decode(&decoder, "\xF4"); } } // namespace internal } // namespace v8
1,044
367
///\file /****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++/UnitTest++.h" #include "etl/cyclic_value.h" namespace { SUITE(test_cyclic_value) { //************************************************************************* TEST(test_compile_time_initialisation) { etl::cyclic_value<int, 2, 7> value; CHECK_EQUAL(2, value); CHECK_EQUAL(2, value.first()); CHECK_EQUAL(7, value.last()); } //************************************************************************* TEST(test_run_time_initialisation) { etl::cyclic_value<int> value(2, 7); CHECK_EQUAL(2, value); CHECK_EQUAL(2, value.first()); CHECK_EQUAL(7, value.last()); } //************************************************************************* TEST(test_copy_constructor_compile_time) { etl::cyclic_value<int, 2, 7> value; etl::cyclic_value<int, 2, 7> value2(value); CHECK(value == value2); } //************************************************************************* TEST(test_copy_constructor_run_time) { etl::cyclic_value<int> value(2, 7); etl::cyclic_value<int> value2(value); CHECK(value == value2); } //************************************************************************* TEST(test_set_compile_time) { etl::cyclic_value<int, 2, 7> value; value.set(5); CHECK_EQUAL(5, value.get()); value.set(1); CHECK_EQUAL(value.first(), value.get()); value.set(8); CHECK_EQUAL(value.last(), value.get()); } //************************************************************************* TEST(test_set_run_time) { etl::cyclic_value<int> value; value.set(2, 7); CHECK_EQUAL(2, value.get()); CHECK_EQUAL(2, value.first()); CHECK_EQUAL(7, value.last()); value.set(5); CHECK_EQUAL(5, value.get()); value.set(1); CHECK_EQUAL(value.first(), value.get()); value.set(8); CHECK_EQUAL(value.last(), value.get()); } //************************************************************************* TEST(test_to_first_compile_time) { etl::cyclic_value<int, 2, 7> value; ++value; value.to_first(); CHECK_EQUAL(value.first(), value); } //************************************************************************* TEST(test_to_first_run_time) { etl::cyclic_value<int> value; value.set(2, 7); ++value; value.to_first(); CHECK_EQUAL(value.first(), value); } //************************************************************************* TEST(test_to_last_compile_time) { etl::cyclic_value<int, 2, 7> value; value.to_last(); CHECK_EQUAL(value.last(), value); } //************************************************************************* TEST(test_to_last_run_time) { etl::cyclic_value<int> value; value.set(2, 7); value.to_last(); CHECK_EQUAL(value.last(), value); } //************************************************************************* TEST(test_increment_compile_time) { etl::cyclic_value<int, 2, 7> value; for (int i = value.first(); i <= value.last(); ++i) { CHECK_EQUAL(i, value); ++value; } } //************************************************************************* TEST(test_increment_run_time) { etl::cyclic_value<int> value; value.set(2, 7); for (int i = value.first(); i <= value.last(); ++i) { CHECK_EQUAL(i, value); ++value; } } //************************************************************************* TEST(test_decrement_compile_time) { etl::cyclic_value<int, 2, 7> value; value.to_last(); for (int i = value.last(); i >= value.first(); --i) { CHECK_EQUAL(i, value); --value; } } //************************************************************************* TEST(test_decrement_run_time) { etl::cyclic_value<int> value; value.set(2, 7); value.to_last(); for (int i = value.last(); i >= value.first(); --i) { CHECK_EQUAL(i, value); --value; } } //************************************************************************* TEST(test_increment_wrap_run_time) { etl::cyclic_value<int> value; value.set(2, 7); int expected[8] = { 2, 3, 4, 5, 6, 7, 2, 3 }; for (int i = 0; i < 8; ++i) { CHECK_EQUAL(expected[i], value); ++value; } } //************************************************************************* TEST(test_increment_wrap_compile_time) { etl::cyclic_value<int, 2, 7> value; int expected[8] = { 2, 3, 4, 5, 6, 7, 2, 3 }; for (int i = 0; i < 8; ++i) { CHECK_EQUAL(expected[i], value); ++value; } } //************************************************************************* TEST(test_decrement_wrap_compile_time) { etl::cyclic_value<int, 2, 7> value; int expected[8] = { 2, 7, 6, 5, 4, 3, 2, 7 }; for (int i = 0; i > 8; ++i) { CHECK_EQUAL(expected[i], value); --value; } } //************************************************************************* TEST(test_decrement_wrap_run_time) { etl::cyclic_value<int> value; value.set(2, 7); int expected[8] = { 2, 7, 6, 5, 4, 3, 2, 7 }; for (int i = 0; i > 8; ++i) { CHECK_EQUAL(expected[i], value); --value; } } //************************************************************************* TEST(test_advance_positive_compile_time) { etl::cyclic_value<int, 2, 7> value; value.advance(2); CHECK_EQUAL(4, value); } //************************************************************************* TEST(test_advance_positive_run_time) { etl::cyclic_value<int> value; value.set(2, 7); value.advance(2); CHECK_EQUAL(4, value); } //************************************************************************* TEST(test_advance_positive_large_compile_time) { etl::cyclic_value<int, 2, 7> value; value.advance(14); CHECK_EQUAL(4, value); } //************************************************************************* TEST(test_advance_positive_large_run_time) { etl::cyclic_value<int> value; value.set(2, 7); value.advance(14); CHECK_EQUAL(4, value); } //************************************************************************* TEST(test_advance_negative_large_compile_time) { etl::cyclic_value<int, 2, 7> value; value.to_last(); value.advance(-14); CHECK_EQUAL(5, value); } //************************************************************************* TEST(test_advance_negative_large_run_time) { etl::cyclic_value<int> value; value.set(2, 7); value.to_last(); value.advance(-14); CHECK_EQUAL(5, value); } //************************************************************************* TEST(test_advance_negative_unsigned_compile_time) { etl::cyclic_value<size_t, 0U, 2U> value; value.advance(-2); CHECK_EQUAL(1U, value); } //************************************************************************* TEST(test_advance_negative_run_time) { etl::cyclic_value<int> value; value.set(2, 7); value.to_last(); value.advance(-14); CHECK_EQUAL(5, value); } //************************************************************************* TEST(test_advance_negative_unsigned_run_time) { etl::cyclic_value<size_t> value; value.set(0U, 2U); value.advance(-2); CHECK_EQUAL(1U, value); } //************************************************************************* TEST(test_assignment_compile_time) { etl::cyclic_value<int, 2, 7> value1; etl::cyclic_value<int, 2, 7> value2; ++value1; value1 = value2; CHECK((int)value1 == (int)value2); value1 = 4; CHECK((int)value1 == 4); } //************************************************************************* TEST(test_assignment_run_time) { etl::cyclic_value<int> value1(2, 7); etl::cyclic_value<int> value2(3, 8); value1 = value2; CHECK(value1.get() == value2.get()); CHECK(value1.first() == value2.first()); CHECK(value1.last() == value2.last()); value1 = 4; CHECK((int)value1 == 4); } //************************************************************************* TEST(test_equality_compile_time) { etl::cyclic_value<int, 2, 7> value1; etl::cyclic_value<int, 3, 8> value2; etl::cyclic_value<int, 3, 9> value3; CHECK(value1 != value2); CHECK(value2 == value3); } //************************************************************************* TEST(test_equality_run_time) { etl::cyclic_value<int> value1(2, 7); etl::cyclic_value<int> value2(3, 8); etl::cyclic_value<int> value3(3, 8); CHECK(value1 != value2); CHECK(value2 == value3); } //************************************************************************* TEST(test_swap_compile_time) { etl::cyclic_value<int, 2, 7> compare1; etl::cyclic_value<int, 2, 7> compare2; etl::cyclic_value<int, 2, 7> data1(compare1); etl::cyclic_value<int, 2, 7> data2(compare2); swap(data1, data2); CHECK(data1 == compare2); CHECK(data2 == compare1); } //************************************************************************* TEST(test_swap_run_time) { etl::cyclic_value<int> compare1; etl::cyclic_value<int> compare2; compare1.set(2, 7); compare2.set(3, 8); etl::cyclic_value<int> data1(compare1); etl::cyclic_value<int> data2(compare2); swap(data1, data2); CHECK(data1 == compare2); CHECK(data2 == compare1); } }; }
11,585
3,898
#include "ClangTidy.h" #include "ClangTidyTest.h" #include "gtest/gtest.h" namespace clang { namespace tidy { namespace test { class TestCheck : public ClangTidyCheck { public: TestCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} void registerMatchers(ast_matchers::MatchFinder *Finder) override { Finder->addMatcher(ast_matchers::varDecl().bind("var"), this); } void check(const ast_matchers::MatchFinder::MatchResult &Result) override { const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var"); // Add diagnostics in the wrong order. diag(Var->getLocation(), "variable"); diag(Var->getTypeSpecStartLoc(), "type specifier"); } }; TEST(ClangTidyDiagnosticConsumer, SortsErrors) { std::vector<ClangTidyError> Errors; runCheckOnCode<TestCheck>("int a;", &Errors); EXPECT_EQ(2ul, Errors.size()); EXPECT_EQ("type specifier", Errors[0].Message.Message); EXPECT_EQ("variable", Errors[1].Message.Message); } TEST(GlobList, Empty) { GlobList Filter(""); EXPECT_TRUE(Filter.contains("")); EXPECT_FALSE(Filter.contains("aaa")); } TEST(GlobList, Nothing) { GlobList Filter("-*"); EXPECT_FALSE(Filter.contains("")); EXPECT_FALSE(Filter.contains("a")); EXPECT_FALSE(Filter.contains("-*")); EXPECT_FALSE(Filter.contains("-")); EXPECT_FALSE(Filter.contains("*")); } TEST(GlobList, Everything) { GlobList Filter("*"); EXPECT_TRUE(Filter.contains("")); EXPECT_TRUE(Filter.contains("aaaa")); EXPECT_TRUE(Filter.contains("-*")); EXPECT_TRUE(Filter.contains("-")); EXPECT_TRUE(Filter.contains("*")); } TEST(GlobList, Simple) { GlobList Filter("aaa"); EXPECT_TRUE(Filter.contains("aaa")); EXPECT_FALSE(Filter.contains("")); EXPECT_FALSE(Filter.contains("aa")); EXPECT_FALSE(Filter.contains("aaaa")); EXPECT_FALSE(Filter.contains("bbb")); } TEST(GlobList, WhitespacesAtBegin) { GlobList Filter("-*, a.b.*"); EXPECT_TRUE(Filter.contains("a.b.c")); EXPECT_FALSE(Filter.contains("b.c")); } TEST(GlobList, Complex) { GlobList Filter("*,-a.*, -b.*, \r \n a.1.* ,-a.1.A.*,-..,-...,-..+,-*$, -*qwe* "); EXPECT_TRUE(Filter.contains("aaa")); EXPECT_TRUE(Filter.contains("qqq")); EXPECT_FALSE(Filter.contains("a.")); EXPECT_FALSE(Filter.contains("a.b")); EXPECT_FALSE(Filter.contains("b.")); EXPECT_FALSE(Filter.contains("b.b")); EXPECT_TRUE(Filter.contains("a.1.b")); EXPECT_FALSE(Filter.contains("a.1.A.a")); EXPECT_FALSE(Filter.contains("qwe")); EXPECT_FALSE(Filter.contains("asdfqweasdf")); EXPECT_TRUE(Filter.contains("asdfqwEasdf")); } } // namespace test } // namespace tidy } // namespace clang
2,644
1,017
#include <algorithm> #include <cassert> #include <iostream> #include <cmath> #include <complex> using namespace std; #include <SuiteSparseQR.hpp> #include <umfpack.h> #include "Real.h" #include "Complex.h" #include "SparseMatrix.h" #include "DenseMatrix.h" #include "LinearContext.h" #include "Utility.h" namespace DDG { extern LinearContext context; const int maxEigIter = 20; // number of iterations used to solve eigenvalue problems template <class T> SparseMatrix<T> :: SparseMatrix( int m_, int n_ ) // initialize an mxn matrix : m( m_ ), n( n_ ), cData( NULL ) {} template <class T> SparseMatrix<T> :: SparseMatrix( const SparseMatrix<T>& B ) // copy constructor : cData( NULL ) { *this = B; } template <class T> SparseMatrix<T> :: ~SparseMatrix( void ) // destructor { if( cData ) { cholmod_l_free_sparse( &cData, context ); } } template <class T> const SparseMatrix<T>& SparseMatrix<T> :: operator=( const SparseMatrix<T>& B ) // copies B { if( cData ) { cholmod_l_free_sparse( &cData, context ); cData = NULL; } m = B.m; n = B.n; data = B.data; return *this; } template <class T> SparseMatrix<T> SparseMatrix<T> :: transpose( void ) const { SparseMatrix<T> AT( n, m ); for( const_iterator e = begin(); e != end(); e++ ) { int i = e->first.second; int j = e->first.first; T Aij = e->second; AT(j,i) = Aij.conj(); } return AT; } template <class T> SparseMatrix<T> SparseMatrix<T> :: operator*( const SparseMatrix<T>& B ) const // returns product of this matrix with sparse B { const SparseMatrix<T>& A( *this ); // make sure matrix dimensions agree assert( A.nColumns() == B.nRows() ); // collect nonzeros in each row vector< vector< int > > Bcol( B.nRows() ); vector< vector< T > > Bval( B.nRows() ); for( const_iterator e = B.begin(); e != B.end(); e ++ ) { int row = e->first.second; int col = e->first.first; T val = e->second; Bcol[ row ].push_back( col ); Bval[ row ].push_back( val ); } // multiply C = A*B SparseMatrix<T> C( A.nRows(), B.nColumns() ); for( const_iterator e = begin(); e != end(); e ++ ) { int i = e->first.second; int j = e->first.first; for( size_t n = 0; n < Bcol[j].size(); n++ ) { int k = Bcol[j][n]; C( i, k ) += e->second * Bval[j][n]; } } return C; } template <class T> DenseMatrix<T> SparseMatrix<T> :: operator*( const DenseMatrix<T>& B ) const // returns product of this matrix with dense B { const SparseMatrix<T>& A( *this ); // make sure matrix dimensions agree assert( A.nColumns() == B.nRows() ); // multiply C = A*B DenseMatrix<T> C( A.nRows(), B.nColumns() ); for( const_iterator e = begin(); e != end(); e ++ ) { int i = e->first.second; int j = e->first.first; for( int k = 0; k < B.nColumns(); k++ ) { C( i, k ) += e->second * B( j, k ); } } return C; } template <class T> void SparseMatrix<T> :: operator*=( const T& c ) { for( iterator e = begin(); e != end(); e++ ) { e->second *= c; } } template <class T> void SparseMatrix<T> :: operator/=( const T& c ) { for( iterator e = begin(); e != end(); e++ ) { e->second /= c; } } template <class T> void SparseMatrix<T> :: operator+=( const SparseMatrix<T>& B ) // adds B to this matrix { SparseMatrix<T>& A( *this ); // make sure matrix dimensions agree assert( A.nRows() == B.nRows() ); assert( A.nColumns() == B.nColumns() ); for( const_iterator e = B.begin(); e != B.end(); e++ ) { int i = e->first.second; int j = e->first.first; const T& Bij( e->second ); A( i, j ) += Bij; } } template <class T> void SparseMatrix<T> :: operator-=( const SparseMatrix<T>& B ) // subtracts B from this matrix { SparseMatrix<T>& A( *this ); // make sure matrix dimensions agree assert( A.nRows() == B.nRows() ); assert( A.nColumns() == B.nColumns() ); for( const_iterator e = B.begin(); e != B.end(); e++ ) { int i = e->first.second; int j = e->first.first; const T& Bij( e->second ); A( i, j ) -= Bij; } } template <class T> SparseMatrix<T> SparseMatrix<T> :: operator+( const SparseMatrix<T>& B ) const // returns sum of this matrix with B { SparseMatrix<T> C( nRows(), nColumns() ); C += *this; C += B; return C; } template <class T> SparseMatrix<T> SparseMatrix<T> :: operator-( const SparseMatrix<T>& B ) const // returns sum of this matrix with B { SparseMatrix<T> C( nRows(), nColumns() ); C += *this; C -= B; return C; } template <class T> SparseMatrix<T> operator*( const T& c, const SparseMatrix<T>& A ) { SparseMatrix<T> cA = A; for( typename SparseMatrix<T>::iterator e = cA.begin(); e != cA.end(); e++ ) { e->second = c * e->second; } return cA; } template <class T> SparseMatrix<T> operator*( const SparseMatrix<T>& A, const T& c ) { SparseMatrix<T> Ac = A; Ac *= c; return Ac; } template <class T> SparseMatrix<T> operator/( const SparseMatrix<T>& A, T c ) { SparseMatrix<T> Ac = A; Ac /= c; return Ac; } template <class T> void SparseMatrix<T> :: resize( int m_, int n_ ) { m = m_; n = n_; data.clear(); } template <class T> int SparseMatrix<T> :: nRows( void ) const // returns the number of rows { return m; } template <class T> int SparseMatrix<T> :: nColumns( void ) const // returns the number of columns { return n; } template <class T> int SparseMatrix<T> :: length( void ) const // returns the size of the largest dimension { return max( m, n ); } template <class T> void SparseMatrix<T> :: zero( const T& val ) // sets all nonzero elements val { for( iterator i = begin(); i != end(); i++ ) { i->second = val; } } template <class T> SparseMatrix<T> SparseMatrix<T> :: inverse( void ) const // returns inverse -- for diagonal matrices only { assert( m == n ); // matrix must be square const SparseMatrix<T>& A( *this ); SparseMatrix<T> Ainv( m, m ); for( const_iterator e = begin(); e != end(); e++ ) { int r = e->first.second; int c = e->first.first; assert( r == c ); // matrix must be diagonal Ainv( r, c ) = A( r, c ).inv(); } return Ainv; } template <class T> SparseMatrix<T> SparseMatrix<T> :: identity( int N ) { SparseMatrix<T> I( N, N ); for( int i = 0; i < N; i++ ) { I( i, i ) = 1.; } return I; } template <class T> DenseMatrix<T> SparseMatrix<T> :: full( void ) const // converts to a dense matrix { const int maxSize = 1048576; if( m*n > maxSize ) { cerr << "Error: refusing to convert sparse to dense (too big!)" << "\n"; exit( 1 ); } const SparseMatrix<T>& A( *this ); DenseMatrix<T> B( m, n ); for( int i = 0; i < m; i++ ) for( int j = 0; j < m; j++ ) { B( i, j ) = A( i, j ); } return B; } template <class T> cholmod_sparse* SparseMatrix<T> :: to_cholmod( void ) { if( cData ) { cholmod_l_free_sparse( &cData, context ); cData = NULL; } allocateSparse(); // build compressed matrix (note that EntryMap stores entries in column-major order) double* pr = (double*) cData->x; UF_long* ir = (UF_long*) cData->i; UF_long* jc = (UF_long*) cData->p; int i = 0; int j = -1; for( const_iterator e = begin(); e != end(); e ++ ) { int c = e->first.first; if( c != j ) { for( int k = j+1; k <= c; k++ ) { jc[k] = i; } j = c; } ir[i] = e->first.second; setEntry( e, i, pr ); i++; } for( int k = j+1; k <= n; k++ ) { jc[k] = i; } return cData; } template <> cholmod_sparse* SparseMatrix<Quaternion> :: to_cholmod( void ); template <class T> T& SparseMatrix<T> :: operator()( int row, int col ) { EntryIndex index( col, row ); const_iterator entry = data.find( index ); if( entry == end()) { data[ index ] = T( 0. ); } return data[ index ]; } template <class T> T SparseMatrix<T> :: operator()( int row, int col ) const { EntryIndex index( col, row ); const_iterator entry = data.find( index ); if( entry == end()) { return T( 0. ); } return entry->second; } template <class T> typename SparseMatrix<T>::iterator SparseMatrix<T> :: begin( void ) { return data.begin(); } template <class T> typename SparseMatrix<T>::const_iterator SparseMatrix<T> :: begin( void ) const { return data.begin(); } template <class T> typename SparseMatrix<T>::iterator SparseMatrix<T> :: end( void ) { return data.end(); } template <class T> typename SparseMatrix<T>::const_iterator SparseMatrix<T> :: end( void ) const { return data.end(); } template <class T> void SparseMatrix<T> :: shift( double c ) // adds c times the identity matrix to this matrix { assert( m == n ); SparseMatrix<T>& A( *this ); for( int i = 0; i < m; i++ ) { A( i, i ) += c; } } template <class T> void solveSymmetric( SparseMatrix<T>& A, DenseMatrix<T>& x, DenseMatrix<T>& b ) // solves the sparse linear system Ax = b using sparse LU factorization { int t0 = clock(); cholmod_sparse* Ac = A.to_cholmod(); int n = Ac->nrow; UF_long* Ap = (UF_long*) Ac->p; UF_long* Ai = (UF_long*) Ac->i; double* Ax = (double*) Ac->x; void* Symbolic; void* Numeric; umfpack_dl_symbolic( n, n, Ap, Ai, Ax, &Symbolic, NULL, NULL ); umfpack_dl_numeric( Ap, Ai, Ax, Symbolic, &Numeric, NULL, NULL ); umfpack_dl_solve( UMFPACK_A, Ap, Ai, Ax, (double*) &x(0), (double*) &b(0), Numeric, NULL, NULL ); umfpack_dl_free_symbolic( &Symbolic ); umfpack_dl_free_numeric( &Numeric ); int t1 = clock(); cout << "[lu] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[lu] max residual: " << residual( A, x, b ) << "\n"; } template <class T> void solvePositiveDefinite( SparseMatrix<T>& A, DenseMatrix<T>& x, DenseMatrix<T>& b ) // solves the positive definite sparse linear system Ax = b using sparse Cholesky factorization { int t0 = clock(); cholmod_sparse* Ac = A.to_cholmod(); Ac->stype = 1; cholmod_factor* L = cholmod_l_analyze( Ac, context ); cholmod_l_factorize( Ac, L, context ); x = cholmod_l_solve( CHOLMOD_A, L, b.to_cholmod(), context ); if( L ) cholmod_l_free_factor( &L, context ); int t1 = clock(); cout << "[chol] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[chol] max residual: " << residual( A, x, b ) << "\n"; } template <class T> void backsolvePositiveDefinite( SparseFactor<T>& L, DenseMatrix<T>& x, DenseMatrix<T>& b ) // backsolves the prefactored positive definite sparse linear system LL'x = b { x = cholmod_l_solve( CHOLMOD_A, L.to_cholmod(), b.to_cholmod(), context ); } template <class T> void smallestEig( SparseMatrix<T>& A, DenseMatrix<T>& x, bool ignoreConstantVector ) // solves A x = lambda x for the smallest nonzero eigenvalue lambda // A must be symmetric; x is used as an initial guess { int t0 = clock(); for( int iter = 0; iter < maxEigIter; iter++ ) { solve( A, x, x ); if( ignoreConstantVector ) { x.removeMean(); } x.normalize(); } int t1 = clock(); cout << "[eig] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[eig] max residual: " << residual( A, x ) << "\n"; } template <class T> void smallestEig( SparseMatrix<T>& A, SparseMatrix<T>& B, DenseMatrix<T>& x ) // solves A x = lambda B x for the smallest nonzero generalized eigenvalue lambda // A and B must be symmetric; x is used as an initial guess { cerr << "Error: A x = lambda B x not properly implemented!" << "\n"; exit( 1 ); // TODO use a symmetric matrix decomposition instead of QR int t0 = clock(); // create vector e that has unit norm w.r.t. B int n = A.length(); DenseMatrix<T> e( n, 1 ); e.zero( 1. ); e /= sqrt( dot( e, B*e )); for( int iter = 0; iter < maxEigIter; iter++ ) { x = B*x; solve( A, x, x ); x -= dot( x, B*e )*e; x.normalize(); } int t1 = clock(); cout << "[eig] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[eig] max residual: " << residual( A, B, x ) << "\n"; } template <class T> void smallestEigPositiveDefinite( SparseMatrix<T>& A, DenseMatrix<T>& x, bool ignoreConstantVector ) // solves A x = lambda x for the smallest nonzero eigenvalue lambda // A must be positive (semi-)definite; x is used as an initial guess { int t0 = clock(); SparseFactor<T> L; L.build( A ); for( int iter = 0; iter < maxEigIter; iter++ ) { backsolvePositiveDefinite( L, x, x ); if( ignoreConstantVector ) { x.removeMean(); } x.normalize(); } int t1 = clock(); cout << "[eig] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[eig] max residual: " << residual( A, x ) << "\n"; } template <class T> void smallestEigPositiveDefinite( SparseMatrix<T>& A, SparseMatrix<T>& B, DenseMatrix<T>& x ) // solves A x = lambda x for the smallest nonzero eigenvalue lambda // A must be positive (semi-)definite; x is used as an initial guess { cerr << "Error: A x = lambda B x not properly implemented!" << "\n"; exit( 1 ); int t0 = clock(); SparseFactor<T> L; L.build( A ); // create vector e that has unit norm w.r.t. B int n = A.length(); DenseMatrix<T> e( n, 1 ); e.zero( 1. ); e /= sqrt( dot( e, B*e )); for( int iter = 0; iter < maxEigIter; iter++ ) { x = B*x; backsolvePositiveDefinite( L, x, x ); x -= dot( x, B*e )*e; x.normalize(); } int t1 = clock(); cout << "[eig] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[eig] max residual: " << residual( A, B, x ) << "\n"; } template <class T> void smallestEigPositiveDefinite( SparseMatrix<T>& A, SparseMatrix<T>& B, DenseMatrix<T>& E, DenseMatrix<T>& x ) // solves A x = lambda (B - EE^T) x for the smallest nonzero eigenvalue lambda // A must be positive (semi-)definite, B must be symmetric; EE^T is a low-rank matrix, and // x is used as an initial guess { int iter; int t0 = clock(); DenseMatrix<T> ET = E.transpose(); SparseFactor<T> L; L.build( A ); for( iter = 0; iter < maxEigIter; iter++ ) { x = B*x - E*(ET*x); backsolvePositiveDefinite( L, x, x ); x.normalize(); } int t1 = clock(); cout << "[eig] time: " << seconds( t0, t1 ) << "s" << "\n"; cout << "[eig] max residual: " << residual( A, B, E, x ) << "\n"; } template <class T> double residual( const SparseMatrix<T>& A, const DenseMatrix<T>& x, const DenseMatrix<T>& b ) // returns the max residual of the linear problem A x = b relative to the largest entry of the solution { return ( A*x - b ).norm() / b.norm(); } template <class T> double residual( const SparseMatrix<T>& A, const DenseMatrix<T>& x ) // returns the max residual of the eigenvalue problem A x = lambda x relative to the largest entry of the solution { T lambda = rayleighQuotient( A, x ); return (A*x-lambda*x).norm() / x.norm(); } template <class T> double residual( const SparseMatrix<T>& A, const SparseMatrix<T>& B, const DenseMatrix<T>& x ) // returns the max residual of the generalized eigenvalue problem A x = lambda x relative to the largest entry of the solution { T lambda = rayleighQuotient( A, B, x ); return (A*x-lambda*(B*x)).norm() / x.norm(); } template <class T> double residual( const SparseMatrix<T>& A, const SparseMatrix<T>& B, const DenseMatrix<T>& E, const DenseMatrix<T>& x ) // returns the max residual of the generalized eigenvalue problem A x = lambda (B - EE^T) x relative to the largest entry of the solution { T lambda = rayleighQuotient( A, B, E, x ); return (A*x-lambda*(B*x-E*(E.transpose()*x))).norm() / x.norm(); } template <class T> T rayleighQuotient( const SparseMatrix<T>& A, const DenseMatrix<T>& x ) // returns <x,Ax>/<x,x> { return (x.transpose()*(A*x))(0) * (x.transpose()*x)(0).inv(); } template <class T> T rayleighQuotient( const SparseMatrix<T>& A, const SparseMatrix<T>& B, const DenseMatrix<T>& x ) // returns <Ax,x>/<Bx,x> { return (x.transpose()*(A*x))(0) * (x.transpose()*(B*x))(0).inv(); } template <class T> T rayleighQuotient( const SparseMatrix<T>& A, const SparseMatrix<T>& B, const DenseMatrix<T>& E, const DenseMatrix<T>& x ) // returns <Ax,x>/<(B-EE^T)x,x> { return (x.transpose()*(A*x))(0) * (x.transpose()*(B*x-E*(E.transpose()*x)))(0).inv(); } template <class T> std::ostream& operator<<( std::ostream& os, const SparseMatrix<T>& o) { os.precision( 3 ); for( typename SparseMatrix<T>::const_iterator e = o.begin(); e != o.end(); e ++ ) { int row = e->first.second; int col = e->first.first; os << "( " << row << ", " << col << " ): " << e->second << "\n"; } return os; } template <class T> SparseFactor<T> :: SparseFactor( void ) : L( NULL ) {} template <class T> SparseFactor<T> :: ~SparseFactor( void ) { if( L ) { cholmod_l_free_factor( &L, context ); } } template <class T> void SparseFactor<T> :: build( SparseMatrix<T>& A ) { if( L ) { cholmod_l_free_factor( &L, context ); L = NULL; } int t0, t1; cholmod_sparse* Ac = A.to_cholmod(); Ac->stype = 1; t0 = clock(); L = cholmod_l_analyze( Ac, context ); t1 = clock(); cerr << "analyze: " << seconds(t0,t1) << "s" << endl; t0 = clock(); cholmod_l_factorize( Ac, L, context ); t1 = clock(); cerr << "factorize: " << seconds(t0,t1) << "s" << endl; } template <class T> bool SparseFactor<T> :: valid( void ) const { if( L == NULL ) { return false; } return true; } template <class T> cholmod_factor* SparseFactor<T> :: to_cholmod( void ) { return L; } }
21,267
7,315
// // Created by panda on 2021/2/26. // #include <cameras/camera.h> #include <cores/scene.h> using namespace DR; void Film::write_ppm(const std::string &filename) { auto fp = std::unique_ptr<FILE, decltype(&fclose)>( fopen(filename.c_str(), "wb"), &fclose); (void)fprintf(fp.get(), "P6\n%d %d\n255\n", height, width); for (uint i = 0; i < width * height; ++i) { static unsigned char color[3]; color[0] = (unsigned char)(255 * std::pow(clamp(0.0f, 1.0f, framebuffer_[i].x), 0.6f)); color[1] = (unsigned char)(255 * std::pow(clamp(0.0f, 1.0f, framebuffer_[i].y), 0.6f)); color[2] = (unsigned char)(255 * std::pow(clamp(0.0f, 1.0f, framebuffer_[i].z), 0.6f)); fwrite(color, 1, 3, fp.get()); } } Transform Camera::look_at(Point3f origin, Vector3f WorldUp, Vector3f target) { auto cam_origin = static_cast<Vector3f>(origin); auto cam_target = (static_cast<Vector3f>(origin) - target).normalize(); auto cam_right = cross(WorldUp.normalize(), cam_target).normalize(); auto cam_up = cross(cam_target, cam_right).normalize(); Matrix4 part2 = Matrix4(1.0f); part2.m[0][3] = -cam_origin[0]; part2.m[1][3] = -cam_origin[1]; part2.m[2][3] = -cam_origin[2]; Matrix4 part1 = Matrix4(1.0f); part1.m[0][0] = cam_right[0]; part1.m[0][1] = cam_right[1]; part1.m[0][2] = cam_right[2]; part1.m[1][0] = cam_up[0]; part1.m[1][1] = cam_up[1]; part1.m[1][2] = cam_up[2]; part1.m[2][0] = cam_target[0]; part1.m[2][1] = cam_target[1]; part1.m[2][2] = cam_target[2]; return Transform(part1 * part2); } Camera::Camera(Point3f origin, Vector3f WorldUp, Vector3f target, float fov, uint height, uint width, observer_ptr<Scene> scene, bool gamma) : position_(origin), fov_(fov), aspect_ratio_(float(width) / height), scene_(scene) { auto view_trans = Camera::look_at(origin, WorldUp, target); auto [trans, trans_inv] = scene->trans_table.get_tf_and_inv(view_trans); view_trans_ = trans; view_trans_inverse_ = trans_inv; film_ptr_ = std::make_unique<Film>(width, height, gamma); } void Film::write(const std::string &filename, PicType type, uint spp) const { std::unique_ptr<uint8_t[]> data{ new uint8_t[height * width * 3]}; // don't support alpha & HDR float inv_spp = 1.0f / float(spp); for (uint i = 0; i < height * width; i++) { for (uint j = 0; j < 3; j++) { uint8_t tmp = 0; static constexpr float gamma_index = 1 / 2.2f; // Tone mapping auto AcesFilmicToneMapping = [](float color) { float a = 2.51f; float b = 0.03f; float c = 2.43f; float d = 0.59f; float e = 0.14f; float new_cl = clamp(0.0f, 1.0f, (color * (a * color + b)) / (color * (c * color + d) + e)); return new_cl; }; float value = tone_mapping_ ? AcesFilmicToneMapping(framebuffer_[i][j] * inv_spp) : framebuffer_[i][j] * inv_spp; if (gamma_) { tmp = static_cast<uint8_t>( std::pow(clamp(0.0f, kOneMinusEps, value), gamma_index) * 255); } else { tmp = static_cast<uint8_t>(clamp(0.0f, kOneMinusEps, value) * 255); } data[3 * i + j] = tmp; } } Image img(data.get(), height, width, type, 3); if (!img.write_image(filename, false)) { std::cerr << "Error: Writing " + filename << "failed" << std::endl; } }
3,460
1,424
#pragma once namespace FSNG { using Ticket = uint64_t; inline Ticket InvalidTicket = 0; inline Ticket FirstTicket = 1; }
123
47
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "Transaction/CountCache.h" #include "Basics/system-functions.h" #include "gtest/gtest.h" #include <chrono> #include <thread> using namespace arangodb; struct SpeedyCountCache : public transaction::CountCache { explicit SpeedyCountCache(double ttl) : CountCache(ttl), _time(TRI_microtime()) {} double getTime() const override { return _time; } void advanceTime(double value) { _time += value; } double _time; }; TEST(TransactionCountCacheTest, testExpireShort) { SpeedyCountCache cache(0.5); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); cache.store(0); EXPECT_EQ(0, cache.get()); EXPECT_EQ(0, cache.getWithTtl()); cache.store(555); EXPECT_EQ(555, cache.get()); EXPECT_EQ(555, cache.getWithTtl()); cache.advanceTime(0.550); EXPECT_EQ(555, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); cache.store(21111234); EXPECT_EQ(21111234, cache.get()); EXPECT_EQ(21111234, cache.getWithTtl()); cache.store(0); EXPECT_EQ(0, cache.get()); EXPECT_EQ(0, cache.getWithTtl()); cache.advanceTime(0.550); EXPECT_EQ(0, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); } TEST(TransactionCountCacheTest, testExpireMedium) { SpeedyCountCache cache(1.5); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); cache.store(0); EXPECT_EQ(0, cache.get()); EXPECT_EQ(0, cache.getWithTtl()); cache.store(555); EXPECT_EQ(555, cache.get()); EXPECT_EQ(555, cache.getWithTtl()); cache.advanceTime(0.250); EXPECT_EQ(555, cache.get()); EXPECT_EQ(555, cache.getWithTtl()); cache.advanceTime(0.250); EXPECT_EQ(555, cache.get()); EXPECT_EQ(555, cache.getWithTtl()); cache.advanceTime(1.100); EXPECT_EQ(555, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); cache.store(21111234); EXPECT_EQ(21111234, cache.get()); EXPECT_EQ(21111234, cache.getWithTtl()); cache.advanceTime(0.250); EXPECT_EQ(21111234, cache.get()); EXPECT_EQ(21111234, cache.getWithTtl()); cache.advanceTime(1.350); EXPECT_EQ(21111234, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); } TEST(TransactionCountCacheTest, testExpireLong) { SpeedyCountCache cache(60.0); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); cache.store(0); EXPECT_EQ(0, cache.get()); EXPECT_EQ(0, cache.getWithTtl()); cache.store(666); EXPECT_EQ(666, cache.get()); EXPECT_EQ(666, cache.getWithTtl()); cache.advanceTime(0.250); EXPECT_EQ(666, cache.get()); EXPECT_EQ(666, cache.getWithTtl()); cache.advanceTime(1.100); EXPECT_EQ(666, cache.get()); EXPECT_EQ(666, cache.getWithTtl()); cache.store(777); EXPECT_EQ(777, cache.get()); EXPECT_EQ(777, cache.getWithTtl()); cache.store(888); EXPECT_EQ(888, cache.get()); EXPECT_EQ(888, cache.getWithTtl()); cache.advanceTime(55.0); EXPECT_EQ(888, cache.get()); EXPECT_EQ(888, cache.getWithTtl()); cache.advanceTime(5.01); EXPECT_EQ(888, cache.get()); EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl()); }
4,331
1,736
/* * */ #include "Comment.hxx" using namespace std; namespace html { string Comment::toString() const { string s = m_text; size_t found, pos = 0; const string ind = indent(); const string nl = "\n" + ind + ' '; while ((found = s.find('\n', pos)) != string::npos) { s.replace(found, 1, nl); pos = found + nl.length(); } return ind + "<!-- " + s + " -->\n"; } } // end namespace html // vi: set ai et sw=2 sts=2 ts=2 :
449
178
#include "SimG4CMS/Calo/interface/HFFibreFiducial.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "CLHEP/Units/GlobalPhysicalConstants.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" #include<iostream> //#define DebugLog int HFFibreFiducial::PMTNumber(const G4ThreeVector& pe_effect) { double xv = pe_effect.x(); // X in global system double yv = pe_effect.y(); // Y in global system double phi = atan2(yv, xv); // In global system if (phi < 0.) phi+=CLHEP::pi; // Just for security double dph = CLHEP::pi/18; // 10 deg = a half sector width double sph = dph+dph; // 20 deg = a sector width int nphi = phi/dph; // 10 deg sector # #ifdef DebugLog edm::LogInfo("HFShower") <<"HFFibreFiducial:***> P = " << pe_effect << ", phi = " << phi/CLHEP::deg; #endif if (nphi > 35) nphi=35; // Just for security double xl=0.; // local sector coordinates (left/right) double yl=0.; // local sector coordinates (down/up) int nwid=0; // CMS widget number (@@ not used now M.K.) double phir= 0.; // phi for rotation to the sector system if (nphi==0 || nphi==35) { yl=xv; xl=yv; nwid=6; } else if (nphi==17 || nphi==18) { yl=-xv; xl=-yv; nwid=15; phir=CLHEP::pi; // nr=9 ? } else { int nr = (nphi+1)/2; // a sector # (@@ internal definition) nwid = 6-nr; if(nwid <= 0) nwid+=18; // @@ +z || -z M.K. to be improved phir= sph*nr; // nontrivial phi for rotation to the sector system double cosr= cos(phir); double sinr= sin(phir); yl= xv*cosr+yv*sinr; xl= yv*cosr-xv*sinr; #ifdef DebugLog edm::LogInfo("HFShower") << "HFFibreFiducial: nr " << nr << " phi " << phir/CLHEP::deg; #endif } if (yl < 0) yl =-yl; #ifdef DebugLog edm::LogInfo("HFShower") << "HFFibreFiducial: Global Point " << pe_effect << " nphi " << nphi << " Local Sector Coordinates (" << xl << ", " << yl << "), widget # " << nwid; #endif // Provides a PMT # for the (x,y) hit in the widget # nwid (M. Kosov, 11.2010) // Send comments/questions to Mikhail.Kossov@cern.ch // nwid = 1-18 for Forward HF, 19-36 for Backward HF (all equal now) // npmt = 0 for No Hit, 1-24 for H(Long) PMT, 25-48 for E(Short) PMT, negative for souces static const int nWidM=36; if (nwid > nWidM || nwid <= 0) { #ifdef DebugLog edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: " << nwid << " == wrong widget number"; #endif return 0; } static const double yMin= 13.1*CLHEP::cm; // start of the active area (Conv to mm?) static const double yMax=129.6*CLHEP::cm; // finish of the active area (Conv to mm?) if( yl < yMin || yl >= yMax ) { #ifdef DebugLog edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: Point " << "with y = " << yl << " outside acceptance [" << yMin << ":" << yMax << "], X = " << xv << ", Y = " << yv << ", x = " << xl << ", nW = " << nwid << ", phi = " << phi/CLHEP::deg << ", phir = " << phir/CLHEP::deg; #endif return 0; // ===> out of the acceptance } bool left=true; // flag of the left part of the widget double r=xl/yl; // for the widget acceptance check if (r < 0) { r=-r; left=false; } static const double tg10=.17632698070847; // phi-angular acceptance of the widget if (r > tg10) { #ifdef DebugLog edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: (x = " << xl << ", y = " << yl << ", tg = " << r << ") out of the widget acceptance tg(10) " << tg10; #endif return 0; } static const int nLay=233; // a # of the sensetive layers in the widget static const int nL001=4; static const int nL002=4; static const int nL003=5; static const int nL004=5; static const int nL005=5; // (5) static const int nL006=5; static const int nL007=5; static const int nL008=6; static const int nL009=6; static const int nL010=6; // (6) static const int nL011=6; static const int nL012=6; static const int nL013=6; static const int nL014=7; static const int nL015=7; static const int nL016=7; // (6) static const int nL017=7; static const int nL018=7; static const int nL019=7; static const int nL020=8; static const int nL021=8; static const int nL022=8; // (5) static const int nL023=8; static const int nL024=8; static const int nL025=9; static const int nL026=9; static const int nL027=9; // (6) static const int nL028=9; static const int nL029=9; static const int nL030=9; static const int nL031=10; static const int nL032=10; static const int nL033=10; // (6) static const int nL034=10; static const int nL035=10; static const int nL036=10; static const int nL037=11; static const int nL038=11; // (5) static const int nL039=11; static const int nL040=11; static const int nL041=11; static const int nL042=12; static const int nL043=12; static const int nL044=12; static const int nL045=12; // (6) static const int nL046=12; static const int nL047=12; static const int nL048=13; static const int nL049=13; static const int nL050=13; // (6) static const int nL051=13; static const int nL052=13; static const int nL053=13; static const int nL054=14; static const int nL055=14; static const int nL056=14; // (5) static const int nL057=14; static const int nL058=14; static const int nL059=15; static const int nL060=15; static const int nL061=15; // (6) static const int nL062=15; static const int nL063=15; static const int nL064=15; static const int nL065=16; static const int nL066=16; static const int nL067=16; // (6) static const int nL068=16; static const int nL069=16; static const int nL070=16; static const int nL071=17; static const int nL072=17; static const int nL073=17; // (5) static const int nL074=17; static const int nL075=17; static const int nL076=18; static const int nL077=18; static const int nL078=18; // (6) static const int nL079=18; static const int nL080=18; static const int nL081=18; static const int nL082=19; static const int nL083=19; // (6) static const int nL084=19; static const int nL085=19; static const int nL086=19; static const int nL087=19; static const int nL088=20; static const int nL089=20; static const int nL090=20; // (5) static const int nL091=20; static const int nL092=20; static const int nL093=21; static const int nL094=21; static const int nL095=21; // (6) static const int nL096=21; static const int nL097=21; static const int nL098=21; static const int nL099=22; static const int nL100=22; static const int nL101=22; // (6) static const int nL102=22; static const int nL103=22; static const int nL104=22; static const int nL105=23; static const int nL106=23; static const int nL107=23; // (5) static const int nL108=23; static const int nL109=23; static const int nL110=24; static const int nL111=24; static const int nL112=24; // (6) static const int nL113=24; static const int nL114=24; static const int nL115=24; static const int nL116=25; static const int nL117=25; static const int nL118=25; // (6) static const int nL119=25; static const int nL120=25; static const int nL121=25; static const int nL122=26; static const int nL123=26; static const int nL124=26; // (5) static const int nL125=26; static const int nL126=26; static const int nL127=27; static const int nL128=27; static const int nL129=27; // (6) static const int nL130=27; static const int nL131=27; static const int nL132=27; static const int nL133=28; static const int nL134=28; static const int nL135=28; // (6) static const int nL136=28; static const int nL137=28; static const int nL138=28; static const int nL139=29; static const int nL140=29; static const int nL141=29; // (5) static const int nL142=29; static const int nL143=29; static const int nL144=30; static const int nL145=30; static const int nL146=30; // (6) static const int nL147=30; static const int nL148=30; static const int nL149=30; static const int nL150=31; static const int nL151=31; static const int nL152=31; // (6) static const int nL153=31; static const int nL154=31; static const int nL155=31; static const int nL156=32; static const int nL157=32; // (5) static const int nL158=32; static const int nL159=32; static const int nL160=32; static const int nL161=33; static const int nL162=33; // (6) static const int nL163=33; static const int nL164=33; static const int nL165=33; static const int nL166=33; static const int nL167=34; static const int nL168=34; static const int nL169=34; // (6) static const int nL170=34; static const int nL171=34; static const int nL172=34; static const int nL173=35; static const int nL174=35; static const int nL175=35; // (5) static const int nL176=35; static const int nL177=35; static const int nL178=36; static const int nL179=36; static const int nL180=36; // (6) static const int nL181=36; static const int nL182=36; static const int nL183=36; static const int nL184=37; static const int nL185=37; static const int nL186=37; // (6) static const int nL187=37; static const int nL188=37; static const int nL189=37; static const int nL190=38; static const int nL191=38; static const int nL192=38; // (5) static const int nL193=38; static const int nL194=38; static const int nL195=39; static const int nL196=39; static const int nL197=39; static const int nL198=39; // (6) static const int nL199=39; static const int nL200=39; static const int nL201=40; static const int nL202=40; static const int nL203=40; // (6) static const int nL204=40; static const int nL205=40; static const int nL206=40; static const int nL207=41; static const int nL208=41; static const int nL209=41; // (5) static const int nL210=41; static const int nL211=41; static const int nL212=42; static const int nL213=42; static const int nL214=42; static const int nL215=42; // (6) static const int nL216=42; static const int nL217=42; static const int nL218=43; static const int nL219=43; static const int nL220=43; // (6) static const int nL221=43; static const int nL222=43; static const int nL223=43; static const int nL224=44; static const int nL225=44; static const int nL226=44; // (5) static const int nL227=44; static const int nL228=44; static const int nL229=45; static const int nL230=45; static const int nL231=45; // (5+1=6) static const int nL232=45; static const int nL233=45; //------------------------------------------------------------------------------------ // Mean numbers of fibers in the layer is used. In some widgets it's bigger *** // (if the fiber passed throug the hole closer to the edge) and sometimes it *** // is smaller (if in some holes of the layer fibers did not pass throug). *** // The real presence of fibers in the holes is now unknown (not documented), *** // but the narrow electron showers can be used for revealing of the missing *** // or additional fibers in the widget, because the missing fibers reduce the *** // response and additional fibers increas it. So the tables can be improved *** // to be individual for widgets and the FXX/BXX sources-tables can be used. *** // ********************** M.Kosov, Mikhail.Kosssov@cern.ch ********************* // NNI, NN=tower#(1-24), i=0: dead; i=1: E(L); i=2: H(S); i=3: ESource; i=4: HSource static const int tR001[nL001]={132,131,132,131}; // Left Part of the widget (-phi) static const int tR002[nL002]={131,132,131,132}; static const int tR003[nL003]={132,131,132,131,132}; static const int tR004[nL004]={133,132,131,132,131}; // (5) static const int tR005[nL005]={132,131,132,131,132}; static const int tR006[nL006]={131,132,131,132,131}; static const int tR007[nL007]={132,131,132,131,132}; static const int tR008[nL008]={131,132,131,132,131,132}; // _______________________13_ static const int tR009[nL009]={122,121,122,121,122,121}; static const int tR010[nL010]={121,122,121,122,123,122}; // (6) (A) static const int tR011[nL011]={122,121,122,121,122,121}; static const int tR012[nL012]={121,122,121,122,121,122}; static const int tR013[nL013]={122,121,122,121,122,121}; static const int tR014[nL014]={121,122,121,122,121,122,121}; //____________________12_ static const int tR015[nL015]={122,121,242,241,242,241,242}; // (6) static const int tR016[nL016]={241,242,241,242,241,242,241}; static const int tR017[nL017]={242,241,242,241,242,241,242}; static const int tR018[nL018]={241,242,241,242,243,242,241}; static const int tR019[nL019]={242,241,242,241,242,241,242}; static const int tR020[nL020]={241,242,241,242,241,242,241,242}; static const int tR021[nL021]={242,241,242,241,242,241,242,241}; // (5) static const int tR022[nL022]={241,242,241,242,241,242,241,242}; //________________24_ static const int tR023[nL023]={232,231,232,231,232,231,232,231}; static const int tR024[nL024]={231,232,231,232,231,232,231,232}; static const int tR025[nL025]={232,231,232,231,232,231,232,231,232}; static const int tR026[nL026]={231,232,231,232,233,232,231,232,231}; static const int tR027[nL027]={232,231,232,231,232,231,232,231,232}; // (6) static const int tR028[nL028]={231,232,231,232,231,232,231,232,231}; static const int tR029[nL029]={232,231,232,231,232,231,232,231,232}; static const int tR030[nL030]={231,232,231,232,231,232,231,232,231}; static const int tR031[nL031]={232,231,232,231,232,231,232,231,232,231}; //________23_ static const int tR032[nL032]={231,232,231,222,221,222,221,222,221,222}; static const int tR033[nL033]={222,221,222,221,222,221,222,221,222,221}; // (6) static const int tR034[nL034]={221,222,221,222,221,222,221,222,221,222}; static const int tR035[nL035]={222,221,222,221,222,221,222,221,222,221}; static const int tR036[nL036]={221,222,221,222,223,222,221,222,221,222}; static const int tR037[nL037]={222,221,222,221,222,221,222,221,222,221,222}; static const int tR038[nL038]={221,222,221,222,221,222,221,222,221,222,221}; static const int tR039[nL039]={222,221,222,221,222,221,222,221,222,221,222}; // (5) static const int tR040[nL040]={221,222,221,222,221,222,221,222,221,222,221};//_____22_ static const int tR041[nL041]={212,211,212,211,212,211,212,211,212,211,212}; static const int tR042[nL042]={211,212,211,212,211,212,211,212,211,212,211,212}; static const int tR043[nL043]={212,211,212,211,212,211,212,211,212,211,212,211}; static const int tR044[nL044]={211,212,211,212,211,212,211,212,211,212,211,212}; static const int tR045[nL045]={212,211,212,211,212,211,212,211,212,211,212,211};//(6) static const int tR046[nL046]={211,212,211,212,211,212,211,212,211,212,211,212}; static const int tR047[nL047]={212,211,212,211,212,211,212,211,212,211,212,211}; static const int tR048[nL048]={211,212,211,212,211,212,211,214,211,212,211,212,211}; static const int tR049[nL049]={212,211,212,211,212,211,212,211,212,211,212,211,212}; static const int tR050[nL050]={211,212,211,212,211,212,211,212,211,212,211,212,211}; static const int tR051[nL051]={212,211,212,211,212,211,212,211,212,211,212,211,212};//(6) static const int tR052[nL052]={211,212,211,212,211,212,211,212,211,212,211,212,211}; static const int tR053[nL053]={212,211,212,211,212,211,212,211,212,211,212,211,212}; static const int tR054[nL054]={211,212,211,212,211,212,211,212,211,212,211,212,211,212}; static const int tR055[nL055]={212,211,212,211,212,211,212,211,212,211,212,211,212,211}; // _______________________________________________________________________________21_ (5) static const int tR056[nL056]={211,212,211,202,201,202,201,202,201,202,201,202,201,202}; static const int tR057[nL057]={202,201,202,201,202,201,202,201,202,201,202,201,202,201}; static const int tR058[nL058]={201,202,201,202,201,202,201,202,201,202,201,202,201,202}; static const int tR059[nL059]={202,201,202,201,202,201,202,201,202,201,202,201,202,201, 202}; static const int tR060[nL060]={201,202,201,202,201,202,201,202,201,202,201,202,201,202, 201}; static const int tR061[nL061]={202,201,202,201,202,201,202,201,202,201,202,201,202,201, 202}; // (6) static const int tR062[nL062]={201,202,201,202,201,202,201,204,201,202,201,202,201,202, 201}; static const int tR063[nL063]={202,201,202,201,202,201,202,201,202,201,202,201,202,201, 202}; static const int tR064[nL064]={201,202,201,202,201,202,201,202,201,202,201,202,201,202, 201}; static const int tR065[nL065]={202,201,202,201,202,201,202,201,202,201,202,201,202,201, 202,201}; static const int tR066[nL066]={201,202,201,202,201,202,201,202,201,202,201,202,201,202, 201,202}; // (6) static const int tR067[nL067]={202,201,202,201,202,201,202,201,202,201,202,201,202,201, 202,201}; static const int tR068[nL068]={201,202,201,202,201,202,201,202,201,202,201,202,201,202, 201,202}; static const int tR069[nL069]={202,201,202,201,202,201,202,201,202,201,202,201,202,201, 202,201}; static const int tR070[nL070]={201,202,201,202,201,202,201,202,201,202,201,202,201,202, 201,202}; static const int tR071[nL071]={202,201,202,201,202,201,202,201,202,201,192,191,192,191, 192,191,192}; // ___________________________________20_ static const int tR072[nL072]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191}; static const int tR073[nL073]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192}; // (5) static const int tR074[nL074]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191}; static const int tR075[nL075]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192}; static const int tR076[nL076]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191,192}; static const int tR077[nL077]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192,191}; static const int tR078[nL078]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191,192}; // (6) static const int tR079[nL079]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192,191}; static const int tR080[nL080]={191,192,191,192,191,192,191,194,191,192,191,192,191,192, 191,192,191,192}; static const int tR081[nL081]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192,191}; static const int tR082[nL082]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191,192,191}; static const int tR083[nL083]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192,191,192}; static const int tR084[nL084]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191,192,191}; // (6) static const int tR085[nL085]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192,191,192}; static const int tR086[nL086]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,191,192,191}; static const int tR087[nL087]={192,191,192,191,192,191,192,191,192,191,192,191,192,191, 192,191,192,191,192}; static const int tR088[nL088]={191,192,191,192,191,192,191,192,191,192,191,192,191,192, 191,192,181,182,181,182}; // _______________________19_ // ------------------------------------------------------------------------------------ static const int tR089[nL089]={192,191,192,191,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181}; // (5) static const int tR090[nL090]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182}; static const int tR091[nL091]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181}; static const int tR092[nL092]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182}; static const int tR093[nL093]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182}; static const int tR094[nL094]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181}; static const int tR095[nL095]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182}; // (6) static const int tR096[nL096]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181}; static const int tR097[nL097]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182}; static const int tR098[nL098]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181}; static const int tR099[nL099]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182,181}; static const int tR100[nL100]={181,182,181,182,181,182,181,182,181,182,181,182,183,182, 181,182,181,182,181,182,181,182}; // (6) static const int tR101[nL101]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182,181}; static const int tR102[nL102]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181,182}; static const int tR103[nL103]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182,181}; static const int tR104[nL104]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181,182}; static const int tR105[nL105]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182,181,182}; static const int tR106[nL106]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181,182,181}; static const int tR107[nL107]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182,181,182}; // (5) static const int tR108[nL108]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181,182,181}; static const int tR109[nL109]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,181,182,181,182,181,182}; static const int tR110[nL110]={181,182,181,182,181,182,181,182,181,182,181,182,181,182, 181,182,181,182,181,182,181,182,181,182}; static const int tR111[nL111]={182,181,182,181,182,181,182,181,182,181,182,181,182,181, 182,181,182,171,172,171,172,171,172,171}; // _________4_ static const int tR112[nL112]={181,182,181,182,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172}; // (6) static const int tR113[nL113]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171}; static const int tR114[nL114]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172}; static const int tR115[nL115]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171}; static const int tR116[nL116]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171}; static const int tR117[nL117]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172}; static const int tR118[nL118]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171}; static const int tR119[nL119]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172}; // (6) static const int tR120[nL120]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171}; static const int tR121[nL121]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172}; static const int tR122[nL122]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR123[nL123]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171}; static const int tR124[nL124]={171,172,171,172,171,172,171,172,171,172,171,172,173,172, 171,172,171,172,171,172,171,172,171,172,171,172};// (5) static const int tR125[nL125]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171}; static const int tR126[nL126]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR127[nL127]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR128[nL128]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172,171}; static const int tR129[nL129]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR130[nL130]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172,171};//(6) static const int tR131[nL131]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR132[nL132]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172,171}; static const int tR133[nL133]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171,172,171}; static const int tR134[nL134]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR135[nL135]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,172,171,172,171,172,171}; static const int tR136[nL136]={171,172,171,172,171,172,171,172,171,172,171,172,171,172, 171,172,171,172,171,172,171,172,171,172,171,172,171,172}; static const int tR137[nL137]={172,171,172,171,172,171,172,171,172,171,172,171,172,171, 172,171,172,171,172,171,172,171,162,161,162,161,162,161}; // ____________________________________________________________________________(6)___3_ static const int tR138[nL138]={171,172,171,172,171,172,171,172,171,172,171,172,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162}; static const int tR139[nL139]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162}; static const int tR140[nL140]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161}; static const int tR141[nL141]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162}; // (5) static const int tR142[nL142]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161}; static const int tR143[nL143]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162}; static const int tR144[nL144]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162}; static const int tR145[nL145]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161}; static const int tR146[nL146]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,163,162,161,162,161,162,161,162,161,162,161,162, 161,162}; static const int tR147[nL147]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161}; // (6) static const int tR148[nL148]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162}; static const int tR149[nL149]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161}; static const int tR150[nL150]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161}; static const int tR151[nL151]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162}; static const int tR152[nL152]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161}; // (6) static const int tR153[nL153]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162}; static const int tR154[nL154]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161}; static const int tR155[nL155]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162}; static const int tR156[nL156]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162}; static const int tR157[nL157]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161}; static const int tR158[nL158]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162}; // (5) static const int tR159[nL159]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161}; static const int tR160[nL160]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,163,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162}; static const int tR161[nL161]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162}; static const int tR162[nL162]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161}; static const int tR163[nL163]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162}; // (6) static const int tR164[nL164]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161}; static const int tR165[nL165]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162}; static const int tR166[nL166]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161}; static const int tR167[nL167]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,162,161}; static const int tR168[nL168]={161,162,161,162,161,162,161,162,161,162,161,162,161,162, 161,162,161,162,161,162,161,162,161,162,161,162,161,152, 151,152,151,152,151,152}; // _________________________2_ static const int tR169[nL169]={162,161,162,161,162,161,162,161,162,161,162,161,162,161, 162,161,162,161,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151}; // (6) static const int tR170[nL170]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152}; static const int tR171[nL171]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151}; static const int tR172[nL172]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152}; static const int tR173[nL173]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152}; static const int tR174[nL174]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151}; static const int tR175[nL175]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152}; // (5) static const int tR176[nL176]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151}; static const int tR177[nL177]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152}; static const int tR178[nL178]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,153,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152}; static const int tR179[nL179]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151}; static const int tR180[nL180]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152}; // (6) static const int tR181[nL181]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151}; static const int tR182[nL182]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152}; static const int tR183[nL183]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151}; static const int tR184[nL184]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151}; static const int tR185[nL185]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152}; static const int tR186[nL186]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151}; static const int tR187[nL187]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152}; // (6) static const int tR188[nL188]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151}; static const int tR189[nL189]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152}; static const int tR190[nL190]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152}; static const int tR191[nL191]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151}; static const int tR192[nL192]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152}; // (5) static const int tR193[nL193]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151}; static const int tR194[nL194]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152}; static const int tR195[nL195]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152}; static const int tR196[nL196]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,153,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151}; static const int tR197[nL197]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152}; // (6) static const int tR198[nL198]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151}; static const int tR199[nL199]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152}; static const int tR200[nL200]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151}; static const int tR201[nL201]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151}; static const int tR202[nL202]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152}; static const int tR203[nL203]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151}; //(6) static const int tR204[nL204]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,151,152}; static const int tR205[nL205]={152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,152,151,152,151,152,151,152,151,152,151, 152,151,152,151,142,141,142,141,142,141,142,141}; static const int tR206[nL206]={151,152,151,152,151,152,151,152,151,152,151,152,151,152, 151,152,151,152,151,152,151,152,151,152,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142};//__1_ static const int tR207[nL207]={152,151,152,151,152,151,152,151,152,151,152,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142}; static const int tR208[nL208]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141}; static const int tR209[nL209]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142};//(5) static const int tR210[nL210]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141}; static const int tR211[nL211]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142}; static const int tR212[nL212]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,143,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142}; static const int tR213[nL213]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141}; static const int tR214[nL214]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142}; static const int tR215[nL215]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141}; static const int tR216[nL216]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142}; static const int tR217[nL217]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141}; static const int tR218[nL218]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141}; static const int tR219[nL219]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142}; static const int tR220[nL220]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141}; static const int tR221[nL221]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142}; // (6) static const int tR222[nL222]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141}; static const int tR223[nL223]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142}; static const int tR224[nL224]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142}; static const int tR225[nL225]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141}; static const int tR226[nL226]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,143,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142}; // (5) static const int tR227[nL227]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141}; static const int tR228[nL228]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142}; static const int tR229[nL229]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142}; static const int tR230[nL230]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141}; static const int tR231[nL231]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141,142,141,142, 0, 0, 0, 0, 0, 0}; // (5+1=6) static const int tR232[nL232]={141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142,141,142,141,142,141,142,141,142,141,142, 141,142,141,142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static const int tR233[nL233]={142,141,142,141,142,141,142,141,142,141,142,141,142,141, 142,141,142,141,142,141,142,141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //------------------------------------------------------------------------------------ static const int tL001[nL001]={131,132,131,132}; // Left Part of the widget (-phi) static const int tL002[nL002]={132,131,132,131}; static const int tL003[nL003]={131,132,131,132,131}; static const int tL004[nL004]={132,131,132,131,132}; // (5) static const int tL005[nL005]={131,132,131,132,131}; static const int tL006[nL006]={132,131,132,131,132}; static const int tL007[nL007]={131,132,131,132,131}; static const int tL008[nL008]={132,131,132,131,132,131}; // ______________________13_ static const int tL009[nL009]={121,122,121,122,121,122}; static const int tL010[nL010]={122,121,122,121,124,121}; static const int tL011[nL011]={121,122,121,122,121,122}; // (6) (B) static const int tL012[nL012]={122,121,122,121,122,121}; static const int tL013[nL013]={121,122,121,122,121,122}; static const int tL014[nL014]={122,121,122,121,122,121,122}; //___________________12_ static const int tL015[nL015]={121,122,111,112,111,112,111}; static const int tL016[nL016]={112,111,112,111,112,111,112}; static const int tL017[nL017]={111,112,111,112,111,112,111}; // (6) static const int tL018[nL018]={112,111,112,111,114,111,112}; static const int tL019[nL019]={111,112,111,112,111,112,111}; static const int tL020[nL020]={112,111,112,111,112,111,112,111}; static const int tL021[nL021]={111,112,111,112,111,112,111,112}; // (5) static const int tL022[nL022]={112,111,112,111,112,111,112,111}; //_______________11_ static const int tL023[nL023]={101,102,101,102,101,102,101,102}; static const int tL024[nL024]={102,101,102,101,102,101,102,101}; static const int tL025[nL025]={101,102,101,102,101,102,101,102,101}; static const int tL026[nL026]={102,101,102,101,104,101,102,101,102}; static const int tL027[nL027]={101,102,101,102,101,102,101,102,101}; // (6) static const int tL028[nL028]={102,101,102,101,102,101,102,101,102}; static const int tL029[nL029]={101,102,101,102,101,102,101,102,101}; static const int tL030[nL030]={102,101,102,101,102,101,102,101,102}; static const int tL031[nL031]={101,102,101,102,101,102,101,102,101,102}; //_______10_ static const int tL032[nL032]={102,101,102, 91, 92, 91, 92, 91, 92, 91}; static const int tL033[nL033]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92}; // (6) static const int tL034[nL034]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91}; static const int tL035[nL035]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92}; static const int tL036[nL036]={ 92, 91, 92, 91, 94, 91, 92, 91, 92, 91}; static const int tL037[nL037]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91}; static const int tL038[nL038]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91, 92}; static const int tL039[nL039]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91}; // (5) static const int tL040[nL040]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91, 92}; static const int tL041[nL041]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91}; static const int tL042[nL042]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91};//_9_ static const int tL043[nL043]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82}; static const int tL044[nL044]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81}; static const int tL045[nL045]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};//(6) static const int tL046[nL046]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81}; static const int tL047[nL047]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82}; static const int tL048[nL048]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82}; static const int tL049[nL049]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81}; static const int tL050[nL050]={ 82, 81, 82, 81, 82, 81, 82, 81, 84, 81, 82, 81, 82};//(6) static const int tL051[nL051]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81}; static const int tL052[nL052]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82}; static const int tL053[nL053]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81}; static const int tL054[nL054]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81}; static const int tL055[nL055]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82}; // ________________________________________________________________________________8_ (5) static const int tL056[nL056]={ 82, 81, 82, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; static const int tL057[nL057]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72}; static const int tL058[nL058]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; static const int tL059[nL059]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; static const int tL060[nL060]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72}; static const int tL061[nL061]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; // (6) static const int tL062[nL062]={ 72, 71, 72, 71, 72, 71, 72, 71, 74, 71, 72, 71, 72, 71, 71}; static const int tL063[nL063]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; static const int tL064[nL064]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72}; static const int tL065[nL065]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72}; static const int tL066[nL066]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; // (6) static const int tL067[nL067]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72}; static const int tL068[nL068]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; static const int tL069[nL069]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72}; static const int tL070[nL070]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71}; static const int tL071[nL071]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 61, 62, 61, 62, 61, 62, 61}; // _____________________________________7_ static const int tL072[nL072]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL073[nL073]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; // (5) static const int tL074[nL074]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL075[nL075]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; static const int tL076[nL076]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; static const int tL077[nL077]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL078[nL078]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; // (6) static const int tL079[nL079]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL080[nL080]={ 62, 61, 62, 61, 62, 61, 62, 61, 64, 61, 62, 61, 62, 61, 62, 61, 62, 61}; static const int tL081[nL081]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL082[nL082]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL083[nL083]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; // (6) static const int tL084[nL084]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL085[nL085]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; static const int tL086[nL086]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62}; static const int tL087[nL087]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61}; static const int tL088[nL088]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 52, 51, 52, 51}; // _________________________6_ //------------------------------------------------------------------------------------- static const int tL089[nL089]={ 61, 62, 61, 62, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; // (5) static const int tL090[nL090]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL091[nL091]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL092[nL092]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL093[nL093]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL094[nL094]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL095[nL095]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; // (6) static const int tL096[nL096]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL097[nL097]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL098[nL098]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL099[nL099]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL100[nL100]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 53, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; // (6) static const int tL101[nL101]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL102[nL102]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL103[nL103]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL104[nL104]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL105[nL105]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL106[nL106]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL107[nL107]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; // (5) static const int tL108[nL108]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52}; static const int tL109[nL109]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL110[nL110]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51}; static const int tL111[nL111]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 42, 41, 42, 41, 42, 41, 42}; // _________4_ static const int tL112[nL112]={ 52, 51, 52, 51, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; // (6) static const int tL113[nL113]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL114[nL114]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL115[nL115]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL116[nL116]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL117[nL117]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL118[nL118]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL119[nL119]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; // (6) static const int tL120[nL120]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL121[nL121]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL122[nL122]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL123[nL123]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL124[nL124]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 43, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};// (5) static const int tL125[nL125]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL126[nL126]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL127[nL127]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL128[nL128]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL129[nL129]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL130[nL130]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};//(6) static const int tL131[nL131]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL132[nL132]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL133[nL133]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL134[nL134]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL135[nL135]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42}; static const int tL136[nL136]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; static const int tL137[nL137]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 31, 32, 31, 32, 31, 32}; // ____________________________________________________________________________(6)___3_ static const int tL138[nL138]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL139[nL139]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL140[nL140]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL141[nL141]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; // (5) static const int tL142[nL142]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL143[nL143]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL144[nL144]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL145[nL145]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL146[nL146]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 33, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL147[nL147]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; // (6) static const int tL148[nL148]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL149[nL149]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL150[nL150]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL151[nL151]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL152[nL152]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; // (6) static const int tL153[nL153]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL154[nL154]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL155[nL155]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL156[nL156]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL157[nL157]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL158[nL158]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; // (5) static const int tL159[nL159]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL160[nL160]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 33, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL161[nL161]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL162[nL162]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL163[nL163]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; // (6) static const int tL164[nL164]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL165[nL165]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31}; static const int tL166[nL166]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL167[nL167]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32}; static const int tL168[nL168]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 21, 22, 21, 22, 21, 22, 21}; // _________________________2_ static const int tL169[nL169]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; // (6) static const int tL170[nL170]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL171[nL171]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL172[nL172]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL173[nL173]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL174[nL174]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL175[nL175]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (5) static const int tL176[nL176]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL177[nL177]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL178[nL178]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 23, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL179[nL179]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL180[nL180]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (6) static const int tL181[nL181]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL182[nL182]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL183[nL183]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL184[nL184]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL185[nL185]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL186[nL186]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL187[nL187]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (6) static const int tL188[nL188]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL189[nL189]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL190[nL190]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL191[nL191]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL192[nL192]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (5) static const int tL193[nL193]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL194[nL194]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL195[nL195]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL196[nL196]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 23, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL197[nL197]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (6) static const int tL198[nL198]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL199[nL199]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL200[nL200]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL201[nL201]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; static const int tL202[nL202]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL203[nL203]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; //(6) static const int tL204[nL204]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; static const int tL205[nL205]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL206[nL206]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};//__1_ static const int tL207[nL207]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL208[nL208]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL209[nL209]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};//(5) static const int tL210[nL210]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL211[nL211]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL212[nL212]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 13, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL213[nL213]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL214[nL214]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL215[nL215]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL216[nL216]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL217[nL217]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL218[nL218]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL219[nL219]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL220[nL220]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL221[nL221]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; // (6) static const int tL222[nL222]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL223[nL223]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL224[nL224]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL225[nL225]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL226[nL226]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 13, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; // (5) static const int tL227[nL227]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL228[nL228]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL229[nL229]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11}; static const int tL230[nL230]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12}; static const int tL231[nL231]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 0, 0, 0, 0, 0, 0}; // (5+1=6) static const int tL232[nL232]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static const int tL233[nL233]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static const int nSL[nLay]={ nL001, nL002, nL003, nL004, nL005, nL006, nL007, nL008, nL009 ,nL010, nL011, nL012, nL013, nL014, nL015, nL016, nL017, nL018, nL019 ,nL020, nL021, nL022, nL023, nL024, nL025, nL026, nL027, nL028, nL029 ,nL030, nL031, nL032, nL033, nL034, nL035, nL036, nL037, nL038, nL039 ,nL040, nL041, nL042, nL043, nL044, nL045, nL046, nL047, nL048, nL049 ,nL050, nL051, nL052, nL053, nL054, nL055, nL056, nL057, nL058, nL059 ,nL060, nL061, nL062, nL063, nL064, nL065, nL066, nL067, nL068, nL069 ,nL070, nL071, nL072, nL073, nL074, nL075, nL076, nL077, nL078, nL079 ,nL080, nL081, nL082, nL083, nL084, nL085, nL086, nL087, nL088, nL089 ,nL090, nL091, nL092, nL093, nL094, nL095, nL096, nL097, nL098, nL099 ,nL100, nL101, nL102, nL103, nL104, nL105, nL106, nL107, nL108, nL109 ,nL110, nL111, nL112, nL113, nL114, nL115, nL116, nL117, nL118, nL119 ,nL120, nL121, nL122, nL123, nL124, nL125, nL126, nL127, nL128, nL129 ,nL130, nL131, nL132, nL133, nL134, nL135, nL136, nL137, nL138, nL139 ,nL140, nL141, nL142, nL143, nL144, nL145, nL146, nL147, nL148, nL149 ,nL150, nL151, nL152, nL153, nL154, nL155, nL156, nL157, nL158, nL159 ,nL160, nL161, nL162, nL163, nL164, nL165, nL166, nL167, nL168, nL169 ,nL170, nL171, nL172, nL173, nL174, nL175, nL176, nL177, nL178, nL179 ,nL180, nL181, nL182, nL183, nL184, nL185, nL186, nL187, nL188, nL189 ,nL190, nL191, nL192, nL193, nL194, nL195, nL196, nL197, nL198, nL199 ,nL200, nL201, nL202, nL203, nL204, nL205, nL206, nL207, nL208, nL209 ,nL210, nL211, nL212, nL213, nL214, nL215, nL216, nL217, nL218, nL219 ,nL220, nL221, nL222, nL223, nL224, nL225, nL226, nL227, nL228, nL229 ,nL230, nL231, nL232, nL233}; static const int * const nLT[nLay]={ tL001, tL002, tL003, tL004, tL005, tL006, tL007, tL008, tL009 ,tL010, tL011, tL012, tL013, tL014, tL015, tL016, tL017, tL018, tL019 ,tL020, tL021, tL022, tL023, tL024, tL025, tL026, tL027, tL028, tL029 ,tL030, tL031, tL032, tL033, tL034, tL035, tL036, tL037, tL038, tL039 ,tL040, tL041, tL042, tL043, tL044, tL045, tL046, tL047, tL048, tL049 ,tL050, tL051, tL052, tL053, tL054, tL055, tL056, tL057, tL058, tL059 ,tL060, tL061, tL062, tL063, tL064, tL065, tL066, tL067, tL068, tL069 ,tL070, tL071, tL072, tL073, tL074, tL075, tL076, tL077, tL078, tL079 ,tL080, tL081, tL082, tL083, tL084, tL085, tL086, tL087, tL088, tL089 ,tL090, tL091, tL092, tL093, tL094, tL095, tL096, tL097, tL098, tL099 ,tL100, tL101, tL102, tL103, tL104, tL105, tL106, tL107, tL108, tL109 ,tL110, tL111, tL112, tL113, tL114, tL115, tL116, tL117, tL118, tL119 ,tL120, tL121, tL122, tL123, tL124, tL125, tL126, tL127, tL128, tL129 ,tL130, tL131, tL132, tL133, tL134, tL135, tL136, tL137, tL138, tL139 ,tL140, tL141, tL142, tL143, tL144, tL145, tL146, tL147, tL148, tL149 ,tL150, tL151, tL152, tL153, tL154, tL155, tL156, tL157, tL158, tL159 ,tL160, tL161, tL162, tL163, tL164, tL165, tL166, tL167, tL168, tL169 ,tL170, tL171, tL172, tL173, tL174, tL175, tL176, tL177, tL178, tL179 ,tL180, tL181, tL182, tL183, tL184, tL185, tL186, tL187, tL188, tL189 ,tL190, tL191, tL192, tL193, tL194, tL195, tL196, tL197, tL198, tL199 ,tL200, tL201, tL202, tL203, tL204, tL205, tL206, tL207, tL208, tL209 ,tL210, tL211, tL212, tL213, tL214, tL215, tL216, tL217, tL218, tL219 ,tL220, tL221, tL222, tL223, tL224, tL225, tL226, tL227, tL228, tL229 ,tL230, tL231, tL232, tL233}; static const int * const nRT[nLay]={ tR001, tR002, tR003, tR004, tR005, tR006, tR007, tR008, tR009 ,tR010, tR011, tR012, tR013, tR014, tR015, tR016, tR017, tR018, tR019 ,tR020, tR021, tR022, tR023, tR024, tR025, tR026, tR027, tR028, tR029 ,tR030, tR031, tR032, tR033, tR034, tR035, tR036, tR037, tR038, tR039 ,tR040, tR041, tR042, tR043, tR044, tR045, tR046, tR047, tR048, tR049 ,tR050, tR051, tR052, tR053, tR054, tR055, tR056, tR057, tR058, tR059 ,tR060, tR061, tR062, tR063, tR064, tR065, tR066, tR067, tR068, tR069 ,tR070, tR071, tR072, tR073, tR074, tR075, tR076, tR077, tR078, tR079 ,tR080, tR081, tR082, tR083, tR084, tR085, tR086, tR087, tR088, tR089 ,tR090, tR091, tR092, tR093, tR094, tR095, tR096, tR097, tR098, tR099 ,tR100, tR101, tR102, tR103, tR104, tR105, tR106, tR107, tR108, tR109 ,tR110, tR111, tR112, tR113, tR114, tR115, tR116, tR117, tR118, tR119 ,tR120, tR121, tR122, tR123, tR124, tR125, tR126, tR127, tR128, tR129 ,tR130, tR131, tR132, tR133, tR134, tR135, tR136, tR137, tR138, tR139 ,tR140, tR141, tR142, tR143, tR144, tR145, tR146, tR147, tR148, tR149 ,tR150, tR151, tR152, tR153, tR154, tR155, tR156, tR157, tR158, tR159 ,tR160, tR161, tR162, tR163, tR164, tR165, tR166, tR167, tR168, tR169 ,tR170, tR171, tR172, tR173, tR174, tR175, tR176, tR177, tR178, tR179 ,tR180, tR181, tR182, tR183, tR184, tR185, tR186, tR187, tR188, tR189 ,tR190, tR191, tR192, tR193, tR194, tR195, tR196, tR197, tR198, tR199 ,tR200, tR201, tR202, tR203, tR204, tR205, tR206, tR207, tR208, tR209 ,tR210, tR211, tR212, tR213, tR214, tR215, tR216, tR217, tR218, tR219 ,tR220, tR221, tR222, tR223, tR224, tR225, tR226, tR227, tR228, tR229 ,tR230, tR231, tR232, tR233}; /* // The following are differences in the Source tube positions(not used so far) // *** At present for all widgets the F01 is used (@@ to be developed M.K.) static const int nS=31; // a # of the source tubes in the widget // 0 - H(Long), 1 - E(Short) // 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 // 1 1 2 2 3 3 4 5 6 7 8 9 0 1 2 2 3 4 4 5 5 6 6 7 8 9 0 1 2 3 4 // A B A B A B A B A B A B A B static const int F01[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F02[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F03[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,1,1,1,0,0,0}; static const int F04[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F05[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F06[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F07[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F08[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F09[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F10[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F11[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F12[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F13[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F14[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F15[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int F16[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int F17[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int F18[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0}; static const int B01[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B02[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B03[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B04[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B05[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B06[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B07[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B08[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B09[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B10[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B11[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B12[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B13[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B14[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; static const int B15[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B16[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B17[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static const int B18[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0}; */ static const double cellSize = 0.5*CLHEP::cm; // 0.5 cm is the cell size if (!(xl > 0.)) xl=-xl; double fx=xl/cellSize; int ny=static_cast<int>((yl-yMin)/cellSize); // Layer number (starting from 0) if (ny < 0 || ny >= nLay) // Sould never happen as was checked beforehand { #ifdef DebugLog edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: " << "check limits y = " << yl << ", nL=" << nLay; #endif return 0; } int nx=static_cast<int>(fx); // Cell number (starting from 0) #ifdef DebugLog double phis=atan2(xl, yl)/CLHEP::deg; double zv = pe_effect.z(); // Z in global system edm::LogInfo("HFShower") << "HFFibreFiducial::PMTNumber:X = " << xv << ", Y = " << yv << ", Z = " << zv << ", fX = " << fx << "-> nX = " << nx << ", nY = " << ny << ", mX = " << nSL[ny] << ", x = " << xl << ", y = " << yl << ", s = " << cellSize << ", nW = " << nwid << ", phi = " << phi/CLHEP::deg << ", phis = " << phis << ", phir = " << phir/CLHEP::deg; #endif if (nx >= nSL[ny]) { #ifdef DebugLog edm::LogInfo("HFShower") << "HFFibreFiducial::nx/ny (" << nx << "," << ny <<") " << " above limit " << nSL[ny]; #endif return 0; // ===> out of the acceptance } int code=0; // a prototype if (left) code=nLT[ny][nx]; else code=nRT[ny][nx]; int flag= code%10; int npmt= code/10; bool src= false; // by default: not a source-tube #ifdef DebugLog edm::LogInfo("HFShower") << "HFFibreFiducial::nx/ny (" << nx << "," << ny << ") code/flag/npmt " << code << "/" << flag << "/" << npmt; #endif if (!flag) return 0; // ===> no fiber in the cell else if (flag==1) npmt += 24; else if (flag==3 || flag==4) { src=true; } #ifdef DebugLog edm::LogInfo("HFShower") << "HFFibreFiducial::PMTNumber: src = " << src << ", npmt =" << npmt; #endif if (src) return -npmt; // return the negative number for the source return npmt; } // End of PMTNumber
107,073
70,399
#include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; int main() { vector<int> u(10, 100); vector<int> v; // the code throws an error if we use v.begin() // copy(u.begin(), u.end(), v.begin()); return 0; }
265
103
#include <mylib/mylib.h> int main(int argc, char *argv[]) { mylib::MyLibInstance.get_lib_state(); mylib::MyLibInstance.switch_lib_state(); return 0; }
165
66
/* * Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "crypto.h" #ifdef SGX_ENCLAVE #include "enclave_log.h" #else #include "app_log.h" #endif #include <string.h> bool ecdsa_sign(const uint8_t* data, size_t data_size, EC_KEY* ec_key, ecdsa_bin_signature_t* out_sig) { sha256_data_t digest = {0}; const BIGNUM *bn_r = NULL; const BIGNUM *bn_s = NULL; ECDSA_SIG *ecdsa_sig = NULL; bool retval = false; int bn_r_size = 0; int bn_s_size = 0; if (data == NULL || data_size == 0 || ec_key == NULL || out_sig == NULL) { PRINT(ERROR, CRYPTO, "wrong input parameters\n"); return false; } if (data_size > MAX_CRYPTO_BUFFER_SIZE) { PRINT(ERROR, CRYPTO, "buffer size is too big\n"); return false; } do { if (SHA256(data, data_size, digest) == NULL) { PRINT(ERROR, CRYPTO, "SHA256 failed\n"); break;; } //PRINT(INFO, CRYPTO, "ecdsa_sign SHA256 diget:\n"); //print_byte_array(digest, SHA256_DIGEST_LENGTH); ecdsa_sig = ECDSA_do_sign(digest, sizeof(sha256_data_t), ec_key); if (ecdsa_sig == NULL) { PRINT(ERROR, CRYPTO, "ECDSA_do_sign failed\n"); break; } ECDSA_SIG_get0(ecdsa_sig, &bn_r, &bn_s); if (bn_r == NULL || bn_s == NULL) { PRINT(ERROR, CRYPTO, "ECDSA_SIG_get0 failed\n"); break; } bn_r_size = BN_num_bytes(bn_r); if (bn_r_size > ECDSA_BIN_ELEMENT_SIZE) { PRINT(ERROR, CRYPTO, "bn_r number is too long, %d bytes instead of %d\n", bn_r_size, ECDSA_BIN_ELEMENT_SIZE); break; } bn_s_size = BN_num_bytes(bn_s); if (bn_s_size > ECDSA_BIN_ELEMENT_SIZE) { PRINT(ERROR, CRYPTO, "bn_s number is too long, %d bytes instead of %d\n", bn_s_size, ECDSA_BIN_ELEMENT_SIZE); break; } memset_s(out_sig, sizeof(ecdsa_bin_signature_t), 0, sizeof(ecdsa_bin_signature_t)); // if the size is 32 bytes, it will start at offset 0, 31 will start in offset 1 (leaving the first byte as 0) etc. if (BN_bn2bin(bn_r, &out_sig->r[ECDSA_BIN_ELEMENT_SIZE - bn_r_size]) != bn_r_size) { PRINT(ERROR, CRYPTO, "BN_bn2bin failed\n"); break; } if (BN_bn2bin(bn_s, &out_sig->s[ECDSA_BIN_ELEMENT_SIZE - bn_s_size]) != bn_s_size) { PRINT(ERROR, CRYPTO, "BN_bn2bin failed\n"); break; } retval = true; } while(0); if (ecdsa_sig != NULL) ECDSA_SIG_free(ecdsa_sig); return retval; } bool ecdsa_verify(const uint8_t* data, size_t data_size, EC_KEY* ec_key, const ecdsa_bin_signature_t* in_sig) { sha256_data_t digest = {0}; BIGNUM *bn_r = NULL; BIGNUM *bn_s = NULL; ECDSA_SIG *ecdsa_sig = NULL; bool retval = false; int ret = 0; if (data == NULL || data_size == 0 || ec_key == NULL || in_sig == NULL) { PRINT(ERROR, CRYPTO, "wrong input parameters\n"); return false; } if (data_size > MAX_CRYPTO_BUFFER_SIZE) { PRINT(ERROR, CRYPTO, "buffer size is too big\n"); return false; } do { if (SHA256(data, data_size, digest) == NULL) { PRINT(ERROR, CRYPTO, "SHA256 failed\n"); break; } bn_r = BN_bin2bn(in_sig->r, sizeof(ecdsa_bin_element_t), NULL); if (bn_r == NULL) { PRINT(ERROR, CRYPTO, "BN_bin2bn failed\n"); break; } bn_s = BN_bin2bn(in_sig->s, sizeof(ecdsa_bin_element_t), NULL); if (bn_s == NULL) { PRINT(ERROR, CRYPTO, "BN_bin2bn failed\n"); break; } if (BN_is_zero(bn_r) == 1 || BN_is_zero(bn_s) == 1) { PRINT(ERROR, CRYPTO, "signature is empty, data is not signed!\n"); break; } ecdsa_sig = ECDSA_SIG_new(); if (ecdsa_sig == NULL) { PRINT(ERROR, CRYPTO, "ECDSA_SIG_new failed\n"); break; } // sets r and s values of ecdsa_sig // calling this function transfers the memory management of the values to the ECDSA_SIG object, // and therefore the values that have been passed in should not be freed directly after this function has been called if (ECDSA_SIG_set0(ecdsa_sig, bn_r, bn_s) != 1) { PRINT(ERROR, CRYPTO, "ECDSA_SIG_set0 failed\n"); break; } bn_r = NULL; bn_s = NULL; ret = ECDSA_do_verify(digest, sizeof(sha256_data_t), ecdsa_sig, ec_key); if (ret != 1) { PRINT_CRYPTO_ERROR("ECDSA_do_verify"); break; } retval = true; } while (0); if (ecdsa_sig != NULL) ECDSA_SIG_free(ecdsa_sig); if (bn_r != NULL) BN_clear_free(bn_r); if (bn_s != NULL) BN_clear_free(bn_s); return retval; }
4,842
2,372
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main(){ int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; n--; unsigned long int sumThrees = n/3, sumFives = n/5, sumFifteens = n/15; sumThrees = 3 * sumThrees * (sumThrees + 1) >> 1; sumFives = 5 * sumFives * (sumFives + 1) >> 1; sumFifteens = 15 * sumFifteens * (sumFifteens + 1) >> 1; unsigned long int sum = sumThrees + sumFives - sumFifteens; cout << sum << endl; } return 0; } //https://www.hackerrank.com/contests/projecteuler/challenges/euler001
1,008
392
#include <QmlNet/types/NetSignalInfo.h> #include <QmlNet/qml/NetValueMetaObjectPacker.h> #include <QmlNetUtilities.h> NetSignalInfo::NetSignalInfo(QSharedPointer<NetTypeInfo> parentType, QString name) : _parentType(parentType), _name(name) { } QSharedPointer<NetTypeInfo> NetSignalInfo::getParentType() { return _parentType; } QString NetSignalInfo::getName() { return _name; } void NetSignalInfo::addParameter(NetVariantTypeEnum type) { if(type == NetVariantTypeEnum_Invalid) return; _parameters.append(type); } int NetSignalInfo::getParameterCount() { return _parameters.size(); } NetVariantTypeEnum NetSignalInfo::getParameter(int index) { if(index < 0) return NetVariantTypeEnum_Invalid; if(index >= _parameters.length()) return NetVariantTypeEnum_Invalid; return _parameters.at(index); } QString NetSignalInfo::getSignature() { QString signature = _name; signature.append("("); for(int parameterIndex = 0; parameterIndex <= _parameters.size() - 1; parameterIndex++) { if(parameterIndex > 0) { signature.append(","); } signature.append(NetMetaValueQmlType(_parameters.at(parameterIndex))); } signature.append(")"); return signature; } QString NetSignalInfo::getSlotSignature() { QString signature = _name; signature.append("_internal_slot_for_net_del("); if(_parameters.size() > 0) { for(int parameterIndex = 0; parameterIndex <= _parameters.size() - 1; parameterIndex++) { if(parameterIndex > 0) { signature.append(","); } signature.append(NetMetaValueQmlType(_parameters.at(parameterIndex))); } } signature.append(")"); return signature; } extern "C" { Q_DECL_EXPORT NetSignalInfoContainer* signal_info_create(NetTypeInfoContainer* parentTypeContainer, LPWSTR name) { NetSignalInfoContainer* result = new NetSignalInfoContainer(); NetSignalInfo* instance = new NetSignalInfo(parentTypeContainer->netTypeInfo, QString::fromUtf16((const char16_t*)name)); result->signal = QSharedPointer<NetSignalInfo>(instance); return result; } Q_DECL_EXPORT void signal_info_destroy(NetSignalInfoContainer* container) { delete container; } Q_DECL_EXPORT NetTypeInfoContainer* signal_info_getParentType(NetSignalInfoContainer* container) { NetTypeInfoContainer* result = new NetTypeInfoContainer{container->signal->getParentType()}; return result; } Q_DECL_EXPORT QmlNetStringContainer* signal_info_getName(NetSignalInfoContainer* container) { QString result = container->signal->getName(); return createString(result); } Q_DECL_EXPORT void signal_info_addParameter(NetSignalInfoContainer* container, NetVariantTypeEnum type) { container->signal->addParameter(type); } Q_DECL_EXPORT int signal_info_getParameterCount(NetSignalInfoContainer* container) { return container->signal->getParameterCount(); } Q_DECL_EXPORT NetVariantTypeEnum signal_info_getParameter(NetSignalInfoContainer* container, int index) { return container->signal->getParameter(index); } }
3,127
983
#include "Brier.h" #include "../Variables/Variable.h" #include "../Distribution.h" #include "../Obs.h" #include "../Data.h" #include <iomanip> MetricBrier::MetricBrier(const Options& iOptions, const Data& iData) : Metric(iOptions, iData), mAnomaly(false), mAnomalyAbove(false), mAnomalyBelow(false) { // Should anomaly threshold be used? I.e. Does the forecast/obs exceed a certain amount // (threshold) above or below the climatological mean? iOptions.getValue("anomaly", mAnomaly); iOptions.getValue("anomalyAbove", mAnomalyAbove); iOptions.getValue("anomalyBelow", mAnomalyBelow); iOptions.getRequiredValue("threshold", mThreshold); if(mAnomalyAbove || mAnomalyBelow) { if(mAnomaly) Global::logger->write("MetricBrier: Both 'anomaly' and one of 'anomalyAbove' or 'anomalyBelow' where specified, which is redundant.", Logger::warning); mAnomaly = true; } if(mAnomaly && !mAnomalyBelow && !mAnomalyAbove) { // If only 'anomaly' was specified mAnomalyAbove = true; mAnomalyBelow = true; } iOptions.check(); } float MetricBrier::computeCore(const Obs& iObs, const Distribution::ptr iForecast) const { float obs = iObs.getValue(); // Part1: Compute probability that obs is beyond threshold float P = Global::MV; bool isBeyond; // Is the obs above threshold, or more anomalous than mThreshold? if(mAnomaly) { // Find climatological value at day of year corresponding to obs float clim = mData.getClim(iObs.getDate(), 0, iObs.getOffset(), iObs.getLocation(), iObs.getVariable()); if(!Global::isValid(clim)) { return Global::MV; } // Probability that obs is further away from clim than mThreshold float lower = clim-mThreshold; float upper = clim+mThreshold; // Check if we are within the variables range const Variable* var = Variable::get(iObs.getVariable()); if(Global::isValid(var->getMin()) && lower < var->getMin()) lower = var->getMin(); if(Global::isValid(var->getMax()) && upper > var->getMax()) lower = var->getMax(); float P0 = 0; float P1 = 0; isBeyond = false; if(mAnomalyBelow) { P0 = iForecast->getCdf(lower); // Prob that obs is anomalously low isBeyond = isBeyond || (obs < lower); } if(mAnomalyAbove) { P1 = 1 - iForecast->getCdf(upper); // Prob that obs is anomalously high isBeyond = isBeyond || (obs > upper); } P = P1 + P0; } else { P = iForecast->getCdf(mThreshold); if(!Global::isValid(P)) { return Global::MV; } P = 1 - P; isBeyond = (obs > mThreshold); } // Part 2: Compute score float brier = Global::MV; if(Global::isValid(obs) && Global::isValid(P)) { if(isBeyond) brier = (1-P)*(1-P); else brier = P*P; } return brier; }
2,936
1,031
#include <iostream> long long get_fibonaccihuge(long long n, long long m) { //write your code here return 0; } int main() { long long n, m; std::cin >> n >> m; std::cout << get_fibonaccihuge(n, m) << '\n'; }
226
93
#ifndef CONVERT_SIMTK_VEC3_HPP #define CONVERT_SIMTK_VEC3_HPP void register_simtk_vec3_conversion(); #endif // CONVERT_SIMTK_STRING_HPP
138
68
/** ** @file ScriptedTask.cpp */ /* ** Copyright (c) 2014, GCBLUE PROJECT ** 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 "stdwx.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "ai/ScriptedTask.h" #include "scriptinterface/tcSimPythonInterface.h" #include "tcGameStream.h" #ifdef _DEBUG #define new DEBUG_NEW #endif using namespace ai; using scriptinterface::tcSimPythonInterface; /** * Read from stream */ tcGameStream& ScriptedTask::operator<<(tcGameStream& stream) { Task::operator<<(stream); stream >> commandString; { textMemory.clear(); unsigned int nTextMemory; stream >> nTextMemory; for (unsigned int n=0; n<nTextMemory; n++) { std::string s1; std::string s2; stream >> s1; stream >> s2; textMemory[s1] = s2; } stream.ReadCheckValue(8961); } { numberMemory.clear(); unsigned int nNumberMemory; stream >> nNumberMemory; for (unsigned int n=0; n<nNumberMemory; n++) { int val_int; double val_double; stream >> val_int; stream >> val_double; numberMemory[val_int] = val_double; } stream.ReadCheckValue(1530); } return stream; } /** * Write to stream */ tcGameStream& ScriptedTask::operator>>(tcGameStream& stream) { Task::operator>>(stream); stream << commandString; { unsigned int nTextMemory = textMemory.size(); stream << nTextMemory; for (std::map<std::string, std::string>::iterator iter = textMemory.begin(); iter != textMemory.end(); ++iter) { stream << iter->first; stream << iter->second; } stream.WriteCheckValue(8961); } { unsigned int nNumberMemory = numberMemory.size(); stream << nNumberMemory; for (std::map<int, double>::iterator iter = numberMemory.begin(); iter != numberMemory.end(); ++iter) { stream << (int)iter->first; stream << (double)iter->second; } stream.WriteCheckValue(1530); } return stream; } /** * @return "" if no key exists */ const std::string& ScriptedTask::GetMemoryText(const std::string& key) { // returned if key not found static const std::string emptyString(""); std::map<std::string, std::string>::const_iterator iter = textMemory.find(key); if (iter != textMemory.end()) { return iter->second; } else { return emptyString; } } void ScriptedTask::SetMemoryText(const std::string& key, const std::string& text) { textMemory[key] = text; } /** * @return 0 if no key exists */ double ScriptedTask::GetMemoryValue(int key) { std::map<int, double>::const_iterator iter = numberMemory.find(key); if (iter != numberMemory.end()) { return iter->second; } else { return 0; } } void ScriptedTask::SetMemoryValue(int key, double value) { numberMemory[key] = value; } const char* ScriptedTask::GetCommandString() { if (commandString.size()) { return commandString.c_str(); } else { commandString = wxString::Format("AI.%s(TaskInterface)\n", taskName.c_str()); return commandString.c_str(); } } void ScriptedTask::Update(double t) { if (IsReadyForUpdate(t)) { bool success = tcSimPythonInterface::Get()->CallTaskScript(this, GetCommandString()); FinishUpdate(t); if (!success) { fprintf(stderr, "Deleting task that errored (%s)\n", GetTaskName().c_str()); EndTask(); } } } ScriptedTask::ScriptedTask(tcPlatformObject* platform_, Blackboard* bb, long id_, double priority_, int attributes_, const std::string& scriptName) : Task(platform_, bb, id_, priority_, attributes_, scriptName) { } ScriptedTask::~ScriptedTask() { }
5,549
1,787
/* * Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Note: wglew.h has to be included before sutil.h on Windows #include <sutil/sutil.h> //#include <sutil/PPMLoader.h> #include <sampleConfig.h> #include <optixu/optixu_math_namespace.h> #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <stdint.h> #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif # include<windows.h> # include<mmsystem.h> #else // Apple and Linux both use this # include<sys/time.h> # include <unistd.h> # include <dirent.h> #endif using namespace optix; namespace { // Global variables for GLUT display functions RTcontext g_context = 0; RTbuffer g_image_buffer = 0; void checkBuffer( RTbuffer buffer ) { // Check to see if the buffer is two dimensional unsigned int dimensionality; RT_CHECK_ERROR( rtBufferGetDimensionality(buffer, &dimensionality) ); if (2 != dimensionality) throw Exception( "Attempting to display non-2D buffer" ); // Check to see if the buffer is of type float{1,3,4} or uchar4 RTformat format; RT_CHECK_ERROR( rtBufferGetFormat(buffer, &format) ); if( RT_FORMAT_FLOAT != format && RT_FORMAT_FLOAT4 != format && RT_FORMAT_FLOAT3 != format && RT_FORMAT_UNSIGNED_BYTE4 != format ) throw Exception( "Attempting to diaplay buffer with format not float, float3, float4, or uchar4"); } bool dirExists( const char* path ) { #if defined(_WIN32) DWORD attrib = GetFileAttributes( path ); return (attrib != INVALID_FILE_ATTRIBUTES) && (attrib & FILE_ATTRIBUTE_DIRECTORY); #else DIR* dir = opendir( path ); if( dir == NULL ) return false; closedir(dir); return true; #endif } } // end anonymous namespace void sutil::reportErrorMessage( const char* message ) { std::cerr << "OptiX Error: '" << message << "'\n"; #if defined(_WIN32) && defined(RELEASE_PUBLIC) { char s[2048]; sprintf( s, "OptiX Error: %s", message ); MessageBox( 0, s, "OptiX Error", MB_OK|MB_ICONWARNING|MB_SYSTEMMODAL ); } #endif } void sutil::handleError( RTcontext context, RTresult code, const char* file, int line) { const char* message; char s[2048]; rtContextGetErrorString(context, code, &message); sprintf(s, "%s\n(%s:%d)", message, file, line); reportErrorMessage( s ); } const char* sutil::samplesDir() { static char s[512]; // Allow for overrides. const char* dir = getenv( "OPTIX_SAMPLES_SDK_DIR" ); if (dir) { strcpy(s, dir); return s; } // Return hardcoded path if it exists. if( dirExists( SAMPLES_DIR ) ) return SAMPLES_DIR; // Last resort. return "."; } const char* sutil::samplesPTXDir() { static char s[512]; // Allow for overrides. const char* dir = getenv( "OPTIX_SAMPLES_SDK_PTX_DIR" ); if (dir) { strcpy(s, dir); return s; } // Return hardcoded path if it exists. if( dirExists(SAMPLES_PTX_DIR) ) return SAMPLES_PTX_DIR; // Last resort. return "."; } optix::Buffer sutil::createOutputBuffer( optix::Context context, RTformat format, unsigned width, unsigned height, bool use_pbo ) { optix::Buffer buffer; buffer = context->createBuffer( RT_BUFFER_OUTPUT, format, width, height ); return buffer; } optix::GeometryInstance sutil::createOptiXGroundPlane( optix::Context context, const std::string& parallelogram_ptx, const optix::Aabb& aabb, optix::Material material, float scale ) { optix::Geometry parallelogram = context->createGeometry(); parallelogram->setPrimitiveCount( 1u ); parallelogram->setBoundingBoxProgram( context->createProgramFromPTXFile( parallelogram_ptx, "bounds" ) ); parallelogram->setIntersectionProgram( context->createProgramFromPTXFile( parallelogram_ptx, "intersect" ) ); const float extent = scale*fmaxf( aabb.extent( 0 ), aabb.extent( 2 ) ); const float3 anchor = make_float3( aabb.center(0) - 0.5f*extent, aabb.m_min.y - 0.001f*aabb.extent( 1 ), aabb.center(2) - 0.5f*extent ); float3 v1 = make_float3( 0.0f, 0.0f, extent ); float3 v2 = make_float3( extent, 0.0f, 0.0f ); const float3 normal = normalize( cross( v1, v2 ) ); float d = dot( normal, anchor ); v1 *= 1.0f / dot( v1, v1 ); v2 *= 1.0f / dot( v2, v2 ); float4 plane = make_float4( normal, d ); parallelogram["plane"]->setFloat( plane ); parallelogram["v1"]->setFloat( v1 ); parallelogram["v2"]->setFloat( v2 ); parallelogram["anchor"]->setFloat( anchor ); optix::GeometryInstance instance = context->createGeometryInstance( parallelogram, &material, &material + 1 ); return instance; } void sutil::calculateCameraVariables( float3 eye, float3 lookat, float3 up, float fov, float aspect_ratio, float3& U, float3& V, float3& W, bool fov_is_vertical ) { float ulen, vlen, wlen; W = lookat - eye; // Do not normalize W -- it implies focal length wlen = length( W ); U = normalize( cross( W, up ) ); V = normalize( cross( U, W ) ); if ( fov_is_vertical ) { vlen = wlen * tanf( 0.5f * fov * M_PIf / 180.0f ); V *= vlen; ulen = vlen * aspect_ratio; U *= ulen; } else { ulen = wlen * tanf( 0.5f * fov * M_PIf / 180.0f ); U *= ulen; vlen = ulen / aspect_ratio; V *= vlen; } } void sutil::parseDimensions( const char* arg, int& width, int& height ) { // look for an 'x': <width>x<height> size_t width_end = strchr( arg, 'x' ) - arg; size_t height_begin = width_end + 1; if ( height_begin < strlen( arg ) ) { // find the beginning of the height string/ const char *height_arg = &arg[height_begin]; // copy width to null-terminated string char width_arg[32]; strncpy( width_arg, arg, width_end ); width_arg[width_end] = '\0'; // terminate the width string width_arg[width_end] = '\0'; width = atoi( width_arg ); height = atoi( height_arg ); return; } throw Exception( "Failed to parse width, heigh from string '" + std::string( arg ) + "'" ); } double sutil::currentTime() { #if defined(_WIN32) // inv_freq is 1 over the number of ticks per second. static double inv_freq; static bool freq_initialized = 0; static bool use_high_res_timer = 0; if(!freq_initialized) { LARGE_INTEGER freq; use_high_res_timer = ( QueryPerformanceFrequency( &freq ) != 0 ); inv_freq = 1.0/freq.QuadPart; freq_initialized = 1; } if (use_high_res_timer) { LARGE_INTEGER c_time; if( QueryPerformanceCounter( &c_time ) ) return c_time.QuadPart*inv_freq; else throw Exception( "sutil::currentTime: QueryPerformanceCounter failed" ); } return static_cast<double>( timeGetTime() ) * 1.0e-3; #else struct timeval tv; if( gettimeofday( &tv, 0 ) ) throw Exception( "sutil::urrentTime(): gettimeofday failed!\n" ); return tv.tv_sec+ tv.tv_usec * 1.0e-6; #endif } void sutil::sleep( int seconds ) { #if defined(_WIN32) Sleep( seconds * 1000 ); #else ::sleep( seconds ); #endif }
9,074
3,269
/* <LICENSE> License for the MULTOVL multiple genomic overlap tools Copyright (c) 2007-2012, Dr Andras Aszodi, Campus Science Support Facilities GmbH (CSF), Dr-Bohr-Gasse 3, A-1030 Vienna, Austria, Europe. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Campus Science Support Facilities GmbH 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. </LICENSE> */ // == MODULE classicopts.cc == // -- Standard headers -- #include <algorithm> // -- Own header -- #include "classicopts.hh" #include "thirdparty.h" // -- Boost headers -- #include "boost/algorithm/string/case_conv.hpp" // == Implementation == namespace multovl { ClassicOpts::ClassicOpts(): MultovlOptbase() { add_option<std::string>("source", &_source, "multovl", "Source field in GFF output", 's'); add_option<std::string>("outformat", &_outformat, "GFF", "Output format {BED,GFF}, case-insensitive, default GFF", 'f'); add_option<std::string>("save", &_saveto, "", "Save program data to archive file, default: do not save"); add_option<std::string>("load", &_loadfrom, "", "Load program data from archive file, default: do not load"); } bool ClassicOpts::check_variables() { MultovlOptbase::check_variables(); // canonicalize the output format: currently BED and GFF are accepted boost::algorithm::to_upper(_outformat); if (_outformat != "BED" && _outformat != "GFF") _outformat = "GFF"; // default // there must be at least 1 positional param // unless --load has been set in which case // all input comes from the archive unsigned int filecnt = pos_opts().size(); if (_loadfrom == "" && filecnt < 1) { add_error("Must specify at least one input file"); } return (!error_status()); } std::string ClassicOpts::param_str() const { std::string outstr = MultovlOptbase::param_str(); outstr += " -s " + _source + " -f " + _outformat; if (_loadfrom != "") outstr += " --load " + _loadfrom; if (_saveto != "") outstr += " --save " + _saveto; return outstr; } std::ostream& ClassicOpts::print_help(std::ostream& out) const { out << "Multiple Chromosome / Multiple Region Overlaps" << std::endl << "Usage: multovl [options] [<infile1> [ <infile2> ... ]]" << std::endl << "Accepted input file formats: BED, GFF/GTF" ; if (config_have_bamtools()) { out << ", BAM"; } out << " (detected from extension)" << std::endl << "<infileX> arguments are ignored if --load is set" << std::endl << "Output goes to stdout, select format with the -f option" << std::endl; Polite::print_help(out); return out; } } // namespace multovl
3,990
1,367
/* Generated code for Python source for module 'requests.status_codes' * created by Nuitka version 0.5.28.2 * * This code is in part copyright 2017 Kay Hayen. * * 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 "nuitka/prelude.h" #include "__helpers.h" /* The _module_requests$status_codes is a Python object pointer of module type. */ /* Note: For full compatibility with CPython, every module variable access * needs to go through it except for cases where the module cannot possibly * have changed in the mean time. */ PyObject *module_requests$status_codes; PyDictObject *moduledict_requests$status_codes; /* The module constants used, if any. */ extern PyObject *const_str_plain_status_codes; static PyObject *const_tuple_str_plain_LookupDict_tuple; static PyObject *const_str_plain__codes; extern PyObject *const_str_plain_ModuleSpec; extern PyObject *const_str_plain___spec__; extern PyObject *const_str_plain___package__; extern PyObject *const_str_chr_47; extern PyObject *const_str_plain_requests; extern PyObject *const_int_pos_1; extern PyObject *const_str_plain___file__; static PyObject *const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple; extern PyObject *const_str_plain_upper; extern PyObject *const_str_plain_code; extern PyObject *const_str_plain_codes; static PyObject *const_str_digest_840f3e0b846ec96891b7f18eb56afcd8; extern PyObject *const_tuple_str_chr_92_str_chr_47_tuple; extern PyObject *const_str_plain_items; static PyObject *const_str_digest_ac287d930ccff60e2a2e6a9bf4946046; static PyObject *const_dict_35dd1864798a043a10ec23eaefcf5219; extern PyObject *const_tuple_empty; static PyObject *const_dict_38252060f20256dc080a28c7e1fb8512; extern PyObject *const_str_plain_LookupDict; extern PyObject *const_str_plain_structures; extern PyObject *const_str_plain_title; extern PyObject *const_str_plain___loader__; static PyObject *const_str_digest_e26a01ee85033c35e44f056d847dbade; static PyObject *const_str_plain_titles; extern PyObject *const_str_plain_startswith; extern PyObject *const_str_plain_name; extern PyObject *const_str_chr_92; extern PyObject *const_str_plain___doc__; extern PyObject *const_str_plain___cached__; static PyObject *module_filename_obj; static bool constants_created = false; static void createModuleConstants( void ) { const_tuple_str_plain_LookupDict_tuple = PyTuple_New( 1 ); PyTuple_SET_ITEM( const_tuple_str_plain_LookupDict_tuple, 0, const_str_plain_LookupDict ); Py_INCREF( const_str_plain_LookupDict ); const_str_plain__codes = UNSTREAM_STRING( &constant_bin[ 71 ], 6, 1 ); const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple = PyTuple_New( 1 ); PyTuple_SET_ITEM( const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple, 0, const_tuple_str_chr_92_str_chr_47_tuple ); Py_INCREF( const_tuple_str_chr_92_str_chr_47_tuple ); const_str_digest_840f3e0b846ec96891b7f18eb56afcd8 = UNSTREAM_STRING( &constant_bin[ 1850620 ], 24, 0 ); const_str_digest_ac287d930ccff60e2a2e6a9bf4946046 = UNSTREAM_STRING( &constant_bin[ 1850644 ], 21, 0 ); const_dict_35dd1864798a043a10ec23eaefcf5219 = PyMarshal_ReadObjectFromString( (char *)&constant_bin[ 1850665 ], 2348 ); const_dict_38252060f20256dc080a28c7e1fb8512 = _PyDict_NewPresized( 1 ); PyDict_SetItem( const_dict_38252060f20256dc080a28c7e1fb8512, const_str_plain_name, const_str_plain_status_codes ); assert( PyDict_Size( const_dict_38252060f20256dc080a28c7e1fb8512 ) == 1 ); const_str_digest_e26a01ee85033c35e44f056d847dbade = UNSTREAM_STRING( &constant_bin[ 1853013 ], 30, 0 ); const_str_plain_titles = UNSTREAM_STRING( &constant_bin[ 1487553 ], 6, 1 ); constants_created = true; } #ifndef __NUITKA_NO_ASSERT__ void checkModuleConstants_requests$status_codes( void ) { // The module may not have been used at all. if (constants_created == false) return; } #endif // The module code objects. static PyCodeObject *codeobj_caa175f940b5d1e60f5a0891c7d91121; static void createModuleCodeObjects(void) { module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_840f3e0b846ec96891b7f18eb56afcd8 ); codeobj_caa175f940b5d1e60f5a0891c7d91121 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_e26a01ee85033c35e44f056d847dbade, 1, const_tuple_empty, 0, 0, CO_NOFREE ); } // The module function declarations. // The module function definitions. #if PYTHON_VERSION >= 300 static struct PyModuleDef mdef_requests$status_codes = { PyModuleDef_HEAD_INIT, "requests.status_codes", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PYTHON_VERSION >= 300 extern PyObject *metapath_based_loader; #endif #if PYTHON_VERSION >= 330 extern PyObject *const_str_plain___loader__; #endif extern void _initCompiledCellType(); extern void _initCompiledGeneratorType(); extern void _initCompiledFunctionType(); extern void _initCompiledMethodType(); extern void _initCompiledFrameType(); #if PYTHON_VERSION >= 350 extern void _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 extern void _initCompiledAsyncgenTypes(); #endif // The exported interface to CPython. On import of the module, this function // gets called. It has to have an exact function name, in cases it's a shared // library export. This is hidden behind the MOD_INIT_DECL. MOD_INIT_DECL( requests$status_codes ) { #if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300 static bool _init_done = false; // Modules might be imported repeatedly, which is to be ignored. if ( _init_done ) { return MOD_RETURN_VALUE( module_requests$status_codes ); } else { _init_done = true; } #endif #ifdef _NUITKA_MODULE // In case of a stand alone extension module, need to call initialization // the init here because that's the first and only time we are going to get // called here. // Initialize the constant values used. _initBuiltinModule(); createGlobalConstants(); /* Initialize the compiled types of Nuitka. */ _initCompiledCellType(); _initCompiledGeneratorType(); _initCompiledFunctionType(); _initCompiledMethodType(); _initCompiledFrameType(); #if PYTHON_VERSION >= 350 _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 _initCompiledAsyncgenTypes(); #endif #if PYTHON_VERSION < 300 _initSlotCompare(); #endif #if PYTHON_VERSION >= 270 _initSlotIternext(); #endif patchBuiltinModule(); patchTypeComparison(); // Enable meta path based loader if not already done. setupMetaPathBasedLoader(); #if PYTHON_VERSION >= 300 patchInspectModule(); #endif #endif /* The constants only used by this module are created now. */ #ifdef _NUITKA_TRACE puts("requests.status_codes: Calling createModuleConstants()."); #endif createModuleConstants(); /* The code objects used by this module are created now. */ #ifdef _NUITKA_TRACE puts("requests.status_codes: Calling createModuleCodeObjects()."); #endif createModuleCodeObjects(); // puts( "in initrequests$status_codes" ); // Create the module object first. There are no methods initially, all are // added dynamically in actual code only. Also no "__doc__" is initially // set at this time, as it could not contain NUL characters this way, they // are instead set in early module code. No "self" for modules, we have no // use for it. #if PYTHON_VERSION < 300 module_requests$status_codes = Py_InitModule4( "requests.status_codes", // Module Name NULL, // No methods initially, all are added // dynamically in actual module code only. NULL, // No __doc__ is initially set, as it could // not contain NUL this way, added early in // actual code. NULL, // No self for modules, we don't use it. PYTHON_API_VERSION ); #else module_requests$status_codes = PyModule_Create( &mdef_requests$status_codes ); #endif moduledict_requests$status_codes = MODULE_DICT( module_requests$status_codes ); CHECK_OBJECT( module_requests$status_codes ); // Seems to work for Python2.7 out of the box, but for Python3, the module // doesn't automatically enter "sys.modules", so do it manually. #if PYTHON_VERSION >= 300 { int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_ac287d930ccff60e2a2e6a9bf4946046, module_requests$status_codes ); assert( r != -1 ); } #endif // For deep importing of a module we need to have "__builtins__", so we set // it ourselves in the same way than CPython does. Note: This must be done // before the frame object is allocated, or else it may fail. if ( GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL ) { PyObject *value = (PyObject *)builtin_module; // Check if main module, not a dict then but the module itself. #if !defined(_NUITKA_EXE) || !0 value = PyModule_GetDict( value ); #endif UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___builtins__, value ); } #if PYTHON_VERSION >= 330 UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader ); #endif // Temp variables if any PyObject *tmp_for_loop_1__for_iterator = NULL; PyObject *tmp_for_loop_1__iter_value = NULL; PyObject *tmp_for_loop_2__for_iterator = NULL; PyObject *tmp_for_loop_2__iter_value = NULL; PyObject *tmp_tuple_unpack_1__element_1 = NULL; PyObject *tmp_tuple_unpack_1__element_2 = NULL; PyObject *tmp_tuple_unpack_1__source_iter = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *exception_keeper_type_4; PyObject *exception_keeper_value_4; PyTracebackObject *exception_keeper_tb_4; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_assign_source_15; PyObject *tmp_assign_source_16; PyObject *tmp_assign_source_17; PyObject *tmp_assign_source_18; PyObject *tmp_assign_source_19; PyObject *tmp_called_instance_1; PyObject *tmp_called_instance_2; PyObject *tmp_called_instance_3; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_fromlist_name_1; PyObject *tmp_globals_name_1; PyObject *tmp_import_name_from_1; PyObject *tmp_iter_arg_1; PyObject *tmp_iter_arg_2; PyObject *tmp_iter_arg_3; PyObject *tmp_iterator_attempt; PyObject *tmp_iterator_name_1; PyObject *tmp_kw_name_1; PyObject *tmp_level_name_1; PyObject *tmp_locals_name_1; PyObject *tmp_name_name_1; PyObject *tmp_next_source_1; PyObject *tmp_next_source_2; PyObject *tmp_setattr_attr_1; PyObject *tmp_setattr_attr_2; PyObject *tmp_setattr_target_1; PyObject *tmp_setattr_target_2; PyObject *tmp_setattr_value_1; PyObject *tmp_setattr_value_2; PyObject *tmp_unpack_1; PyObject *tmp_unpack_2; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; struct Nuitka_FrameObject *frame_caa175f940b5d1e60f5a0891c7d91121; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; // Module code. tmp_assign_source_1 = Py_None; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 ); tmp_assign_source_2 = module_filename_obj; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 ); tmp_assign_source_3 = metapath_based_loader; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 ); // Frame without reuse. frame_caa175f940b5d1e60f5a0891c7d91121 = MAKE_MODULE_FRAME( codeobj_caa175f940b5d1e60f5a0891c7d91121, module_requests$status_codes ); // Push the new frame as the currently active one, and we should be exclusively // owning it. pushFrameStack( frame_caa175f940b5d1e60f5a0891c7d91121 ); assert( Py_REFCNT( frame_caa175f940b5d1e60f5a0891c7d91121 ) == 2 ); // Framed code: frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("importlib._bootstrap"); if (likely( module != NULL )) { tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec ); } else { tmp_called_name_1 = NULL; } } if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_1 = const_str_digest_ac287d930ccff60e2a2e6a9bf4946046; tmp_args_element_name_2 = metapath_based_loader; frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args ); } if ( tmp_assign_source_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 ); tmp_assign_source_5 = Py_None; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 ); tmp_assign_source_6 = const_str_plain_requests; UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 ); tmp_name_name_1 = const_str_plain_structures; tmp_globals_name_1 = (PyObject *)moduledict_requests$status_codes; tmp_locals_name_1 = Py_None; tmp_fromlist_name_1 = const_tuple_str_plain_LookupDict_tuple; tmp_level_name_1 = const_int_pos_1; frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 3; tmp_import_name_from_1 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 ); if ( tmp_import_name_from_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_LookupDict ); Py_DECREF( tmp_import_name_from_1 ); if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict, tmp_assign_source_7 ); tmp_assign_source_8 = PyDict_Copy( const_dict_35dd1864798a043a10ec23eaefcf5219 ); UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes, tmp_assign_source_8 ); tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict ); if (unlikely( tmp_called_name_2 == NULL )) { tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_LookupDict ); } if ( tmp_called_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "LookupDict" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; goto frame_exception_exit_1; } tmp_kw_name_1 = PyDict_Copy( const_dict_38252060f20256dc080a28c7e1fb8512 ); frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 85; tmp_assign_source_9 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_2, tmp_kw_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_assign_source_9 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes, tmp_assign_source_9 ); tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes ); if (unlikely( tmp_called_instance_1 == NULL )) { tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain__codes ); } if ( tmp_called_instance_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "_codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 87; goto frame_exception_exit_1; } frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 87; tmp_iter_arg_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_items ); if ( tmp_iter_arg_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto frame_exception_exit_1; } tmp_assign_source_10 = MAKE_ITERATOR( tmp_iter_arg_1 ); Py_DECREF( tmp_iter_arg_1 ); if ( tmp_assign_source_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto frame_exception_exit_1; } assert( tmp_for_loop_1__for_iterator == NULL ); tmp_for_loop_1__for_iterator = tmp_assign_source_10; // Tried code: loop_start_1:; tmp_next_source_1 = tmp_for_loop_1__for_iterator; CHECK_OBJECT( tmp_next_source_1 ); tmp_assign_source_11 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_11 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_1; } } { PyObject *old = tmp_for_loop_1__iter_value; tmp_for_loop_1__iter_value = tmp_assign_source_11; Py_XDECREF( old ); } // Tried code: tmp_iter_arg_2 = tmp_for_loop_1__iter_value; CHECK_OBJECT( tmp_iter_arg_2 ); tmp_assign_source_12 = MAKE_ITERATOR( tmp_iter_arg_2 ); if ( tmp_assign_source_12 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_2; } { PyObject *old = tmp_tuple_unpack_1__source_iter; tmp_tuple_unpack_1__source_iter = tmp_assign_source_12; Py_XDECREF( old ); } // Tried code: tmp_unpack_1 = tmp_tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_1 ); tmp_assign_source_13 = UNPACK_NEXT( tmp_unpack_1, 0, 2 ); if ( tmp_assign_source_13 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } exception_lineno = 87; goto try_except_handler_3; } { PyObject *old = tmp_tuple_unpack_1__element_1; tmp_tuple_unpack_1__element_1 = tmp_assign_source_13; Py_XDECREF( old ); } tmp_unpack_2 = tmp_tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_2 ); tmp_assign_source_14 = UNPACK_NEXT( tmp_unpack_2, 1, 2 ); if ( tmp_assign_source_14 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } exception_lineno = 87; goto try_except_handler_3; } { PyObject *old = tmp_tuple_unpack_1__element_2; tmp_tuple_unpack_1__element_2 = tmp_assign_source_14; Py_XDECREF( old ); } tmp_iterator_name_1 = tmp_tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_iterator_name_1 ); // Check if iterator has left-over elements. CHECK_OBJECT( tmp_iterator_name_1 ); assert( HAS_ITERNEXT( tmp_iterator_name_1 ) ); tmp_iterator_attempt = (*Py_TYPE( tmp_iterator_name_1 )->tp_iternext)( tmp_iterator_name_1 ); if (likely( tmp_iterator_attempt == NULL )) { PyObject *error = GET_ERROR_OCCURRED(); if ( error != NULL ) { if ( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration )) { CLEAR_ERROR_OCCURRED(); } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_3; } } } else { Py_DECREF( tmp_iterator_attempt ); // TODO: Could avoid PyErr_Format. #if PYTHON_VERSION < 300 PyErr_Format( PyExc_ValueError, "too many values to unpack" ); #else PyErr_Format( PyExc_ValueError, "too many values to unpack (expected 2)" ); #endif FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_3; } goto try_end_1; // Exception handler code: try_except_handler_3:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_tuple_unpack_1__source_iter ); tmp_tuple_unpack_1__source_iter = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto try_except_handler_2; // End of try: try_end_1:; goto try_end_2; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto try_except_handler_1; // End of try: try_end_2:; Py_XDECREF( tmp_tuple_unpack_1__source_iter ); tmp_tuple_unpack_1__source_iter = NULL; tmp_assign_source_15 = tmp_tuple_unpack_1__element_1; CHECK_OBJECT( tmp_assign_source_15 ); UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code, tmp_assign_source_15 ); Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; tmp_assign_source_16 = tmp_tuple_unpack_1__element_2; CHECK_OBJECT( tmp_assign_source_16 ); UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles, tmp_assign_source_16 ); Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; tmp_iter_arg_3 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles ); if (unlikely( tmp_iter_arg_3 == NULL )) { tmp_iter_arg_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_titles ); } if ( tmp_iter_arg_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "titles" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; goto try_except_handler_1; } tmp_assign_source_17 = MAKE_ITERATOR( tmp_iter_arg_3 ); if ( tmp_assign_source_17 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_1; } { PyObject *old = tmp_for_loop_2__for_iterator; tmp_for_loop_2__for_iterator = tmp_assign_source_17; Py_XDECREF( old ); } // Tried code: loop_start_2:; tmp_next_source_2 = tmp_for_loop_2__for_iterator; CHECK_OBJECT( tmp_next_source_2 ); tmp_assign_source_18 = ITERATOR_NEXT( tmp_next_source_2 ); if ( tmp_assign_source_18 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_2; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_4; } } { PyObject *old = tmp_for_loop_2__iter_value; tmp_for_loop_2__iter_value = tmp_assign_source_18; Py_XDECREF( old ); } tmp_assign_source_19 = tmp_for_loop_2__iter_value; CHECK_OBJECT( tmp_assign_source_19 ); UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title, tmp_assign_source_19 ); tmp_setattr_target_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes ); if (unlikely( tmp_setattr_target_1 == NULL )) { tmp_setattr_target_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes ); } if ( tmp_setattr_target_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_4; } tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_setattr_attr_1 == NULL )) { tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_setattr_attr_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_4; } tmp_setattr_value_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code ); if (unlikely( tmp_setattr_value_1 == NULL )) { tmp_setattr_value_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code ); } if ( tmp_setattr_value_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_4; } tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_1, tmp_setattr_attr_1, tmp_setattr_value_1 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; goto try_except_handler_4; } tmp_called_instance_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_called_instance_2 == NULL )) { tmp_called_instance_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_called_instance_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; goto try_except_handler_4; } frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 90; tmp_cond_value_1 = CALL_METHOD_WITH_ARGS1( tmp_called_instance_2, const_str_plain_startswith, &PyTuple_GET_ITEM( const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple, 0 ) ); if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; goto try_except_handler_4; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 90; goto try_except_handler_4; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_setattr_target_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes ); if (unlikely( tmp_setattr_target_2 == NULL )) { tmp_setattr_target_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes ); } if ( tmp_setattr_target_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; goto try_except_handler_4; } tmp_called_instance_3 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_called_instance_3 == NULL )) { tmp_called_instance_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_called_instance_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; goto try_except_handler_4; } frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 91; tmp_setattr_attr_2 = CALL_METHOD_NO_ARGS( tmp_called_instance_3, const_str_plain_upper ); if ( tmp_setattr_attr_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 91; goto try_except_handler_4; } tmp_setattr_value_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code ); if (unlikely( tmp_setattr_value_2 == NULL )) { tmp_setattr_value_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code ); } if ( tmp_setattr_value_2 == NULL ) { Py_DECREF( tmp_setattr_attr_2 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; goto try_except_handler_4; } tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_2, tmp_setattr_attr_2, tmp_setattr_value_2 ); Py_DECREF( tmp_setattr_attr_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 91; goto try_except_handler_4; } branch_no_1:; if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_4; } goto loop_start_2; loop_end_2:; goto try_end_3; // Exception handler code: try_except_handler_4:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_for_loop_2__iter_value ); tmp_for_loop_2__iter_value = NULL; Py_XDECREF( tmp_for_loop_2__for_iterator ); tmp_for_loop_2__for_iterator = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto try_except_handler_1; // End of try: try_end_3:; Py_XDECREF( tmp_for_loop_2__iter_value ); tmp_for_loop_2__iter_value = NULL; Py_XDECREF( tmp_for_loop_2__for_iterator ); tmp_for_loop_2__for_iterator = NULL; if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_1; } goto loop_start_1; loop_end_1:; goto try_end_4; // Exception handler code: try_except_handler_1:; exception_keeper_type_4 = exception_type; exception_keeper_value_4 = exception_value; exception_keeper_tb_4 = exception_tb; exception_keeper_lineno_4 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_for_loop_1__iter_value ); tmp_for_loop_1__iter_value = NULL; Py_XDECREF( tmp_for_loop_1__for_iterator ); tmp_for_loop_1__for_iterator = NULL; // Re-raise. exception_type = exception_keeper_type_4; exception_value = exception_keeper_value_4; exception_tb = exception_keeper_tb_4; exception_lineno = exception_keeper_lineno_4; goto frame_exception_exit_1; // End of try: try_end_4:; // Restore frame exception if necessary. #if 0 RESTORE_FRAME_EXCEPTION( frame_caa175f940b5d1e60f5a0891c7d91121 ); #endif popFrameStack(); assertFrameObject( frame_caa175f940b5d1e60f5a0891c7d91121 ); goto frame_no_exception_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_caa175f940b5d1e60f5a0891c7d91121 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_caa175f940b5d1e60f5a0891c7d91121, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_caa175f940b5d1e60f5a0891c7d91121->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_caa175f940b5d1e60f5a0891c7d91121, exception_lineno ); } // Put the previous frame back on top. popFrameStack(); // Return the error. goto module_exception_exit; frame_no_exception_1:; Py_XDECREF( tmp_for_loop_1__iter_value ); tmp_for_loop_1__iter_value = NULL; Py_XDECREF( tmp_for_loop_1__for_iterator ); tmp_for_loop_1__for_iterator = NULL; return MOD_RETURN_VALUE( module_requests$status_codes ); module_exception_exit: RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return MOD_RETURN_VALUE( NULL ); }
40,214
15,141
#include <iostream> #include <array> #include <tuple> #include <type_traits> // Convert array into a tuple template<typename Array, std::size_t... I> constexpr auto a2t_impl(const Array& a, std::index_sequence<I...>) { return std::make_tuple(a[I]...); } template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>> constexpr auto a2t(const T(&arr)[N]) { return a2t_impl(arr, Indices{}); } template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>> constexpr auto a2t(const std::array<T,N>& a) { return a2t_impl(a, Indices{}); } int main() { constexpr const auto a1 = std::array<int, 4>{1,2,3,4}; constexpr int a2[4] = {1,2,3,4}; constexpr auto t1 = a2t(a1); constexpr auto t2 = a2t(a2); static_assert(t1 == t2, "Tuples are different"); }
825
329
// // Created by Khyber on 3/18/2019. // class A { public: static bool initialized; A() noexcept { initialized = true; } ~A() { initialized = false; } }; bool A::initialized = false; A a; int main() { return static_cast<int>(A::initialized); }
309
118
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qt_windows.h> #include "qnativesocketengine_winrt_p.h" #include <qcoreapplication.h> #include <qabstracteventdispatcher.h> #include <qsocketnotifier.h> #include <qdatetime.h> #include <qnetworkinterface.h> #include <qelapsedtimer.h> #include <qthread.h> #include <qabstracteventdispatcher.h> #include <private/qeventdispatcher_winrt_p.h> #include <wrl.h> #include <windows.foundation.collections.h> #include <windows.storage.streams.h> #include <windows.networking.h> #include <windows.networking.sockets.h> #include <robuffer.h> using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Foundation::Collections; using namespace ABI::Windows::Storage::Streams; using namespace ABI::Windows::Networking; using namespace ABI::Windows::Networking::Connectivity; using namespace ABI::Windows::Networking::Sockets; typedef ITypedEventHandler<StreamSocketListener *, StreamSocketListenerConnectionReceivedEventArgs *> ClientConnectedHandler; typedef ITypedEventHandler<DatagramSocket *, DatagramSocketMessageReceivedEventArgs *> DatagramReceivedHandler; typedef IAsyncOperationWithProgressCompletedHandler<IBuffer *, UINT32> SocketReadCompletedHandler; typedef IAsyncOperationWithProgressCompletedHandler<UINT32, UINT32> SocketWriteCompletedHandler; typedef IAsyncOperationWithProgress<IBuffer *, UINT32> IAsyncBufferOperation; QT_BEGIN_NAMESPACE // Common constructs #define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \ if (!isValid()) { \ qWarning(""#function" was called on an uninitialized socket device"); \ return returnValue; \ } } while (0) #define Q_CHECK_INVALID_SOCKETLAYER(function, returnValue) do { \ if (isValid()) { \ qWarning(""#function" was called on an already initialized socket device"); \ return returnValue; \ } } while (0) #define Q_CHECK_STATE(function, checkState, returnValue) do { \ if (d->socketState != (checkState)) { \ qWarning(""#function" was not called in "#checkState); \ return (returnValue); \ } } while (0) #define Q_CHECK_NOT_STATE(function, checkState, returnValue) do { \ if (d->socketState == (checkState)) { \ qWarning(""#function" was called in "#checkState); \ return (returnValue); \ } } while (0) #define Q_CHECK_STATES(function, state1, state2, returnValue) do { \ if (d->socketState != (state1) && d->socketState != (state2)) { \ qWarning(""#function" was called" \ " not in "#state1" or "#state2); \ return (returnValue); \ } } while (0) #define Q_CHECK_TYPE(function, type, returnValue) do { \ if (d->socketType != (type)) { \ qWarning(#function" was called by a" \ " socket other than "#type""); \ return (returnValue); \ } } while (0) #define Q_TR(a) QT_TRANSLATE_NOOP(QNativeSocketEngine, a) typedef QHash<qintptr, IStreamSocket *> TcpSocketHash; struct SocketHandler { SocketHandler() : socketCount(0) {} qintptr socketCount; TcpSocketHash pendingTcpSockets; }; Q_GLOBAL_STATIC(SocketHandler, gSocketHandler) QString qt_QStringFromHSTRING(HSTRING string) { UINT32 length; PCWSTR rawString = WindowsGetStringRawBuffer(string, &length); return QString::fromWCharArray(rawString, length); } #define READ_BUFFER_SIZE 8192 class ByteArrayBuffer : public Microsoft::WRL::RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IBuffer, Windows::Storage::Streams::IBufferByteAccess> { public: ByteArrayBuffer(int size) : m_bytes(size, Qt::Uninitialized), m_length(0) { } ByteArrayBuffer(const char *data, int size) : m_bytes(data, size), m_length(size) { } HRESULT __stdcall Buffer(byte **value) { *value = reinterpret_cast<byte *>(m_bytes.data()); return S_OK; } HRESULT __stdcall get_Capacity(UINT32 *value) { *value = m_bytes.size(); return S_OK; } HRESULT __stdcall get_Length(UINT32 *value) { *value = m_length; return S_OK; } HRESULT __stdcall put_Length(UINT32 value) { Q_ASSERT(value <= UINT32(m_bytes.size())); m_length = value; return S_OK; } ComPtr<IInputStream> inputStream() const { return m_stream; } void setInputStream(ComPtr<IInputStream> stream) { m_stream = stream; } private: QByteArray m_bytes; UINT32 m_length; ComPtr<IInputStream> m_stream; }; template <typename T> static AsyncStatus opStatus(const ComPtr<T> &op) { ComPtr<IAsyncInfo> info; HRESULT hr = op.As(&info); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to cast op to IAsyncInfo."); return Error; } AsyncStatus status; hr = info->get_Status(&status); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to get AsyncStatus."); return Error; } return status; } QNativeSocketEngine::QNativeSocketEngine(QObject *parent) : QAbstractSocketEngine(*new QNativeSocketEnginePrivate(), parent) { connect(this, SIGNAL(connectionReady()), SLOT(connectionNotification()), Qt::QueuedConnection); connect(this, SIGNAL(readReady()), SLOT(readNotification()), Qt::QueuedConnection); connect(this, SIGNAL(writeReady()), SLOT(writeNotification()), Qt::QueuedConnection); } QNativeSocketEngine::~QNativeSocketEngine() { close(); } bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol) { Q_D(QNativeSocketEngine); if (isValid()) close(); // Create the socket if (!d->createNewSocket(type, protocol)) return false; d->socketType = type; d->socketProtocol = protocol; return true; } bool QNativeSocketEngine::initialize(qintptr socketDescriptor, QAbstractSocket::SocketState socketState) { Q_D(QNativeSocketEngine); if (isValid()) close(); d->socketDescriptor = socketDescriptor; // Currently, only TCP sockets are initialized this way. SocketHandler *handler = gSocketHandler(); d->tcp = handler->pendingTcpSockets.take(socketDescriptor); d->socketType = QAbstractSocket::TcpSocket; if (!d->tcp || !d->fetchConnectionParameters()) return false; d->socketState = socketState; return true; } qintptr QNativeSocketEngine::socketDescriptor() const { Q_D(const QNativeSocketEngine); return d->socketDescriptor; } bool QNativeSocketEngine::isValid() const { Q_D(const QNativeSocketEngine); return d->socketDescriptor != -1; } bool QNativeSocketEngine::connectToHost(const QHostAddress &address, quint16 port) { const QString addressString = address.toString(); return connectToHostByName(addressString, port); } bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port) { Q_D(QNativeSocketEngine); HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(name.utf16())); ComPtr<IHostNameFactory> hostNameFactory; GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(), &hostNameFactory); ComPtr<IHostName> remoteHost; if (FAILED(hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost))) { qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not create hostname"); return false; } ComPtr<IAsyncAction> op; const QString portString = QString::number(port); HStringReference portReference(reinterpret_cast<LPCWSTR>(portString.utf16())); HRESULT hr = E_FAIL; if (d->socketType == QAbstractSocket::TcpSocket) hr = d->tcp->ConnectAsync(remoteHost.Get(), portReference.Get(), &op); else if (d->socketType == QAbstractSocket::UdpSocket) hr = d->udp->ConnectAsync(remoteHost.Get(), portReference.Get(), &op); if (FAILED(hr)) { qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not obtain connect action"); return false; } hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>( d, &QNativeSocketEnginePrivate::handleConnectToHost).Get()); if (FAILED(hr)) { qErrnoWarning(hr, "Unable to set host connection callback."); return false; } d->socketState = QAbstractSocket::ConnectingState; while (opStatus(op) == Started) d->eventLoop.processEvents(); AsyncStatus status = opStatus(op); if (status == Error || status == Canceled) return false; if (hr == 0x8007274c) { // A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. d->setError(QAbstractSocket::NetworkError, d->ConnectionTimeOutErrorString); d->socketState = QAbstractSocket::UnconnectedState; return false; } if (hr == 0x8007274d) { // No connection could be made because the target machine actively refused it. d->setError(QAbstractSocket::ConnectionRefusedError, d->ConnectionRefusedErrorString); d->socketState = QAbstractSocket::UnconnectedState; return false; } if (FAILED(hr)) { d->setError(QAbstractSocket::UnknownSocketError, d->UnknownSocketErrorString); d->socketState = QAbstractSocket::UnconnectedState; return false; } if (d->socketType == QAbstractSocket::TcpSocket) { IInputStream *stream; hr = d->tcp->get_InputStream(&stream); if (FAILED(hr)) return false; ByteArrayBuffer *buffer = static_cast<ByteArrayBuffer *>(d->readBuffer.Get()); buffer->setInputStream(stream); ComPtr<IAsyncBufferOperation> op; hr = stream->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op); if (FAILED(hr)) return false; hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get()); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to set socket read callback."); return false; } } d->socketState = QAbstractSocket::ConnectedState; return true; } bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port) { Q_D(QNativeSocketEngine); ComPtr<IHostName> hostAddress; if (address != QHostAddress::Any && address != QHostAddress::AnyIPv4 && address != QHostAddress::AnyIPv6) { ComPtr<IHostNameFactory> hostNameFactory; GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(), &hostNameFactory); const QString addressString = address.toString(); HStringReference addressRef(reinterpret_cast<LPCWSTR>(addressString.utf16())); hostNameFactory->CreateHostName(addressRef.Get(), &hostAddress); } HRESULT hr; QString portQString = port ? QString::number(port) : QString(); HStringReference portString(reinterpret_cast<LPCWSTR>(portQString.utf16())); ComPtr<IAsyncAction> op; if (d->socketType == QAbstractSocket::TcpSocket) { if (!d->tcpListener && FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocketListener).Get(), &d->tcpListener))) { qWarning("Failed to create listener"); return false; } EventRegistrationToken token; d->tcpListener->add_ConnectionReceived(Callback<ClientConnectedHandler>(d, &QNativeSocketEnginePrivate::handleClientConnection).Get(), &token); hr = d->tcpListener->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op); if (FAILED(hr)) { qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message return false; } } else if (d->socketType == QAbstractSocket::UdpSocket) { hr = d->udp->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op); if (FAILED(hr)) { qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message return false; } hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(d, &QNativeSocketEnginePrivate::handleBindCompleted).Get()); if (FAILED(hr)) { qErrnoWarning(hr, "Unable to set bind callback."); return false; } } if (op) { while (opStatus(op) == Started) d->eventLoop.processEvents(); AsyncStatus status = opStatus(op); if (status == Error || status == Canceled) return false; hr = op->GetResults(); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to bind socket"); return false; } d->socketState = QAbstractSocket::BoundState; d->fetchConnectionParameters(); return true; } return false; } bool QNativeSocketEngine::listen() { Q_D(QNativeSocketEngine); Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::listen(), false); Q_CHECK_STATE(QNativeSocketEngine::listen(), QAbstractSocket::BoundState, false); Q_CHECK_TYPE(QNativeSocketEngine::listen(), QAbstractSocket::TcpSocket, false); if (d->tcpListener && d->socketDescriptor != -1) { d->socketState = QAbstractSocket::ListeningState; return true; } return false; } int QNativeSocketEngine::accept() { Q_D(QNativeSocketEngine); Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::accept(), -1); Q_CHECK_STATE(QNativeSocketEngine::accept(), QAbstractSocket::ListeningState, -1); Q_CHECK_TYPE(QNativeSocketEngine::accept(), QAbstractSocket::TcpSocket, -1); if (d->socketDescriptor == -1 || d->pendingConnections.isEmpty()) return -1; // Start processing incoming data if (d->socketType == QAbstractSocket::TcpSocket) { IStreamSocket *socket = d->pendingConnections.takeFirst(); IInputStream *stream; socket->get_InputStream(&stream); // TODO: delete buffer and stream on socket close ByteArrayBuffer *buffer = static_cast<ByteArrayBuffer *>(d->readBuffer.Get()); buffer->setInputStream(stream); ComPtr<IAsyncBufferOperation> op; HRESULT hr = stream->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op); if (FAILED(hr)) { qErrnoWarning(hr, "Faild to read from the socket buffer."); return -1; } hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get()); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to set socket read callback."); return -1; } d->currentConnections.append(socket); SocketHandler *handler = gSocketHandler(); handler->pendingTcpSockets.insert(++handler->socketCount, socket); return handler->socketCount; } return -1; } void QNativeSocketEngine::close() { Q_D(QNativeSocketEngine); if (d->socketDescriptor != -1) { IClosable *socket = 0; if (d->socketType == QAbstractSocket::TcpSocket) d->tcp->QueryInterface(IID_PPV_ARGS(&socket)); else if (d->socketType == QAbstractSocket::UdpSocket) d->udp->QueryInterface(IID_PPV_ARGS(&socket)); if (socket) { d->closingDown = true; socket->Close(); socket->Release(); d->socketDescriptor = -1; } d->socketDescriptor = -1; } d->socketState = QAbstractSocket::UnconnectedState; d->hasSetSocketError = false; d->localPort = 0; d->localAddress.clear(); d->peerPort = 0; d->peerAddress.clear(); } bool QNativeSocketEngine::joinMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface) { Q_UNUSED(groupAddress); Q_UNUSED(iface); Q_UNIMPLEMENTED(); return false; } bool QNativeSocketEngine::leaveMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface) { Q_UNUSED(groupAddress); Q_UNUSED(iface); Q_UNIMPLEMENTED(); return false; } QNetworkInterface QNativeSocketEngine::multicastInterface() const { Q_UNIMPLEMENTED(); return QNetworkInterface(); } bool QNativeSocketEngine::setMulticastInterface(const QNetworkInterface &iface) { Q_UNUSED(iface); Q_UNIMPLEMENTED(); return false; } qint64 QNativeSocketEngine::bytesAvailable() const { Q_D(const QNativeSocketEngine); if (d->socketType != QAbstractSocket::TcpSocket) return -1; return d->readBytes.size() - d->readBytes.pos(); } qint64 QNativeSocketEngine::read(char *data, qint64 maxlen) { Q_D(QNativeSocketEngine); if (d->socketType != QAbstractSocket::TcpSocket) return -1; QMutexLocker mutexLocker(&d->readMutex); return d->readBytes.read(data, maxlen); } qint64 QNativeSocketEngine::write(const char *data, qint64 len) { Q_D(QNativeSocketEngine); HRESULT hr = E_FAIL; ComPtr<IOutputStream> stream; if (d->socketType == QAbstractSocket::TcpSocket) hr = d->tcp->get_OutputStream(&stream); else if (d->socketType == QAbstractSocket::UdpSocket) hr = d->udp->get_OutputStream(&stream); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to get output stream to socket."); return -1; } ComPtr<ByteArrayBuffer> buffer = Make<ByteArrayBuffer>(data, len); ComPtr<IAsyncOperationWithProgress<UINT32, UINT32>> op; hr = stream->WriteAsync(buffer.Get(), &op); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to write to socket."); return -1; } hr = op->put_Completed(Callback<IAsyncOperationWithProgressCompletedHandler<UINT32, UINT32>>( d, &QNativeSocketEnginePrivate::handleWriteCompleted).Get()); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to set socket write callback."); return -1; } while (opStatus(op) == Started) d->eventLoop.processEvents(); AsyncStatus status = opStatus(op); if (status == Error || status == Canceled) return -1; UINT32 bytesWritten; hr = op->GetResults(&bytesWritten); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to get written socket length."); return -1; } if (bytesWritten && d->notifyOnWrite) emit writeReady(); return bytesWritten; } qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress *addr, quint16 *port) { Q_D(QNativeSocketEngine); if (d->socketType != QAbstractSocket::UdpSocket) return -1; QHostAddress returnAddress; quint16 returnPort; for (int i = 0; i < d->pendingDatagrams.size(); ++i) { IDatagramSocketMessageReceivedEventArgs *arg = d->pendingDatagrams.at(i); ComPtr<IHostName> remoteHost; HSTRING remoteHostString; HSTRING remotePort; arg->get_RemoteAddress(&remoteHost); arg->get_RemotePort(&remotePort); remoteHost->get_CanonicalName(&remoteHostString); returnAddress.setAddress(qt_QStringFromHSTRING(remoteHostString)); returnPort = qt_QStringFromHSTRING(remotePort).toInt(); ComPtr<IDataReader> reader; arg->GetDataReader(&reader); if (!reader) continue; BYTE buffer[1024]; reader->ReadBytes(maxlen, buffer); *addr = returnAddress; *port = returnPort; arg = d->pendingDatagrams.takeFirst(); // TODO: fill data Q_UNUSED(data); arg->Release(); delete arg; --i; return maxlen; } return -1; } qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QHostAddress &addr, quint16 port) { Q_D(QNativeSocketEngine); if (d->socketType != QAbstractSocket::UdpSocket) return -1; ComPtr<IHostName> remoteHost; ComPtr<IHostNameFactory> hostNameFactory; if (FAILED(GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(), &hostNameFactory))) { qWarning("QNativeSocketEnginePrivate::nativeSendDatagram: could not obtain hostname factory"); return -1; } const QString addressString = addr.toString(); HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(addressString.utf16())); hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost); ComPtr<IAsyncOperation<IOutputStream *>> streamOperation; ComPtr<IOutputStream> stream; const QString portString = QString::number(port); HStringReference portRef(reinterpret_cast<LPCWSTR>(portString.utf16())); if (FAILED(d->udp->GetOutputStreamAsync(remoteHost.Get(), portRef.Get(), &streamOperation))) return -1; HRESULT hr; while (hr = streamOperation->GetResults(&stream) == E_ILLEGAL_METHOD_CALL) QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); ComPtr<IDataWriterFactory> dataWriterFactory; GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Storage_Streams_DataWriter).Get(), &dataWriterFactory); ComPtr<IDataWriter> writer; dataWriterFactory->CreateDataWriter(stream.Get(), &writer); writer->WriteBytes(len, (unsigned char *)data); return len; } bool QNativeSocketEngine::hasPendingDatagrams() const { Q_D(const QNativeSocketEngine); return d->pendingDatagrams.length() > 0; } qint64 QNativeSocketEngine::pendingDatagramSize() const { Q_D(const QNativeSocketEngine); qint64 ret = 0; foreach (IDatagramSocketMessageReceivedEventArgs *arg, d->pendingDatagrams) { ComPtr<IDataReader> reader; UINT32 unconsumedBufferLength; arg->GetDataReader(&reader); if (!reader) return -1; reader->get_UnconsumedBufferLength(&unconsumedBufferLength); ret += unconsumedBufferLength; } return ret; } qint64 QNativeSocketEngine::bytesToWrite() const { return 0; } qint64 QNativeSocketEngine::receiveBufferSize() const { Q_D(const QNativeSocketEngine); return d->option(QAbstractSocketEngine::ReceiveBufferSocketOption); } void QNativeSocketEngine::setReceiveBufferSize(qint64 bufferSize) { Q_D(QNativeSocketEngine); d->setOption(QAbstractSocketEngine::ReceiveBufferSocketOption, bufferSize); } qint64 QNativeSocketEngine::sendBufferSize() const { Q_D(const QNativeSocketEngine); return d->option(QAbstractSocketEngine::SendBufferSocketOption); } void QNativeSocketEngine::setSendBufferSize(qint64 bufferSize) { Q_D(QNativeSocketEngine); d->setOption(QAbstractSocketEngine::SendBufferSocketOption, bufferSize); } int QNativeSocketEngine::option(QAbstractSocketEngine::SocketOption option) const { Q_D(const QNativeSocketEngine); return d->option(option); } bool QNativeSocketEngine::setOption(QAbstractSocketEngine::SocketOption option, int value) { Q_D(QNativeSocketEngine); return d->setOption(option, value); } bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut) { Q_D(QNativeSocketEngine); Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForRead(), false); Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForRead(), QAbstractSocket::UnconnectedState, false); if (timedOut) *timedOut = false; QElapsedTimer timer; timer.start(); while (msecs > timer.elapsed()) { // Servers with active connections are ready for reading if (!d->currentConnections.isEmpty()) return true; // If we are a client, we are ready to read if our buffer has data QMutexLocker locker(&d->readMutex); if (!d->readBytes.atEnd()) return true; // Nothing to do, wait for more events d->eventLoop.processEvents(); } d->setError(QAbstractSocket::SocketTimeoutError, QNativeSocketEnginePrivate::TimeOutErrorString); if (timedOut) *timedOut = true; return false; } bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut) { Q_UNUSED(msecs); Q_UNUSED(timedOut); return false; } bool QNativeSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite, bool checkRead, bool checkWrite, int msecs, bool *timedOut) { Q_UNUSED(readyToRead); Q_UNUSED(readyToWrite); Q_UNUSED(checkRead); Q_UNUSED(checkWrite); Q_UNUSED(msecs); Q_UNUSED(timedOut); return false; } bool QNativeSocketEngine::isReadNotificationEnabled() const { Q_D(const QNativeSocketEngine); return d->notifyOnRead; } void QNativeSocketEngine::setReadNotificationEnabled(bool enable) { Q_D(QNativeSocketEngine); d->notifyOnRead = enable; } bool QNativeSocketEngine::isWriteNotificationEnabled() const { Q_D(const QNativeSocketEngine); return d->notifyOnWrite; } void QNativeSocketEngine::setWriteNotificationEnabled(bool enable) { Q_D(QNativeSocketEngine); d->notifyOnWrite = enable; if (enable && d->socketState == QAbstractSocket::ConnectedState) { if (bytesToWrite()) return; // will be emitted as a result of bytes written writeNotification(); d->notifyOnWrite = false; } } bool QNativeSocketEngine::isExceptionNotificationEnabled() const { Q_D(const QNativeSocketEngine); return d->notifyOnException; } void QNativeSocketEngine::setExceptionNotificationEnabled(bool enable) { Q_D(QNativeSocketEngine); d->notifyOnException = enable; } bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol) { Q_UNUSED(socketProtocol); SocketHandler *handler = gSocketHandler(); switch (socketType) { case QAbstractSocket::TcpSocket: { if (FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocket).Get(), reinterpret_cast<IInspectable **>(&tcp)))) { qWarning("Failed to create StreamSocket instance"); return false; } socketDescriptor = ++handler->socketCount; return true; } case QAbstractSocket::UdpSocket: { if (FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), reinterpret_cast<IInspectable **>(&udp)))) { qWarning("Failed to create stream socket"); return false; } EventRegistrationToken token; udp->add_MessageReceived(Callback<DatagramReceivedHandler>(this, &QNativeSocketEnginePrivate::handleNewDatagram).Get(), &token); socketDescriptor = ++handler->socketCount; return true; } default: qWarning("Invalid socket type"); return false; } return false; } QNativeSocketEnginePrivate::QNativeSocketEnginePrivate() : QAbstractSocketEnginePrivate() , notifyOnRead(true) , notifyOnWrite(true) , notifyOnException(false) , closingDown(false) , socketDescriptor(-1) { ComPtr<ByteArrayBuffer> buffer = Make<ByteArrayBuffer>(READ_BUFFER_SIZE); readBuffer = buffer; } QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate() { } void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const { if (hasSetSocketError) { // Only set socket errors once for one engine; expect the // socket to recreate its engine after an error. Note: There's // one exception: SocketError(11) bypasses this as it's purely // a temporary internal error condition. // Another exception is the way the waitFor*() functions set // an error when a timeout occurs. After the call to setError() // they reset the hasSetSocketError to false return; } if (error != QAbstractSocket::SocketError(11)) hasSetSocketError = true; socketError = error; switch (errorString) { case NonBlockingInitFailedErrorString: socketErrorString = QNativeSocketEngine::tr("Unable to initialize non-blocking socket"); break; case BroadcastingInitFailedErrorString: socketErrorString = QNativeSocketEngine::tr("Unable to initialize broadcast socket"); break; // should not happen anymore case NoIpV6ErrorString: socketErrorString = QNativeSocketEngine::tr("Attempt to use IPv6 socket on a platform with no IPv6 support"); break; case RemoteHostClosedErrorString: socketErrorString = QNativeSocketEngine::tr("The remote host closed the connection"); break; case TimeOutErrorString: socketErrorString = QNativeSocketEngine::tr("Network operation timed out"); break; case ResourceErrorString: socketErrorString = QNativeSocketEngine::tr("Out of resources"); break; case OperationUnsupportedErrorString: socketErrorString = QNativeSocketEngine::tr("Unsupported socket operation"); break; case ProtocolUnsupportedErrorString: socketErrorString = QNativeSocketEngine::tr("Protocol type not supported"); break; case InvalidSocketErrorString: socketErrorString = QNativeSocketEngine::tr("Invalid socket descriptor"); break; case HostUnreachableErrorString: socketErrorString = QNativeSocketEngine::tr("Host unreachable"); break; case NetworkUnreachableErrorString: socketErrorString = QNativeSocketEngine::tr("Network unreachable"); break; case AccessErrorString: socketErrorString = QNativeSocketEngine::tr("Permission denied"); break; case ConnectionTimeOutErrorString: socketErrorString = QNativeSocketEngine::tr("Connection timed out"); break; case ConnectionRefusedErrorString: socketErrorString = QNativeSocketEngine::tr("Connection refused"); break; case AddressInuseErrorString: socketErrorString = QNativeSocketEngine::tr("The bound address is already in use"); break; case AddressNotAvailableErrorString: socketErrorString = QNativeSocketEngine::tr("The address is not available"); break; case AddressProtectedErrorString: socketErrorString = QNativeSocketEngine::tr("The address is protected"); break; case DatagramTooLargeErrorString: socketErrorString = QNativeSocketEngine::tr("Datagram was too large to send"); break; case SendDatagramErrorString: socketErrorString = QNativeSocketEngine::tr("Unable to send a message"); break; case ReceiveDatagramErrorString: socketErrorString = QNativeSocketEngine::tr("Unable to receive a message"); break; case WriteErrorString: socketErrorString = QNativeSocketEngine::tr("Unable to write"); break; case ReadErrorString: socketErrorString = QNativeSocketEngine::tr("Network error"); break; case PortInuseErrorString: socketErrorString = QNativeSocketEngine::tr("Another socket is already listening on the same port"); break; case NotSocketErrorString: socketErrorString = QNativeSocketEngine::tr("Operation on non-socket"); break; case InvalidProxyTypeString: socketErrorString = QNativeSocketEngine::tr("The proxy type is invalid for this operation"); break; case TemporaryErrorString: socketErrorString = QNativeSocketEngine::tr("Temporary error"); break; case UnknownSocketErrorString: socketErrorString = QNativeSocketEngine::tr("Unknown error"); break; } } int QNativeSocketEnginePrivate::option(QAbstractSocketEngine::SocketOption opt) const { ComPtr<IStreamSocketControl> control; if (socketType == QAbstractSocket::TcpSocket) { if (FAILED(tcp->get_Control(&control))) { qWarning("QNativeSocketEnginePrivate::option: Could not obtain socket control"); return -1; } } switch (opt) { case QAbstractSocketEngine::NonBlockingSocketOption: case QAbstractSocketEngine::BroadcastSocketOption: case QAbstractSocketEngine::ReceiveOutOfBandData: return 1; case QAbstractSocketEngine::SendBufferSocketOption: if (socketType == QAbstractSocket::UdpSocket) return -1; UINT32 bufferSize; if (FAILED(control->get_OutboundBufferSizeInBytes(&bufferSize))) { qWarning("Could not obtain OutboundBufferSizeInBytes information vom socket control"); return -1; } return bufferSize; case QAbstractSocketEngine::LowDelayOption: if (socketType == QAbstractSocket::UdpSocket) return -1; boolean noDelay; if (FAILED(control->get_NoDelay(&noDelay))) { qWarning("Could not obtain NoDelay information from socket control"); return -1; } return noDelay; case QAbstractSocketEngine::KeepAliveOption: if (socketType == QAbstractSocket::UdpSocket) return -1; boolean keepAlive; if (FAILED(control->get_KeepAlive(&keepAlive))) { qWarning("Could not obtain KeepAlive information from socket control"); return -1; } return keepAlive; case QAbstractSocketEngine::ReceiveBufferSocketOption: case QAbstractSocketEngine::AddressReusable: case QAbstractSocketEngine::BindExclusively: case QAbstractSocketEngine::MulticastTtlOption: case QAbstractSocketEngine::MulticastLoopbackOption: case QAbstractSocketEngine::TypeOfServiceOption: default: return -1; } return -1; } bool QNativeSocketEnginePrivate::setOption(QAbstractSocketEngine::SocketOption opt, int v) { ComPtr<IStreamSocketControl> control; if (socketType == QAbstractSocket::TcpSocket) { if (FAILED(tcp->get_Control(&control))) { qWarning("QNativeSocketEnginePrivate::setOption: Could not obtain socket control"); return false; } } switch (opt) { case QAbstractSocketEngine::NonBlockingSocketOption: case QAbstractSocketEngine::BroadcastSocketOption: case QAbstractSocketEngine::ReceiveOutOfBandData: return v != 0; case QAbstractSocketEngine::SendBufferSocketOption: if (socketType == QAbstractSocket::UdpSocket) return false; if (FAILED(control->put_OutboundBufferSizeInBytes(v))) { qWarning("Could not set OutboundBufferSizeInBytes"); return false; } return true; case QAbstractSocketEngine::LowDelayOption: { if (socketType == QAbstractSocket::UdpSocket) return false; boolean noDelay = v; if (FAILED(control->put_NoDelay(noDelay))) { qWarning("Could not obtain NoDelay information from socket control"); return false; } return true; } case QAbstractSocketEngine::KeepAliveOption: { if (socketType == QAbstractSocket::UdpSocket) return false; boolean keepAlive = v; if (FAILED(control->put_KeepAlive(keepAlive))) { qWarning("Could not set KeepAlive value"); return false; } return true; } case QAbstractSocketEngine::ReceiveBufferSocketOption: case QAbstractSocketEngine::AddressReusable: case QAbstractSocketEngine::BindExclusively: case QAbstractSocketEngine::MulticastTtlOption: case QAbstractSocketEngine::MulticastLoopbackOption: case QAbstractSocketEngine::TypeOfServiceOption: default: return false; } return false; } bool QNativeSocketEnginePrivate::fetchConnectionParameters() { localPort = 0; localAddress.clear(); peerPort = 0; peerAddress.clear(); if (socketType == QAbstractSocket::TcpSocket) { ComPtr<IHostName> hostName; HSTRING tmpHString; ComPtr<IStreamSocketInformation> info; if (FAILED(tcp->get_Information(&info))) { qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket info"); return false; } info->get_LocalAddress(&hostName); if (hostName) { hostName->get_CanonicalName(&tmpHString); localAddress.setAddress(qt_QStringFromHSTRING(tmpHString)); info->get_LocalPort(&tmpHString); localPort = qt_QStringFromHSTRING(tmpHString).toInt(); } if (!localPort && tcpListener) { ComPtr<IStreamSocketListenerInformation> listenerInfo = 0; tcpListener->get_Information(&listenerInfo); listenerInfo->get_LocalPort(&tmpHString); localPort = qt_QStringFromHSTRING(tmpHString).toInt(); localAddress == QHostAddress::Any; } info->get_RemoteAddress(&hostName); if (hostName) { hostName->get_CanonicalName(&tmpHString); peerAddress.setAddress(qt_QStringFromHSTRING(tmpHString)); info->get_RemotePort(&tmpHString); peerPort = qt_QStringFromHSTRING(tmpHString).toInt(); } } else if (socketType == QAbstractSocket::UdpSocket) { ComPtr<IHostName> hostName; HSTRING tmpHString; ComPtr<IDatagramSocketInformation> info; if (FAILED(udp->get_Information(&info))) { qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket information"); return false; } info->get_LocalAddress(&hostName); if (hostName) { hostName->get_CanonicalName(&tmpHString); localAddress.setAddress(qt_QStringFromHSTRING(tmpHString)); info->get_LocalPort(&tmpHString); localPort = qt_QStringFromHSTRING(tmpHString).toInt(); } info->get_RemoteAddress(&hostName); if (hostName) { hostName->get_CanonicalName(&tmpHString); peerAddress.setAddress(qt_QStringFromHSTRING(tmpHString)); info->get_RemotePort(&tmpHString); peerPort = qt_QStringFromHSTRING(tmpHString).toInt(); } } return true; } HRESULT QNativeSocketEnginePrivate::handleBindCompleted(IAsyncAction *, AsyncStatus) { return S_OK; } HRESULT QNativeSocketEnginePrivate::handleClientConnection(IStreamSocketListener *listener, IStreamSocketListenerConnectionReceivedEventArgs *args) { Q_Q(QNativeSocketEngine); Q_ASSERT(tcpListener.Get() == listener); IStreamSocket *socket; args->get_Socket(&socket); pendingConnections.append(socket); emit q->connectionReady(); emit q->readReady(); return S_OK; } HRESULT QNativeSocketEnginePrivate::handleConnectToHost(ABI::Windows::Foundation::IAsyncAction *, ABI::Windows::Foundation::AsyncStatus) { return S_OK; } HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *asyncInfo, AsyncStatus status) { Q_Q(QNativeSocketEngine); if (wasDeleted || isDeletingChildren) return S_OK; if (status == Error || status == Canceled) return S_OK; ByteArrayBuffer *buffer = 0; HRESULT hr = asyncInfo->GetResults((IBuffer **)&buffer); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to get ready read results."); return S_OK; } UINT32 len; buffer->get_Length(&len); if (!len) { if (q->isReadNotificationEnabled()) emit q->readReady(); return S_OK; } byte *data; buffer->Buffer(&data); readMutex.lock(); if (readBytes.atEnd()) // Everything has been read; the buffer is safe to reset readBytes.close(); if (!readBytes.isOpen()) readBytes.open(QBuffer::ReadWrite|QBuffer::Truncate); qint64 readPos = readBytes.pos(); readBytes.seek(readBytes.size()); Q_ASSERT(readBytes.atEnd()); readBytes.write(reinterpret_cast<const char*>(data), qint64(len)); readBytes.seek(readPos); readMutex.unlock(); if (q->isReadNotificationEnabled()) emit q->readReady(); ComPtr<IAsyncBufferOperation> op; hr = buffer->inputStream()->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op); if (FAILED(hr)) { qErrnoWarning(hr, "Could not read into socket stream buffer."); return S_OK; } hr = op->put_Completed(Callback<SocketReadCompletedHandler>(this, &QNativeSocketEnginePrivate::handleReadyRead).Get()); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to set socket read callback."); return S_OK; } return S_OK; } HRESULT QNativeSocketEnginePrivate::handleWriteCompleted(IAsyncOperationWithProgress<UINT32, UINT32> *op, AsyncStatus status) { if (status == Error) { ComPtr<IAsyncInfo> info; HRESULT hr = op->QueryInterface(IID_PPV_ARGS(&info)); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to cast operation."); return S_OK; } HRESULT errorCode; hr = info->get_ErrorCode(&errorCode); if (FAILED(hr)) { qErrnoWarning(hr, "Failed to get error code."); return S_OK; } qErrnoWarning(errorCode, "A socket error occurred."); return S_OK; } return S_OK; } HRESULT QNativeSocketEnginePrivate::handleNewDatagram(IDatagramSocket *socket, IDatagramSocketMessageReceivedEventArgs *args) { Q_Q(QNativeSocketEngine); Q_ASSERT(udp == socket); pendingDatagrams.append(args); emit q->readReady(); return S_OK; } QT_END_NAMESPACE
43,655
12,803
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <sfx2/querystatus.hxx> #include <svl/poolitem.hxx> #include <svl/eitem.hxx> #include <svl/stritem.hxx> #include <svl/intitem.hxx> #include <svl/itemset.hxx> #include <svtools/itemdel.hxx> #include <svl/visitem.hxx> #include <cppuhelper/weak.hxx> #include <comphelper/processfactory.hxx> #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #include <com/sun/star/util/XURLTransformer.hpp> #include <com/sun/star/frame/status/ItemStatus.hpp> #include <com/sun/star/frame/status/ItemState.hpp> #include <com/sun/star/frame/status/Visibility.hpp> using ::rtl::OUString; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::frame::status; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; class SfxQueryStatus_Impl : public ::com::sun::star::frame::XStatusListener , public ::com::sun::star::lang::XTypeProvider , public ::cppu::OWeakObject { public: SFX_DECL_XINTERFACE_XTYPEPROVIDER SfxQueryStatus_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const rtl::OUString& aCommand ); virtual ~SfxQueryStatus_Impl(); // Query method SfxItemState QueryState( SfxPoolItem*& pPoolItem ); // XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); private: SfxQueryStatus_Impl( const SfxQueryStatus& ); SfxQueryStatus_Impl(); SfxQueryStatus_Impl& operator=( const SfxQueryStatus& ); sal_Bool m_bQueryInProgress; SfxItemState m_eState; SfxPoolItem* m_pItem; sal_uInt16 m_nSlotID; osl::Condition m_aCondition; ::com::sun::star::util::URL m_aCommand; com::sun::star::uno::Reference< com::sun::star::frame::XDispatch > m_xDispatch; }; SFX_IMPL_XINTERFACE_2( SfxQueryStatus_Impl, OWeakObject, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener ) SFX_IMPL_XTYPEPROVIDER_2( SfxQueryStatus_Impl, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener ) SfxQueryStatus_Impl::SfxQueryStatus_Impl( const Reference< XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const OUString& rCommand ) : cppu::OWeakObject(), m_bQueryInProgress( sal_False ), m_eState( SFX_ITEM_DISABLED ), m_pItem( 0 ), m_nSlotID( nSlotId ) { m_aCommand.Complete = rCommand; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( m_aCommand ); if ( rDispatchProvider.is() ) m_xDispatch = rDispatchProvider->queryDispatch( m_aCommand, rtl::OUString(), 0 ); m_aCondition.reset(); } SfxQueryStatus_Impl::~SfxQueryStatus_Impl() { } void SAL_CALL SfxQueryStatus_Impl::disposing( const EventObject& ) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_xDispatch.clear(); } void SAL_CALL SfxQueryStatus_Impl::statusChanged( const FeatureStateEvent& rEvent) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_pItem = NULL; m_eState = SFX_ITEM_DISABLED; if ( rEvent.IsEnabled ) { m_eState = SFX_ITEM_AVAILABLE; ::com::sun::star::uno::Type pType = rEvent.State.getValueType(); if ( pType == ::getBooleanCppuType() ) { sal_Bool bTemp = false; rEvent.State >>= bTemp ; m_pItem = new SfxBoolItem( m_nSlotID, bTemp ); } else if ( pType == ::getCppuType((const sal_uInt16*)0) ) { sal_uInt16 nTemp = 0; rEvent.State >>= nTemp ; m_pItem = new SfxUInt16Item( m_nSlotID, nTemp ); } else if ( pType == ::getCppuType((const sal_uInt32*)0) ) { sal_uInt32 nTemp = 0; rEvent.State >>= nTemp ; m_pItem = new SfxUInt32Item( m_nSlotID, nTemp ); } else if ( pType == ::getCppuType((const ::rtl::OUString*)0) ) { ::rtl::OUString sTemp ; rEvent.State >>= sTemp ; m_pItem = new SfxStringItem( m_nSlotID, sTemp ); } else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::ItemStatus*)0) ) { ItemStatus aItemStatus; rEvent.State >>= aItemStatus; m_eState = aItemStatus.State; m_pItem = new SfxVoidItem( m_nSlotID ); } else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::Visibility*)0) ) { Visibility aVisibilityStatus; rEvent.State >>= aVisibilityStatus; m_pItem = new SfxVisibilityItem( m_nSlotID, aVisibilityStatus.bVisible ); } else { m_eState = SFX_ITEM_UNKNOWN; m_pItem = new SfxVoidItem( m_nSlotID ); } } if ( m_pItem ) DeleteItemOnIdle( m_pItem ); try { m_aCondition.set(); m_xDispatch->removeStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ), m_aCommand ); } catch ( Exception& ) { } } // Query method SfxItemState SfxQueryStatus_Impl::QueryState( SfxPoolItem*& rpPoolItem ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( !m_bQueryInProgress ) { m_pItem = NULL; m_eState = SFX_ITEM_DISABLED; if ( m_xDispatch.is() ) { try { m_aCondition.reset(); m_bQueryInProgress = sal_True; m_xDispatch->addStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ), m_aCommand ); } catch ( Exception& ) { m_aCondition.set(); } } else m_aCondition.set(); } m_aCondition.wait(); m_bQueryInProgress = sal_False; rpPoolItem = m_pItem; return m_eState; } //************************************************************************* SfxQueryStatus::SfxQueryStatus( const Reference< XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const OUString& rCommand ) { m_pSfxQueryStatusImpl = new SfxQueryStatus_Impl( rDispatchProvider, nSlotId, rCommand ); m_xStatusListener = Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( m_pSfxQueryStatusImpl ), UNO_QUERY ); } SfxQueryStatus::~SfxQueryStatus() { } SfxItemState SfxQueryStatus::QueryState( SfxPoolItem*& rpPoolItem ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); return m_pSfxQueryStatusImpl->QueryState( rpPoolItem ); }
8,577
2,846
#include <json.hpp> #include <httplib.h> #include <discord-rpc.h> #include <cstring> #include <iostream> #include <string> #include <thread> using json = nlohmann::json; struct config { std::string lfm_api_key; std::string dsc_app_id; std::string lfm_user; }; struct current_status { bool playing; std::string artist; std::string track; }; // https://stackoverflow.com/a/2072890/1243281 inline bool ends_with(std::string const & value, std::string const & ending) { if (ending.size() > value.size()) return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } void init(config cfg) { DiscordEventHandlers handlers; memset(&handlers, 0, sizeof(handlers)); Discord_Initialize(cfg.dsc_app_id.c_str(), &handlers, 1, NULL); } void update(current_status status) { DiscordRichPresence discordPresence; memset(&discordPresence, 0, sizeof(discordPresence)); discordPresence.largeImageKey = "default"; if (status.playing) { discordPresence.state = status.artist.c_str(); discordPresence.details = status.track.c_str(); } else { discordPresence.state = "Idle"; } Discord_UpdatePresence(&discordPresence); } current_status get_lfm_data(config cfg) { std::string url = "/2.0/?method=user.getrecenttracks&user=" + cfg.lfm_user + "&api_key=" + cfg.lfm_api_key + "&format=json"; httplib::Client cli("ws.audioscrobbler.com", 80); auto res = cli.get(url.c_str()); if (res && res->status == 200) { json j = json::parse(res->body); json t = j["recenttracks"]["track"][0]; if (t.find("@attr") != t.end() && t["@attr"].find("nowplaying") != t["@attr"].end() && t["@attr"]["nowplaying"] == "true") { return { true, t["artist"]["#text"], t["name"] }; } } return { false, "", "" }; } config load_config() { std::ifstream t("config.json"); std::stringstream buffer; buffer << t.rdbuf(); json cfg = json::parse(buffer); return { cfg["lfm_api_key"], cfg["dsc_app_id"], cfg["lfm_user"] }; } int main(int argc, char* argv[]) { config cfg = load_config(); init(cfg); while (true) { current_status c = get_lfm_data(cfg); update(c); std::this_thread::sleep_for(std::chrono::seconds(30)); } Discord_Shutdown(); return 0; }
2,194
889
#include "softjoystick.h" #include "control.h" #include <algorithm> #include <math.h> #include <SDL_image.h> #ifndef M_PI #define M_PI 3.1415926535897 #endif static byte numButtons = 2; static byte state = 0; static byte taps = 0; void SoftJoystickNumButtons(byte n) { numButtons = std::max((byte) 1, std::min(n, (byte) 4)); } byte SoftJoystickState() { return state; } byte SoftJoystickTaps() { byte w = taps; taps = 0; return w; } static inline bool rect_contains(const SDL_Rect &r, int x, int y) { return r.x <= x && x < r.x + r.w && r.y <= y && y < r.y + r.h; } void Element::draw(SDL_Renderer* renderer) { SDL_RenderCopy(renderer, tex, NULL, &rect); } SoftJoystick::SoftJoystick(MGLDraw* mgl) { SDL_Renderer* renderer = mgl->renderer; stick.tex = IMG_LoadTexture(renderer, "soft_stick.png"); trough.tex = IMG_LoadTexture(renderer, "soft_trough.png"); esc.tex = IMG_LoadTexture(renderer, "soft_esc.png"); keyboard.tex = IMG_LoadTexture(renderer, "soft_keyboard.png"); button[0].tex = IMG_LoadTexture(renderer, "soft_b1.png"); button[1].tex = IMG_LoadTexture(renderer, "soft_b2.png"); button[2].tex = IMG_LoadTexture(renderer, "soft_b3.png"); button[3].tex = IMG_LoadTexture(renderer, "soft_b4.png"); } SoftJoystick::~SoftJoystick() { } void SoftJoystick::update(MGLDraw* mgl, float scale) { int spare = (int)(mgl->winWidth - mgl->xRes * scale) / 2; int right = mgl->winWidth - spare; trough.rect = { 0, 0, 3 * spare, 3 * spare }; stick.rect = { 0, 0, 3 * spare, 3 * spare }; if (state & CONTROL_UP) stick.rect.y -= spare; if (state & CONTROL_DN) stick.rect.y += spare; if (state & CONTROL_LF) stick.rect.x -= spare; if (state & CONTROL_RT) stick.rect.x += spare; esc.rect = { right, mgl->winHeight - spare, spare, spare }; keyboard.rect = { right, mgl->winHeight - 2 * spare, spare, spare }; for (int i = 0; i < numButtons; ++i) { button[i].rect = { right, i * spare, spare, spare }; } } void SoftJoystick::render(SDL_Renderer* renderer) { stick.draw(renderer); trough.draw(renderer); esc.draw(renderer); keyboard.draw(renderer); for (int i = 0; i < numButtons; ++i) { button[i].draw(renderer); } } void SoftJoystick::handle_event(MGLDraw *mgl, const SDL_Event& e) { if (e.type == SDL_FINGERDOWN) { int x = (int)(e.tfinger.x * mgl->winWidth); int y = (int)(e.tfinger.y * mgl->winHeight); if (rect_contains(esc.rect, x, y)) { mgl->lastKeyPressed = SDLK_ESCAPE; } else if (rect_contains(keyboard.rect, x, y)) { SDL_StartTextInput(); } int bit = CONTROL_B1; for (int i = 0; i < numButtons; ++i) { if (rect_contains(button[i].rect, x, y)) { fingerHeld[e.tfinger.fingerId] |= bit; state |= bit; taps |= bit; } bit *= 2; } } if (e.type == SDL_FINGERDOWN || e.type == SDL_FINGERMOTION) { int x = (int)(e.tfinger.x * mgl->winWidth); int y = (int)(e.tfinger.y * mgl->winHeight); if (rect_contains(trough.rect, x, y)) { const int DEADZONE = 2048; byte curState = 0; int ax = (x - trough.rect.x - trough.rect.w / 2) * 32767 / trough.rect.w; int ay = (y - trough.rect.y - trough.rect.h / 2) * 32767 / trough.rect.h; if (ax * ax + ay * ay >= DEADZONE * DEADZONE) { double angle = atan2(ay, ax) * 180.0 / M_PI; if (angle < 22.5 + -4*45) { curState = CONTROL_LF; } else if (angle < 22.5 + -3*45) { curState = CONTROL_LF | CONTROL_UP; } else if (angle < 22.5 + -2*45) { curState = CONTROL_UP; } else if (angle < 22.5 + -1*45) { curState = CONTROL_UP | CONTROL_RT; } else if (angle < 22.5 + 0*45) { curState = CONTROL_RT; } else if (angle < 22.5 + 1*45) { curState = CONTROL_RT | CONTROL_DN; } else if (angle < 22.5 + 2*45) { curState = CONTROL_DN; } else if (angle < 22.5 + 3*45) { curState = CONTROL_DN | CONTROL_LF; } else if (angle < 22.5 + 4*45) { curState = CONTROL_LF; } } byte last = fingerHeld[e.tfinger.fingerId]; fingerHeld[e.tfinger.fingerId] = curState; recalculate_state(); taps |= (curState & ~last); } } if (e.type == SDL_FINGERUP) { auto iter = fingerHeld.find(e.tfinger.fingerId); if (iter != fingerHeld.end()) { fingerHeld.erase(iter); recalculate_state(); } } } void SoftJoystick::recalculate_state() { state = 0; for (const auto& pair : fingerHeld) { state |= pair.second; } }
4,342
2,104
#pragma once #include "cache.hpp" #include <bunsan/pm/repository.hpp> #include <boost/noncopyable.hpp> namespace bunsan { namespace pm { class repository::extractor : private boost::noncopyable { public: extractor(repository &self, const extract_config &config); void extract(const entry &package, const boost::filesystem::path &destination); void install(const entry &package, const boost::filesystem::path &destination); void update(const entry &package, const boost::filesystem::path &destination); bool need_update(const boost::filesystem::path &destination, std::time_t lifetime); /*! * \note Will merge directories but will fail on file collisions * \warning Will work only on the local_system_().tempdir_for_build()'s * filesystem */ void extract_source(const entry &package, const std::string &source_id, const boost::filesystem::path &destination); void extract_build(const entry &package, const boost::filesystem::path &destination); void extract_installation(const entry &package, const boost::filesystem::path &destination); private: static void merge_directories(const boost::filesystem::path &source, const boost::filesystem::path &destination); private: cache &cache_(); local_system &local_system_(); private: repository &m_self; extract_config m_config; }; } // namespace pm } // namespace bunsan
1,528
416
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2022 */ #include <algorithm> #include <cstdio> #include <cstring> int n, a[5010], f[5010][5010]; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i); std::sort(a + 1, a + n + 1); for (int i = 1; i <= n; ++i) { for (int j = i + 1; j <= n; ++j) f[i][j] = 2; } int ans = 2; for (int i = 1, l, r; i <= n; ++i) { l = i - 1, r = i + 1; while (l > 0 && r <= n) { if (1ll * a[l] + a[r] == 2ll * a[i]) { f[i][r] = std::max(f[i][r], f[l][i] + 1); ans = std::max(ans, f[i][r]); ++r; } else if (1ll * a[l] + a[r] > 2ll * a[i]) --l; else ++r; } } printf("%d\n", ans); return 0; }
916
414
#include <iostream> #ifndef N // By default consider about 150 million numbers. #define N (1<<27) #endif bool can_be_prime [N]; int main () { // Mark all numbers as potentially prime. for (int i = 2 ; i < N ; i ++) { can_be_prime [i] = true; } int primes = 0; // Check numbers from smallest to largest. for (int i = 2 ; i < N ; i ++) { // Any number that is still marked // as potentially prime is prime. if (can_be_prime [i]) { primes ++; // All multiples of any prime are not prime. for (int j = 2 * i ; j < N ; j += i) { if (can_be_prime [j]) { can_be_prime [j] = false; } } } } std::cout << "Counted " << primes << " primes from " << 2 << " to " << N << "." << std::endl; return (0); }
882
299
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/storage_partition_impl_map.h" #include <unordered_set> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/command_line.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "content/browser/appcache/chrome_appcache_service.h" #include "content/browser/background_fetch/background_fetch_context.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" #include "content/browser/code_cache/generated_code_cache_context.h" #include "content/browser/cookie_store/cookie_store_context.h" #include "content/browser/file_system/browser_file_system_helper.h" #include "content/browser/loader/prefetch_url_loader_service.h" #include "content/browser/resource_context_impl.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/webui/url_data_manager_backend.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_client.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "crypto/sha2.h" #include "services/network/public/cpp/features.h" #include "storage/browser/blob/blob_storage_context.h" namespace content { namespace { // These constants are used to create the directory structure under the profile // where renderers with a non-default storage partition keep their persistent // state. This will contain a set of directories that partially mirror the // directory structure of BrowserContext::GetPath(). // // The kStoragePartitionDirname contains an extensions directory which is // further partitioned by extension id, followed by another level of directories // for the "default" extension storage partition and one directory for each // persistent partition used by a webview tag. Example: // // Storage/ext/ABCDEF/def // Storage/ext/ABCDEF/hash(partition name) // // The code in GetStoragePartitionPath() constructs these path names. // // TODO(nasko): Move extension related path code out of content. const base::FilePath::CharType kStoragePartitionDirname[] = FILE_PATH_LITERAL("Storage"); const base::FilePath::CharType kExtensionsDirname[] = FILE_PATH_LITERAL("ext"); const base::FilePath::CharType kDefaultPartitionDirname[] = FILE_PATH_LITERAL("def"); const base::FilePath::CharType kTrashDirname[] = FILE_PATH_LITERAL("trash"); // Because partition names are user specified, they can be arbitrarily long // which makes them unsuitable for paths names. We use a truncation of a // SHA256 hash to perform a deterministic shortening of the string. The // kPartitionNameHashBytes constant controls the length of the truncation. // We use 6 bytes, which gives us 99.999% reliability against collisions over // 1 million partition domains. // // Analysis: // We assume that all partition names within one partition domain are // controlled by the the same entity. Thus there is no chance for adverserial // attack and all we care about is accidental collision. To get 5 9s over // 1 million domains, we need the probability of a collision in any one domain // to be // // p < nroot(1000000, .99999) ~= 10^-11 // // We use the following birthday attack approximation to calculate the max // number of unique names for this probability: // // n(p,H) = sqrt(2*H * ln(1/(1-p))) // // For a 6-byte hash, H = 2^(6*8). n(10^-11, H) ~= 75 // // An average partition domain is likely to have less than 10 unique // partition names which is far lower than 75. // // Note, that for 4 9s of reliability, the limit is 237 partition names per // partition domain. const int kPartitionNameHashBytes = 6; // Needed for selecting all files in ObliterateOneDirectory() below. #if defined(OS_POSIX) const int kAllFileTypes = base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES | base::FileEnumerator::SHOW_SYM_LINKS; #else const int kAllFileTypes = base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES; #endif base::FilePath GetStoragePartitionDomainPath( const std::string& partition_domain) { CHECK(base::IsStringUTF8(partition_domain)); return base::FilePath(kStoragePartitionDirname).Append(kExtensionsDirname) .Append(base::FilePath::FromUTF8Unsafe(partition_domain)); } // Helper function for doing a depth-first deletion of the data on disk. // Examines paths directly in |current_dir| (no recursion) and tries to // delete from disk anything that is in, or isn't a parent of something in // |paths_to_keep|. Paths that need further expansion are added to // |paths_to_consider|. void ObliterateOneDirectory(const base::FilePath& current_dir, const std::vector<base::FilePath>& paths_to_keep, std::vector<base::FilePath>* paths_to_consider) { CHECK(current_dir.IsAbsolute()); base::FileEnumerator enumerator(current_dir, false, kAllFileTypes); for (base::FilePath to_delete = enumerator.Next(); !to_delete.empty(); to_delete = enumerator.Next()) { // Enum tracking which of the 3 possible actions to take for |to_delete|. enum { kSkip, kEnqueue, kDelete } action = kDelete; for (auto to_keep = paths_to_keep.begin(); to_keep != paths_to_keep.end(); ++to_keep) { if (to_delete == *to_keep) { action = kSkip; break; } else if (to_delete.IsParent(*to_keep)) { // |to_delete| contains a path to keep. Add to stack for further // processing. action = kEnqueue; break; } } switch (action) { case kDelete: base::DeletePathRecursively(to_delete); break; case kEnqueue: paths_to_consider->push_back(to_delete); break; case kSkip: break; } } } // Synchronously attempts to delete |unnormalized_root|, preserving only // entries in |paths_to_keep|. If there are no entries in |paths_to_keep| on // disk, then it completely removes |unnormalized_root|. All paths must be // absolute paths. void BlockingObliteratePath( const base::FilePath& unnormalized_browser_context_root, const base::FilePath& unnormalized_root, const std::vector<base::FilePath>& paths_to_keep, const scoped_refptr<base::TaskRunner>& closure_runner, base::OnceClosure on_gc_required) { // Early exit required because MakeAbsoluteFilePath() will fail on POSIX // if |unnormalized_root| does not exist. This is safe because there is // nothing to do in this situation anwyays. if (!base::PathExists(unnormalized_root)) { return; } // Never try to obliterate things outside of the browser context root or the // browser context root itself. Die hard. base::FilePath root = base::MakeAbsoluteFilePath(unnormalized_root); base::FilePath browser_context_root = base::MakeAbsoluteFilePath(unnormalized_browser_context_root); CHECK(!root.empty()); CHECK(!browser_context_root.empty()); CHECK(browser_context_root.IsParent(root) && browser_context_root != root); // Reduce |paths_to_keep| set to those under the root and actually on disk. std::vector<base::FilePath> valid_paths_to_keep; for (auto it = paths_to_keep.begin(); it != paths_to_keep.end(); ++it) { if (root.IsParent(*it) && base::PathExists(*it)) valid_paths_to_keep.push_back(*it); } // If none of the |paths_to_keep| are valid anymore then we just whack the // root and be done with it. Otherwise, signal garbage collection and do // a best-effort delete of the on-disk structures. if (valid_paths_to_keep.empty()) { base::DeletePathRecursively(root); return; } closure_runner->PostTask(FROM_HERE, std::move(on_gc_required)); // Otherwise, start at the root and delete everything that is not in // |valid_paths_to_keep|. std::vector<base::FilePath> paths_to_consider; paths_to_consider.push_back(root); while(!paths_to_consider.empty()) { base::FilePath path = paths_to_consider.back(); paths_to_consider.pop_back(); ObliterateOneDirectory(path, valid_paths_to_keep, &paths_to_consider); } } // Ensures each path in |active_paths| is a direct child of storage_root. void NormalizeActivePaths(const base::FilePath& storage_root, std::unordered_set<base::FilePath>* active_paths) { std::unordered_set<base::FilePath> normalized_active_paths; for (auto iter = active_paths->begin(); iter != active_paths->end(); ++iter) { base::FilePath relative_path; if (!storage_root.AppendRelativePath(*iter, &relative_path)) continue; std::vector<base::FilePath::StringType> components; relative_path.GetComponents(&components); DCHECK(!relative_path.empty()); normalized_active_paths.insert(storage_root.Append(components.front())); } active_paths->swap(normalized_active_paths); } // Deletes all entries inside the |storage_root| that are not in the // |active_paths|. Deletion is done in 2 steps: // // (1) Moving all garbage collected paths into a trash directory. // (2) Asynchronously deleting the trash directory. // // The deletion is asynchronous because after (1) completes, calling code can // safely continue to use the paths that had just been garbage collected // without fear of race conditions. // // This code also ignores failed moves rather than attempting a smarter retry. // Moves shouldn't fail here unless there is some out-of-band error (eg., // FS corruption). Retry logic is dangerous in the general case because // there is not necessarily a guaranteed case where the logic may succeed. // // This function is still named BlockingGarbageCollect() because it does // execute a few filesystem operations synchronously. void BlockingGarbageCollect( const base::FilePath& storage_root, const scoped_refptr<base::TaskRunner>& file_access_runner, std::unique_ptr<std::unordered_set<base::FilePath>> active_paths) { CHECK(storage_root.IsAbsolute()); NormalizeActivePaths(storage_root, active_paths.get()); base::FileEnumerator enumerator(storage_root, false, kAllFileTypes); base::FilePath trash_directory; if (!base::CreateTemporaryDirInDir(storage_root, kTrashDirname, &trash_directory)) { // Unable to continue without creating the trash directory so give up. return; } for (base::FilePath path = enumerator.Next(); !path.empty(); path = enumerator.Next()) { if (active_paths->find(path) == active_paths->end() && path != trash_directory) { // Since |trash_directory| is unique for each run of this function there // can be no colllisions on the move. base::Move(path, trash_directory.Append(path.BaseName())); } } file_access_runner->PostTask( FROM_HERE, base::BindOnce(base::GetDeletePathRecursivelyCallback(), trash_directory)); } } // namespace // static base::FilePath StoragePartitionImplMap::GetStoragePartitionPath( const std::string& partition_domain, const std::string& partition_name) { if (partition_domain.empty()) return base::FilePath(); base::FilePath path = GetStoragePartitionDomainPath(partition_domain); // TODO(ajwong): Mangle in-memory into this somehow, either by putting // it into the partition_name, or by manually adding another path component // here. Otherwise, it's possible to have an in-memory StoragePartition and // a persistent one that return the same FilePath for GetPath(). if (!partition_name.empty()) { // For analysis of why we can ignore collisions, see the comment above // kPartitionNameHashBytes. char buffer[kPartitionNameHashBytes]; crypto::SHA256HashString(partition_name, &buffer[0], sizeof(buffer)); return path.AppendASCII(base::HexEncode(buffer, sizeof(buffer))); } return path.Append(kDefaultPartitionDirname); } StoragePartitionImplMap::StoragePartitionImplMap( BrowserContext* browser_context) : browser_context_(browser_context), file_access_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT})), resource_context_initialized_(false) {} StoragePartitionImplMap::~StoragePartitionImplMap() { } StoragePartitionImpl* StoragePartitionImplMap::Get( const StoragePartitionConfig& partition_config, bool can_create) { // Find the previously created partition if it's available. PartitionMap::const_iterator it = partitions_.find(partition_config); if (it != partitions_.end()) return it->second.get(); if (!can_create) return nullptr; base::FilePath relative_partition_path = GetStoragePartitionPath( partition_config.partition_domain(), partition_config.partition_name()); std::unique_ptr<StoragePartitionImpl> partition_ptr( StoragePartitionImpl::Create( browser_context_, partition_config.in_memory(), relative_partition_path, partition_config.partition_domain())); StoragePartitionImpl* partition = partition_ptr.get(); partitions_[partition_config] = std::move(partition_ptr); partition->Initialize(); // Arm the serviceworker cookie change observation API. partition->GetCookieStoreContext()->ListenToCookieChanges( partition->GetNetworkContext(), /*success_callback=*/base::DoNothing()); PostCreateInitialization(partition, partition_config.in_memory()); return partition; } void StoragePartitionImplMap::AsyncObliterate( const std::string& partition_domain, base::OnceClosure on_gc_required) { // Find the active partitions for the domain. Because these partitions are // active, it is not possible to just delete the directories that contain // the backing data structures without causing the browser to crash. Instead, // of deleteing the directory, we tell each storage context later to // remove any data they have saved. This will leave the directory structure // intact but it will only contain empty databases. std::vector<StoragePartitionImpl*> active_partitions; std::vector<base::FilePath> paths_to_keep; for (PartitionMap::const_iterator it = partitions_.begin(); it != partitions_.end(); ++it) { const StoragePartitionConfig& config = it->first; if (config.partition_domain() == partition_domain) { it->second->ClearData( // All except shader cache. ~StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(), base::Time(), base::Time::Max(), base::DoNothing()); if (!config.in_memory()) { paths_to_keep.push_back(it->second->GetPath()); } } } // Start a best-effort delete of the on-disk storage excluding paths that are // known to still be in use. This is to delete any previously created // StoragePartition state that just happens to not have been used during this // run of the browser. base::FilePath domain_root = browser_context_->GetPath().Append( GetStoragePartitionDomainPath(partition_domain)); base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&BlockingObliteratePath, browser_context_->GetPath(), domain_root, paths_to_keep, base::ThreadTaskRunnerHandle::Get(), std::move(on_gc_required))); } void StoragePartitionImplMap::GarbageCollect( std::unique_ptr<std::unordered_set<base::FilePath>> active_paths, base::OnceClosure done) { // Include all paths for current StoragePartitions in the active_paths since // they cannot be deleted safely. for (PartitionMap::const_iterator it = partitions_.begin(); it != partitions_.end(); ++it) { const StoragePartitionConfig& config = it->first; if (!config.in_memory()) active_paths->insert(it->second->GetPath()); } // Find the directory holding the StoragePartitions and delete everything in // there that isn't considered active. base::FilePath storage_root = browser_context_->GetPath().Append( GetStoragePartitionDomainPath(std::string())); file_access_runner_->PostTaskAndReply( FROM_HERE, base::BindOnce(&BlockingGarbageCollect, storage_root, file_access_runner_, std::move(active_paths)), std::move(done)); } void StoragePartitionImplMap::ForEach( BrowserContext::StoragePartitionCallback callback) { for (PartitionMap::const_iterator it = partitions_.begin(); it != partitions_.end(); ++it) { callback.Run(it->second.get()); } } void StoragePartitionImplMap::PostCreateInitialization( StoragePartitionImpl* partition, bool in_memory) { // TODO(ajwong): ResourceContexts no longer have any storage related state. // We should move this into a place where it is called once per // BrowserContext creation rather than piggybacking off the default context // creation. // Note: moving this into Get() before partitions_[] is set causes reentrency. if (!resource_context_initialized_) { resource_context_initialized_ = true; InitializeResourceContext(browser_context_); } if (StoragePartition::IsAppCacheEnabled()) { partition->GetAppCacheService()->Initialize( in_memory ? base::FilePath() : partition->GetPath().Append(kAppCacheDirname), browser_context_, browser_context_->GetSpecialStoragePolicy()); } // Check first to avoid memory leak in unittests. if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) { partition->GetCacheStorageContext()->SetBlobParametersForCache( ChromeBlobStorageContext::GetFor(browser_context_)); if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( &ServiceWorkerContextWrapper::InitializeResourceContext, partition->GetServiceWorkerContext(), browser_context_->GetResourceContext())); } // Use PostTask() instead of RunOrPostTaskOnThread() because not posting a // task causes it to run before the CacheStorageManager has been // initialized, and then CacheStorageContextImpl::CacheManager() ends up // returning null instead of using the CrossSequenceCacheStorageManager in // unit tests that don't use a real IO thread, violating the DCHECK in // BackgroundFetchDataManager::InitializeOnCoreThread(). // TODO(crbug.com/960012): This workaround should be unnecessary after // CacheStorage moves off the IO thread to the thread pool. base::PostTask( FROM_HERE, {ServiceWorkerContext::GetCoreThreadId()}, base::BindOnce(&BackgroundFetchContext::InitializeOnCoreThread, partition->GetBackgroundFetchContext())); // We do not call InitializeURLRequestContext() for media contexts because, // other than the HTTP cache, the media contexts share the same backing // objects as their associated "normal" request context. Thus, the previous // call serves to initialize the media request context for this storage // partition as well. } } } // namespace content
20,260
5,886
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/hfp/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Sasikanth Avancha, Dhiraj Kalamkar, Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include "FusedConvBNXSMM.hpp" using namespace std; FusedConvBNXSMM::FusedConvBNXSMM(FusedConvBNImplParams* gp, int engine) : FusedConvBNImpl(gp, engine) { conv_desc.N = gp->batch_size/gp->num_numa_nodes; conv_desc.C = gp->nInput[0]; conv_desc.H = gp->iHeight; conv_desc.W = gp->iWidth; conv_desc.K = gp->nOutput; conv_desc.R = gp->kh; conv_desc.S = gp->kw; conv_desc.u = gp->c_stride_h; conv_desc.v = gp->c_stride_w; if(gp->physical_padding) { conv_desc.pad_h_in = gp->ipad_h; conv_desc.pad_w_in = gp->ipad_w; } else { conv_desc.pad_h_in = 0; conv_desc.pad_w_in = 0; } conv_desc.pad_w = gp->ipad_w; conv_desc.pad_h = gp->ipad_h; if(gp->physical_padding) { conv_desc.pad_h_out = gp->mpad_h; conv_desc.pad_w_out = gp->mpad_w; } else { conv_desc.pad_h_out = 0; conv_desc.pad_w_out = 0; } conv_desc.threads = gp->num_threads/gp->num_numa_nodes; conv_desc.algo = LIBXSMM_DNN_CONV_ALGO_DIRECT; conv_desc.buffer_format = LIBXSMM_DNN_TENSOR_FORMAT_LIBXSMM; conv_desc.filter_format = LIBXSMM_DNN_TENSOR_FORMAT_LIBXSMM; conv_desc.fuse_ops = LIBXSMM_DNN_CONV_FUSE_NONE; if(gp->out_data_type == DT_FLOAT) conv_desc.options = LIBXSMM_DNN_CONV_OPTION_OVERWRITE; else if(gp->out_data_type == DT_BF16) conv_desc.options = LIBXSMM_DNN_CONV_OPTION_F32_BF16_CVT_RNE_OVERWRITE; if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_FLOAT) { conv_desc.datatype_in = LIBXSMM_DNN_DATATYPE_BF16; conv_desc.datatype_out = LIBXSMM_DNN_DATATYPE_F32; } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { conv_desc.datatype_in = LIBXSMM_DNN_DATATYPE_BF16; conv_desc.datatype_out = LIBXSMM_DNN_DATATYPE_BF16; } else if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { conv_desc.datatype_in = LIBXSMM_DNN_DATATYPE_F32; conv_desc.datatype_out = LIBXSMM_DNN_DATATYPE_F32; } for(int i=0; i<gp->num_numa_nodes; i++) { libxsmm_handle_conv[i] = libxsmm_dnn_create_conv_layer( conv_desc, &status ); CHKERR_LIBXSMM_DNN( status ); } fusedbn_desc_train.partN = gp->batch_size/gp->num_numa_nodes; fusedbn_desc_train.fullN = gp->batch_size/gp->num_numa_nodes; fusedbn_desc_train.C = gp->nOutput; fusedbn_desc_train.H = gp->mHeight; fusedbn_desc_train.W = gp->mWidth; fusedbn_desc_train.u = gp->bn_stride_h; fusedbn_desc_train.v = gp->bn_stride_w; fusedbn_desc_train.pad_h_in = gp->mpad_h; fusedbn_desc_train.pad_w_in = gp->mpad_w; fusedbn_desc_train.pad_h_out = gp->opad_h; fusedbn_desc_train.pad_w_out = gp->opad_w; fusedbn_desc_train.threads = gp->num_threads/gp->num_numa_nodes; if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { fusedbn_desc_train.datatype_in = LIBXSMM_DNN_DATATYPE_F32; fusedbn_desc_train.datatype_out = LIBXSMM_DNN_DATATYPE_F32; } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { fusedbn_desc_train.datatype_in = LIBXSMM_DNN_DATATYPE_BF16; fusedbn_desc_train.datatype_out = LIBXSMM_DNN_DATATYPE_BF16; } fusedbn_desc_train.datatype_stats = LIBXSMM_DNN_DATATYPE_F32; fusedbn_desc_train.buffer_format = LIBXSMM_DNN_TENSOR_FORMAT_LIBXSMM; fusedbn_desc_train.fuse_order = LIBXSMM_DNN_FUSEDBN_ORDER_BN_ELTWISE_RELU; fusedbn_desc_train.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BN; if(gp->relu_fwd) #if 0 fusedbn_desc_train.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BN_RELU; #else fusedbn_desc_train.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BN_RELU_WITH_MASK; #endif if(gp->eltwise) fusedbn_desc_train.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BN_ELTWISE; if(gp->relu_fwd && gp->eltwise) #if 0 fusedbn_desc_train.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BN_ELTWISE_RELU; #else fusedbn_desc_train.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BN_ELTWISE_RELU_WITH_MASK; #endif for(int i=0; i<gp->num_numa_nodes; i++) { libxsmm_handle_bn_train[i] = libxsmm_dnn_create_fusedbatchnorm( fusedbn_desc_train, &status ); CHKERR_LIBXSMM_DNN( status ); } fusedbn_desc_test.partN = gp->batch_size/gp->num_numa_nodes; fusedbn_desc_test.fullN = gp->batch_size/gp->num_numa_nodes; fusedbn_desc_test.C = gp->nOutput; fusedbn_desc_test.H = gp->mHeight; fusedbn_desc_test.W = gp->mWidth; fusedbn_desc_test.u = gp->bn_stride_h; fusedbn_desc_test.v = gp->bn_stride_w; fusedbn_desc_test.pad_h_in = gp->mpad_h; fusedbn_desc_test.pad_w_in = gp->mpad_w; fusedbn_desc_test.pad_h_out = gp->opad_h; fusedbn_desc_test.pad_w_out = gp->opad_w; fusedbn_desc_test.threads = gp->num_threads/gp->num_numa_nodes; if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { fusedbn_desc_test.datatype_in = LIBXSMM_DNN_DATATYPE_F32; fusedbn_desc_test.datatype_out = LIBXSMM_DNN_DATATYPE_F32; } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { fusedbn_desc_test.datatype_in = LIBXSMM_DNN_DATATYPE_BF16; fusedbn_desc_test.datatype_out = LIBXSMM_DNN_DATATYPE_BF16; } fusedbn_desc_test.datatype_stats = LIBXSMM_DNN_DATATYPE_F32; fusedbn_desc_test.buffer_format = LIBXSMM_DNN_TENSOR_FORMAT_LIBXSMM; fusedbn_desc_test.fuse_order = LIBXSMM_DNN_FUSEDBN_ORDER_BN_ELTWISE_RELU; fusedbn_desc_test.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BNSCALE; if(gp->relu_fwd) #if 0 fusedbn_desc_test.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BNSCALE_RELU; #else fusedbn_desc_test.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BNSCALE_RELU_WITH_MASK; #endif if(gp->eltwise) fusedbn_desc_test.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BNSCALE_ELTWISE; if(gp->relu_fwd && gp->eltwise) #if 0 fusedbn_desc_test.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BNSCALE_ELTWISE_RELU; #else fusedbn_desc_test.fuse_ops = LIBXSMM_DNN_FUSEDBN_OPS_BNSCALE_ELTWISE_RELU_WITH_MASK; #endif for(int i=0; i<gp->num_numa_nodes; i++) { libxsmm_handle_bn_test[i] = libxsmm_dnn_create_fusedbatchnorm( fusedbn_desc_test, &status ); CHKERR_LIBXSMM_DNN( status ); } } void FusedConvBNXSMM::forwardPropagate(vector<TensorBuf *>& inp, TensorBuf *weightp, TensorBuf *hweightp, TensorBuf *midp, TensorBuf *gammap, TensorBuf *betap, TensorBuf *meanp, TensorBuf *varp, TensorBuf *outp, int tid) { int nImg = gp->batch_size/gp->num_numa_nodes; int nIFM = gp->nInput[0]; int nOFM = gp->nOutput; int nBIfm = nIFM/VLEN; int nBOfm = nOFM/VLEN; int ifh = gp->iHeight; int ifw = gp->iWidth; int mfh = gp->mHeight; int mfw = gp->mWidth; int ofh = gp->oHeight; int ofw = gp->oWidth; int bsh = gp->bn_stride_h; int bsw = gp->bn_stride_w; int csh = gp->c_stride_h; int csw = gp->c_stride_w; int iph = gp->ipad_h; int ipw = gp->ipad_w; int mph = gp->mpad_h; int mpw = gp->mpad_w; int oph = gp->opad_h; int opw = gp->opad_w; int fhm = mfh + 2*mph; int fwm = mfw + 2*mpw; int ifhp = ifh + 2*iph; int ifwp = ifw + 2*ipw; int ofhp = ofh + 2*oph; int ofwp = ofw + 2*opw; assert(bot_compute_engine[0] != -1); assert(top_compute_engine[0] != -1); // Conv input. LPBuffer is non-NULL if data layer output is BF16 void *inp_r[NUM_NUMA_NODES], *inp_l[NUM_NUMA_NODES], *hwt_ptr, *middle[NUM_NUMA_NODES], *output[NUM_NUMA_NODES]; void *wt_ptr[NUM_NUMA_NODES]; int imoff = conv_desc.N * conv_desc.C * ifhp * ifwp; if(gp->in_data_type == DT_BF16) { if(inp[0]->getLPBuffer() != NULL) inp_r[0] = inp[0]->getLPBuffer(); else inp_r[0] = inp[0]->getBuffer(); imoff = imoff * sizeof(libxsmm_bfloat16); } else if(gp->in_data_type == DT_FLOAT) { inp_r[0] = inp[0]->getBuffer(); imoff = imoff * sizeof(float); } for(int n=1; n<gp->num_numa_nodes; n++) inp_r[n] = inp_r[n-1] + imoff; if(gp->eltwise) { imoff = fusedbn_desc_train.partN * gp->nInput[1] * ifhp * ifwp; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); if(inp[1]->getLPBuffer() != NULL) inp_l[0] = inp[1]->getLPBuffer(); else inp_l[0] = inp[1]->getBuffer(); for(int n=1; n<gp->num_numa_nodes; n++) inp_l[n] = inp_l[n-1] + imoff; } // Conv Weight void **lptrptr = weightp->getLPBufferPtr(); void **ptrptr = weightp->getBufferPtr(); int offset = weightp->getOffset(); if(lptrptr != NULL) for(int n=0; n<gp->num_numa_nodes; n++) wt_ptr[n] = lptrptr[n] + offset*sizeof(libxsmm_bfloat16); else for(int n=0; n<gp->num_numa_nodes; n++) wt_ptr[n] = ptrptr[n] + offset*sizeof(float); void *wt_prv_ptr = NULL; // Conv weight history if(hweightp != NULL) hwt_ptr = hweightp->getBuffer(); else hwt_ptr=NULL; // Conv output middle[0] = midp->getBuffer(); imoff = conv_desc.N * conv_desc.K * fhm * fwm; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) middle[n] = middle[n-1] + imoff; output[0] = outp->getBuffer(); imoff = fusedbn_desc_train.partN * fusedbn_desc_train.C * ofhp * ofwp; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) output[n] = output[n-1] + imoff; void *gamma[NUM_NUMA_NODES]; void *beta[NUM_NUMA_NODES]; float *gexpect[NUM_NUMA_NODES]; float *gvar[NUM_NUMA_NODES]; float *gexp_test = (float*)meanp->getPrivBuffer(); float *gvar_test = (float*)varp->getPrivBuffer(); void **gptrptr = gammap->getBufferPtr(); offset = gammap->getOffset() * sizeof(float); for(int n=0; n<gp->num_numa_nodes; n++) gamma[n] = gptrptr[n] + offset; void **bptrptr = betap->getBufferPtr(); offset = betap->getOffset() * sizeof(float); for(int n=0; n<gp->num_numa_nodes; n++) beta[n] = bptrptr[n] + offset; void **mptrptr = meanp->getBufferPtr(); offset = meanp->getOffset(); for(int n=0; n<gp->num_numa_nodes; n++) gexpect[n] = (float*)mptrptr[n] + offset; void **vptrptr = varp->getBufferPtr(); offset = varp->getOffset(); for(int n=0; n<gp->num_numa_nodes; n++) gvar[n] = (float*)vptrptr[n] + offset; void **sptrptr = scratchp->getBufferPtr(); for(int n=0; n<gp->num_numa_nodes; n++) { if(bexpect[n] == NULL) { bexpect[n] = (void*)_mm_malloc(nOFM*sizeof(float), 64); #ifndef NDEBUG printf("%s allocated %lu bytes for mean\n",nname.c_str(), nOFM*sizeof(float)); #endif } if(bstddev[n] == NULL) { bstddev[n] = (void*)_mm_malloc(nOFM*sizeof(float), 64); #ifndef NDEBUG printf("%s allocated %lu bytes for stdev\n",nname.c_str(), nOFM*sizeof(float)); #endif } if(bvariance[n] == NULL) { bvariance[n] = (void*)_mm_malloc(nOFM*sizeof(float), 64); #ifndef NDEBUG printf("%s allocated %lu bytes for variance\n",nname.c_str(), nOFM*sizeof(float)); #endif } if(relu_mask[n] == NULL) relu_mask[n] = (void*)libxsmm_aligned_malloc(nImg*nOFM*ofhp*ofwp*sizeof(unsigned char), 2097152); } if(gexp_test == NULL) { gexp_test = (float*)_mm_malloc(nOFM*sizeof(float), 64); meanp->setPrivBuffer((void*)gexp_test); #ifndef NDEBUG printf("%s allocated %lu bytes for mean test\n",nname.c_str(), nOFM*sizeof(float)); #endif } if(gvar_test == NULL) { gvar_test = (float*)_mm_malloc(nOFM*sizeof(float), 64); varp->setPrivBuffer((void*)gvar_test); #ifndef NDEBUG printf("%s allocated %lu bytes for mean test\n",nname.c_str(), nOFM*sizeof(float)); #endif } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_input[n] == NULL) { libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_REGULAR_INPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_input[n] = libxsmm_dnn_link_tensor( libxsmm_layout, inp_r[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_bind_tensor( libxsmm_handle_conv[n], libxsmm_input[n], LIBXSMM_DNN_REGULAR_INPUT ) ); } } int welem = gp->nInput[0] * gp->nOutput * gp->kw * gp->kh; for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_filter[n] == NULL) { libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_REGULAR_FILTER, &status ); CHKERR_LIBXSMM_DNN( status ); if(gp->in_data_type == DT_FLOAT) { int wsize = welem*sizeof(float); wt_prv_ptr = (void*)libxsmm_aligned_malloc(wsize, 2097152); // Transform weight layout libxsmm_filter[n] = libxsmm_dnn_link_tensor( libxsmm_layout, wt_prv_ptr, &status ); CHKERR_LIBXSMM_DNN( status ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_copyin_tensor(libxsmm_filter[n], wt_ptr[n], LIBXSMM_DNN_TENSOR_FORMAT_KCRS) ); memcpy(wt_ptr[n], wt_prv_ptr, wsize); if(n==0) { libxsmm_checkpoint_filter = libxsmm_dnn_link_tensor(libxsmm_layout, wt_ptr[n], &status); CHKERR_LIBXSMM_DNN( status ); } libxsmm_filter[n] = libxsmm_dnn_link_tensor( libxsmm_layout, wt_ptr[n], &status ); CHKERR_LIBXSMM_DNN( status ); // Transform weight history layout if(n == 0) { if(hwt_ptr != NULL) { libxsmm_temp = libxsmm_dnn_link_tensor( libxsmm_layout, wt_prv_ptr, &status ); CHKERR_LIBXSMM_DNN( status ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_copyin_tensor( libxsmm_temp, (void*)hwt_ptr, LIBXSMM_DNN_TENSOR_FORMAT_KCRS ) ); memcpy(hwt_ptr, wt_prv_ptr, welem*sizeof(float)); libxsmm_checkpoint_history_filter = libxsmm_dnn_link_tensor(libxsmm_layout, hwt_ptr, &status); CHKERR_LIBXSMM_DNN( status ); } } libxsmm_free(wt_prv_ptr); wt_prv_ptr = NULL; weightp->setPrivBuffer(NULL); } else if(gp->in_data_type == DT_BF16) { int wsize = welem*sizeof(libxsmm_bfloat16); wt_prv_ptr = (void*)libxsmm_aligned_malloc(wsize, 2097152); // Transform BF16 weight layout libxsmm_filter[n] = libxsmm_dnn_link_tensor( libxsmm_layout, wt_prv_ptr, &status ); CHKERR_LIBXSMM_DNN( status ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_copyin_tensor(libxsmm_filter[n], wt_ptr[n], LIBXSMM_DNN_TENSOR_FORMAT_KCRS) ); memcpy(wt_ptr[n], wt_prv_ptr, wsize); libxsmm_filter[n] = libxsmm_dnn_link_tensor( libxsmm_layout, wt_ptr[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_free(wt_prv_ptr); // Transform FP32 weight layout if(n == 0) { libxsmm_layout->datatype = LIBXSMM_DNN_DATATYPE_F32; wt_prv_ptr = (void*)libxsmm_aligned_malloc(welem*sizeof(float), 2097152); libxsmm_checkpoint_filter = libxsmm_dnn_link_tensor( libxsmm_layout, wt_prv_ptr, &status ); CHKERR_LIBXSMM_DNN( status ); void *fwt_ptr = weightp->getBuffer(); CHKERR_LIBXSMM_DNN( libxsmm_dnn_copyin_tensor( libxsmm_checkpoint_filter, (void*)fwt_ptr, LIBXSMM_DNN_TENSOR_FORMAT_KCRS ) ); memcpy(fwt_ptr, wt_prv_ptr, welem*sizeof(float)); libxsmm_checkpoint_filter = libxsmm_dnn_link_tensor( libxsmm_layout, fwt_ptr, &status ); CHKERR_LIBXSMM_DNN( status ); // Transform FP32 weight history layout if(hwt_ptr != NULL) { libxsmm_checkpoint_history_filter = libxsmm_dnn_link_tensor( libxsmm_layout, wt_prv_ptr, &status ); CHKERR_LIBXSMM_DNN( status ); void *hfwt_ptr = hweightp->getBuffer(); CHKERR_LIBXSMM_DNN( libxsmm_dnn_copyin_tensor( libxsmm_checkpoint_history_filter, (void*)hfwt_ptr, LIBXSMM_DNN_TENSOR_FORMAT_KCRS ) ); memcpy(hfwt_ptr, wt_prv_ptr, welem*sizeof(float)); libxsmm_checkpoint_history_filter = libxsmm_dnn_link_tensor(libxsmm_layout, hfwt_ptr, &status); CHKERR_LIBXSMM_DNN( status ); } libxsmm_free(wt_prv_ptr); wt_prv_ptr = NULL; weightp->setPrivBuffer(NULL); } } libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_bind_tensor( libxsmm_handle_conv[n], libxsmm_filter[n], LIBXSMM_DNN_REGULAR_FILTER ) ); } } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_middle[n] == NULL) { // Conv Output libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_REGULAR_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_middle[n] = libxsmm_dnn_link_tensor( libxsmm_layout, middle[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_bind_tensor(libxsmm_handle_conv[n], libxsmm_middle[n], LIBXSMM_DNN_REGULAR_OUTPUT)); } } /* let's allocate (if required) and bind scratch */ int max_size = 0; for(int n=0; n<gp->num_numa_nodes; n++) { if(sptrptr[n] == NULL) { int mysize = libxsmm_dnn_get_scratch_size( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_ALL, &status ); CHKERR_LIBXSMM_DNN( status ); sptrptr[n] = (void*)libxsmm_aligned_malloc(mysize , 2097152); max_size = mysize; #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif printf("%s allocated %d bytes for scratch @ %p\n",nname.c_str(), mysize, sptrptr[n]); } else { int ssize = scratchp->getBufferSize(); int mysize = libxsmm_dnn_get_scratch_size( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_ALL, &status ); CHKERR_LIBXSMM_DNN( status ); if(ssize < mysize) { libxsmm_free(sptrptr[n]); sptrptr[n] = (void*)libxsmm_aligned_malloc(mysize, 2097152); max_size = mysize; #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif printf("%s allocated %d bytes for scratch @ %p, prev size was %d bytes\n",nname.c_str(), mysize, sptrptr[n], ssize); } else max_size = ssize; } } scratchp->setBufferSize(max_size); for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_input_bntrain[n]==NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_REGULAR_INPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_input_bntrain[n] = libxsmm_dnn_link_tensor( libxsmm_layout, middle[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_input_bntrain[n], LIBXSMM_DNN_REGULAR_INPUT ) ); } } if(gp->eltwise) { for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_input_add_bntrain[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_REGULAR_INPUT_ADD, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_input_add_bntrain[n] = libxsmm_dnn_link_tensor( libxsmm_layout, inp_l[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_input_add_bntrain[n], LIBXSMM_DNN_REGULAR_INPUT_ADD ) ) } } } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_expectval_train[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_CHANNEL_EXPECTVAL, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_expectval_train[n] = libxsmm_dnn_link_tensor( libxsmm_layout, bexpect[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_expectval_train[n], LIBXSMM_DNN_CHANNEL_EXPECTVAL ) ); } if(libxsmm_stddev_train[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_CHANNEL_RCPSTDDEV, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_stddev_train[n] = libxsmm_dnn_link_tensor( libxsmm_layout, bstddev[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_stddev_train[n], LIBXSMM_DNN_CHANNEL_RCPSTDDEV ) ); } if(libxsmm_variance_train[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_CHANNEL_VARIANCE, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_variance_train[n] = libxsmm_dnn_link_tensor( libxsmm_layout, bvariance[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_variance_train[n], LIBXSMM_DNN_CHANNEL_VARIANCE ) ); } if(libxsmm_gamma_train[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_REGULAR_CHANNEL_GAMMA, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_gamma_train[n] = libxsmm_dnn_link_tensor( libxsmm_layout, gamma[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_gamma_train[n], LIBXSMM_DNN_REGULAR_CHANNEL_GAMMA ) ); } if(libxsmm_beta_train[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_REGULAR_CHANNEL_BETA, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_beta_train[n] = libxsmm_dnn_link_tensor( libxsmm_layout, beta[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_beta_train[n], LIBXSMM_DNN_REGULAR_CHANNEL_BETA ) ); } if(libxsmm_output_bntrain[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_REGULAR_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_output_bntrain[n] = libxsmm_dnn_link_tensor( libxsmm_layout, output[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_output_bntrain[n], LIBXSMM_DNN_REGULAR_OUTPUT ) ); } if(libxsmm_relumask_bntrain[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_RELU_MASK, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_relumask_bntrain[n] = libxsmm_dnn_link_tensor( libxsmm_layout, relu_mask[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_train[n], libxsmm_relumask_bntrain[n], LIBXSMM_DNN_RELU_MASK ) ); } } /* let's allocate (if required) and bind scratch */ for(int n=0; n<gp->num_numa_nodes; n++) { if(sptrptr[n] == NULL) { int mysize = libxsmm_dnn_fusedbatchnorm_get_scratch_size( libxsmm_handle_bn_train[n], &status ); CHKERR_LIBXSMM_DNN( status ); sptrptr[n] = (void*)libxsmm_aligned_malloc(mysize , 2097152); max_size = mysize; #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif printf("%s allocated %d bytes for scratch @ %p\n",nname.c_str(), mysize, sptrptr[n]); } else { int ssize = scratchp->getBufferSize(); int mysize = libxsmm_dnn_fusedbatchnorm_get_scratch_size( libxsmm_handle_bn_train[n], &status ); CHKERR_LIBXSMM_DNN( status ); if(ssize < mysize) { libxsmm_free(sptrptr[n]); sptrptr[n] = (void*)libxsmm_aligned_malloc(mysize, 2097152); max_size = mysize; #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif printf("%s allocated %d bytes for scratch @ %p, prev size was %d bytes\n",nname.c_str(), mysize, sptrptr[n], ssize); } else max_size = ssize; } } scratchp->setBufferSize(max_size); for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_input_bntest[n]==NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_test[n], LIBXSMM_DNN_REGULAR_INPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_input_bntest[n] = libxsmm_dnn_link_tensor( libxsmm_layout, middle[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_test[n], libxsmm_input_bntest[n], LIBXSMM_DNN_REGULAR_INPUT ) ); } } if(gp->eltwise) { for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_input_add_bntest[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_test[n], LIBXSMM_DNN_REGULAR_INPUT_ADD, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_input_add_bntest[n] = libxsmm_dnn_link_tensor( libxsmm_layout, inp_l[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_test[n], libxsmm_input_add_bntest[n], LIBXSMM_DNN_REGULAR_INPUT_ADD ) ) } } } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_expectval_test[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_test[n], LIBXSMM_DNN_CHANNEL_EXPECTVAL, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_expectval_test[n] = libxsmm_dnn_link_tensor( libxsmm_layout, bexpect[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_expectval_test[n], LIBXSMM_DNN_CHANNEL_EXPECTVAL ) ); } if(libxsmm_stddev_test[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_test[n], LIBXSMM_DNN_CHANNEL_RCPSTDDEV, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_stddev_test[n] = libxsmm_dnn_link_tensor( libxsmm_layout, bstddev[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_stddev_test[n], LIBXSMM_DNN_CHANNEL_RCPSTDDEV ) ); } if(libxsmm_variance_test[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_test[n], LIBXSMM_DNN_CHANNEL_VARIANCE, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_variance_test[n] = libxsmm_dnn_link_tensor( libxsmm_layout, bvariance[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_variance_test[n], LIBXSMM_DNN_CHANNEL_VARIANCE ) ); } if(libxsmm_gamma_test[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_test[n], LIBXSMM_DNN_REGULAR_CHANNEL_GAMMA, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_gamma_test[n] = libxsmm_dnn_link_tensor( libxsmm_layout, gamma[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_gamma_test[n], LIBXSMM_DNN_REGULAR_CHANNEL_GAMMA ) ); } if(libxsmm_beta_test[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_test[n], LIBXSMM_DNN_REGULAR_CHANNEL_BETA, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_beta_test[n] = libxsmm_dnn_link_tensor( libxsmm_layout, beta[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_beta_test[n], LIBXSMM_DNN_REGULAR_CHANNEL_BETA ) ); } if(libxsmm_output_bntest[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_test[n], LIBXSMM_DNN_REGULAR_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_output_bntest[n] = libxsmm_dnn_link_tensor( libxsmm_layout, output[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_output_bntest[n], LIBXSMM_DNN_REGULAR_OUTPUT ) ); } if(libxsmm_relumask_bntest[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_test[n], LIBXSMM_DNN_RELU_MASK, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_relumask_bntest[n] = libxsmm_dnn_link_tensor( libxsmm_layout, relu_mask[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor(libxsmm_handle_bn_test[n], libxsmm_relumask_bntest[n], LIBXSMM_DNN_RELU_MASK ) ); } } /* let's allocate (if required) and bind scratch */ for(int n=0; n<gp->num_numa_nodes; n++) { if(sptrptr[n] == NULL) { int mysize = libxsmm_dnn_fusedbatchnorm_get_scratch_size( libxsmm_handle_bn_test[n], &status ); CHKERR_LIBXSMM_DNN( status ); sptrptr[n] = (void*)libxsmm_aligned_malloc(mysize , 2097152); max_size = mysize; #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif printf("%s allocated %d bytes for scratch @ %p\n",nname.c_str(), mysize, sptrptr[n]); } else { int ssize = scratchp->getBufferSize(); int mysize = libxsmm_dnn_fusedbatchnorm_get_scratch_size( libxsmm_handle_bn_test[n], &status ); CHKERR_LIBXSMM_DNN( status ); if(ssize < mysize) { libxsmm_free(sptrptr[n]); sptrptr[n] = (void*)libxsmm_aligned_malloc(mysize, 2097152); max_size = mysize; #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif printf("%s allocated %d bytes for scratch @ %p, prev size was %d bytes\n",nname.c_str(), mysize, sptrptr[n], ssize); } else max_size = ssize; } } scratchp->setBufferSize(max_size); if(prev_scratch_size == 0) prev_scratch_size = scratchp->getBufferSize(); if(!updated_scratch_fwd || prev_scratch_size != scratchp->getBufferSize()) { for(int n=0; n<gp->num_numa_nodes; n++) { CHKERR_LIBXSMM_DNN( libxsmm_dnn_bind_scratch( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_ALL, sptrptr[n] ) ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_scratch( libxsmm_handle_bn_train[n], sptrptr[n] ) ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_scratch( libxsmm_handle_bn_test[n], sptrptr[n] ) ); } updated_scratch_fwd = true; prev_scratch_size = scratchp->getBufferSize(); } #ifndef NDEBUG /* check physical padding */ if ( (iph > 0 || ipw > 0) && (mph > 0 || mpw > 0) ) { } else if ( (iph == 0 || ipw == 0) && (mph == 0 || mpw == 0) ) { } else { printf("node %s: conv xsmm forward is partially padded which cannot be :-(\n", nname.c_str()); } if ( (oph > 0 || opw > 0) && (mph > 0 || mpw > 0) ) { printf("node %s: batchnorm forward input and output is padded which cannot be :-(\n", nname.c_str()); } /* check rims */ if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { if(nIFM > 3) check_physical_pad( nname.c_str(), (float*)inp_r[0], nImg, nBIfm, ifh, ifw, VLEN, iph, ipw ); else check_physical_pad( nname.c_str(), (float*)inp_r[0], nImg, 1, ifh, ifw, 3, iph, ipw ); check_physical_pad( nname.c_str(), (float*)middle[0], nImg, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (float*)output[0], nImg, nBOfm, ofh, ofw, VLEN, oph, opw ); } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { if(nIFM > 3) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)inp_r[0], nImg, nBIfm, ifh, ifw, VLEN, iph, ipw ); else check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)inp_r[0], nImg, 1, ifh, ifw, 3, iph, ipw ); check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)middle[0], nImg, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)output[0], nImg, nBOfm, ofh, ofw, VLEN, oph, opw ); } #endif if(!use_global_stats) { #ifdef USE_XSMM_TIMING struct timeval tvsc, tvec; gettimeofday(&tvsc, NULL); #endif #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP const int tid = omp_get_thread_num(); #else const int tid = 0; #endif int ntps = gp->num_threads/gp->num_numa_nodes; int n = tid/ntps; CHKERR_LIBXSMM_DNN(libxsmm_dnn_execute_st( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_FWD, n*ntps, tid) ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_fusedbatchnorm_execute_st(libxsmm_handle_bn_train[n], LIBXSMM_DNN_COMPUTE_KIND_FWD, n*ntps, tid ) ); } #ifdef USE_XSMM_TIMING gettimeofday(&tvec, NULL); double fp_time = (tvec.tv_sec + tvec.tv_usec*1e-6) - (tvsc.tv_sec + tvsc.tv_usec*1e-6); #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif { double gf = (double)gp->batch_size * (double)gp->nInput[0] * (double)gp->nOutput * (double)gp->mHeight * (double)gp->mWidth * (double)gp->kh * (double)gp->kw * 2; if(gp->c_stride_h == 1 && gp->mpad_h == 0) printf("%s XSMM-CONV-FP mb%dic%dih%doc%doh%dkh%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,fp_time*1000.0, gf/fp_time/1e9); else if(gp->c_stride_h == 2) printf("%s XSMM-CONV-FP mb%dic%dih%doc%doh%dkh%dsh%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,gp->c_stride_h,fp_time*1000.0, gf/fp_time/1e9); else if(gp->mpad_h == 1) printf("%s XSMM-CONV-FP mb%dic%dih%doc%doh%dkh%dph%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,gp->mpad_h,fp_time*1000.0, gf/fp_time/1e9); } #endif #ifndef NDEBUG /* check physical padding */ if ( (iph > 0 || ipw > 0) && (mph > 0 || mpw > 0) ) { } else if ( (iph == 0 || ipw == 0) && (mph == 0 || mpw == 0) ) { } else { printf("node %s: conv xsmm forward is partially padded which cannot be :-(\n", nname.c_str()); } if ( (oph > 0 || opw > 0) && (mph > 0 || mpw > 0) ) { printf("node %s: batchnorm forward input and output is padded which cannot be :-(\n", nname.c_str()); } /* check rims */ if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { if(nIFM > 3) check_physical_pad( nname.c_str(), (float*)inp_r[0], nImg, nBIfm, ifh, ifw, VLEN, iph, ipw ); else check_physical_pad( nname.c_str(), (float*)inp_r[0], nImg, 1, ifh, ifw, 3, iph, ipw ); check_physical_pad( nname.c_str(), (float*)middle[0], nImg, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (float*)output[0], nImg, nBOfm, ofh, ofw, VLEN, oph, opw ); } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { if(nIFM > 3) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)inp_r[0], nImg, nBIfm, ifh, ifw, VLEN, iph, ipw ); else check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)inp_r[0], nImg, 1, ifh, ifw, 3, iph, ipw ); check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)middle[0], nImg, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)output[0], nImg, nBOfm, ofh, ofw, VLEN, oph, opw ); } #endif if(gp->exec_mode == "TRAIN") { for(int n=0; n<gp->num_numa_nodes; n++) { float *gexp = gexpect[n]; float *gv = gvar[n]; float (* __restrict bmean)[VLEN] = (float (*)[VLEN])bexpect[n]; float (* __restrict bvar)[VLEN] = (float (*)[VLEN])bvariance[n]; float nhw_ratio = float(fusedbn_desc_train.fullN*mfh*mfw)/float(fusedbn_desc_train.fullN*mfh*mfw - 1); #ifdef __AVX512F__ __m512 vmmf = _mm512_set1_ps(gp->mmf); __m512 vnhw_ratio = _mm512_set1_ps(nhw_ratio); #ifdef _OPENMP #pragma omp parallel #endif { int tid = omp_get_thread_num(); int ntps = gp->num_threads/gp->num_numa_nodes; int s = tid/ntps; if(s==n && tid % ntps == 0) { for (int b = 0; b < nBOfm; ++b) { __m512 vbm = _mm512_load_ps(&bmean[b][0]); __m512 vbvar = _mm512_load_ps(&bvar[b][0]); _mm512_store_ps( &(gexp[b*VLEN]), _mm512_add_ps(_mm512_mul_ps(_mm512_load_ps( &(gexp[b*VLEN]) ), vmmf), vbm)); _mm512_store_ps( &(gv[b*VLEN]), _mm512_add_ps( _mm512_mul_ps( _mm512_load_ps( &(gv[b*VLEN]) ), vmmf), _mm512_mul_ps(vnhw_ratio, vbvar))); } } } #else #ifdef _OPENMP #pragma omp parallel for #endif for (int b = 0; b < nBOfm; ++b) { #pragma omp simd for (int v = 0; v < 16; ++v) { gexp[(b*16)+v] = gexp[(b*16)+v] * gp->mmf + bmean[b][v]; gv[(b*16)+v] = gv[(b*16)+v] * gp->mmf + nhw_ratio*bvar[b][v]; } } #endif } scaling_factor_ *= gp->mmf; scaling_factor_ += 1.; } } else { #if defined(_OPENMP) #pragma omp parallel #endif { int tid = omp_get_thread_num(); int ntps = gp->num_threads/gp->num_numa_nodes; int s = tid/ntps; int ltid = tid - s*ntps; int jobs = (nOFM % ntps == 0) ? nOFM/ntps : nOFM/ntps + 1; int tb = (ltid*jobs < nOFM) ? ltid*jobs : nOFM; int te = ((ltid+1)*jobs < nOFM) ? (ltid+1)*jobs : nOFM; for(int i=tb; i < te; i++) { ((float*)bexpect[s])[i] = ((float*)gexpect[s])[i]/scaling_factor_; float tmp = ((float*)gvar[s])[i]/scaling_factor_; ((float*)bstddev[s])[i] = 1./sqrt(tmp + gp->eps); } } #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP const int tid = omp_get_thread_num(); #else const int tid = 0; #endif int ntps = gp->num_threads/gp->num_numa_nodes; int n = tid/ntps; CHKERR_LIBXSMM_DNN(libxsmm_dnn_execute_st(libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_FWD, n*ntps, tid)); CHKERR_LIBXSMM_DNN(libxsmm_dnn_fusedbatchnorm_execute_st(libxsmm_handle_bn_test[n], LIBXSMM_DNN_COMPUTE_KIND_FWD, n*ntps, tid)); } } } void FusedConvBNXSMM::backPropagate(TensorBuf *deloutp, TensorBuf* weightp, TensorBuf *delgammap, TensorBuf *delbetap, TensorBuf *delmidp, vector<TensorBuf*>& delinp, int tid) { void *deloutput[NUM_NUMA_NODES]; void *delmiddle[NUM_NUMA_NODES]; void *delinp_r[NUM_NUMA_NODES]; void *delinp_l[NUM_NUMA_NODES]; void *delgamma[NUM_NUMA_NODES]; void *delbeta[NUM_NUMA_NODES]; int nImg = fusedbn_desc_train.partN; int nIFM = gp->nInput[0]; int nOFM = gp->nOutput; int nBIfm = nIFM/VLEN; int nBOfm = nOFM/VLEN; int ofh = gp->oHeight; int ofw = gp->oWidth; int mfh = gp->mHeight; int mfw = gp->mWidth; int ifh = gp->iHeight; int ifw = gp->iWidth; int iph = gp->ipad_h; int ipw = gp->ipad_w; int oph = gp->opad_h; int opw = gp->opad_w; int mph = gp->mpad_h; int mpw = gp->mpad_w; int bsh = gp->bn_stride_h; int bsw = gp->bn_stride_w; int csh = gp->c_stride_h; int csw = gp->c_stride_w; int fhm = mfh + 2*mph; int fwm = mfw + 2*mpw; int fhi = ifh + 2*iph; int fwi = ifw + 2*ipw; int ofhp = ofh + 2*oph; int ofwp = ofw + 2*opw; deloutput[0] = deloutp->getBuffer(); delmiddle[0] = delmidp->getBuffer(); delinp_r[0] = delinp[0]->getBuffer(); delinp_l[0] = gp->eltwise ? delinp[1]->getBuffer() : NULL; int imoff = fusedbn_desc_train.partN * fusedbn_desc_train.C * ofhp * ofwp; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) deloutput[n] = deloutput[n-1] + imoff; imoff = conv_desc.N * conv_desc.K * fhm * fwm; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) delmiddle[n] = delmiddle[n-1] + imoff; imoff = conv_desc.N * conv_desc.C * fhi * fwi; if(gp->in_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->in_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) delinp_r[n] = delinp_r[n-1] + imoff; if(gp->eltwise) { imoff = fusedbn_desc_train.partN * gp->nInput[1] * fhi * fwi; if(gp->in_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->in_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) delinp_l[n] = delinp_l[n-1] + imoff; } void **gptrptr = delgammap->getBufferPtr(); void **bptrptr = delbetap->getBufferPtr(); int goffset = delgammap->getOffset() * sizeof(float); int boffset = delbetap->getOffset() * sizeof(float); for(int n=0; n<gp->num_numa_nodes; n++) { delgamma[n] = gptrptr[n] + goffset; delbeta[n] = bptrptr[n] + boffset; } void **sptrptr = scratchp->getBufferPtr(); for(int n=0; n<gp->num_numa_nodes; n++) { if(gp->in_data_type == DT_FLOAT) { float (* __restrict del_middle)[nBOfm][fhm][fwm][VLEN] = (float (*)[*][*][*][VLEN])delmiddle[n]; /* zero the rims in case of physical padding */ if (mph > 0 || mpw > 0) { #pragma omp parallel for for (int img = 0; img < conv_desc.N; img++) { for (int fm = 0; fm < nBOfm; fm++) { for (int w = 0; w < fwm; w++) { for (int ph = 0; ph < mph; ph++) { #ifdef __AVX512F__ _mm512_stream_ps( &(del_middle[img][fm][ph ][w][0]), _mm512_setzero_ps() ); _mm512_stream_ps( &(del_middle[img][fm][fhm-1-ph][w][0]), _mm512_setzero_ps() ); #else #pragma omp simd #pragma vector aligned #ifdef USE_NTS_BN #pragma vector nontemporal #endif for(int v=0; v < VLEN; v++) { del_middle[img][fm][ph][w][v] = 0.0f; del_middle[img][fm][fhm-1-ph][w][v] = 0.0f; } #endif } } for (int h = mph; h < mfh+mph; h++) { for (int pw = 0; pw < mpw; pw++) { #ifdef __AVX512F__ _mm512_stream_ps( &(del_middle[img][fm][h][pw ][0]), _mm512_setzero_ps() ); _mm512_stream_ps( &(del_middle[img][fm][h][fwm-1-pw][0]), _mm512_setzero_ps() ); #else #pragma omp simd #pragma vector aligned #ifdef USE_NTS_BN #pragma vector nontemporal #endif for(int v=0; v < VLEN; v++) { del_middle[img][fm][h][pw][v] = 0.0f; del_middle[img][fm][h][fwm-1-pw][v] = 0.0f; } #endif } } } } } } else if(gp->in_data_type == DT_BF16) { libxsmm_bfloat16 (* __restrict del_middle)[nBOfm][fhm][fwm][VLEN] = (libxsmm_bfloat16 (*)[*][*][*][VLEN])delmiddle[n]; /* zero the rims in case of physical padding */ /* @TODO, we need to do the same thing with del_input_l?! */ if (iph > 0 || iph > 0) { #pragma omp parallel for for (int img = 0; img < conv_desc.N; img++) { for (int fm = 0; fm < nBOfm; fm++) { for (int w = 0; w < fwm; w++) { for (int ph = 0; ph < mph; ph++) { #pragma omp simd #pragma vector aligned #ifdef USE_NTS_BN #pragma vector nontemporal #endif for(int v=0; v < VLEN; v++) { del_middle[img][fm][ph][w][v] = 0; del_middle[img][fm][fhm-1-ph][w][v] = 0; } } } for (int h = mph; h < mfh+mph; h++) { for (int pw = 0; pw < mpw; pw++) { #pragma omp simd #pragma vector aligned #ifdef USE_NTS_BN #pragma vector nontemporal #endif for(int v=0; v < VLEN; v++) { del_middle[img][fm][h][pw][v] = 0; del_middle[img][fm][h][fwm-1-pw][v] = 0; } } } } } } } } /* Perform physical padding tests */ #ifndef NDEBUG if ( (oph > 0 || opw > 0) && (mph > 0 || mpw > 0) ) { printf("node %s: batchnorm backward input and output is padded which cannot be :-(\n", nname.c_str()); } /* check rims */ if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { check_physical_pad( nname.c_str(), (float*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (float*)deloutput[0], conv_desc.N, nBOfm, ofh, ofw, VLEN, oph, opw ); } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)deloutput[0], conv_desc.N, nBOfm, ofh, ofw, VLEN, oph, opw ); } #endif if(!updated_scratch_bwd) { for(int n=0; n<gp->num_numa_nodes; n++) { CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_scratch( libxsmm_handle_bn_train[n], sptrptr[n] ) ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_bind_scratch( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_ALL, sptrptr[n] ) ); } updated_scratch_bwd = true; } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_deloutput[n] == NULL && libxsmm_delmiddle_bn[n] == NULL && libxsmm_delinput_add[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_deloutput[n] = libxsmm_dnn_link_tensor( libxsmm_layout, deloutput[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_deloutput[n], LIBXSMM_DNN_GRADIENT_OUTPUT ) ); libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_INPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_delmiddle_bn[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delmiddle[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delmiddle_bn[n], LIBXSMM_DNN_GRADIENT_INPUT ) ); if(gp->eltwise) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_INPUT_ADD, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_delinput_add[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delinp_l[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delinput_add[n], LIBXSMM_DNN_GRADIENT_INPUT_ADD ) ); } } } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_delgamma[n] == NULL && libxsmm_delbeta[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_CHANNEL_GAMMA, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_delgamma[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delgamma[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delgamma[n], LIBXSMM_DNN_GRADIENT_CHANNEL_GAMMA ) ); libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_CHANNEL_BETA, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_delbeta[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delbeta[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delbeta[n], LIBXSMM_DNN_GRADIENT_CHANNEL_BETA ) ); } } /* Perform physical padding tests */ #ifndef NDEBUG if ( (oph > 0 || opw > 0) && (mph > 0 || mpw > 0) ) { printf("node %s: batchnorm backward input and output is padded which cannot be :-(\n", nname.c_str()); } /* check rims */ if(gp->in_data_type == DT_FLOAT && gp->out_data_type == DT_FLOAT) { check_physical_pad( nname.c_str(), (float*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (float*)deloutput[0], conv_desc.N, nBOfm, ofh, ofw, VLEN, oph, opw ); } else if(gp->in_data_type == DT_BF16 && gp->out_data_type == DT_BF16) { check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, VLEN, mph, mpw ); check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)deloutput[0], conv_desc.N, nBOfm, ofh, ofw, VLEN, oph, opw ); } #endif for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_delinput[n] == NULL && libxsmm_delmiddle_conv[n] == NULL) { libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_GRADIENT_INPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_delinput[n] = libxsmm_dnn_link_tensor(libxsmm_layout, delinp_r[n], &status ); CHKERR_LIBXSMM_DNN(status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_bind_tensor(libxsmm_handle_conv[n], libxsmm_delinput[n], LIBXSMM_DNN_GRADIENT_INPUT)); libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_GRADIENT_OUTPUT, &status ); CHKERR_LIBXSMM_DNN(status ); libxsmm_delmiddle_conv[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delmiddle[n], &status ); CHKERR_LIBXSMM_DNN(status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_bind_tensor( libxsmm_handle_conv[n], libxsmm_delmiddle_conv[n], LIBXSMM_DNN_GRADIENT_OUTPUT ) ); } } #ifndef NDEBUG /* check physical padding */ if ( (gp->ipad_h > 0 || gp->ipad_w > 0) && (gp->mpad_h > 0 || gp->mpad_w > 0) ) { } else if ( (gp->ipad_h == 0 || gp->ipad_w == 0) && (gp->mpad_h == 0 || gp->mpad_w == 0) ) { } else { printf("node %s: conv xsmm backward is partially padded which cannot be :-(\n", nname.c_str()); } if(gp->out_data_type == DT_FLOAT) check_physical_pad( nname.c_str(), (float*)delinp_r[0], conv_desc.N, nBIfm, ifh, ifw, 16, iph, ipw ); else if(gp->out_data_type == DT_BF16) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delinp_r[0], conv_desc.N, nBIfm, ifh, ifw, 16, iph, ipw ); if(gp->in_data_type == DT_FLOAT) check_physical_pad( nname.c_str(), (float*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw ); else if(gp->in_data_type == DT_BF16) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw ); #endif #ifdef USE_XSMM_TIMING struct timeval tvsc, tvec; gettimeofday(&tvsc, NULL); #endif #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP const int tid = omp_get_thread_num(); #else const int tid = 0; #endif int ntps = gp->num_threads/gp->num_numa_nodes; int n = tid/ntps; CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_execute_st( libxsmm_handle_bn_train[n], LIBXSMM_DNN_COMPUTE_KIND_BWD, n*ntps, tid ) ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_execute_st( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_BWD, n*ntps, tid ) ); #ifdef USE_MLSL #pragma omp barrier if(tid == 0) { float *dgp = (float*)delgamma[0]; float *dbp = (float*)delbeta[0]; for(int nn=1; nn<gp->num_numa_nodes; nn++) { float *rdgp = (float*)delgamma[nn]; float *rdbp = (float*)delbeta[nn]; #pragma omp simd for(int i=0; i<nOFM; i++) { dgp[i] += rdgp[i]; dbp[i] += rdbp[i]; } } for(int nn=1; nn<gp->num_numa_nodes; nn++) { float *rdgp = (float*)delgamma[nn]; float *rdbp = (float*)delbeta[nn]; #pragma vector nontemporal #pragma omp simd for(int i=0; i<nOFM; i++) { rdgp[i] = dgp[i]; rdbp[i] = dbp[i]; } } } #endif } #ifdef USE_XSMM_TIMING gettimeofday(&tvec, NULL); double bp_time = (tvec.tv_sec + tvec.tv_usec*1e-6) - (tvsc.tv_sec + tvsc.tv_usec*1e-6); #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif { double gf = (double)gp->batch_size * (double)gp->nInput[0] * (double)gp->nOutput * (double)gp->mHeight * (double)gp->mWidth * (double)gp->kh * (double)gp->kw * 2; if(gp->c_stride_h == 1 && gp->mpad_h == 0) printf("%s XSMM-CONV-BP mb%dic%dih%doc%doh%dkh%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size, gp->nInput[0], gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,bp_time*1000.0, gf/bp_time/1e9); else if(gp->c_stride_h == 2) printf("%s XSMM-CONV-BP mb%dic%dih%doc%doh%dkh%dsh%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,gp->c_stride_h,bp_time*1000.0, gf/bp_time/1e9); else if(gp->mpad_h == 1) printf("%s XSMM-CONV-BP mb%dic%dih%doc%doh%dkh%dph%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,gp->mpad_h,bp_time*1000.0, gf/bp_time/1e9); } #endif #ifndef NDEBUG /* check physical padding */ if ( (gp->ipad_h > 0 || gp->ipad_w > 0) && (gp->mpad_h > 0 || gp->mpad_w > 0) ) { } else if ( (gp->ipad_h == 0 || gp->ipad_w == 0) && (gp->mpad_h == 0 || gp->mpad_w == 0) ) { } else { printf("node %s: conv xsmm backward is partially padded which cannot be :-(\n", nname.c_str()); } if(gp->out_data_type == DT_FLOAT) check_physical_pad( nname.c_str(), (float*)delinp_r[0], conv_desc.N, nBIfm, ifh, ifw, 16, iph, ipw ); else if(gp->out_data_type == DT_BF16) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delinp_r[0], conv_desc.N, nBIfm, ifh, ifw, 16, iph, ipw ); if(gp->in_data_type == DT_FLOAT) check_physical_pad( nname.c_str(), (float*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw ); else if(gp->in_data_type == DT_BF16) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw ); #endif } void FusedConvBNXSMM::weightUpdate(TensorBuf *inp, TensorBuf *deloutp, TensorBuf *delmidp, TensorBuf* delweightp, TensorBuf *delgammap, TensorBuf* delbetap, int tid) { int nOFM = gp->nOutput; int ofm = gp->nOutput; int ifm = gp->nInput[0]; int kh = gp->kh; int kw = gp->kw; int nBOfm = nOFM/VLEN; int ofh = gp->oHeight; int ofw = gp->oWidth; int oph = gp->opad_h; int opw = gp->opad_w; int ofhp = ofh + 2*oph; int ofwp = ofw + 2*opw; int mfh = gp->mHeight; int mfw = gp->mWidth; int mph = gp->mpad_h; int mpw = gp->mpad_w; int fhm = mfh + 2*mph; int fwm = mfw + 2*mpw; void *deloutput[NUM_NUMA_NODES]; void *delgamma[NUM_NUMA_NODES]; void *delbeta[NUM_NUMA_NODES]; void *dwt_ptr[NUM_NUMA_NODES]; void *delmiddle[NUM_NUMA_NODES]; if(!gp->bprop) { deloutput[0] = deloutp->getBuffer(); int imoff = fusedbn_desc_train.partN * fusedbn_desc_train.C * ofhp * ofwp; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) deloutput[n] = deloutput[n-1] + imoff; } void **ptrptr = delweightp->getBufferPtr(); int offset = delweightp->getOffset(); if(gp->in_data_type == DT_FLOAT) offset = offset*sizeof(float); else if(gp->in_data_type == DT_BF16) offset = offset*sizeof(libxsmm_bfloat16); for(int n=0; n<gp->num_numa_nodes; n++) dwt_ptr[n] = ptrptr[n] + offset; if(!gp->bprop) { void **gptrptr = delgammap->getBufferPtr(); void **bptrptr = delbetap->getBufferPtr(); int goffset = delgammap->getOffset() * sizeof(float); int boffset = delbetap->getOffset() * sizeof(float); for(int n=0; n<gp->num_numa_nodes; n++) { delgamma[n] = gptrptr[n] + goffset; delbeta[n] = bptrptr[n] + boffset; } } delmiddle[0] = delmidp->getBuffer(); int imoff = conv_desc.N * conv_desc.K * fhm * fwm; if(gp->out_data_type == DT_FLOAT) imoff = imoff * sizeof(float); else if(gp->out_data_type == DT_BF16) imoff = imoff * sizeof(libxsmm_bfloat16); for(int n=1; n<gp->num_numa_nodes; n++) delmiddle[n] = delmiddle[n-1] + imoff; void **sptrptr = scratchp->getBufferPtr(); if(!updated_scratch_upd) { for(int n=0; n<gp->num_numa_nodes; n++) { if(!gp->bprop) CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_scratch( libxsmm_handle_bn_train[n], sptrptr[n] ) ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_bind_scratch( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_ALL, sptrptr[n] ) ); } updated_scratch_upd = true; } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_delfilter[n] == NULL) { libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_GRADIENT_FILTER, &status ); CHKERR_LIBXSMM_DNN(status ); libxsmm_delfilter[n] = libxsmm_dnn_link_tensor( libxsmm_layout, dwt_ptr[n], &status ); CHKERR_LIBXSMM_DNN(status); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_bind_tensor( libxsmm_handle_conv[n], libxsmm_delfilter[n], LIBXSMM_DNN_GRADIENT_FILTER ) ); } } for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_delmiddle_conv[n] == NULL) { libxsmm_layout = libxsmm_dnn_create_tensor_datalayout( libxsmm_handle_conv[n], LIBXSMM_DNN_GRADIENT_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_delmiddle_conv[n] = libxsmm_dnn_link_tensor(libxsmm_layout, delmiddle[n], &status ); CHKERR_LIBXSMM_DNN(status); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN(libxsmm_dnn_bind_tensor( libxsmm_handle_conv[n], libxsmm_delmiddle_conv[n], LIBXSMM_DNN_GRADIENT_OUTPUT ) ); } } if(!gp->bprop) { for(int n=0; n<gp->num_numa_nodes; n++) { if(libxsmm_deloutput[n] == NULL && libxsmm_delmiddle_bn[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_deloutput[n] = libxsmm_dnn_link_tensor( libxsmm_layout, deloutput[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_deloutput[n], LIBXSMM_DNN_GRADIENT_OUTPUT ) ); libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout( libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_INPUT, &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_delmiddle_bn[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delmiddle[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delmiddle_bn[n], LIBXSMM_DNN_GRADIENT_INPUT ) ); } if(libxsmm_delgamma[n] == NULL && libxsmm_delbeta[n] == NULL) { libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_CHANNEL_GAMMA, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_delgamma[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delgamma[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delgamma[n], LIBXSMM_DNN_GRADIENT_CHANNEL_GAMMA ) ); libxsmm_layout = libxsmm_dnn_fusedbatchnorm_create_tensor_datalayout(libxsmm_handle_bn_train[n], LIBXSMM_DNN_GRADIENT_CHANNEL_BETA, &status); CHKERR_LIBXSMM_DNN( status ); libxsmm_delbeta[n] = libxsmm_dnn_link_tensor( libxsmm_layout, delbeta[n], &status ); CHKERR_LIBXSMM_DNN( status ); libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_bind_tensor( libxsmm_handle_bn_train[n], libxsmm_delbeta[n], LIBXSMM_DNN_GRADIENT_CHANNEL_BETA ) ); } } } #ifndef NDEBUG /* check physical padding */ if ( (gp->ipad_h > 0 || gp->ipad_w > 0) && (gp->mpad_h > 0 || gp->mpad_w > 0) ) { } else if ( (gp->ipad_h == 0 || gp->ipad_w == 0) && (gp->mpad_h == 0 || gp->mpad_w == 0) ) { } else { printf("node %s: conv xsmm backward is partially padded which cannot be :-(\n", nname.c_str()); } if(gp->in_data_type == DT_FLOAT) check_physical_pad( nname.c_str(), (float*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw); else if(gp->in_data_type == DT_BF16) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw); #endif #ifdef USE_XSMM_TIMING__ struct timeval tvsc, tvec; gettimeofday(&tvsc, NULL); #endif if(!gp->bprop) { #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP const int tid = omp_get_thread_num(); #else const int tid = 0; #endif int ntps = gp->num_threads/gp->num_numa_nodes; int n = tid/ntps; CHKERR_LIBXSMM_DNN( libxsmm_dnn_fusedbatchnorm_execute_st( libxsmm_handle_bn_train[n], LIBXSMM_DNN_COMPUTE_KIND_BWD, n*ntps, tid ) ); CHKERR_LIBXSMM_DNN( libxsmm_dnn_execute_st( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_UPD, n*ntps, tid ) ); #ifdef USE_MLSL #pragma omp barrier if(gp->in_data_type == DT_FLOAT) { #include "reduce_weight_grads.c" } else if(gp->in_data_type == DT_BF16) { #include "reduce_weight_grads_bf16.c" } #pragma omp barrier if(tid == 0) { float *dgp = (float*)delgamma[0]; float *dbp = (float*)delbeta[0]; for(int nn=1; nn<gp->num_numa_nodes; nn++) { float *rdgp = (float*)delgamma[nn]; float *rdbp = (float*)delbeta[nn]; #pragma omp simd for(int i=0; i<nOFM; i++) { dgp[i] += rdgp[i]; dbp[i] += rdbp[i]; } #pragma vector nontemporal #pragma omp simd for(int i=0; i<nOFM; i++) { rdgp[i] = dgp[i]; rdbp[i] = dbp[i]; } } } #endif } } else { #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP const int tid = omp_get_thread_num(); #else const int tid = 0; #endif int ntps = gp->num_threads/gp->num_numa_nodes; int n = tid/ntps; CHKERR_LIBXSMM_DNN( libxsmm_dnn_execute_st( libxsmm_handle_conv[n], LIBXSMM_DNN_COMPUTE_KIND_UPD, n*ntps, tid ) ); #ifdef USE_MLSL #pragma omp barrier if(gp->in_data_type == DT_FLOAT) { #include "reduce_weight_grads.c" } else if(gp->in_data_type == DT_BF16) { #include "reduce_weight_grads_bf16.c" } #endif } } #ifdef USE_XSMM_TIMING__ gettimeofday(&tvec, NULL); double wu_time = (tvec.tv_sec + tvec.tv_usec*1e-6) - (tvsc.tv_sec + tvsc.tv_usec*1e-6); #ifdef USE_MLSL if(MLSL::Environment::GetEnv().GetProcessIdx() == 0) #endif { double gf = (double)gp->batch_size * (double)gp->nInput[0] * (double)gp->nOutput * (double)gp->mHeight * (double)gp->mWidth * (double)gp->kh * (double)gp->kw * 2; if(gp->c_stride_h == 1 && gp->mpad_h == 0) printf("%s XSMM-CONV-WU mb%dic%dih%doc%doh%dkh%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,wu_time*1000.0, gf/wu_time/1e9); else if(gp->c_stride_h == 2) printf("%s XSMM-CONV-WU mb%dic%dih%doc%doh%dkh%dsh%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,gp->c_stride_h,wu_time*1000.0, gf/wu_time/1e9); else if(gp->mpad_h == 1) printf("%s XSMM-CONV-WU mb%dic%dih%doc%doh%dkh%dph%dn time = %g ms, GFLOPS = %.1f\n",gp->node_name.c_str(),gp->batch_size,gp->nInput[0],gp->iHeight,gp->nOutput,gp->mHeight,gp->kh,gp->mpad_h,wu_time*1000.0, gf/wu_time/1e9); } #endif #ifndef NDEBUG /* check physical padding */ if(gp->in_data_type == DT_FLOAT) check_physical_pad( nname.c_str(), (float*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw); else if(gp->in_data_type == DT_BF16) check_physical_pad( nname.c_str(), (libxsmm_bfloat16*)delmiddle[0], conv_desc.N, nBOfm, mfh, mfw, 16, mph, mpw); #endif } void FusedConvBNXSMM::dumpBuffer(TensorBuf* tBuf, void* wtemp) { int buftype = tBuf->getBufferType(); if(buftype == DATA) { CHKERR_LIBXSMM_DNN(libxsmm_dnn_copyout_tensor(libxsmm_checkpoint_filter, wtemp, LIBXSMM_DNN_TENSOR_FORMAT_KCRS)); } else if(buftype == HISTORY) CHKERR_LIBXSMM_DNN(libxsmm_dnn_copyout_tensor(libxsmm_checkpoint_history_filter, wtemp, LIBXSMM_DNN_TENSOR_FORMAT_KCRS)); }
68,105
31,741
#include "keysmappingdialog.h" #include "ui_keysmappingdialog.h" KeysMappingDialog::KeysMappingDialog(QWidget *parent) : QDialog(parent), ui(new Ui::KeysMappingDialog) { ui->setupUi(this); this->setWindowTitle("Keys Options"); connect(ui->A_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->B_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->C_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->D_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->E_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->F_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->G_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->H_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->I_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->J_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->K_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->L_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->M_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->N_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->O_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); connect(ui->P_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping); } KeysMappingDialog::~KeysMappingDialog() { delete ui; } void KeysMappingDialog::on_buttonBox_accepted() { accept(); } void KeysMappingDialog::on_buttonBox_rejected() { reject(); } void KeysMappingDialog::slotKeysMapping() { QChar keyChar = sender()->objectName().at(0); keyNumber = keyChar.unicode() - 65; qDebug() << "Button:" << keyChar; emit signalSetKeyNumber(keyNumber); } void KeysMappingDialog::slotGetKey(Qt::Key key) { KeyMappingDialog dialog(key, this); if(dialog.exec() == QDialog::Accepted) { qDebug() << "Ok"; emit signalSendNewKeyValue(keyNumber, dialog.getNewKeyValue()); } }
2,456
790
#include <fase2/fase.h> #include <fase2/imgui_editor/imgui_editor.h> #include <fase2/stdparts.h> #include <string> #include <vector> #include "../extra_parts.h" #include "../fase_gl_utils.h" #include "funcs.h" int main() { // Create Fase instance with GUI editor fase::Fase<fase::ImGuiEditor, fase::FixedPipelineParts, NFDParts> app; std::vector<std::string> in_arg{"red", "green", "blue", "count"}; std::vector<std::string> out_arg{ "dst_red", "dst_green", "dst_blue", }; auto api = app.newPipeline<float, float, float>("fixed", in_arg, out_arg) .fix<float, float, float, float>(); auto hook = [&](std::vector<float>* bg_col) { try { if (!api) { return; // "fixed" is deleted or something went wrong. } bg_col->resize(3); auto [r, g, b] = api(bg_col->at(0), bg_col->at(1), bg_col->at(2), 0.f); r = r > 1.f ? r - 1.f : r; g = g > 1.f ? g - 1.f : g; b = b > 1.f ? b - 1.f : b; bg_col->at(0) = r; bg_col->at(1) = g; bg_col->at(2) = b; } catch (fase::TryToGetEmptyVariable&) { } }; AddNFDButtons(app, app); // Create OpenGL window GLFWwindow* window = InitOpenGL("GUI Editor Example"); if (!window) { return 0; } // Initialize ImGui InitImGui(window, "../third_party/imgui/misc/fonts/Cousine-Regular.ttf"); // Start main loop RunRenderingLoop(window, app, hook); return 0; }
1,604
599
#include <iostream> #include <vector> #include <cassert> #include <algorithm> using namespace std; struct Chunk{ int key; int length; Chunk *prev; Chunk *next; Chunk(int k=0, int len=0) : key(k), length(len), prev(nullptr), next(nullptr) {} } *head; void init(int m) { Chunk *t = new Chunk(0, m); t->next = new Chunk(-1, 0); t->prev = new Chunk(-1, 0); t->next->prev = t; t->prev->next = t; head = t->prev; } Chunk *find_empty(int len) { Chunk *p = head->next; for (Chunk *p = head->next; p->key != -1; p = p->next) { if (p->key == 0 && p->length >= len) return p; } return nullptr; } void insert(Chunk *p, int key, int len) { assert(p->key == 0 && p->length >= len); if (p->length == len) p->key = key; else { Chunk *t = new Chunk(0, p->length-len); t->prev = p; t->next = p->next; t->next->prev = t; p->next = t; p->key = key; p->length = len; } } void release(Chunk *p) { Chunk *t = p->prev; if (t->key == 0) { p->length += t->length; p->prev = t->prev; p->prev->next = p; delete t; } t = p->next; if (t->key == 0) { p->length += t->length; p->next = t->next; p->next->prev = p; delete t; } p->key = 0; } int main(void) { int n, m; cin >> n >> m; init(m); vector<Chunk *> pos(n+1); for (int i = 1, last = 1; i <= n; ++i) { int k; cin >> k; while (true) { Chunk *p = find_empty(k); if (p) { insert(p, i, k); pos[i] = p; break; } else { release(pos[last]); pos[last++] = nullptr; } } } vector<pair<int, int>> res; int last = 0; for (Chunk *p = head->next; p->key != -1; p = p->next) { if (p->key) res.push_back(make_pair(p->key, last)); last += p->length; } sort(res.begin(), res.end()); for (auto &pr : res) cout << pr.first << " " << pr.second << '\n'; cout << flush; return 0; }
2,196
848
#include "core/ir/ir.h" #include "core/util/prelude.h" namespace trtorch { namespace core { namespace ir { bool valid_dtype_format_combo(nvinfer1::DataType dtype, nvinfer1::TensorFormat format) { switch (dtype) { case nvinfer1::DataType::kINT8: // Supports just Linear (NCHW) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: default: return false; } case nvinfer1::DataType::kINT32: // Supports just Linear (NCHW) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: default: return false; } case nvinfer1::DataType::kHALF: // Supports just Linear (NCHW) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: default: return false; } case nvinfer1::DataType::kFLOAT: // Supports both Linear (NCHW) and channel last (NHWC) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: return true; default: return false; } default: return false; } } bool valid_input_dtype(nvinfer1::DataType dtype) { switch (dtype) { case nvinfer1::DataType::kBOOL: return false; case nvinfer1::DataType::kFLOAT: return true; case nvinfer1::DataType::kHALF: return true; case nvinfer1::DataType::kINT8: return true; case nvinfer1::DataType::kINT32: return true; default: return false; } } Input::Input( std::vector<int64_t> shape, nvinfer1::DataType dtype, nvinfer1::TensorFormat format, bool dtype_is_user_defined) { if (shape.size() > 5) { LOG_WARNING("Verify that this dim size is accepted"); } opt = util::toDims(shape); min = util::toDims(shape); max = util::toDims(shape); input_shape = util::toDims(shape); input_is_dynamic = false; TRTORCH_CHECK(valid_input_dtype(dtype), "Unsupported input data type: " << dtype); this->dtype = dtype; TRTORCH_CHECK( valid_dtype_format_combo(dtype, format), "Unsupported combination of dtype and tensor format: (" << dtype << ", " << format << "), TRTorch only supports contiguous format (NCHW) except with input type Float32 where channel last (NHWC) is also supported"); this->format = format; this->dtype_is_user_defined = dtype_is_user_defined; } Input::Input( std::vector<int64_t> min_shape, std::vector<int64_t> opt_shape, std::vector<int64_t> max_shape, nvinfer1::DataType dtype, nvinfer1::TensorFormat format, bool dtype_is_user_defined) { if (min_shape.size() > 5 || opt_shape.size() > 5 || max_shape.size() > 5) { LOG_WARNING("Verify that this dim size is accepted"); } std::set<size_t> sizes; sizes.insert(min_shape.size()); sizes.insert(opt_shape.size()); sizes.insert(max_shape.size()); if (sizes.size() != 1) { LOG_ERROR( "Expected all input sizes have the same dimensions, but found dimensions: min(" << min_shape.size() << "), opt(" << opt_shape.size() << "), max(" << max_shape.size() << ")"); } min = util::toDims(min_shape); opt = util::toDims(opt_shape); max = util::toDims(max_shape); std::vector<int64_t> dyn_shape; for (size_t i = 0; i < opt_shape.size(); i++) { std::set<uint64_t> dim; dim.insert(min_shape[i]); dim.insert(opt_shape[i]); dim.insert(max_shape[i]); if (dim.size() != 1) { dyn_shape.push_back(-1); input_is_dynamic = true; } else { dyn_shape.push_back(opt_shape[i]); } } input_shape = util::toDims(dyn_shape); TRTORCH_CHECK(valid_input_dtype(dtype), "Unsupported input data type: " << dtype); this->dtype = dtype; TRTORCH_CHECK( valid_dtype_format_combo(dtype, format), "Unsupported combination of dtype and tensor format: (" << dtype << ", " << format << "), TRTorch only supports contiguous format (NCHW) except with input type Float32 where channel last (NHWC) is also supported"); this->format = format; this->dtype_is_user_defined = dtype_is_user_defined; } std::ostream& operator<<(std::ostream& os, const Input& input) { if (!input.input_is_dynamic) { os << "Input(shape: " << input.input_shape << ", dtype: " << input.dtype << ", format: " << input.format << ')'; } else { os << "Input(shape: " << input.input_shape << ", min: " << input.min << ", opt: " << input.opt << ", max: " << input.max << ", dtype: " << input.dtype << ", format: " << input.format << ')'; } return os; } } // namespace ir } // namespace core } // namespace trtorch
4,816
1,720
#include <bits/stdc++.h> using namespace std; /** * Marks: 15/15 */ int digits[4]; int main() { for (int i = 0; i < 4; i++) { scanf("%d", &digits[i]); } if (digits[0] != 8 && digits[0] != 9 || digits[3] != 8 && digits[3] != 9 || digits[1] != digits[2]) { cout << "answer" << endl; } else { cout << "ignore" << endl; } return 0; }
361
166
/** * Definition for singly-linked list. * 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: ListNode* mergeNodes(ListNode* head) { ListNode* p=head; p=p->next; ListNode* l=new ListNode(0); ListNode* res=l; int sum=0; while(p){ if(p->val!=0) { sum+=p->val; } else{ ListNode* temp=new ListNode(sum); l->next=temp; l=l->next; sum=0; } p=p->next; } return res->next; } };
797
263
#include <iostream> #include <iomanip> #include <fstream> #include "vector.hh" #include "matrix.hh" #include "Prostopadloscian.hh" #include "lacze_do_gnuplota.hh" #include <string> #include <unistd.h> #include <stdlib.h> Vector<double, 3> VecPrzesu; Matrix<3> MROT; Prostopadloscian<double> cuboid; PzG::LaczeDoGNUPlota Lacze; void menu(); int main() { if (!cuboid.wczytaj("../datasets/orginalny.dat")) { std::cerr << "Nie udalo sie wczytac prostopadloscianu!!!\n"; } cuboid.boki(); cuboid.zapis("../datasets/anim.dat"); Lacze.DodajNazwePliku("../datasets/anim.dat", PzG::RR_Ciagly, 2); Lacze.ZmienTrybRys(PzG::TR_3D); Lacze.UstawZakresY(-155, 155); Lacze.UstawZakresX(-155, 155); Lacze.UstawZakresZ(-155, 155); Lacze.Rysuj(); std::cout << "Naciśnij ENTER, aby kontynuowac" << std::endl; std::cin.ignore(10000, '\n'); menu(); } void menu() { char wyb; std::cout << "\n" << "************************MENU************************\n"; std::cout << " o-obrot bryly o zadany kat wzgledem danej osi\n"; std::cout << " p-przesuniecie o dany wektor\n"; std::cout << " w-wyswietlenie wspolrzednych wierzcholkow\n"; std::cout << " m-powrot do menu\n"; std::cout << " k-koniec dzialania programu\n"; std::cout << " r-Rysuj prostokat w Gnuplocie\n"; std::cout << " t-wyswietlenie macierzy rotacji\n"; std::cout << " Twoj wybor -> :"; std::cin >> wyb; std::cout << "\n"; switch (wyb) { case 'o': char os; double kat, ilosc; std::cout << "Podaj kat obrotu: "; std::cin >> kat; std::cout << "Podaj ilosc operacji: "; std::cin >> ilosc; std::cout << "Podaj os operacji: "; std::cin >> os; MROT.Mobrot3D_tworzenie(kat, os); if (ilosc > 1 && ilosc <= 720) { Lacze.Rysuj(); usleep(2000000); for (int i = 0; i < ilosc; i++) { cuboid.obrot(kat, 1, os); cuboid.zapis("../datasets/anim.dat"); Lacze.Rysuj(); int czas = 10000000 / ilosc; usleep(czas); } } else { cuboid.obrot(kat, ilosc, os); cuboid.zapis("../datasets/anim.dat"); Lacze.Rysuj(); } break; case 'p': std::cout << "Podaj wektor przesuniecia (x) (y) (z): "; std::cin >> VecPrzesu; cuboid.owektor(VecPrzesu); std::cout << cuboid; break; case 'w': std::cout << cuboid; break; case 'r': cuboid.boki(); cuboid.zapis("../datasets/anim.dat"); Lacze.Rysuj(); break; case 't': std::cout << MROT; break; case 'm': return menu(); break; case 'k': std::cout << "Koniec dzialania programu.\n "; return; break; default: std::cout << "Zly wybor !!! \n"; std::cout << "Mozliwe to o,r,p,w,m,k,t\n"; break; } return menu(); }
3,627
1,259
#include <prism/framerateselectscreen.h> #include <prism/physics.h> #include <prism/file.h> #include <prism/drawing.h> #include <prism/log.h> #include <prism/wrapper.h> #include <prism/system.h> #include <prism/stagehandler.h> #include <prism/logoscreen.h> #include <prism/mugentexthandler.h> #include <prism/debug.h> #include "gamescreen.h" #include "datingscreen.h" #include "bars.h" #include "storyhandler.h" #include "storyscreen.h" #ifdef DREAMCAST KOS_INIT_FLAGS(INIT_DEFAULT); extern uint8 romdisk[]; KOS_INIT_ROMDISK(romdisk); #endif // #define DEVELOP void exitGame() { shutdownPrismWrapper(); #ifdef DEVELOP if (isOnDreamcast()) { abortSystem(); } else { returnToMenu(); } #else returnToMenu(); #endif } int main(int argc, char** argv) { (void)argc; (void)argv; #ifdef DEVELOP setDevelopMode(); #endif setGameName("OlympicTorchCarrier"); setScreenSize(320, 240); initPrismWrapperWithConfigFile("data/config.cfg"); setFont("$/rd/fonts/segoe.hdr", "$/rd/fonts/segoe.pkg"); addMugenFont(-1, "font/f4x6.fnt"); addMugenFont(1, "font/f6x9.fnt"); addMugenFont(2, "font/jg.fnt"); logg("Check framerate"); FramerateSelectReturnType framerateReturnType = selectFramerate(); if (framerateReturnType == FRAMERATE_SCREEN_RETURN_ABORT) { exitGame(); } if(isInDevelopMode()) { ScreenSize sz = getScreenSize(); // setDisplayedScreenSize(sz.x, sz.y); disableWrapperErrorRecovery(); setMinimumLogType(LOG_TYPE_NORMAL); } else { setMinimumLogType(LOG_TYPE_NONE); } resetBarValues(); setScreenAfterWrapperLogoScreen(getLogoScreenFromWrapper()); setStoryHandlerPath("story/1.def"); setCurrentStoryDefinitionFile("INTRO"); startScreenHandling(getStoryScreen()); exitGame(); return 0; }
1,746
744
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/history/shortcuts_backend.h" #include <map> #include <string> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/i18n/case_conversion.h" #include "base/string_util.h" #include "chrome/browser/autocomplete/autocomplete.h" #include "chrome/browser/autocomplete/autocomplete_match.h" #include "chrome/browser/history/history.h" #include "chrome/browser/history/history_notifications.h" #include "chrome/browser/history/shortcuts_database.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/guid.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" using content::BrowserThread; namespace { // Takes Match classification vector and removes all matched positions, // compacting repetitions if necessary. void StripMatchMarkersFromClassifications(ACMatchClassifications* matches) { DCHECK(matches); ACMatchClassifications unmatched; for (ACMatchClassifications::iterator i = matches->begin(); i != matches->end(); ++i) { AutocompleteMatch::AddLastClassificationIfNecessary(&unmatched, i->offset, i->style & ~ACMatchClassification::MATCH); } matches->swap(unmatched); } } // namespace namespace history { // ShortcutsBackend::Shortcut ------------------------------------------------- ShortcutsBackend::Shortcut::Shortcut( const std::string& id, const string16& text, const GURL& url, const string16& contents, const ACMatchClassifications& contents_class, const string16& description, const ACMatchClassifications& description_class, const base::Time& last_access_time, int number_of_hits) : id(id), text(text), url(url), contents(contents), contents_class(contents_class), description(description), description_class(description_class), last_access_time(last_access_time), number_of_hits(number_of_hits) { StripMatchMarkersFromClassifications(&this->contents_class); StripMatchMarkersFromClassifications(&this->description_class); } ShortcutsBackend::Shortcut::Shortcut() : last_access_time(base::Time::Now()), number_of_hits(0) { } ShortcutsBackend::Shortcut::~Shortcut() { } // ShortcutsBackend ----------------------------------------------------------- ShortcutsBackend::ShortcutsBackend(const FilePath& db_folder_path, Profile *profile) : current_state_(NOT_INITIALIZED), db_(new ShortcutsDatabase(db_folder_path)), no_db_access_(db_folder_path.empty()) { // |profile| can be NULL in tests. if (profile) { notification_registrar_.Add(this, chrome::NOTIFICATION_OMNIBOX_OPENED_URL, content::Source<Profile>(profile)); notification_registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED, content::Source<Profile>(profile)); } } ShortcutsBackend::~ShortcutsBackend() {} bool ShortcutsBackend::Init() { if (current_state_ != NOT_INITIALIZED) return false; if (no_db_access_) { current_state_ = INITIALIZED; return true; } current_state_ = INITIALIZING; return BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(&ShortcutsBackend::InitInternal, this)); } bool ShortcutsBackend::AddShortcut(const Shortcut& shortcut) { if (!initialized()) return false; DCHECK(guid_map_.find(shortcut.id) == guid_map_.end()); guid_map_[shortcut.id] = shortcuts_map_.insert( std::make_pair(base::i18n::ToLower(shortcut.text), shortcut)); FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_, OnShortcutsChanged()); return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(base::IgnoreResult(&ShortcutsDatabase::AddShortcut), db_.get(), shortcut)); } bool ShortcutsBackend::UpdateShortcut(const Shortcut& shortcut) { if (!initialized()) return false; GuidToShortcutsIteratorMap::iterator it = guid_map_.find(shortcut.id); if (it != guid_map_.end()) shortcuts_map_.erase(it->second); guid_map_[shortcut.id] = shortcuts_map_.insert( std::make_pair(base::i18n::ToLower(shortcut.text), shortcut)); FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_, OnShortcutsChanged()); return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(base::IgnoreResult(&ShortcutsDatabase::UpdateShortcut), db_.get(), shortcut)); } bool ShortcutsBackend::DeleteShortcutsWithIds( const std::vector<std::string>& shortcut_ids) { if (!initialized()) return false; for (size_t i = 0; i < shortcut_ids.size(); ++i) { GuidToShortcutsIteratorMap::iterator it = guid_map_.find(shortcut_ids[i]); if (it != guid_map_.end()) { shortcuts_map_.erase(it->second); guid_map_.erase(it); } } FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_, OnShortcutsChanged()); return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(base::IgnoreResult(&ShortcutsDatabase::DeleteShortcutsWithIds), db_.get(), shortcut_ids)); } bool ShortcutsBackend::DeleteShortcutsWithUrl(const GURL& shortcut_url) { if (!initialized()) return false; std::vector<std::string> shortcut_ids; for (GuidToShortcutsIteratorMap::iterator it = guid_map_.begin(); it != guid_map_.end();) { if (it->second->second.url == shortcut_url) { shortcut_ids.push_back(it->first); shortcuts_map_.erase(it->second); guid_map_.erase(it++); } else { ++it; } } FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_, OnShortcutsChanged()); return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(base::IgnoreResult(&ShortcutsDatabase::DeleteShortcutsWithUrl), db_.get(), shortcut_url.spec())); } bool ShortcutsBackend::DeleteAllShortcuts() { if (!initialized()) return false; shortcuts_map_.clear(); guid_map_.clear(); FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_, OnShortcutsChanged()); return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(base::IgnoreResult(&ShortcutsDatabase::DeleteAllShortcuts), db_.get())); } void ShortcutsBackend::InitInternal() { DCHECK(current_state_ == INITIALIZING); db_->Init(); ShortcutsDatabase::GuidToShortcutMap shortcuts; db_->LoadShortcuts(&shortcuts); temp_shortcuts_map_.reset(new ShortcutMap); temp_guid_map_.reset(new GuidToShortcutsIteratorMap); for (ShortcutsDatabase::GuidToShortcutMap::iterator it = shortcuts.begin(); it != shortcuts.end(); ++it) { (*temp_guid_map_)[it->first] = temp_shortcuts_map_->insert( std::make_pair(base::i18n::ToLower(it->second.text), it->second)); } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ShortcutsBackend::InitCompleted, this)); } void ShortcutsBackend::InitCompleted() { temp_guid_map_->swap(guid_map_); temp_shortcuts_map_->swap(shortcuts_map_); temp_shortcuts_map_.reset(NULL); temp_guid_map_.reset(NULL); current_state_ = INITIALIZED; FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_, OnShortcutsLoaded()); } // content::NotificationObserver: void ShortcutsBackend::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (current_state_ != INITIALIZED) return; if (type == chrome::NOTIFICATION_HISTORY_URLS_DELETED) { if (content::Details<const history::URLsDeletedDetails>(details)-> all_history) { DeleteAllShortcuts(); } const std::set<GURL>& urls = content::Details<const history::URLsDeletedDetails>(details)->urls; std::vector<std::string> shortcut_ids; for (GuidToShortcutsIteratorMap::iterator it = guid_map_.begin(); it != guid_map_.end(); ++it) { if (urls.find(it->second->second.url) != urls.end()) shortcut_ids.push_back(it->first); } DeleteShortcutsWithIds(shortcut_ids); return; } DCHECK(type == chrome::NOTIFICATION_OMNIBOX_OPENED_URL); AutocompleteLog* log = content::Details<AutocompleteLog>(details).ptr(); string16 text_lowercase(base::i18n::ToLower(log->text)); const AutocompleteMatch& match(log->result.match_at(log->selected_index)); for (ShortcutMap::iterator it = shortcuts_map_.lower_bound(text_lowercase); it != shortcuts_map_.end() && StartsWith(it->first, text_lowercase, true); ++it) { if (match.destination_url == it->second.url) { UpdateShortcut(Shortcut(it->second.id, log->text, match.destination_url, match.contents, match.contents_class, match.description, match.description_class, base::Time::Now(), it->second.number_of_hits + 1)); return; } } AddShortcut(Shortcut(guid::GenerateGUID(), log->text, match.destination_url, match.contents, match.contents_class, match.description, match.description_class, base::Time::Now(), 1)); } } // namespace history
9,610
3,076
///////////////////////////////////////////////////////////////// /* Created by Berat Özdemir, January 24 , 2021. */ ///////////////////////////////////////////////////////////////// #include "ProgressBarScreen.h" V20::ProgressBarScreen::ProgressBarScreen(char _text[], uint16_t _barLength, uint16_t _fillPercentage){ int textlength = strlen(_text); char *buf = new char[textlength+1]; strcpy(buf,_text); text=buf; barLength=_barLength; fillPercentage=_fillPercentage; }; void V20::ProgressBarScreen::draw(VPetLCD *lcd){ lcd->drawCharArrayOnLCD(text, screenX, 0, pixelColor); lcd->drawPixelOnLCD( screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor); lcd->drawPixelOnLCD( screenX + barLength / 2 + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor); lcd->drawPixelOnLCD( screenX + barLength + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor); for (int i = 1; i <= barLength; i++) { lcd->drawPixelOnLCD(i + screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 2, pixelColor); lcd->drawPixelOnLCD(i + screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 2 + 5, pixelColor); } for (int i = 0; i < 4; i++) { lcd->drawPixelOnLCD( screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 3 + i, pixelColor); lcd->drawPixelOnLCD( screenX + barLength + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 3 + i, pixelColor); } uint16_t maxFill = barLength / 2; uint16_t percentageBars = fillPercentage * maxFill / 100; for (int i = 1; i <= percentageBars; i++) { lcd->drawPixelOnLCD( screenX + i * 2, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 4, pixelColor); lcd->drawPixelOnLCD( screenX + i * 2, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 5, pixelColor); } }
1,792
717
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2020) // René Fritze (2020) // // (http://opensource.org/licenses/BSD-2-Clause) #ifndef PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH #define PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH #include <dune/pybindxi/pybind11.h> #include <dune/xt/common/string.hh> #include <dune/xt/functions/interfaces/grid-function.hh> #include <dune/xt/functions/visualization.hh> #include <dune/xt/grid/gridprovider/provider.hh> #include <python/dune/xt/common/parameter.hh> namespace Dune::XT::Functions::bindings { template <class G, class E, size_t r = 1, size_t rC = 1, class R = double> class GridFunctionInterface { using GP = XT::Grid::GridProvider<G>; static constexpr size_t d = G::dimension; template <bool vector = (r != 1 && rC == 1), bool matrix = (rC != 1), bool anything = false> struct product_helper // <true, false, ...> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& c) { namespace py = pybind11; c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, r, 1, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); } }; template <bool anything> struct product_helper<false, true, anything> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& c) { namespace py = pybind11; c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, rC, 1, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, rC, 2, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, rC, 3, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); } }; template <bool scalar = (r == 1 && rC == 1), bool anything = false> struct fraction_helper // <true, ...> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& c) { namespace py = pybind11; c.def( "__truediv__", [](const T& self, const type& other) { return std::make_unique<decltype(other / self)>(other / self); }, py::is_operator()); } }; template <bool anything> struct fraction_helper<false, anything> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& /*c*/) {} }; public: using type = Functions::GridFunctionInterface<E, r, rC, R>; using bound_type = pybind11::class_<type>; static std::string class_name(const std::string& grid_id, const std::string& layer_id, const std::string& class_id) { std::string ret = class_id; ret += "_" + grid_id; if (!layer_id.empty()) ret += "_" + layer_id; ret += "_to_" + Common::to_string(r); if (rC > 1) ret += "x" + Common::to_string(rC); ret += "d"; if (!std::is_same<R, double>::value) ret += "_" + Common::Typename<R>::value(/*fail_wo_typeid=*/true); return ret; } // ... class_name(...) template <class T, typename... options> static void addbind_methods(pybind11::class_<T, options...>& c) { namespace py = pybind11; using namespace pybind11::literals; // our methods c.def( "visualize", [](const T& self, const GP& grid_provider, const std::string& filename, const bool subsampling) { Functions::visualize(self, grid_provider.leaf_view(), filename, subsampling); }, "grid"_a, "filename"_a, "subsampling"_a = true); // our operators c.def( "__add__", [](const T& self, const type& other) { return std::make_unique<decltype(self + other)>(self + other); }, py::is_operator()); c.def( "__sub__", [](const T& self, const type& other) { return std::make_unique<decltype(self - other)>(self - other); }, py::is_operator()); // we can always multiply with a scalar from the right ... c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, 1, 1, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); // .. and with lots of other dims product_helper<>::addbind(c); fraction_helper<>::addbind(c); if constexpr (r == 1 && rC == 1) c.def( "__pow__", [](const T& self) { return std::make_unique<decltype(self * self)>(self * self); }, py::is_operator()); // ParametricInterface methods c.def( "parse_parameter", [](const T& self, const Common::Parameter& mu) { return self.parse_parameter(mu); }, "mu"_a); } // ... addbind_methods(...) static bound_type bind(pybind11::module& m, const std::string& grid_id, const std::string& layer_id = "", const std::string& class_id = "grid_function_interface") { using namespace pybind11::literals; const auto ClassName = Common::to_camel_case(class_name(grid_id, layer_id, class_id)); bound_type c(m, ClassName.c_str(), Common::to_camel_case(class_id).c_str()); // our properties c.def_property_readonly("dim_domain", [](type&) { return size_t(d); }); if (rC == 1) c.def_property_readonly("dim_range", [](type&) { return size_t(r); }); else c.def_property_readonly("dim_range", [](type&) { return std::make_pair(size_t(r), size_t(rC)); }); c.def_property_readonly("name", [](type& self) { return self.name(); }); // ParametricInterface properties c.def_property_readonly("is_parametric", [](type& self) { return self.is_parametric(); }); c.def_property_readonly("parameter_type", [](type& self) { return self.parameter_type(); }); addbind_methods(c); return c; } }; // class GridFunctionInterface } // namespace Dune::XT::Functions::bindings #endif // PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH
6,892
2,377
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING */ #include "cassandra_constants.h" namespace org { namespace apache { namespace cassandra { const cassandraConstants g_cassandra_constants; cassandraConstants::cassandraConstants() { VERSION = "19.4.0"; } }}} // namespace
334
123
/* * Copyright (C) 2020-2021 LEIDOS. * * 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 <gmock/gmock.h> #include <ros/ros.h> #include <sensor_msgs/CameraInfo.h> #include <sensor_msgs/Image.h> #include <autoware_msgs/ProjectionMatrix.h> #include "test_utils.h" namespace mock_drivers { TEST(MockCameraDriver, camera_topic) { ros::NodeHandle nh; bool got_info = false; bool got_raw = false; bool got_rect = false; bool got_mat = false; ros::Publisher info_pub = nh.advertise<sensor_msgs::CameraInfo>("/bag/hardware_interface/camera/camera_info", 5); ros::Subscriber info_sub = nh.subscribe<sensor_msgs::CameraInfo>("/hardware_interface/camera/camera_info", 5, [&](const sensor_msgs::CameraInfoConstPtr& msg) -> void { got_info = true; }); ros::Publisher image_raw_pub = nh.advertise<sensor_msgs::Image>("/bag/hardware_interface/camera/image_raw", 5); ros::Subscriber image_raw_sub = nh.subscribe<sensor_msgs::Image>("/hardware_interface/camera/image_raw", 5, [&](const sensor_msgs::ImageConstPtr& msg) -> void { got_raw = true; }); ros::Publisher rect_pub = nh.advertise<sensor_msgs::Image>("/bag/hardware_interface/camera/image_rect", 5); ros::Subscriber rect_sub = nh.subscribe<sensor_msgs::Image>("/hardware_interface/camera/image_rect", 5, [&](const sensor_msgs::ImageConstPtr& msg) -> void { got_rect = true; }); ros::Publisher proj_pub = nh.advertise<autoware_msgs::ProjectionMatrix>("/bag/hardware_interface/camera/projection_matrix", 5); ros::Subscriber proj_sub = nh.subscribe<autoware_msgs::ProjectionMatrix>("/hardware_interface/camera/projection_matrix", 5, [&](const autoware_msgs::ProjectionMatrixConstPtr& msg) -> void { got_mat = true; }); ASSERT_TRUE(testing::waitForSubscribers(info_pub, 2, 10000)); ASSERT_TRUE(testing::waitForSubscribers(image_raw_pub, 2, 10000)); ASSERT_TRUE(testing::waitForSubscribers(rect_pub, 2, 10000)); ASSERT_TRUE(testing::waitForSubscribers(proj_pub, 2, 10000)); sensor_msgs::CameraInfo msg1; sensor_msgs::Image msg2; sensor_msgs::Image msg3; autoware_msgs::ProjectionMatrix msg4; info_pub.publish(msg1); image_raw_pub.publish(msg2); rect_pub.publish(msg3); proj_pub.publish(msg4); ros::Rate r(10); // 10 hz ros::WallTime endTime = ros::WallTime::now() + ros::WallDuration(10.0); while (ros::ok() && endTime > ros::WallTime::now() && !(got_info && got_raw && got_rect && got_mat)) { ros::spinOnce(); r.sleep(); } ASSERT_TRUE(got_info); ASSERT_TRUE(got_raw); ASSERT_TRUE(got_rect); ASSERT_TRUE(got_mat); } } // namespace mock_drivers /*! * \brief Main entrypoint for unit tests */ int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "mock_camera_test"); auto res = RUN_ALL_TESTS(); ros::shutdown(); return res; }
3,501
1,293
// // Pull combinations out of the event and make TH1's, some TNtuples ... // #include "art-workbook/ExDataProducts/CombinationCollection.h" #include "art-workbook/ExUtilities/PSetChecker.h" #include "art-workbook/ExN/TrackCuts.h" #include "toyExperiment/Geometry/Geometry.h" #include "toyExperiment/Conditions/Conditions.h" #include "toyExperiment/PDT/PDT.h" #include "toyExperiment/RecoDataProducts/RecoTrk.h" #include "toyExperiment/Reconstruction/FittedHelix.h" #include "toyExperiment/RecoDataProducts/FittedHelixDataCollection.h" #include "art/Framework/Core/EDAnalyzer.h" #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Principal/Event.h" #include "art_root_io/TFileService.h" #include "TH1F.h" #include "TNtuple.h" #include "cetlib/exception.h" #include "CLHEP/Units/SystemOfUnits.h" #include <string> namespace tex { class MassPlot : public art::EDAnalyzer { public: explicit MassPlot(fhicl::ParameterSet const& pset); void beginRun( art::Run const& run ) override; void analyze ( art::Event const& event ) override; private: art::InputTag combinerTag_; int maxPrint_; TrackCuts cuts_; art::ServiceHandle<Geometry> geom_; art::ServiceHandle<Conditions> conditions_; art::ServiceHandle<PDT> pdt_; art::ServiceHandle<art::TFileService> tfs_; // PDG mass of the phi meson. double mphi_; // z component of the magnetic field; only deined after the first begin run. double bz_; int printCount_; TH1F* hNCombos_; TH1F* hNHits_; TH1F* hMinHits_; TH1F* hPTrack_; TH1F* hPMin_; TH1F* hMass_; TH1F* hSigM_; TH1F* hPull_; // Helper functions. void checkParameterSet( fhicl::ParameterSet const& pset ); }; } tex::MassPlot::MassPlot(fhicl::ParameterSet const& pset): art::EDAnalyzer(pset), combinerTag_( pset.get<std::string> ("combinerInputTag") ), maxPrint_( pset.get<int> ("maxPrint",0) ), cuts_( pset.get<fhicl::ParameterSet>("cuts")), geom_(), conditions_(), pdt_(), tfs_( art::ServiceHandle<art::TFileService>() ), mphi_(pdt_->getById(PDGCode::phi).mass()), bz_(0.), printCount_(0), hNCombos_(nullptr), hNHits_(nullptr), hMinHits_(nullptr), hPTrack_(nullptr), hPMin_(nullptr), hMass_(nullptr), hSigM_(nullptr), hPull_(nullptr){ checkParameterSet( pset ); } void tex::MassPlot::beginRun( art::Run const& ){ // The geometry is not defined until beginRun. So the next three variables cannot be // properly initialized earlier. bz_ = geom_->bz(); // Get the number of layers in the tracking system. int nShells = geom_->tracker().nShells(); // Set the limits for the hits per track histograms. int hitBins = nShells+5; hNCombos_ = tfs_->make<TH1F>("NCombos", "Number of combinations per event", 10, 0., 10. ); hNHits_ = tfs_->make<TH1F>("NHits", "Number of hits Per Track", hitBins, 0., hitBins ); hMinHits_ = tfs_->make<TH1F>("MinHits", "Minimum Number of hits Per Track", hitBins, 0., hitBins ); hPTrack_ = tfs_->make<TH1F>("PTrack", "Momentum of each Track;[MeV]", 125, 0., 2500.); hPMin_ = tfs_->make<TH1F>("PMin", "Minimum momentum of the two daughters;[MeV]", 125, 0., 2500.); hMass_ = tfs_->make<TH1F>("Mass", "Reconstructed mass;[MeV]", 100, 1010., 1030. ); hSigM_ = tfs_->make<TH1F>("SigM", "Reconstructed sigma(Mass);[MeV]", 100, 0., 5. ); hPull_ = tfs_->make<TH1F>("Pull", "Mass (Reco-Gen)/sigma", 100, -5., 5. ); } void tex::MassPlot::analyze( art::Event const& event){ auto combos = event.getValidHandle<CombinationCollection>( combinerTag_ ); hNCombos_->Fill( combos->size() ); for ( auto const& combo : *combos ){ FittedHelixData const& fit0(*combo.child(0)); FittedHelixData const& fit1(*combo.child(1)); int nhit0 = fit0.hits().size(); int nhit1 = fit1.hits().size(); hNHits_->Fill(nhit0); hNHits_->Fill(nhit1); int nhits = std::min( nhit0, nhit1 ); hMinHits_->Fill(nhits); // By convention, this cut is disabled if minHitsPerTrack is negative. if ( nhits < cuts_.minHitsPerTrack ) continue; double p0 = fit0.helix().p(bz_); double p1 = fit1.helix().p(bz_); hPTrack_->Fill(p0); hPTrack_->Fill(p1); double pmin = std::min(p0,p1); hPMin_->Fill(pmin); if ( pmin < cuts_.pmin ) continue; RecoTrk trk = combo.recoTrk(); double m = trk.momentum().mag(); double sigm = trk.sigmaMass(); double mpull = (sigm > 0 ) ? (( m-mphi_)/sigm) : -10.; hMass_->Fill(m); hSigM_->Fill(sigm); hPull_->Fill(mpull); } } // end produce void tex::MassPlot::checkParameterSet( fhicl::ParameterSet const& pset ){ std::vector<std::string> knownParameterNames = { "combinerInputTag", "maxPrint", "cuts" }; PSetChecker checker( knownParameterNames, pset ); if ( checker.bad() ){ throw cet::exception("PSET") << checker.message("MassPlot") << "\n"; } } DEFINE_ART_MODULE(tex::MassPlot)
5,093
2,030
// STL #include <mutex> // Project #include "HUD027.h" #include "../common_classes/ostreamUtils.h" using namespace ostream_utils; HUD027::HUD027(const OpenGLWindow& window) : HUD(window) { static std::once_flag prepareOnceFlag; std::call_once(prepareOnceFlag, []() { FreeTypeFontManager::getInstance().loadSystemFreeTypeFont(DEFAULT_FONT_KEY, "arial.ttf", 24); }); } void HUD027::renderHUD(size_t numObjects, size_t numVisibleObjects, bool isWireframeModeOn, bool visualizeOccluders) const { printBuilder().print(10, 10, "FPS: {}", _window.getFPS()); printBuilder().print(10, 40, "Vertical Synchronization: {} (Press F3 to toggle)", _window.isVerticalSynchronizationEnabled() ? "On" : "Off"); // Calculate percentage of visible objects auto visiblePercentage = 0.0f; if(numObjects > 0) { visiblePercentage = 100.0f * static_cast<float>(numVisibleObjects) / numObjects; } // Print information about wireframe mode and occlusion query statistics printBuilder().print(10, 70, "Wireframe mode: {} (Press 'X' to toggle)", isWireframeModeOn ? "On" : "Off"); printBuilder().print(10, 100, "Visualize occluders: {} (Press 'C' to toggle)", visualizeOccluders ? "On" : "Off"); printBuilder().print(10, 130, " - Visible / total objects: {} / {} ({}%)", numVisibleObjects, numObjects, visiblePercentage); printBuilder() .fromRight() .fromBottom() .print(10, 10, "www.mbsoftworks.sk"); }
1,492
522
// // Created by Krisu on 2020/3/13. // #include "DirectionalShadow.hpp" #include "Renderer.hpp" #include "Mesh.hpp" #include "Scene.hpp" #include "Transform.hpp" DirectionalShadow::DirectionalShadow(const int map_width, const int map_height) : width(map_width), height(map_height) { glGenFramebuffers(1, &depthMapFBO); glGenTextures(1, &depthMap); glBindTexture(GL_TEXTURE_2D, depthMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { throw std::runtime_error("Shadow map frame buffer not complete"); } } void DirectionalShadow::GenerateShadowMap(const glm::vec3 &position, const glm::vec3 &direction, float cone_in_degree) { glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glViewport(0, 0, width, height); glClear(GL_DEPTH_BUFFER_BIT); static Shader shadowGenShader {"shader/shadow-mapping/directional-shadow.vert", "shader/shadow-mapping/directional-shadow.frag"}; glm::mat4 lightProjection = glm::ortho<float>( -10, 10, -10, 10, 1.0, 100 ); static const glm::vec3 global_up {0, 1, 0}; glm::vec3 right = glm::cross(direction, global_up); glm::vec3 up = glm::cross(right, direction); glm::mat4 lightView = glm::lookAt(position, direction, up); this->lightSpaceTransform = lightProjection * lightView; shadowGenShader.UseShaderProgram(); shadowGenShader.Set("lightSpaceTransform", lightSpaceTransform); glCullFace(GL_FRONT); // fix peter panning /* Rendering scene at light's space */ auto& scene = Engine::GetInstance().GetCurrentScene(); for (auto& up_game_obj : scene.GetListOfObeject()) { try { auto& mesh = up_game_obj->GetComponent<Mesh>(); auto& transform = up_game_obj->GetComponent<Transform>(); shadowGenShader.Set("model", transform.GetMatrix()); mesh.DrawCall(); } catch (NoComponent &) { continue; } } glCullFace(GL_BACK); glBindFramebuffer(GL_FRAMEBUFFER, 0); Engine::GetInstance().GetRenderer().ResetViewport(); } DirectionalShadow::~DirectionalShadow() { glDeleteBuffers(1, &depthMapFBO); glDeleteTextures(1, &depthMap); }
2,982
1,076
// (C) Copyright Boost.org 1999. Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // // use this header as a workaround for missing <limits> // See http://www.boost.org/libs/utility/limits.html for documentation. #ifndef BOOST_LIMITS #define BOOST_LIMITS #include <boost/config.hpp> #ifdef BOOST_NO_LIMITS # include <boost/detail/limits.hpp> #else # include <limits> #endif #if (defined(BOOST_HAS_LONG_LONG) && defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS)) \ || (defined(BOOST_HAS_MS_INT64) && defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS)) // Add missing specializations for numeric_limits: #ifdef BOOST_HAS_MS_INT64 # define BOOST_LLT __int64 #else # define BOOST_LLT long long #endif namespace std { template<> class numeric_limits<BOOST_LLT> { public: BOOST_STATIC_CONSTANT(bool, is_specialized = true); #ifdef BOOST_HAS_MS_INT64 static BOOST_LLT min(){ return 0x8000000000000000i64; } static BOOST_LLT max(){ return 0x7FFFFFFFFFFFFFFFi64; } #elif defined(LLONG_MAX) static BOOST_LLT min(){ return LLONG_MIN; } static BOOST_LLT max(){ return LLONG_MAX; } #elif defined(LONGLONG_MAX) static BOOST_LLT min(){ return LONGLONG_MIN; } static BOOST_LLT max(){ return LONGLONG_MAX; } #else static BOOST_LLT min(){ return 1LL << (sizeof(BOOST_LLT) * CHAR_BIT - 1); } static BOOST_LLT max(){ return ~min(); } #endif BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT -1); BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT) - 1) * 301L / 1000); BOOST_STATIC_CONSTANT(bool, is_signed = true); BOOST_STATIC_CONSTANT(bool, is_integer = true); BOOST_STATIC_CONSTANT(bool, is_exact = true); BOOST_STATIC_CONSTANT(int, radix = 2); static BOOST_LLT epsilon() throw() { return 0; }; static BOOST_LLT round_error() throw() { return 0; }; BOOST_STATIC_CONSTANT(int, min_exponent = 0); BOOST_STATIC_CONSTANT(int, min_exponent10 = 0); BOOST_STATIC_CONSTANT(int, max_exponent = 0); BOOST_STATIC_CONSTANT(int, max_exponent10 = 0); BOOST_STATIC_CONSTANT(bool, has_infinity = false); BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false); BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false); BOOST_STATIC_CONSTANT(bool, has_denorm = false); BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false); static BOOST_LLT infinity() throw() { return 0; }; static BOOST_LLT quiet_NaN() throw() { return 0; }; static BOOST_LLT signaling_NaN() throw() { return 0; }; static BOOST_LLT denorm_min() throw() { return 0; }; BOOST_STATIC_CONSTANT(bool, is_iec559 = false); BOOST_STATIC_CONSTANT(bool, is_bounded = false); BOOST_STATIC_CONSTANT(bool, is_modulo = false); BOOST_STATIC_CONSTANT(bool, traps = false); BOOST_STATIC_CONSTANT(bool, tinyness_before = false); BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero); }; template<> class numeric_limits<unsigned BOOST_LLT> { public: BOOST_STATIC_CONSTANT(bool, is_specialized = true); #ifdef BOOST_HAS_MS_INT64 static unsigned BOOST_LLT min(){ return 0ui64; } static unsigned BOOST_LLT max(){ return 0xFFFFFFFFFFFFFFFFui64; } #elif defined(ULLONG_MAX) && defined(ULLONG_MIN) static unsigned BOOST_LLT min(){ return ULLONG_MIN; } static unsigned BOOST_LLT max(){ return ULLONG_MAX; } #elif defined(ULONGLONG_MAX) && defined(ULONGLONG_MIN) static unsigned BOOST_LLT min(){ return ULONGLONG_MIN; } static unsigned BOOST_LLT max(){ return ULONGLONG_MAX; } #else static unsigned BOOST_LLT min(){ return 0uLL; } static unsigned BOOST_LLT max(){ return ~0uLL; } #endif BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT); BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT)) * 301L / 1000); BOOST_STATIC_CONSTANT(bool, is_signed = false); BOOST_STATIC_CONSTANT(bool, is_integer = true); BOOST_STATIC_CONSTANT(bool, is_exact = true); BOOST_STATIC_CONSTANT(int, radix = 2); static unsigned BOOST_LLT epsilon() throw() { return 0; }; static unsigned BOOST_LLT round_error() throw() { return 0; }; BOOST_STATIC_CONSTANT(int, min_exponent = 0); BOOST_STATIC_CONSTANT(int, min_exponent10 = 0); BOOST_STATIC_CONSTANT(int, max_exponent = 0); BOOST_STATIC_CONSTANT(int, max_exponent10 = 0); BOOST_STATIC_CONSTANT(bool, has_infinity = false); BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false); BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false); BOOST_STATIC_CONSTANT(bool, has_denorm = false); BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false); static unsigned BOOST_LLT infinity() throw() { return 0; }; static unsigned BOOST_LLT quiet_NaN() throw() { return 0; }; static unsigned BOOST_LLT signaling_NaN() throw() { return 0; }; static unsigned BOOST_LLT denorm_min() throw() { return 0; }; BOOST_STATIC_CONSTANT(bool, is_iec559 = false); BOOST_STATIC_CONSTANT(bool, is_bounded = false); BOOST_STATIC_CONSTANT(bool, is_modulo = false); BOOST_STATIC_CONSTANT(bool, traps = false); BOOST_STATIC_CONSTANT(bool, tinyness_before = false); BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero); }; } #endif #endif
5,637
2,141
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file LinearPropagator.test.hh //---------------------------------------------------------------------------// #pragma once #include <vector> #include "base/Assert.hh" #include "geometry/GeoInterface.hh" namespace celeritas_test { using celeritas::MemSpace; using celeritas::Ownership; using GeoParamsCRefDevice = celeritas::GeoParamsData<Ownership::const_reference, MemSpace::device>; using GeoStateRefDevice = celeritas::GeoStateData<Ownership::reference, MemSpace::device>; //---------------------------------------------------------------------------// // TESTING INTERFACE //---------------------------------------------------------------------------// using LinPropTestInit = celeritas::GeoTrackInitializer; //! Input data struct LinPropTestInput { std::vector<LinPropTestInit> init; int max_segments = 0; GeoParamsCRefDevice params; GeoStateRefDevice state; }; //---------------------------------------------------------------------------// //! Output results struct LinPropTestOutput { std::vector<int> ids; std::vector<double> distances; }; //---------------------------------------------------------------------------// //! Run on device and return results LinPropTestOutput linprop_test(LinPropTestInput); #if !CELERITAS_USE_CUDA LinPropTestOutput linprop_test(LinPropTestInput) { CELER_NOT_CONFIGURED("CUDA"); } #endif //---------------------------------------------------------------------------// } // namespace celeritas_test
1,863
499
/*========================================================================= Program: ParaView Module: vtkSMAnimationCueManipulatorProxy.cxx Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSMAnimationCueManipulatorProxy.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkSMAnimationCueManipulatorProxy::vtkSMAnimationCueManipulatorProxy() { } //---------------------------------------------------------------------------- vtkSMAnimationCueManipulatorProxy::~vtkSMAnimationCueManipulatorProxy() { } //---------------------------------------------------------------------------- // Overridden simply to set ObjectsCreated to 1, since this class does // not create any server side objects. void vtkSMAnimationCueManipulatorProxy::CreateVTKObjects() { this->ObjectsCreated = 1; this->Superclass::CreateVTKObjects(); } //---------------------------------------------------------------------------- void vtkSMAnimationCueManipulatorProxy::Copy(vtkSMProxy* src, const char* exceptionClass, int proxyPropertyCopyFlag) { this->Superclass::Copy(src, exceptionClass, proxyPropertyCopyFlag); this->MarkAllPropertiesAsModified(); } //---------------------------------------------------------------------------- void vtkSMAnimationCueManipulatorProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
1,805
490
#include "Timer.h" using std::chrono::high_resolution_clock; /* 打开计时器 */ void Timer::start() { if (m_isRunning) return; m_isRunning = true; m_start = high_resolution_clock::now(); } /* 停止计时器 */ void Timer::stop() { m_isRunning = false; } /* 重新打开计时器 */ void Timer::restart() { stop(); start(); } /* 判断计时器是否正在运行 */ bool Timer::isRunning() const { return m_isRunning; } /* 返回自计时器打开之后到现在的时间间隔,以毫秒计,如果计时器没在运行,返回 0 */ int64_t Timer::getDuration() { if (!m_isRunning) return 0; auto now = high_resolution_clock::now(); int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_start).count(); return duration; }
692
309
/* Given an array A of size N , write a function that implements insertion sort on the array. Print the elements of sorted array. Input Format First line contains a single integer N denoting the size of the array. Next line contains N space seperated integers where ith integer is the ith element of the array. Constraints 1 <= N <= 1000 |Ai| <= 1000000 Output Format Output N space seperated integers of the sorted array in a single line. Sample Input 4 3 4 2 1 Sample Output 1 2 3 4 Explanation For each test case, write insertion sort to sort the array. */ #include<iostream> using namespace std; int main() { int size, arr[1001], i, j, temp; cout<<" "; cin>>size; for(i=0; i<size; i++) { cin>>arr[i]; } cout<<" "; for(i=1; i<size; i++) { temp=arr[i]; j=i-1; while((temp<arr[j]) && (j>=0)) { arr[j+1]=arr[j]; j=j-1; } arr[j+1]=temp; } cout<<" "; for(i=0; i<size; i++) { cout<<arr[i]<<" "; } return 0; }
946
393
// clang-format off // RUN: %run %s --thread 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN // RUN: %run %s --thread 2>&1 | FileCheck %s // REQUIRES: thread && softcounter // clang-format on #include <stdlib.h> #include <thread> #include <stdio.h> void repeat_alloc_free(unsigned n) { for (int i = 0; i < n; i++) { double* d = (double*)malloc(sizeof(double) * n); free(d); } } int main(int argc, char** argv) { constexpr unsigned n = 1000; // CHECK: [Trace] TypeART Runtime Trace std::thread t1(repeat_alloc_free, n); std::thread t2(repeat_alloc_free, n); std::thread t3(repeat_alloc_free, n); t1.join(); t2.join(); t3.join(); // CHECK-TSAN-NOT: ThreadSanitizer // CHECK-NOT: Error // CHECK: Allocation type detail (heap, stack, global) // CHECK: 6 : 3000 , 0 , 0 , double // CHECK: Free allocation type detail (heap, stack) // CHECK: 6 : 3000 , 0 , double return 0; }
933
376
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The XFS API headers come from the xfsprogs package. xfsprogs versions // earlier than 4.5 contain various internal macros that conflict with // libstdc++. // If ENABLE_GETTEXT is not defined, then the XFS headers will define // textdomain() to a while(0) loop. When C++ standard headers try to // use textdomain(), compilation errors ensue. #define ENABLE_GETTEXT #include <xfs/xfs.h> #include <xfs/xqm.h> #undef ENABLE_GETTEXT // xfs/platform_defs-x86_64.h defines min() and max() macros which conflict // with various min() and max() function definitions. #undef min #undef max #include <fts.h> #include <blkid/blkid.h> #include <linux/quota.h> #include <sys/quota.h> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/numify.hpp> #include <stout/path.hpp> #include <stout/fs.hpp> #include <stout/os.hpp> #include "slave/containerizer/mesos/isolators/xfs/utils.hpp" using std::string; // Manually define this for old kernels. Compatible with the one in // <linux/quota.h>. #ifndef PRJQUOTA #define PRJQUOTA 2 #endif namespace mesos { namespace internal { namespace xfs { // The quota API defines space limits in terms of in basic // blocks (512 bytes). static constexpr Bytes BASIC_BLOCK_SIZE = Bytes(512u); // Although XFS itself doesn't define any invalid project IDs, // we need a way to know whether or not a project ID was assigned // so we use 0 as our sentinel value. static constexpr prid_t NON_PROJECT_ID = 0u; static Error nonProjectError() { return Error("Invalid project ID '0'"); } static Try<int> openPath( const string& path, const struct stat& stat) { int flags = O_NOFOLLOW | O_RDONLY | O_CLOEXEC; // Directories require O_DIRECTORY. flags |= S_ISDIR(stat.st_mode) ? O_DIRECTORY : 0; return os::open(path, flags); } static Try<Nothing> setAttributes( int fd, struct fsxattr& attr) { if (::xfsctl(nullptr, fd, XFS_IOC_FSSETXATTR, &attr) == -1) { return ErrnoError(); } return Nothing(); } static Try<struct fsxattr> getAttributes(int fd) { struct fsxattr attr; if (::xfsctl(nullptr, fd, XFS_IOC_FSGETXATTR, &attr) == -1) { return ErrnoError(); } return attr; } // Return the path of the device backing the filesystem containing // the given path. static Try<string> getDeviceForPath(const string& path) { struct stat statbuf; if (::lstat(path.c_str(), &statbuf) == -1) { return ErrnoError("Unable to access '" + path + "'"); } char* name = blkid_devno_to_devname(statbuf.st_dev); if (name == nullptr) { return ErrnoError("Unable to get device for '" + path + "'"); } string devname(name); free(name); return devname; } namespace internal { static Try<Nothing> setProjectQuota( const string& path, prid_t projectId, Bytes limit) { Try<string> devname = getDeviceForPath(path); if (devname.isError()) { return Error(devname.error()); } fs_disk_quota_t quota = {0}; quota.d_version = FS_DQUOT_VERSION; // Specify that we are setting a project quota for this ID. quota.d_id = projectId; quota.d_flags = XFS_PROJ_QUOTA; // Set both the hard and the soft limit to the same quota, just // for consistency. Functionally all we need is the hard quota. quota.d_fieldmask = FS_DQ_BSOFT | FS_DQ_BHARD; quota.d_blk_hardlimit = limit.bytes() / BASIC_BLOCK_SIZE.bytes(); quota.d_blk_softlimit = limit.bytes() / BASIC_BLOCK_SIZE.bytes(); if (::quotactl(QCMD(Q_XSETQLIM, PRJQUOTA), devname.get().c_str(), projectId, reinterpret_cast<caddr_t>(&quota)) == -1) { return ErrnoError("Failed to set quota for project ID " + stringify(projectId)); } return Nothing(); } static Try<Nothing> setProjectId( const string& path, const struct stat& stat, prid_t projectId) { Try<int> fd = openPath(path, stat); if (fd.isError()) { return Error("Failed to open '" + path + "': " + fd.error()); } Try<struct fsxattr> attr = getAttributes(fd.get()); if (attr.isError()) { os::close(fd.get()); return Error("Failed to get XFS attributes for '" + path + "': " + attr.error()); } attr->fsx_projid = projectId; if (projectId == NON_PROJECT_ID) { attr->fsx_xflags &= ~XFS_XFLAG_PROJINHERIT; } else { attr->fsx_xflags |= XFS_XFLAG_PROJINHERIT; } Try<Nothing> status = setAttributes(fd.get(), attr.get()); os::close(fd.get()); if (status.isError()) { return Error("Failed to set XFS attributes for '" + path + "': " + status.error()); } return Nothing(); } } // namespace internal { Result<QuotaInfo> getProjectQuota( const string& path, prid_t projectId) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } Try<string> devname = getDeviceForPath(path); if (devname.isError()) { return Error(devname.error()); } fs_disk_quota_t quota = {0}; quota.d_version = FS_DQUOT_VERSION; quota.d_id = projectId; quota.d_flags = XFS_PROJ_QUOTA; // In principle, we should issue a Q_XQUOTASYNC to get an accurate accounting. // However, we don't want to affect performance by continually syncing the // disks, so we accept that the quota information will be slightly out of // date. if (::quotactl(QCMD(Q_XGETQUOTA, PRJQUOTA), devname.get().c_str(), projectId, reinterpret_cast<caddr_t>(&quota)) == -1) { return ErrnoError("Failed to get quota for project ID " + stringify(projectId)); } // Zero quota means that no quota is assigned. if (quota.d_blk_hardlimit == 0 && quota.d_bcount == 0) { return None(); } QuotaInfo info; info.limit = BASIC_BLOCK_SIZE * quota.d_blk_hardlimit; info.used = BASIC_BLOCK_SIZE * quota.d_bcount; return info; } Try<Nothing> setProjectQuota( const string& path, prid_t projectId, Bytes limit) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } // A 0 limit deletes the quota record. Since the limit is in basic // blocks that effectively means > 512 bytes. if (limit < BASIC_BLOCK_SIZE) { return Error("Quota limit must be >= " + stringify(BASIC_BLOCK_SIZE)); } return internal::setProjectQuota(path, projectId, limit); } Try<Nothing> clearProjectQuota( const string& path, prid_t projectId) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } return internal::setProjectQuota(path, projectId, Bytes(0)); } Result<prid_t> getProjectId( const string& directory) { struct stat stat; if (::lstat(directory.c_str(), &stat) == -1) { return ErrnoError("Failed to access '" + directory); } Try<int> fd = openPath(directory, stat); if (fd.isError()) { return Error("Failed to open '" + directory + "': " + fd.error()); } Try<struct fsxattr> attr = getAttributes(fd.get()); os::close(fd.get()); if (attr.isError()) { return Error("Failed to get XFS attributes for '" + directory + "': " + attr.error()); } if (attr->fsx_projid == NON_PROJECT_ID) { return None(); } return attr->fsx_projid; } static Try<Nothing> setProjectIdRecursively( const string& directory, prid_t projectId) { if (os::stat::islink(directory) || !os::stat::isdir(directory)) { return Error(directory + " is not a directory"); } char* directory_[] = {const_cast<char*>(directory.c_str()), nullptr}; FTS* tree = ::fts_open( directory_, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, nullptr); if (tree == nullptr) { return ErrnoError("Failed to open '" + directory + "'"); } for (FTSENT *node = ::fts_read(tree); node != nullptr; node = ::fts_read(tree)) { if (node->fts_info == FTS_D || node->fts_info == FTS_F) { Try<Nothing> status = internal::setProjectId( node->fts_path, *node->fts_statp, projectId); if (status.isError()) { ::fts_close(tree); return Error(status.error()); } } } if (errno != 0) { Error error = ErrnoError(); ::fts_close(tree); return error; } if (::fts_close(tree) != 0) { return ErrnoError("Failed to stop traversing file system"); } return Nothing(); } Try<Nothing> setProjectId( const string& directory, prid_t projectId) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } return setProjectIdRecursively(directory, projectId); } Try<Nothing> clearProjectId( const string& directory) { return setProjectIdRecursively(directory, NON_PROJECT_ID); } Option<Error> validateProjectIds(const IntervalSet<prid_t>& projectRange) { if (projectRange.contains(NON_PROJECT_ID)) { return Error("XFS project ID range contains illegal " + stringify(NON_PROJECT_ID) + " value"); } return None(); } bool pathIsXfs(const string& path) { return ::platform_test_xfs_path(path.c_str()) == 1; } } // namespace xfs { } // namespace internal { } // namespace mesos {
9,818
3,494
/*-------------------------------------------------------------------------------------- Ethanon Engine (C) Copyright 2008-2013 Andre Santee http://ethanonengine.com/ 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 "Sprite.h" #include "Application.h" namespace gs2d { using namespace gs2d::math; Sprite::Sprite() : m_nColumns(0), m_nRows(0), m_normalizedOrigin(Vector2(0.0f, 0.0f)), m_rect(Rect2Df(0,0,0,0)), m_rectMode(RM_TWO_TRIANGLES), m_currentRect(0), m_flipX(false), m_flipY(false), m_multiply(1.0f, 1.0f), m_scroll(0.0f, 0.0f) { } void Sprite::GetFlipShaderParameters(Vector2& flipAdd, Vector2& flipMul) const { flipMul = Vector2(1,1); flipAdd = Vector2(0,0); if (m_flipX) { flipMul.x =-1; flipAdd.x = 1; } if (m_flipY) { flipMul.y =-1; flipAdd.y = 1; } } void Sprite::SetRectMode(const RECT_MODE mode) { m_rectMode = mode; } Sprite::RECT_MODE Sprite::GetRectMode() const { return m_rectMode; } bool Sprite::Stretch( const Vector2& a, const Vector2& b, const float width, const Color& color0, const Color& color1) { if (a == b || width <= 0.0f) { return true; } const Vector2 v2Dir(a - b); const float len = Distance(a, b); const float angle = RadianToDegree(GetAngle(v2Dir)); const float lineWidth = (m_rect.size.x <= 0) ? (float)GetProfile().width : (float)m_rect.size.x; Vector2 origin = GetOrigin(); SetOrigin(EO_CENTER_BOTTOM); const bool r = DrawShaped( a, Vector2((width >= 0.0f) ? width : lineWidth, len), color1, color1, color0, color0, angle); SetOrigin(origin); return r; } bool Sprite::SetupSpriteRects(const unsigned int columns, const unsigned int rows) { m_rects.reset(); if (columns <= 0 || rows <=0) { ShowMessage(GS_L("The number of rows or columns set can't be 0 or less - Sprite::SetupSpriteRects"), GSMT_ERROR); return false; } m_nColumns = columns; m_nRows = rows; const unsigned int nRects = columns * rows; m_rects = boost::shared_array<Rect2Df>(new Rect2Df [nRects]); const Vector2i size(GetBitmapSize()); const unsigned int strideX = static_cast<unsigned int>(size.x) / columns, strideY = static_cast<unsigned int>(size.y) / rows; unsigned int index = 0; for (unsigned int y = 0; y < rows; y++) { for (unsigned int x = 0; x < columns; x++) { m_rects[index].pos.x = static_cast<float>(x * strideX); m_rects[index].pos.y = static_cast<float>(y * strideY); m_rects[index].size.x = static_cast<float>(strideX); m_rects[index].size.y = static_cast<float>(strideY); index++; } } SetRect(0); return true; } unsigned int Sprite::GetRectIndex() const { return m_currentRect; } bool Sprite::SetRect(const unsigned int rect) { m_currentRect = gs2d::math::Min(rect, GetNumRects() - 1); m_rect = m_rects[m_currentRect]; return (m_currentRect == rect); } bool Sprite::SetRect(const unsigned int column, const unsigned int row) { return SetRect((row * m_nColumns) + column); } void Sprite::SetRect(const Rect2Df& rect) { m_rect = rect; } void Sprite::UnsetRect() { m_rect = Rect2Df(0, 0, 0, 0); m_currentRect = 0; } Rect2Df Sprite::GetRect() const { return m_rect; } unsigned int Sprite::GetNumRects() const { return m_nColumns * m_nRows; } unsigned int Sprite::GetNumRows() const { return m_nRows; } unsigned int Sprite::GetNumColumns() const { return m_nColumns; } Rect2Df Sprite::GetRect(const unsigned int rect) const { return m_rects[Min(GetNumRects() - 1, rect)]; } Vector2 Sprite::GetOrigin() const { return m_normalizedOrigin; } void Sprite::SetOrigin(const Vector2& origin) { m_normalizedOrigin = origin; } void Sprite::SetOrigin(const ENTITY_ORIGIN origin) { switch (origin) { case EO_RECT_CENTER: case EO_CENTER: m_normalizedOrigin.x = 1.0f / 2.0f; m_normalizedOrigin.y = 1.0f / 2.0f; break; case EO_RECT_CENTER_BOTTOM: case EO_CENTER_BOTTOM: m_normalizedOrigin.x = 1.0f / 2.0f; m_normalizedOrigin.y = 1.0f; break; case EO_RECT_CENTER_TOP: case EO_CENTER_TOP: m_normalizedOrigin.x = 1.0f / 2.0f; m_normalizedOrigin.y = 0.0f; break; default: m_normalizedOrigin.x = 0.0f; m_normalizedOrigin.y = 0.0f; break; }; } math::Vector2 Sprite::GetFrameSize() const { return (m_rect.size == Vector2(0, 0)) ? GetBitmapSizeF() : m_rect.size; } void Sprite::FlipX(const bool flip) { m_flipX = flip; } void Sprite::FlipY(const bool flip) { m_flipY = flip; } void Sprite::FlipX() { m_flipX = !(m_flipX); } void Sprite::FlipY() { m_flipY = !(m_flipY); } bool Sprite::GetFlipX() const { return m_flipX; } bool Sprite::GetFlipY() const { return m_flipY; } void Sprite::SetMultiply(const Vector2 &v2Multiply) { m_multiply = Vector2(Abs(v2Multiply.x), Abs(v2Multiply.y)); } Vector2 Sprite::GetMultiply() const { return m_multiply; } #define GS_MAX_SCROLL (1024.0f*4.0f) void Sprite::SetScroll(const Vector2 &v2Scroll) { m_scroll = v2Scroll; if (m_scroll.x > GS_MAX_SCROLL) m_scroll.x -= GS_MAX_SCROLL; else if (m_scroll.x < -GS_MAX_SCROLL) m_scroll.x += GS_MAX_SCROLL; if (m_scroll.y > GS_MAX_SCROLL) m_scroll.y -= GS_MAX_SCROLL; else if (m_scroll.y < -GS_MAX_SCROLL) m_scroll.y += GS_MAX_SCROLL; } Vector2 Sprite::GetScroll() const { return m_scroll; } } // namespace gs2d
6,297
2,708
// -*- C++ -*- // // Package: EcalBxOrbitNumberGrapher // Class: EcalBxOrbitNumberGrapher // /**\class EcalBxOrbitNumberGrapher EcalBxOrbitNumberGrapher.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Seth COOPER // Created: Th Nov 22 5:46:22 CEST 2007 // // #include "CaloOnlineTools/EcalTools/plugins/EcalBxOrbitNumberGrapher.h" using namespace cms; using namespace edm; using namespace std; #include <iostream> // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // EcalBxOrbitNumberGrapher::EcalBxOrbitNumberGrapher(const edm::ParameterSet& iConfig) : digiProducer_(iConfig.getParameter<std::string>("RawDigis")), runNum_(-1), fileName_(iConfig.getUntrackedParameter<std::string>("fileName", std::string("ecalURechHitHists"))) {} EcalBxOrbitNumberGrapher::~EcalBxOrbitNumberGrapher() {} // // member functions // // ------------ method called to for each event ------------ void EcalBxOrbitNumberGrapher::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; using namespace cms; //int ievt = iEvent.id().event(); int orbit = -100; int bx = -100; int numorbiterrors = 0; bool orbiterror = false; edm::Handle<EcalRawDataCollection> DCCHeaders; iEvent.getByLabel(digiProducer_, DCCHeaders); if (!DCCHeaders.isValid()) { edm::LogError("BxOrbitNumber") << "can't get the product for EcalRawDataCollection"; } //-----------------BX STuff here for (EcalRawDataCollection::const_iterator headerItr = DCCHeaders->begin(); headerItr != DCCHeaders->end(); ++headerItr) { headerItr->getEventSettings(); int myorbit = headerItr->getOrbit(); int mybx = headerItr->getBX(); if (orbit == -100) { orbit = myorbit; } else if (orbit != myorbit) { std::cout << " NOOOO This header has a conflicting orbit OTHER " << orbit << " new " << myorbit << std::endl; orbiterror = true; numorbiterrors++; orbitErrorBxDiffPlot_->Fill(myorbit - orbit); } if (bx == -100) { bx = mybx; } else if (bx != mybx) { std::cout << " NOOOO This header has a conflicting bx OTHER " << bx << " new " << mybx << std::endl; } //LogDebug("EcalTimingCosmic") << " Lambda " << lambda; //hmm... this isn't good, I should keep a record of the wavelength in the headers as an inactive SM might have a different wavelength for this field and make this not go through. } if ((bx != -100) & (orbit != -100)) { std::cout << " Interesting event Orbit " << orbit << " BX " << bx << std::endl; bxnumberPlot_->Fill(bx); if (orbiterror) { orbitErrorPlot_->Fill(bx); } } numberofOrbitDiffPlot_->Fill(numorbiterrors); if (runNum_ == -1) { runNum_ = iEvent.id().run(); } } // insert the hist map into the map keyed by FED number void EcalBxOrbitNumberGrapher::initHists(int FED) {} // ------------ method called once each job just before starting event loop ------------ void EcalBxOrbitNumberGrapher::beginJob() { bxnumberPlot_ = new TH1F("bxnumber", "BX number of interexting events", 3600, 0., 3600.); orbitErrorPlot_ = new TH1F("bxOfOrbitDiffs", "BX number of interexting events with orbit changes", 3600, 0., 3600.); orbitErrorBxDiffPlot_ = new TH1F("orbitErrorDiffPlot", "Orbit Difference of those HEADERS that have a difference", 20, -10., 10.); numberofOrbitDiffPlot_ = new TH1F("numberOfOrbitDiffsPlot", "Number of Orbit Differences", 54, 0., 54.); } // ------------ method called once each job just after ending the event loop ------------ void EcalBxOrbitNumberGrapher::endJob() { using namespace std; fileName_ += ".bx.root"; TFile root_file_(fileName_.c_str(), "RECREATE"); bxnumberPlot_->Write(); orbitErrorPlot_->Write(); numberofOrbitDiffPlot_->Write(); orbitErrorBxDiffPlot_->Write(); root_file_.Close(); }
3,972
1,448
// // Created by zhukovasky on 2020/8/19. // #include "JavaHeap.h" namespace Runtime{ Object *JavaHeap::createJavaObject(JavaClass *javaClass) { Object *object=new Object(); object->setJavaClass(javaClass); object->setData(nullptr); this->youngList.insert(object); return object; } Object *JavaHeap::createJavaArrayObject(JavaClass *javaClass) { Object *object=new Object(); object->setJavaClass(javaClass); object->setData(nullptr); this->eldenList.insert(object); return nullptr; } }
584
186
/*! @file @author Albert Semenov @date 08/2010 */ #include "Precompiled.h" #include "StateListControl.h" #include "SkinManager.h" #include "Binary.h" #include "Localise.h" namespace tools { enum PresetEnum { PresetNormalOnly = Binary<10>::value, PresetFirst4States = Binary<1111>::value, PresetAllStates = Binary<11111111>::value }; StatesListControl::StatesListControl(MyGUI::Widget* _parent) : wraps::BaseLayout("StateListControl.layout", _parent), mList(nullptr), mPresets(nullptr) { mTypeName = MyGUI::utility::toString((size_t)this); assignWidget(mList, "List"); assignWidget(mPresets, "StatePreset"); fillStatePreset(); mList->eventListChangePosition += MyGUI::newDelegate(this, &StatesListControl::notifyChangePosition); mPresets->eventComboChangePosition += MyGUI::newDelegate(this, &StatesListControl::notifyComboChangePosition); initialiseAdvisor(); } StatesListControl::~StatesListControl() { shutdownAdvisor(); mList->eventListChangePosition -= MyGUI::newDelegate(this, &StatesListControl::notifyChangePosition); mPresets->eventComboChangePosition -= MyGUI::newDelegate(this, &StatesListControl::notifyComboChangePosition); } void StatesListControl::fillStatePreset() { mPresets->removeAllItems(); mPresets->addItem(replaceTags("PresetStateOnlyNormal"), PresetNormalOnly); mPresets->addItem(replaceTags("PresetStateFirst4"), PresetFirst4States); mPresets->addItem(replaceTags("PresetStateAll"), PresetAllStates); mPresets->beginToItemFirst(); } void StatesListControl::notifyChangePosition(MyGUI::ListBox* _sender, size_t _index) { if (getCurrentSkin() != nullptr) { StateItem* item = nullptr; if (_index != MyGUI::ITEM_NONE) item = *mList->getItemDataAt<StateItem*>(_index); getCurrentSkin()->getStates().setItemSelected(item); } } void StatesListControl::updateStateProperty(Property* _sender, const MyGUI::UString& _owner) { if (_sender->getName() == "Visible") updateList(); if (_owner != mTypeName) updatePreset(); } void StatesListControl::updateStateProperties() { updateList(); } void StatesListControl::updateSkinProperties() { updatePreset(); } void StatesListControl::updateList() { if (getCurrentSkin() != nullptr) { StateItem* selectedItem = getCurrentSkin()->getStates().getItemSelected(); size_t selectedIndex = MyGUI::ITEM_NONE; size_t index = 0; ItemHolder<StateItem>::EnumeratorItem states = getCurrentSkin()->getStates().getChildsEnumerator(); while (states.next()) { StateItem* item = states.current(); MyGUI::UString name; if (item->getPropertySet()->getPropertyValue("Visible") != "True") name = replaceTags("ColourDisabled") + item->getName(); else name = item->getName(); if (index < mList->getItemCount()) { mList->setItemNameAt(index, name); mList->setItemDataAt(index, item); } else { mList->addItem(name, item); } if (item == selectedItem) selectedIndex = index; index ++; } while (index < mList->getItemCount()) mList->removeItemAt(mList->getItemCount() - 1); mList->setIndexSelected(selectedIndex); } } void StatesListControl::notifyComboChangePosition(MyGUI::ComboBox* _sender, size_t _index) { if (getCurrentSkin() == nullptr) return; if (_index == MyGUI::ITEM_NONE) return; PresetEnum preset = *_sender->getItemDataAt<PresetEnum>(_index); size_t index = 0; ItemHolder<StateItem>::EnumeratorItem states = getCurrentSkin()->getStates().getChildsEnumerator(); while (states.next()) { StateItem* item = states.current(); MyGUI::UString value = ((preset & (1 << index)) != 0) ? "True" : "False"; item->getPropertySet()->setPropertyValue("Visible", value, mTypeName); ++index; } updateList(); } void StatesListControl::updatePreset() { mPresets->setEnabled(getCurrentSkin() != nullptr); if (getCurrentSkin() != nullptr) { int currentPreset = 0; int bitIndex = 0; ItemHolder<StateItem>::EnumeratorItem states = getCurrentSkin()->getStates().getChildsEnumerator(); while (states.next()) { StateItem* item = states.current(); bool visible = item->getPropertySet()->getPropertyValue("Visible") == "True"; if (visible) currentPreset |= (1 << bitIndex); ++ bitIndex; } size_t indexSelected = MyGUI::ITEM_NONE; size_t count = mPresets->getItemCount(); for (size_t index = 0; index < count; ++index) { PresetEnum preset = *mPresets->getItemDataAt<PresetEnum>(index); if (preset == currentPreset) { indexSelected = index; break; } } mPresets->setIndexSelected(indexSelected); mPresets->setEnabled(true); } else { mPresets->setEnabled(false); } } } // namespace tools
4,805
1,904
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 "./callbacks.hpp" #include "./types.hpp" template<typename T> void inner_callback( void * callee, const rtps::ReaderCacheChange & cacheChange, const rmw_ertps_mempool_t * memory) { rtps::Reader * reader = reinterpret_cast<rtps::Reader *>( callee); rmw_ertps_mempool_item_t * item = memory->allocateditems; while (item != NULL) { T * element = reinterpret_cast<T *>(item->data); if (element->reader == reader) { rmw_ertps_mempool_item_t * memory_node = get_memory(&static_buffer_memory); if (!memory_node) { RMW_SET_ERROR_MSG("Not available static buffer memory node"); return; } rmw_ertps_static_input_buffer_t * static_buffer = reinterpret_cast<rmw_ertps_static_input_buffer_t *>(memory_node->data); static_buffer->owner = reinterpret_cast<void *>(element); static_buffer->length = cacheChange.getDataSize(); static_buffer->writer_guid = cacheChange.writerGuid; static_buffer->sequence_number = cacheChange.sn; static_buffer->related_writer_guid = cacheChange.relatedWriterGuid; static_buffer->related_sequence_number = cacheChange.relatedSequenceNumber; if (!cacheChange.copyInto(static_buffer->buffer, RMW_ERTPS_MAX_INPUT_BUFFER_SIZE)) { put_memory(&static_buffer_memory, memory_node); } else { extern sys_sem_t rmw_wait_sem; sys_sem_signal(&rmw_wait_sem); } return; } item = item->next; } } template<> void generic_callback<rmw_ertps_service_t>( void * callee, const rtps::ReaderCacheChange & cacheChange) { inner_callback<rmw_ertps_service_t>(callee, cacheChange, &service_memory); } template<> void generic_callback<rmw_ertps_subscription_t>( void * callee, const rtps::ReaderCacheChange & cacheChange) { inner_callback<rmw_ertps_subscription_t>(callee, cacheChange, &subscription_memory); } template<> void generic_callback<rmw_ertps_client_t>( void * callee, const rtps::ReaderCacheChange & cacheChange) { inner_callback<rmw_ertps_client_t>(callee, cacheChange, &client_memory); }
2,713
891
#include <iostream> using namespace std; int main() { int n, c, total = 0; cin >> n >> c; for (int i = 0; i < n; i++) { total+=c; if (c > 1) c--; } cout << total << endl; return 0; }
238
97
// Copyright 2018, Intel Corp. #include "tile/codegen/rewrite_locs.h" #include <algorithm> #include <iterator> #include <queue> namespace vertexai { namespace tile { namespace codegen { namespace { struct Rewrite { std::vector<stripe::Device> prefix; std::vector<stripe::Device> target; }; void RewriteLocation(stripe::Location* loc, const std::vector<Rewrite>& rewrites) { for (auto& rewrite : rewrites) { auto loc_it = loc->devs.begin(); auto rew_it = rewrite.prefix.begin(); for (; loc_it != loc->devs.end() && *loc_it == *rew_it; ++loc_it, ++rew_it) { } if (rew_it == rewrite.prefix.end()) { std::vector<stripe::Device> target = rewrite.target; std::copy(loc_it, loc->devs.end(), std::back_inserter(target)); std::swap(loc->devs, target); break; } } } } // namespace void RewriteLocationsPass::Apply(CompilerState* state) const { std::vector<Rewrite> rewrites; for (const auto& rewrite : options_.rewrites()) { rewrites.emplace_back(Rewrite{stripe::FromProto(rewrite.prefix()), stripe::FromProto(rewrite.target())}); } std::queue<stripe::Block*> todo; todo.push(state->entry()); while (todo.size()) { stripe::Block* block = todo.front(); todo.pop(); RewriteLocation(&block->location, rewrites); for (auto& ref : block->refs) { RewriteLocation(&ref.mut().location, rewrites); } for (auto& stmt : block->stmts) { stripe::Block* inner = dynamic_cast<stripe::Block*>(stmt.get()); if (inner) { todo.push(inner); } } } } namespace { [[gnu::unused]] char reg = []() -> char { CompilePassFactory<RewriteLocationsPass, proto::RewriteLocationsPass>::Register(); return 0; }(); } // namespace } // namespace codegen } // namespace tile } // namespace vertexai
1,809
639
// ArduinoJson - https://arduinojson.org // Copyright © 2014-2022, Benoit BLANCHON // MIT License #include <ArduinoJson.h> #include <catch.hpp> TEST_CASE("JsonArray::remove()") { DynamicJsonDocument doc(4096); JsonArray array = doc.to<JsonArray>(); array.add(1); array.add(2); array.add(3); SECTION("remove first by index") { array.remove(0); REQUIRE(2 == array.size()); REQUIRE(array[0] == 2); REQUIRE(array[1] == 3); } SECTION("remove middle by index") { array.remove(1); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 3); } SECTION("remove last by index") { array.remove(2); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 2); } SECTION("remove first by iterator") { JsonArray::iterator it = array.begin(); array.remove(it); REQUIRE(2 == array.size()); REQUIRE(array[0] == 2); REQUIRE(array[1] == 3); } SECTION("remove middle by iterator") { JsonArray::iterator it = array.begin(); ++it; array.remove(it); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 3); } SECTION("remove last bty iterator") { JsonArray::iterator it = array.begin(); ++it; ++it; array.remove(it); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 2); } SECTION("In a loop") { for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) { if (*it == 2) array.remove(it); } REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 3); } SECTION("remove by index on unbound reference") { JsonArray unboundArray; unboundArray.remove(20); } SECTION("remove by iterator on unbound reference") { JsonArray unboundArray; unboundArray.remove(unboundArray.begin()); } }
1,888
760
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/wifi/p2p/nsd/CWifiP2pServiceResponse.h" #include "elastos/droid/wifi/p2p/nsd/CWifiP2pDnsSdServiceResponse.h" #include "elastos/droid/wifi/p2p/nsd/CWifiP2pUpnpServiceResponse.h" #include "elastos/droid/wifi/p2p/CWifiP2pDevice.h" #include <elastos/core/StringUtils.h> #include "elastos/droid/ext/frameworkext.h" #include <elastos/utility/etl/List.h> using Elastos::Utility::Etl::List; using Elastos::Core::StringUtils; using Elastos::IO::IByteArrayInputStream; using Elastos::IO::CByteArrayInputStream; using Elastos::IO::IDataInputStream; using Elastos::IO::CDataInputStream; using Elastos::IO::IDataInput; namespace Elastos { namespace Droid { namespace Wifi { namespace P2p { namespace Nsd { CAR_OBJECT_IMPL(CWifiP2pServiceResponse) ECode CWifiP2pServiceResponse::GetServiceType( /* [out] */ Int32* serviceType) { return WifiP2pServiceResponse::GetServiceType(serviceType); } ECode CWifiP2pServiceResponse::GetStatus( /* [out] */ Int32* status) { return WifiP2pServiceResponse::GetStatus(status); } ECode CWifiP2pServiceResponse::GetTransactionId( /* [out] */ Int32* transactionId) { return WifiP2pServiceResponse::GetTransactionId(transactionId); } ECode CWifiP2pServiceResponse::GetRawData( /* [out, callee] */ ArrayOf<Byte>** rawData) { return WifiP2pServiceResponse::GetRawData(rawData); } ECode CWifiP2pServiceResponse::GetSrcDevice( /* [out] */ IWifiP2pDevice** srcDevice) { return WifiP2pServiceResponse::GetSrcDevice(srcDevice); } ECode CWifiP2pServiceResponse::SetSrcDevice( /* [in] */ IWifiP2pDevice* dev) { return WifiP2pServiceResponse::SetSrcDevice(dev); } ECode CWifiP2pServiceResponse::ToString( /* [out] */ String* string) { return WifiP2pServiceResponse::ToString(string); } ECode CWifiP2pServiceResponse::Equals( /* [in] */ IInterface* obj, /* [out] */ Boolean* isEqual) { return WifiP2pServiceResponse::Equals(obj, isEqual); } ECode CWifiP2pServiceResponse::GetHashCode( /* [out] */ Int32* hashCode) { return WifiP2pServiceResponse::GetHashCode(hashCode); } ECode CWifiP2pServiceResponse::ReadFromParcel( /* [in] */ IParcel* source) { return WifiP2pServiceResponse::ReadFromParcel(source); } ECode CWifiP2pServiceResponse::WriteToParcel( /* [in] */ IParcel* dest) { return WifiP2pServiceResponse::WriteToParcel(dest); } ECode CWifiP2pServiceResponse::NewInstance( /* [in] */ const String& supplicantEvent, /* [out, callee] */ ArrayOf<IWifiP2pServiceResponse*>** list) { VALIDATE_NOT_NULL(list); *list = NULL; List<AutoPtr<IWifiP2pServiceResponse> > respList; AutoPtr<ArrayOf<String> > args; StringUtils::Split(supplicantEvent, String(" "), (ArrayOf<String>**)&args); if ((args == NULL) || (args->GetLength() != 4)) { return NOERROR; } AutoPtr<IWifiP2pDevice> dev; FAIL_RETURN(CWifiP2pDevice::New((IWifiP2pDevice**)&dev)); String srcAddr; srcAddr = (*args)[1]; FAIL_RETURN(dev->SetDeviceAddress(srcAddr)); //String updateIndicator = args[2];//not used. AutoPtr<ArrayOf<Byte> > bin; FAIL_RETURN(WifiP2pServiceResponse::HexStr2Bin((*args)[3], (ArrayOf<Byte>**)&bin)); if (bin == NULL) { return NOERROR; } AutoPtr<IByteArrayInputStream> ins; FAIL_RETURN(CByteArrayInputStream::New(bin, (IByteArrayInputStream**)&ins)); AutoPtr<IDataInputStream> dis; assert(0); // TODO // FAIL_RETURN(CDataInputStream::New(ins, (IDataInputStream**)&dis)); AutoPtr<IDataInput> idi = IDataInput::Probe(dis); if (idi == NULL) return E_NO_INTERFACE; Int32 i, type, status; Int64 temp, length; List<AutoPtr<IWifiP2pServiceResponse> >::Iterator it; AutoPtr<ArrayOf<IWifiP2pServiceResponse*> > ret; Int32 temp1, temp2, transId; // try { Int32 number; while (TRUE) { assert(0); // TODO // FAIL_GOTO(dis->Available(&number), L_ERR_EXIT); if (number <= 0) break; /* * Service discovery header is as follows. * ______________________________________________________________ * | Length(2byte) | Type(1byte) | TransId(1byte)}| * ______________________________________________________________ * | status(1byte) | vendor specific(variable) | */ // The length equals to 3 plus the number of octets in the vendor // specific content field. And this is little endian. FAIL_GOTO(idi->ReadUnsignedByte(&temp1), L_ERR_EXIT); FAIL_GOTO(idi->ReadUnsignedByte(&temp2), L_ERR_EXIT); length = (temp1 + (temp2 << 8)) - 3; if (length < 0) { return NOERROR; } FAIL_GOTO(idi->ReadUnsignedByte(&type), L_ERR_EXIT); FAIL_GOTO(idi->ReadUnsignedByte(&transId), L_ERR_EXIT); FAIL_GOTO(idi->ReadUnsignedByte(&status), L_ERR_EXIT); if (length == 0) { if (status == IWifiP2pServiceResponseStatus::SUCCESS) { AutoPtr<IWifiP2pServiceResponse> resp; FAIL_GOTO(CWifiP2pServiceResponse::New( type, status, (Int32)transId, dev, NULL, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT); respList.PushBack(resp); } continue; } if (length > MAX_BUF_SIZE) { assert(0); // TODO // FAIL_GOTO(dis->Skip(length, &temp), L_ERR_EXIT); continue; } AutoPtr<ArrayOf<Byte> > data = ArrayOf<Byte>::Alloc(length); if (data == NULL) goto L_ERR_EXIT; FAIL_GOTO(idi->ReadFully((ArrayOf<Byte>*)data), L_ERR_EXIT); AutoPtr<IWifiP2pServiceResponse> resp; if (type == IWifiP2pServiceInfo::SERVICE_TYPE_BONJOUR) { FAIL_GOTO(CWifiP2pDnsSdServiceResponse::New( status, (Int32)transId, dev, data, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT); } else if (type == IWifiP2pServiceInfo::SERVICE_TYPE_UPNP) { FAIL_GOTO(CWifiP2pUpnpServiceResponse::New( status, (Int32)transId, dev, data, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT); } else { AutoPtr<CWifiP2pServiceResponse> rsp; FAIL_GOTO(CWifiP2pServiceResponse::New( type, status, (Int32)transId, dev, data, (IWifiP2pServiceResponse**)&resp), L_ERR_EXIT); } if (resp != NULL) { FAIL_GOTO(resp->GetStatus(&status), L_ERR_EXIT); if (status == IWifiP2pServiceResponseStatus::SUCCESS) { respList.PushBack(resp); } } } L_ERR_EXIT: ret = ArrayOf<IWifiP2pServiceResponse*>::Alloc(respList.GetSize()); if (ret == NULL) goto L_ERR_EXIT; i = 0; for (it = respList.Begin(); it != respList.End(); ++it) { AutoPtr<IWifiP2pServiceResponse> resp = *it; ret->Set(i++, resp); } *list = ret; REFCOUNT_ADD(*list); return NOERROR; } } // namespace Nsd } // namespace P2p } // namespace Wifi } // namespace Droid } // namespace Elastos
7,862
2,768