hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
bedf9bf367676509351f56af3d525586bf7520cd
1,210
cpp
C++
src/main.cpp
lukasz-pawlos/ukladV2
56d643d339160a891e5168fdaa576bab0a87f8a4
[ "MIT" ]
null
null
null
src/main.cpp
lukasz-pawlos/ukladV2
56d643d339160a891e5168fdaa576bab0a87f8a4
[ "MIT" ]
null
null
null
src/main.cpp
lukasz-pawlos/ukladV2
56d643d339160a891e5168fdaa576bab0a87f8a4
[ "MIT" ]
null
null
null
#include <iostream> #include "SWektor.hh" #include "Macierz.hh" #include "UkladRownan.hh" #include "rozmiar.h" #include "LZespolona.hh" using namespace std; int main() { char x; cin >> x; if (x == 'r') ///DLA DOUBLE { UkladRownanLiniowych<double, ROZMIAR> B; SWektor<double, ROZMIAR> C, D; cin >> B; C = B.obliczuklad(); //Obliczenie wektora wynikow B.wywtrans(); //Ztransponowanie macierzy cout << B; D = B.wekbl(C); //Obliczenie wektora bledu wyswrozw(C, D); // Wyswietlenie rozwiazan return 0; } else if (x == 'z') ///DLA ZESPOLONYCH { UkladRownanLiniowych<LZespolona, ROZMIAR> B; SWektor<LZespolona, ROZMIAR> C, D; cin >> B; C = B.obliczuklad(); //Obliczenie wektora wynikow B.wywtrans(); //Ztransponowanie macierzy cout << B; D = B.wekbl(C); //Obliczenie wektora bledu wyswrozw(C, D); // Wyswietlenie rozwiazan return 0; } else { cout << endl << "Nieprawidlowa opcja wywolania!" << endl; cout << "Dostepne opcje to: 'r'->(rzeczywiste) lub 'z'->(zespolone)" << endl; return 1; } }
20.166667
84
0.561157
lukasz-pawlos
bee1e1e4b5c5800a360b7a72a22951d90ac2ce30
4,666
cpp
C++
ch16-09-extruded-a/src/Utils.cpp
pulpobot/C-SFML-html5-animation
14154008b853d1235e8ca35a5b23b6a70366f914
[ "MIT" ]
73
2017-12-14T00:33:23.000Z
2022-02-09T12:04:52.000Z
ch17-03-extruded-a-light/src/Utils.cpp
threaderic/C-SFML-html5-animation
22f302cdf7c7c00247609da30e1bcf472d134583
[ "MIT" ]
null
null
null
ch17-03-extruded-a-light/src/Utils.cpp
threaderic/C-SFML-html5-animation
22f302cdf7c7c00247609da30e1bcf472d134583
[ "MIT" ]
5
2017-12-26T03:30:07.000Z
2020-07-05T04:58:24.000Z
#include <sstream> #include <iostream> #include "Utils.h" void Utils::Bezier::QuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments, std::vector<sf::Vector2f> &curvePoints, bool throughControlPoint) { //If there are any segments required if (segments <= 0) return; //Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2); curvePoints.clear(); float stepIncreasement = 1.0f / segments; float t = 0.0f; float px = 0.0f; float py = 0.0f; if (throughControlPoint) { p1.x = p1.x * 2 - (p0.x + p2.x) / 2; p1.y = p1.y * 2 - (p0.y + p2.y) / 2; } for (int i = 0; i <= segments; i++) { px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x); py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y); curvePoints.push_back(sf::Vector2f(px, py)); t += stepIncreasement; } } void Utils::Bezier::QuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments, std::vector<sf::Vertex> &curvePoints, sf::Color lineColor, bool throughControlPoint) { //If there are any segments required if (segments <= 0) return; //Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2); curvePoints.clear(); float stepIncreasement = 1.0f / segments; float t = 0; float px = 0; float py = 0; if (throughControlPoint) { p1.x = p1.x * 2 - (p0.x + p2.x) / 2; p1.y = p1.y * 2 - (p0.y + p2.y) / 2; } //Add points based on control point's position for (int i = 0; i <= segments; i++) { px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x); py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y); curvePoints.push_back(sf::Vertex(sf::Vector2f(px, py), lineColor)); t += stepIncreasement; } } ///Same as QuadraticBezierCurve, but it doesn't clear the array before pushing vertex void Utils::Bezier::AccumulativeQuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments, std::vector<sf::Vertex> &curvePoints, sf::Color lineColor, bool throughControlPoint) { //If there are any segments required if (segments <= 0) return; //Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2); float stepIncreasement = 1.0f / segments; float t = 0; float px = 0; float py = 0; if (throughControlPoint) { p1.x = p1.x * 2 - (p0.x + p2.x) / 2; p1.y = p1.y * 2 - (p0.y + p2.y) / 2; } //Add points based on control point's position for (int i = 0; i <= segments; i++) { px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x); py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y); curvePoints.push_back(sf::Vertex(sf::Vector2f(px, py), lineColor)); t += stepIncreasement; } } bool ::Utils::ContainsPoint(sf::FloatRect rect, float x, float y) { //SFML already has a "contains" function inside FloatRect class //return rect.contains(x,y); return !(x < rect.left || x > rect.left + rect.width || y < rect.top || y > rect.top + rect.height); } bool ::Utils::Intersects(sf::FloatRect rectA, sf::FloatRect rectB) { //SFML already has an "intersects" function inside FloatRect class //return rectA.intersects(rectB); return !(rectA.left + rectA.width < rectB.left || rectB.left + rectB.width < rectA.left || rectA.top + rectA.width < rectB.top || rectB.top + rectB.width < rectA.top ); } /// Input string examples: "#ffcccc" - "ffcccc" - "#ff" - "ffccccff" - "ffcccc" sf::Color Utils::HexColorToSFMLColor(std::string hexValue){ //remove # symbol if(hexValue.size() % 2 != 0) hexValue = hexValue.substr(1); unsigned int r = std::stoul(hexValue.substr(0,2), nullptr, 16); unsigned int g = (hexValue.size() > 2) ? std::stoul(hexValue.substr(2,2), nullptr, 16) : 0; unsigned int b = (hexValue.size() > 4) ? std::stoul(hexValue.substr(4,2), nullptr, 16) : 0; unsigned int a = (hexValue.size() > 6) ? std::stoul(hexValue.substr(6,2), nullptr, 16) : 255; return sf::Color(r,g,b,a); }
39.542373
114
0.536434
pulpobot
bee226083cad300103ba217fb6ad1b1e20152853
983
cpp
C++
tests/whole-program/structreturn.cpp
v8786339/NyuziProcessor
34854d333d91dbf69cd5625505fb81024ec4f785
[ "Apache-2.0" ]
1,388
2015-02-05T17:16:17.000Z
2022-03-31T07:17:08.000Z
tests/whole-program/structreturn.cpp
czvf/NyuziProcessor
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
[ "Apache-2.0" ]
176
2015-02-02T02:54:06.000Z
2022-02-01T06:00:21.000Z
tests/whole-program/structreturn.cpp
czvf/NyuziProcessor
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
[ "Apache-2.0" ]
271
2015-02-18T02:19:04.000Z
2022-03-28T13:30:25.000Z
// // Copyright 2011-2015 Jeff Bush // // 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 <stdio.h> // // Struct as return value // struct MyStruct { int a; int b; }; MyStruct __attribute__ ((noinline)) doIt(int a, int b) { MyStruct s1; s1.a = a; s1.b = b; return s1; } int main() { MyStruct s1 = doIt(0x37523482, 0x10458422); printf("s1a 0x%08x\n", s1.a); // CHECK: s1a 0x37523482 printf("s1b 0x%08x\n", s1.b); // CHECK: s1b 0x10458422 return 0; }
20.914894
75
0.693795
v8786339
bee3e00eb1fadc197284ad56a53b228d4fe3a61e
4,061
cpp
C++
inetsrv/iis/svcs/cmp/aspcmp/shared/src/instrm.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/cmp/aspcmp/shared/src/instrm.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/cmp/aspcmp/shared/src/instrm.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1997 Microsoft Corporation Module Name : InStrm.cpp Abstract: A lightweight implementation of input streams. This class provides the interface, as well as a basic skeleton for input streams. Author: Neil Allain ( a-neilal ) August-1997 Revision History: --*/ #include "stdafx.h" #include "InStrm.h" static void throwIOException( HRESULT s ); void throwIOException( HRESULT s ) { if ( s != InStream::EndOfFile ) { ATLTRACE( _T("InStream error: %d\n"), s ); } } bool IsWhiteSpace::operator()( _TCHAR c ) { bool rc = false; switch ( c ) { case _T('\r'): case _T(' '): case _T('\t'): case _T('\n'): { rc = true; } break; } return rc; } bool IsNewLine::operator()( _TCHAR c ) { bool rc = false; if ( ( c != _T('\n') ) && ( c != _T('\r') ) ) { } else { rc = true; } return rc; } InStream::InStream() : m_bEof(false), m_lastError( S_OK ) { } HRESULT InStream::readInt16( SHORT& i ) { String str; HRESULT rc = readString( str ); if ( ( rc == S_OK ) || rc == EndOfFile ) { i = str.toInt16(); } setLastError( rc ); return rc; } HRESULT InStream::readInt( int& i ) { String str; HRESULT rc = readString( str ); if ( ( rc == S_OK ) || rc == EndOfFile ) { i = str.toInt32(); } setLastError( rc ); return rc; } HRESULT InStream::readInt32( LONG& i ) { String str; HRESULT rc = readString( str ); if ( ( rc == S_OK ) || rc == EndOfFile ) { i = str.toInt32(); } setLastError( rc ); return rc; } HRESULT InStream::readUInt32( ULONG& i ) { String str; HRESULT rc = readString( str ); if ( ( rc == S_OK ) || rc == EndOfFile ) { i = str.toUInt32(); } setLastError( rc ); return rc; } HRESULT InStream::readFloat( float& f ) { String str; HRESULT rc = readString( str ); if ( ( rc == S_OK ) || rc == EndOfFile ) { f = str.toFloat(); } setLastError( rc ); return rc; } HRESULT InStream::readDouble( double& f ) { String str; HRESULT rc = readString( str ); if ( ( rc == S_OK ) || rc == EndOfFile ) { f = str.toDouble(); } setLastError( rc ); return rc; } HRESULT InStream::readString( String& str ) { return read( IsWhiteSpace(), str ); } HRESULT InStream::readLine( String& str ) { return read( IsNewLine(), str ); } HRESULT InStream::skipWhiteSpace() { return skip( IsWhiteSpace() ); } InStream& InStream::operator>>( _TCHAR& c ) { HRESULT s = readChar(c); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( SHORT& i ) { HRESULT s = readInt16(i); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( int& i ) { HRESULT s = readInt(i); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( LONG& i ) { HRESULT s = readInt32(i); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( ULONG& i ) { HRESULT s = readUInt32(i); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( float& f ) { HRESULT s = readFloat(f); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( double& f ) { HRESULT s = readDouble(f); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } InStream& InStream::operator>>( String& str ) { HRESULT s = readString(str); if ( s == S_OK ) { } else { throwIOException(s); } return *this; } void InStream::setLastError( HRESULT hr ) { if ( hr == S_OK ) { } else { if ( hr == EndOfFile ) { m_bEof = true; } m_lastError = hr; } }
12.122388
70
0.534351
npocmaka
bee879658e13c9e5d37bbf59ce9afb46702e32d4
1,406
cpp
C++
src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
null
null
null
src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
null
null
null
src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
2
2016-09-19T00:16:05.000Z
2021-03-29T22:06:45.000Z
/**************************************************************************** ** CUBE http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2016 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** Copyright (c) 2009-2015 ** ** German Research School for Simulation Sciences GmbH, ** ** Laboratory for Parallel Programming ** ** ** ** This software may be modified and distributed under the terms of ** ** a BSD-style license. See the COPYING file in the package base ** ** directory for details. ** ****************************************************************************/ #ifndef __NULLARY_EVALUATION_CPP #define __NULLARY_EVALUATION_CPP 0 #include "CubeNullaryEvaluation.h" using namespace cube; NullaryEvaluation::NullaryEvaluation() : GeneralEvaluation() { }; NullaryEvaluation::~NullaryEvaluation() { } size_t NullaryEvaluation::getNumOfArguments() { return 0; } #endif
36.051282
77
0.396159
OpenCMISS-Dependencies
bee973e6c2fd0c9807aab42fd68929f55c1ceaf2
6,965
cxx
C++
src/writeMerge.cxx
fermi-lat/eventFile
36bae3f7b949c7eaa77725dc6d7ec919f77b14ee
[ "BSD-3-Clause" ]
null
null
null
src/writeMerge.cxx
fermi-lat/eventFile
36bae3f7b949c7eaa77725dc6d7ec919f77b14ee
[ "BSD-3-Clause" ]
null
null
null
src/writeMerge.cxx
fermi-lat/eventFile
36bae3f7b949c7eaa77725dc6d7ec919f77b14ee
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <iostream> #include <fstream> #include <string> #include <map> #include <sstream> #include <stdexcept> #include <algorithm> #include "eventFile/LSEReader.h" #include "eventFile/LSEWriter.h" #include "eventFile/LSE_Context.h" #include "eventFile/LSE_Info.h" #include "eventFile/LPA_Handler.h" #include "eventFile/EBF_Data.h" #include "eventFile/LSE_Keys.h" struct EvtIdx { std::string tag; unsigned startedAt; unsigned long long sequence; unsigned long long elapsed; unsigned long long livetime; double evtUTC; unsigned scid; unsigned apid; unsigned datagrams; unsigned dgmevt; std::string oaction; std::string caction; double dgmUTC; off_t fileofst; std::string evtfile; EvtIdx( const std::string& idxline ) { // make the text line into an input stream std::istringstream iss( idxline ); // extract the components iss >> tag; iss >> startedAt; iss >> sequence; // iss >> elapsed; // iss >> livetime; // iss >> evtUTC; // iss >> scid; iss >> apid; iss >> datagrams; // iss >> dgmevt; iss >> oaction; iss >> caction; // iss >> dgmUTC; iss >> fileofst; iss >> evtfile; }; }; typedef std::map< std::string, eventFile::LSEReader* > lser_map; typedef lser_map::iterator lser_iter; struct cleanup { void operator() ( lser_map::value_type x ) { delete x.second; } }; int main( int argc, char* argv[] ) { // get the input and output file names if ( argc < 4 ) { std::cout << "writeMerge: not enough input arguments" << std::endl; exit( EXIT_FAILURE ); } std::string idxfile( argv[1] ); std::string evtfile( argv[2] ); // this contains format specifiers int downlinkID = atoi( argv[3] ); // add support for configurable output file size int maxEvents = -1; if ( argc >= 5 ) { maxEvents = atoi( argv[4] ); } int currMax = maxEvents; // make the output-file-size scaling externally tunable double WRITEMERGE_CHUNKSCALE = 0.90; char* envbuf = getenv( "WRITEMERGE_CHUNKSCALE" ); if ( envbuf ) { WRITEMERGE_CHUNKSCALE = atof( envbuf ); } double WRITEMERGE_CHUNKFLOOR = 0.50; envbuf = getenv( "WRITEMERGE_CHUNKFLOOR" ); if ( envbuf ) { WRITEMERGE_CHUNKFLOOR = atof( envbuf ); } // add support for overriding translated LATC master key unsigned long overrideLATC = 0xffffffff; if ( argc >= 6 ) { overrideLATC = strtoul( argv[5], NULL, 0 ); std::cout << "writeMerge: overriding LATC key to " << overrideLATC << std::endl; } else { std::cout << "writeMerge: no LATC key override" << std::endl; } // declare the file-output object pointer int eventsOut = 0; eventFile::LSEWriter* pLSEW = NULL; // create a container for the chunk-evt input files lser_map mapLSER; // declare object to receive the event information eventFile::LSE_Context ctx; eventFile::EBF_Data ebf; eventFile::LSE_Info::InfoType infotype; eventFile::LPA_Info pinfo; eventFile::LCI_ACD_Info ainfo; eventFile::LCI_CAL_Info cinfo; eventFile::LCI_TKR_Info tinfo; eventFile::LSE_Keys::KeysType ktype; eventFile::LPA_Keys pakeys; eventFile::LCI_Keys cikeys; // read the index file and parse the entries, retrieving the // requeseted events as we go std::string idxline; std::ifstream idx( idxfile.c_str() ); if ( idx.fail() ) { std::cout << "writeMerge: failed to open " << idxfile; std::cout << " (" << errno << ":" << strerror(errno) << ")" << std::endl; exit( EXIT_FAILURE ); } while ( getline( idx, idxline ) ) { // skip non-event records if ( idxline.find( "EVT:" ) != 0 ) continue; // make an event-index object EvtIdx edx( idxline ); // get an LSEReader for the file lser_iter it = mapLSER.find( edx.evtfile ); if ( it == mapLSER.end() ) { try { it = mapLSER.insert( std::pair< std::string, eventFile::LSEReader* >( edx.evtfile, new eventFile::LSEReader( edx.evtfile ) ) ).first; } catch ( std::runtime_error& e ) { std::cout << e.what() << std::endl; exit( EXIT_FAILURE ); } } // read the event at the specified location bool bevtread = false; try { it->second->seek( edx.fileofst ); bevtread = it->second->read( ctx, ebf, infotype, pinfo, ainfo, cinfo, tinfo, ktype, pakeys, cikeys ); } catch( std::runtime_error e ) { std::cout << e.what() << std::endl; exit( EXIT_FAILURE ); } if ( !bevtread ) { std::cout << "no event read from " << edx.fileofst << " of " << edx.evtfile << std::endl; exit( EXIT_FAILURE); } // open an output file if necessary if ( !pLSEW ) { // create the output filename from the user-supplied template char ofn[512]; #ifndef _FILE_OFFSET_BITS _snprintf( ofn, 512, evtfile.c_str(), ctx.run.startedAt, ctx.scalers.sequence ); #else snprintf( ofn, 512, evtfile.c_str(), ctx.run.startedAt, ctx.scalers.sequence ); #endif // open the output file try { pLSEW = new eventFile::LSEWriter( std::string( ofn ), downlinkID ); } catch ( std::runtime_error& e ) { std::cout << e.what() << std::endl; exit( EXIT_FAILURE ); } std::cout << "writeMerge: created output file " << pLSEW->name() << std::endl; } // write the event to the merged file try { switch( infotype ) { case eventFile::LSE_Info::LPA: if ( overrideLATC != 0xffffffff ) { pakeys.LATC_master = overrideLATC; } pLSEW->write( ctx, ebf, pinfo, pakeys ); break; case eventFile::LSE_Info::LCI_ACD: pLSEW->write( ctx, ebf, ainfo, cikeys ); break; case eventFile::LSE_Info::LCI_CAL: pLSEW->write( ctx, ebf, cinfo, cikeys ); break; case eventFile::LSE_Info::LCI_TKR: pLSEW->write( ctx, ebf, tinfo, cikeys ); break; default: std::ostringstream ess; ess << "writeMerge: unknown LSE_Info type " << infotype; ess << " at offset " << edx.fileofst; ess << " in " << edx.evtfile; throw std::runtime_error( ess.str() ); break; } } catch ( std::runtime_error& e ) { std::cout << e.what() << std::endl; exit( EXIT_FAILURE ); } // check to see if the output file is full if ( currMax > 0 && ++eventsOut >= currMax ) { // close the current file and reset the event counter std::cout << "writeMerge: wrote " << pLSEW->evtcnt() << " events to " << pLSEW->name() << std::endl; delete pLSEW; pLSEW = NULL; eventsOut = 0; // rescale the max-event count for the next file currMax = ( currMax <= WRITEMERGE_CHUNKFLOOR * maxEvents ) ? maxEvents : WRITEMERGE_CHUNKSCALE * currMax; } } std::for_each( mapLSER.begin(), mapLSER.end(), cleanup() ); idx.close(); if ( pLSEW ) { std::cout << "writeMerge: wrote " << pLSEW->evtcnt() << " events to " << pLSEW->name() << std::endl; delete pLSEW; } // all done return 0; }
28.900415
134
0.628141
fermi-lat
bef417c20988375bffb50833d1b329e3772f95dd
26,949
cpp
C++
orca/gporca/server/src/unittest/gpopt/base/CStatsEquivClassTest.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
orca/gporca/server/src/unittest/gpopt/base/CStatsEquivClassTest.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
orca/gporca/server/src/unittest/gpopt/base/CStatsEquivClassTest.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CStatsEquivClassTest.cpp // // @doc: // Test for constraint // // @owner: // // // @test: // // //--------------------------------------------------------------------------- #include "unittest/base.h" #include "unittest/gpopt/base/CStatsEquivClassTest.h" #include "unittest/gpopt/base/CConstraintTest.h" #include "gpopt/operators/CPredicateUtils.h" #include "gpopt/base/CStatsEquivClass.h" #include "gpopt/eval/CConstExprEvaluatorDefault.h" //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::EresUnittest // // @doc: // Unittest for ranges // //--------------------------------------------------------------------------- GPOS_RESULT CStatsEquivClassTest::EresUnittest() { CUnittest rgut[] = { GPOS_UNITTEST_FUNC(CStatsEquivClassTest::EresUnittest_EquivClassFromScalarExpr), }; CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(pmp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc ( pmp, &mda, NULL, /* pceeval */ CTestUtils::Pcm(pmp) ); return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut)); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::EresUnittest_EquivClassFromScalarExpr // // @doc: // Equivalence class from scalar expressions tests // //--------------------------------------------------------------------------- GPOS_RESULT CStatsEquivClassTest::EresUnittest_EquivClassFromScalarExpr() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(pmp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); CColumnFactory *pcf = COptCtxt::PoctxtFromTLS()->Pcf(); SEquivClassSTestCase rgequivclasstc[] = { {PequivclasstcScIdCmpConst}, {PequivclasstcScIdCmpScId}, {PequivclasstcSameCol}, {PequivclasstcConj1}, {PequivclasstcConj2}, {PequivclasstcConj3}, {PequivclasstcConj4}, {PequivclasstcConj5}, {PequivclasstcDisj1}, {PequivclasstcDisj2}, {PequivclasstcDisjConj1}, {PequivclasstcDisjConj2}, {PequivclasstcDisjConj3}, {PequivclasstcCast} }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgequivclasstc); for (ULONG ul = 0; ul < ulTestCases; ul++) { SEquivClassSTestCase elem = rgequivclasstc[ul]; GPOS_CHECK_ABORT; // generate the test case FnPequivclass *pf = elem.m_pf; GPOS_ASSERT(NULL != pf); SEquivClass *pequivclass = pf(pmp, pcf, &mda); CExpression *pexpr = pequivclass->Pexpr(); DrgPcrs *pdrgpcrsExpected = pequivclass->PdrgpcrsEquivClass(); DrgPcrs *pdrgpcrsActual = CStatsEquivClass::PdrgpcrsEquivClassFromScalarExpr(pmp, pexpr); { // debug print CAutoTrace at(pmp); at.Os() << std::endl; at.Os() << "EXPR:" << std::endl << *pexpr << std::endl; } CConstraintTest::PrintEquivClasses(pmp, pdrgpcrsActual, false /* fExpected */); CConstraintTest::PrintEquivClasses(pmp, pdrgpcrsExpected, true /* fExpected */); if (!FMatchingEquivClasses(pdrgpcrsActual, pdrgpcrsExpected)) { return GPOS_FAILED; } // clean up CRefCount::SafeRelease(pdrgpcrsActual); GPOS_DELETE(pequivclass); } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcScIdCmpConst // // @doc: // Expression and equivalence classes of a scalar comparison between // column reference and a constant // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcScIdCmpConst ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr = pcf->PcrCreate(pmdtypeint4); IDatum *pdatum = (IDatum *) pmda->PtMDType<IMDTypeInt4>(CTestUtils::m_sysidDefault)->PdatumInt4(pmp, 1, false /* fNull */); CExpression *pexprConst = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarConst(pmp, pdatum)); // col1 == const CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr), pexprConst); // Equivalence class {} DrgPcrs *pdrpcrs = NULL; SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrpcrs); return pequivclass; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcScIdCmpScId // // @doc: // Expression and equivalence classes of a scalar comparison between // column references // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcScIdCmpScId ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); // col1 == col2 CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); // Equivalence class {1,2} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2)); SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); return pequivclass; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcSameCol // // @doc: // Expression and equivalence classes of a predicate on same column // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcSameCol ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); // col1 == col1 CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr1)); // Equivalence class {} DrgPcrs *pdrgpcrs = NULL; SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); return pequivclass; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcConj1 // // @doc: // Expression and its equivalence class for a conjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcConj1 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp); const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); // (col1 == col2) AND (col1 == const) AND (col1 == col1) // (col1 == col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexpr->Append(pexpr1); // (col1 == const) IDatum *pdatum = (IDatum *) pmda->PtMDType<IMDTypeInt4>(CTestUtils::m_sysidDefault)->PdatumInt4(pmp, 1, false /* fNull */); CExpression *pexprConst = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarConst(pmp, pdatum)); CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), pexprConst); pdrgpexpr->Append(pexpr2); // (col1 == col1) CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr1)); pdrgpexpr->Append(pexpr3); CExpression *pexpr = CPredicateUtils::PexprConjunction(pmp, pdrgpexpr); // Equivalence class {1,2} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2)); SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); return pequivclass; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcConj2 // // @doc: // Expression and equivalence classes for a conjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcConj2 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) AND (col1 = col3) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col1 = col3) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3)); pdrgpexprA->Append(pexpr2); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // Equivalence class {1,2,3} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2); pcrs->Include(pcr3); pdrgpcrs->Append(pcrs); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcConj3 // // @doc: // Expression and equivalence classes for a conjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcConj3 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) AND (col2 = col3) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col2 = col3) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr2), CUtils::PexprScalarIdent(pmp, pcr3)); pdrgpexprA->Append(pexpr2); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // Equivalence class {1,2,3} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2); pcrs->Include(pcr3); pdrgpcrs->Append(pcrs); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcConj4 // // @doc: // Expression and equivalence classes for a conjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcConj4 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr4 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) AND (col3 = col4) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col3 = col4) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr4)); pdrgpexprA->Append(pexpr2); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // Equivalence class {1,2} {3,4} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2)); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr3, pcr4)); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcConj5 // // @doc: // Expression and equivalence classes for a conjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcConj5 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) AND (col3 = col3) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col3 = col3) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr3)); pdrgpexprA->Append(pexpr2); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // Equivalence class {1,2} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2)); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcDisj1 // // @doc: // Expression and its equivalence class for a disjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcDisj1 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp); const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexpr->Append(pexpr1); // (col1 = const) IDatum *pdatum = (IDatum *) pmda->PtMDType<IMDTypeInt4>(CTestUtils::m_sysidDefault)->PdatumInt4(pmp, 1, false /* fNull */); CExpression *pexprConst = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarConst(pmp, pdatum)); CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), pexprConst); pdrgpexpr->Append(pexpr2); // (col1 = col1) CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr1)); pdrgpexpr->Append(pexpr3); // (col1 = col3) CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3)); pdrgpexpr->Append(pexpr4); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr); // Equivalence class {} DrgPcrs *pdrgpcrs = NULL; SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); return pequivclass; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcDisj2 // // @doc: // Expression and its equivalence class for a disjunctive predicate // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcDisj2 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp); const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexpr->Append(pexpr1); // (col1 = col2) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexpr->Append(pexpr2); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr); // Equivalence class {1,2} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2)); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcDisjConj1 // // @doc: // Expression and equivalence classes of a predicate with disjunction and conjunction // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcDisjConj1 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) AND (col1 = col3) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col1 = col3) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3)); pdrgpexprA->Append(pexpr2); CExpression *pexprA = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // (col3 = col2) AND (col1 = col2) DrgPexpr *pdrgpexprB = GPOS_NEW(pmp) DrgPexpr(pmp); // (col3 = col2) CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprB->Append(pexpr3); // (col1 = col2) CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprB->Append(pexpr4); CExpression *pexprB = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprB); // exprA OR exprB DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp); pdrgpexpr->Append(pexprA); pdrgpexpr->Append(pexprB); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr); // Equivalence class {1,2,3} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2); pcrs->Include(pcr3); pdrgpcrs->Append(pcrs); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcDisjConj2 // // @doc: // Expression and equivalence classes of a predicate with disjunction and conjunction // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcDisjConj2 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr4 = pcf->PcrCreate(pmdtypeint4); // (col1 = col2) AND (col1 = col3) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col3 = col4) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr4)); pdrgpexprA->Append(pexpr2); CExpression *pexprA = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // (col1 = col2) AND (col2 = col4) DrgPexpr *pdrgpexprB = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprB->Append(pexpr3); // (col2 = col4) CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr2), CUtils::PexprScalarIdent(pmp, pcr4)); pdrgpexprB->Append(pexpr4); CExpression *pexprB = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprB); // exprA OR exprB DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp); pdrgpexpr->Append(pexprA); pdrgpexpr->Append(pexprB); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr); // Equivalence class {1,2} DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2); pdrgpcrs->Append(pcrs); return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcDisjConj3 // // @doc: // Expression and equivalence classes of a predicate with disjunction and conjunction // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcDisjConj3 ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr4 = pcf->PcrCreate(pmdtypeint4); // exprA: (col1 = col2) AND (col3 = col4) DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col2) CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2)); pdrgpexprA->Append(pexpr1); // (col3 = col4) CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr4)); pdrgpexprA->Append(pexpr2); CExpression *pexprA = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA); // exprB: (col1 = col3) AND (col2 = col4) DrgPexpr *pdrgpexprB = GPOS_NEW(pmp) DrgPexpr(pmp); // (col1 = col3) CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3)); pdrgpexprB->Append(pexpr3); // (col2 = col4) CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr2), CUtils::PexprScalarIdent(pmp, pcr4)); pdrgpexprB->Append(pexpr4); CExpression *pexprB = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprB); // exprA OR exprB DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp); pdrgpexpr->Append(pexprA); pdrgpexpr->Append(pexprB); CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr); // Equivalence class {} DrgPcrs *pdrgpcrs = NULL; return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::PequivclasstcCast // // @doc: // Expression and equivalence classes of a scalar comparison between // column references // //--------------------------------------------------------------------------- CStatsEquivClassTest::SEquivClass * CStatsEquivClassTest::PequivclasstcCast ( IMemoryPool *pmp, CColumnFactory *pcf, CMDAccessor *pmda ) { const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>(); const IMDTypeInt4 *pmdtypeint8 = pmda->PtMDType<IMDTypeInt4>(); // col1::int8 = col2 CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4); CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4); CExpression *pexprScId1 = CUtils::PexprScalarIdent(pmp, pcr1); CExpression *pexprCast = CPredicateUtils::PexprCast(pmp, pmda, pexprScId1, pmdtypeint8->Pmdid()); CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, pexprCast, CUtils::PexprScalarIdent(pmp, pcr2)); DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp); pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2)); // Equivalence class {} SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs); return pequivclass; } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::FMatchingEquivClasses // // @doc: // Check if the two equivalence classes match // //--------------------------------------------------------------------------- BOOL CStatsEquivClassTest::FMatchingEquivClasses ( const DrgPcrs *pdrgpcrsActual, const DrgPcrs *pdrgpcrsExpected ) { if (NULL != pdrgpcrsExpected && NULL != pdrgpcrsActual) { const ULONG ulActual = pdrgpcrsActual->UlLength(); const ULONG ulExpected = pdrgpcrsExpected->UlLength(); if (ulActual < ulExpected) { // there can be equivalence classes that can be singleton in pdrgpcrsActual return false; } for (ULONG ulA = 0; ulA < ulActual; ulA++) { CColRefSet *pcrsActual = (*pdrgpcrsActual)[ulA]; BOOL fMatch = (1 == pcrsActual->CElements()); for (ULONG ulE = 0; ulE < ulExpected && !fMatch; ulE++) { CColRefSet *pcrsExpected = (*pdrgpcrsExpected)[ulE]; if (pcrsActual->FEqual(pcrsExpected)) { fMatch = true; } } if (!fMatch) { return false; } } return true; } return (UlEquivClasses(pdrgpcrsExpected) == UlEquivClasses(pdrgpcrsActual)); } //--------------------------------------------------------------------------- // @function: // CStatsEquivClassTest::UlEquivClasses // // @doc: // Return the number of non-singleton equivalence classes // //--------------------------------------------------------------------------- ULONG CStatsEquivClassTest::UlEquivClasses ( const DrgPcrs *pdrgpcrs ) { ULONG ulSize = 0; if (NULL == pdrgpcrs) { return ulSize; } const ULONG ulActual = pdrgpcrs->UlLength(); for (ULONG ul = 0; ul < ulActual; ul++) { CColRefSet *pcrs = (*pdrgpcrs)[ul]; if (1 != pcrs->CElements()) { ulSize++; } } return ulSize; } // EOF
30.279775
127
0.653605
vitessedata
befaaa250ca59ec25b0ef40e6f1523895ff98a9f
2,625
cpp
C++
Client/Client.cpp
Vasar007/HW
e441f87dfeb58ab3c7b3120c9972cae5fd8d869d
[ "Apache-2.0" ]
null
null
null
Client/Client.cpp
Vasar007/HW
e441f87dfeb58ab3c7b3120c9972cae5fd8d869d
[ "Apache-2.0" ]
null
null
null
Client/Client.cpp
Vasar007/HW
e441f87dfeb58ab3c7b3120c9972cae5fd8d869d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <thread> #include "Client.h" namespace vasily { Client::Client(const quint16 serverPort, const std::string& serverIP, QObject* parent) : QObject(parent), _serverPort(serverPort), _socket(std::make_unique<QTcpSocket>(this)), _serverIP(serverIP) { qDebug() << "Server Port:" << serverPort << "\nLayer IP:" << serverIP.c_str() << '\n'; connect(_socket.get(), &QTcpSocket::readyRead, this, &Client::slotReadFromServer); connect(_socket.get(), &QTcpSocket::disconnected, this, &Client::slotServerDisconnected, Qt::QueuedConnection); connect(this, &Client::signalToSend, this, &Client::slotSendDataToServer); } void Client::slotReadFromServer() const { if (_socket->bytesAvailable() > 0) { const QByteArray array = _socket->readAll(); const std::string receivedData = array.toStdString(); qDebug() << _socket->localPort() << '-' << array << '\n'; } } void Client::slotServerDisconnected() const { qDebug() << "\nServer disconnected!\n"; tryReconnect(); } void Client::slotSendDataToServer(const QByteArray& data) const { _socket->write(data); qDebug() << "Sent data:" << data << "successfully.\n"; } void Client::run() { std::thread workThread(&Client::waitLoop, this); workThread.detach(); } void Client::waitLoop() const { qDebug() << "\nWaiting for reply...\n\n"; while (true) { std::string input; qDebug() << "Enter command: "; std::getline(std::cin, input); if (!input.empty()) { sendData(input); } } } bool Client::tryConnect(const quint16 port, const std::string& ip, QTcpSocket* socketToConnect, const int msecs) const { if (socketToConnect->isOpen()) { socketToConnect->close(); } socketToConnect->connectToHost(ip.c_str(), port); if (socketToConnect->waitForConnected(msecs)) { qDebug() << "Connected to Server!\n"; return true; } qDebug() << "Not connected to Server!\n"; return false; } void Client::tryReconnect() const { launch(); } void Client::launch() const { bool isConnected = tryConnect(_serverPort, _serverIP, _socket.get(), true); while (!isConnected) { isConnected = tryConnect(_serverPort, _serverIP, _socket.get(), true); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } qDebug() << "\nClient launched...\n"; } void Client::sendData(const std::string& data) const { emit signalToSend(data.c_str()); } } // namespace vasily
22.435897
95
0.620952
Vasar007
befdb4dc51f299c04b6b126655aa1748ff502e0f
629
cpp
C++
comsci-110/Chapter 5/consoleInput.cpp
colmentse/Cplusplus-class
0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050
[ "MIT" ]
null
null
null
comsci-110/Chapter 5/consoleInput.cpp
colmentse/Cplusplus-class
0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050
[ "MIT" ]
null
null
null
comsci-110/Chapter 5/consoleInput.cpp
colmentse/Cplusplus-class
0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050
[ "MIT" ]
null
null
null
/* Author : Colmen Tse Compsci : 120 5.6 consoleinput.cpp */ #include <string> #include <iostream> #include <cmath> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; cin.ignore(1000, 10); string name; cout << "Enter your name: "; getline(cin, name); double temp; cout << "Enter the temperature outside right now (degrees F): "; cin >> temp; cin.ignore(1000, 10); string location; cout << "What city are you in right now? "; getline(cin, location); cout << name << " is " << age << " years old." << endl; cout << "It's " << temp << " degrees F in " << location << endl; }
17.971429
65
0.613672
colmentse
befefa3a238c5a224d33a3c2e82fabedb5ecc0ad
67
cc
C++
fluid/src/framework/op_desc.cc
ImageMetrics/paddle-mobile
8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4
[ "MIT" ]
2
2018-07-17T10:55:48.000Z
2018-08-03T01:35:20.000Z
fluid/src/framework/op_desc.cc
ImageMetrics/paddle-mobile
8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4
[ "MIT" ]
null
null
null
fluid/src/framework/op_desc.cc
ImageMetrics/paddle-mobile
8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4
[ "MIT" ]
null
null
null
// // Created by liuRuiLong on 2018/4/23. // #include "op_desc.h"
11.166667
38
0.641791
ImageMetrics
8305a43c0016eb26e8d544d2c621426147818ff0
5,383
cpp
C++
tests/collection.cpp
dead1ock/algorithms-cpp
35b79b4cfe5db24e83ce157765fbcb221bc2ed38
[ "MIT" ]
null
null
null
tests/collection.cpp
dead1ock/algorithms-cpp
35b79b4cfe5db24e83ce157765fbcb221bc2ed38
[ "MIT" ]
null
null
null
tests/collection.cpp
dead1ock/algorithms-cpp
35b79b4cfe5db24e83ce157765fbcb221bc2ed38
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <collection/FixedArrayStack.h> #include <collection/FixedQueue.h> #include <collection/LinkedListStack.h> #include <collection/LinkedQueue.h> #include <collection/ResizableStack.h> #include <collection/ResizableQueue.h> TEST(LINKEDLISTSTACK, PushPopCount) { LinkedListStack<int> stack; stack.Push(100); stack.Push(200); stack.Push(300); EXPECT_EQ(3, stack.Count()); EXPECT_EQ(300, stack.Pop()); EXPECT_EQ(200, stack.Pop()); EXPECT_EQ(100, stack.Pop()); } TEST(LINKEDLISTSTACK, Push1000) { LinkedListStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(LINKEDLISTSTACK, Push100000) { LinkedListStack<int> stack; for (int x = 1; x <= 100000; x++) stack.Push(x); EXPECT_EQ(100000, stack.Count()); } TEST(LINKEDLISTSTACK, Push1000000) { LinkedListStack<int> stack; for (int x = 1; x <= 1000000; x++) stack.Push(x); EXPECT_EQ(1000000, stack.Count()); } // ===================================================== // // ===================================================== TEST(FixedArrayStack, PushPopCount) { FixedArrayStack<int> stack(3); stack.Push(100); stack.Push(200); stack.Push(300); EXPECT_EQ(3, stack.Count()); EXPECT_EQ(300, stack.Pop()); EXPECT_EQ(200, stack.Pop()); EXPECT_EQ(100, stack.Pop()); } TEST(FixedArrayStack, Push1000) { FixedArrayStack<int> stack(1000); for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(FixedArrayStack, Push100000) { FixedArrayStack<int> stack(100000); for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(FixedArrayStack, Push1000000) { FixedArrayStack<int> stack(1000000); for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } // ===================================================== // // ===================================================== TEST(ResizableStack, PushPopCount) { ResizableStack<int> stack; stack.Push(100); stack.Push(200); stack.Push(300); EXPECT_EQ(3, stack.Count()); EXPECT_EQ(300, stack.Pop()); EXPECT_EQ(200, stack.Pop()); EXPECT_EQ(100, stack.Pop()); } TEST(ResizableStack, Push1000) { ResizableStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(ResizableStack, Push100000) { ResizableStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(ResizableStack, Push1000000) { ResizableStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } // ===================================================== // // ===================================================== TEST(FixedQueue, EnqueueDequeueCount) { FixedQueue<int> queue(3); queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); EXPECT_EQ(3, queue.Count()); EXPECT_EQ(100, queue.Dequeue()); EXPECT_EQ(200, queue.Dequeue()); EXPECT_EQ(300, queue.Dequeue()); } TEST(FixedQueue, Enqueue1000) { FixedQueue<int> queue(1000); for (int x = 1; x <= 1000; x++) queue.Enqueue(x); EXPECT_EQ(1000, queue.Count()); } TEST(FixedQueue, Enqueue100000) { FixedQueue<int> queue(100000); for (int x = 1; x <= 100000; x++) queue.Enqueue(x); EXPECT_EQ(100000, queue.Count()); } TEST(FixedQueue, Enqueue1000000) { FixedQueue<int> queue(1000000); for (int x = 1; x <= 1000000; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); } TEST(FixedQueue, ProduceEnqueueOverflow) { FixedQueue<int> queue(1000000); for (int x = 1; x <= 1000001; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); } // ===================================================== // // ===================================================== TEST(LinkedQueue, EnqueueDequeueCount) { LinkedQueue<int> queue; queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); EXPECT_EQ(3, queue.Count()); EXPECT_EQ(100, queue.Dequeue()); EXPECT_EQ(200, queue.Dequeue()); EXPECT_EQ(300, queue.Dequeue()); } TEST(LinkedQueue, Enqueue1000) { LinkedQueue<int> queue; for (int x = 1; x <= 1000; x++) queue.Enqueue(x); EXPECT_EQ(1000, queue.Count()); } TEST(LinkedQueue, Enqueue100000) { LinkedQueue<int> queue; for (int x = 1; x <= 100000; x++) queue.Enqueue(x); EXPECT_EQ(100000, queue.Count()); } TEST(LinkedQueue, Enqueue1000000) { LinkedQueue<int> queue; for (int x = 1; x <= 1000000; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); } // ===================================================== // // ===================================================== TEST(ResizableQueue, EnqueueDequeueCount) { ResizableQueue<int> queue; queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); EXPECT_EQ(3, queue.Count()); EXPECT_EQ(100, queue.Dequeue()); EXPECT_EQ(200, queue.Dequeue()); EXPECT_EQ(300, queue.Dequeue()); } TEST(ResizableQueue, Enqueue1000) { ResizableQueue<int> queue; for (int x = 1; x <= 1000; x++) queue.Enqueue(x); EXPECT_EQ(1000, queue.Count()); } TEST(ResizableQueue, Enqueue100000) { ResizableQueue<int> queue; for (int x = 1; x <= 100000; x++) queue.Enqueue(x); EXPECT_EQ(100000, queue.Count()); } TEST(ResizableQueue, Enqueue1000000) { ResizableQueue<int> queue; for (int x = 1; x <= 1000000; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); }
17.824503
56
0.602638
dead1ock
8306d502d0de3894cbff049ac4e1904b81fd428b
729
cpp
C++
test/examples_test/04_module_test/04_module_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206
e1fb506dbe4b068c01db307cd7626fd88b456a20
[ "MIT" ]
null
null
null
test/examples_test/04_module_test/04_module_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206
e1fb506dbe4b068c01db307cd7626fd88b456a20
[ "MIT" ]
1
2020-10-30T23:36:49.000Z
2020-11-06T19:33:56.000Z
test/examples_test/04_module_test/04_module_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206
e1fb506dbe4b068c01db307cd7626fd88b456a20
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("Verify sum of squares function") { REQUIRE(sum_of_squares(3)==14); REQUIRE(sum_of_squares(4)==30); REQUIRE(sum_of_squares(5)==55); } TEST_CASE("Verify sum numbers function") { REQUIRE(sum_numbers(4)==20); } TEST_CASE("Test get area with default parameters") { REQUIRE(get_area()==200); REQUIRE(get_area(5)==50); REQUIRE(get_area(20,20)==400); } TEST_CASE("Test value and reference parameters") { int num1=0, num2=0; pass_by_val_and_ref(num1, num2); REQUIRE(num1==0); REQUIRE(num2==50); }
20.828571
97
0.702332
acc-cosc-1337-fall-2020
8308730f7101ec449e3d4e3edfe2a179f4995b52
776
cpp
C++
Backtracking/ModularExpression.cpp
ssokjin/Interview-Bit
8714d3d627eb5875f49d205af779b59ca33ab4a3
[ "MIT" ]
513
2016-08-16T12:52:14.000Z
2022-03-30T19:32:10.000Z
Backtracking/ModularExpression.cpp
CodeOctal/Interview-Bit
88c021685d6cdef17906d077411ce34723363a08
[ "MIT" ]
25
2018-02-14T15:25:48.000Z
2022-03-23T11:52:08.000Z
Backtracking/ModularExpression.cpp
CodeOctal/Interview-Bit
88c021685d6cdef17906d077411ce34723363a08
[ "MIT" ]
505
2016-09-02T15:04:20.000Z
2022-03-25T06:36:31.000Z
// https://www.interviewbit.com/problems/modular-expression/ long long int calMod(int A, int B, int C){ if(B == 0){ return 1; } else if(B%2 == 0){ long long int y = calMod(A, B/2, C); return (y*y)%C; } else{ return ((A%C)*calMod(A,B-1,C))%C; } } int Solution::Mod(int A, int B, int C) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details if(A == 0){ return 0; } if(calMod(A, B, C) < 0){ return C+(int)calMod(A, B, C); } return (int)calMod(A, B, C); }
24.25
93
0.552835
ssokjin
830b9919832d3b721808454193278df544785653
570
cpp
C++
input/array.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/array.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/array.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; main(){ string name[5] = {"apple", "google", "microsoft", "ibm", "tesla"}; string arr[5] = {"ab", "bc", "cd", "de", "ff"}; string arr2[] = {"apappappapapap", "hghghdgahdgahsdghag"}; int num = sizeof(name[4]); int num2 = sizeof(arr[0]); int num3 = sizeof(arr2); cout << "The size of this array is "<< num; // The output will be 24 bcz of 3 pointers. cout << "The size of array 2 is "<< num2; // Each of size 8 bit. Thats why 8*3 = 24. cout << "The size of array 3 is "<< num3; return 0; }
38
91
0.578947
xdevkartik
830c7aed466d2196cbf375ac5744dff58545af4e
2,429
cpp
C++
source/file_interface/bit_field.cpp
burz/tap
61f8f2cf2022db99e02992340735e342f4a8394d
[ "MIT" ]
1
2016-10-07T01:52:57.000Z
2016-10-07T01:52:57.000Z
source/file_interface/bit_field.cpp
burz/tap
61f8f2cf2022db99e02992340735e342f4a8394d
[ "MIT" ]
null
null
null
source/file_interface/bit_field.cpp
burz/tap
61f8f2cf2022db99e02992340735e342f4a8394d
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include "bit_field.h" typedef struct { unsigned short width; unsigned short height; size_t type_size; GLint internal_format; GLenum format; GLenum type; } BF_HEADER; void create_bit_field_file(const char *destination, unsigned short width, unsigned short height, size_t type_size, GLint internal_format, GLenum format, GLenum type, void *data) { BF_HEADER header; header.width = width; header.height = height; header.type_size = type_size; header.internal_format = internal_format; header.format = format; header.type = type; FILE *file = fopen(destination, "w+b"); if(file == NULL) { fprintf(stderr, "Could not open %s for writting.\n", destination); exit(1); } if( fwrite(&header, sizeof(BF_HEADER), 1, file) != 1) { fprintf(stderr, "Writting to %s failed.\n", destination); exit(1); } if(fwrite(data, width * height * type_size, 1, file) != 1) { fprintf(stderr, "Writting to %s failed.\n", destination); exit(1); } fclose( file ); } void read_bit_field_file(const char *source, unsigned short *width, unsigned short *height, size_t *type_size, GLint *internal_format, GLenum *format, GLenum *type, void **data) { FILE *file = fopen(source, "rb"); if(file == NULL) { fprintf(stderr, "Could not open %s for reading.\n", source); exit(1); } BF_HEADER header; if(fread(&header, sizeof(BF_HEADER), 1, file) != 1) { fprintf(stderr, "Could not read the header of %s\n", source); exit(1); } if(width != NULL) *width = header.width; if(height != NULL) *height = header.height; if(type_size != NULL) *type_size = header.type_size; if(internal_format != NULL) *internal_format = header.internal_format; if(format != NULL) *format = header.format; if(type != NULL) *type = header.type; if(data == NULL) return; unsigned long image_size = header.height * header.width * header.type_size; *data = malloc(image_size); if(*data == NULL) { fprintf(stderr, "Could not allocate enough space to load %s", source); exit(1); } if(fread(*data, image_size, 1, file) != 1) { fprintf(stderr, "Could not read image data from %s", source); free(*data); exit(1); } fclose(file); }
22.915094
89
0.616715
burz
83124097feb5012b57dc4f4fec5f0ab33adc840f
1,446
hpp
C++
code/aoce/Module/ModuleManager.hpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
71
2020-10-15T03:13:50.000Z
2022-03-30T02:04:28.000Z
code/aoce/Module/ModuleManager.hpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
9
2021-02-20T10:30:10.000Z
2022-03-04T07:59:58.000Z
code/aoce/Module/ModuleManager.hpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
19
2021-01-01T12:03:02.000Z
2022-03-21T07:59:59.000Z
#pragma once #include <map> #include <memory> #include <string> #include <vector> #include "IModule.hpp" namespace aoce { typedef IModule* (*loadModuleAction)(); typedef std::function<IModule*(void)> loadModuleHandle; class ModuleInfo { public: void* handle = nullptr; IModule* module = nullptr; std::string name = ""; loadModuleHandle onLoadEvent = nullptr; bool load = false; public: ModuleInfo(/* args */){}; ~ModuleInfo(){}; }; class ACOE_EXPORT ModuleManager { public: static ModuleManager& Get(); ~ModuleManager(); protected: ModuleManager(); private: static ModuleManager* instance; std::map<std::string, ModuleInfo*> modules; private: ModuleManager(const ModuleManager&) = delete; ModuleManager& operator=(const ModuleManager&) = delete; /* data */ public: void registerModule(const char* name, loadModuleHandle handle = nullptr); void loadModule(const char* name); void unloadModule(const char* name); void regAndLoad(const char* name); public: bool checkLoadModel(const char* name); }; template <class module> class StaticLinkModule { public: StaticLinkModule(const std::string& name) { auto& fun = std::bind(&StaticLinkModule<module>::InitModeule, this); ModuleManager::Get().registerModule(name, fun); } public: IModule* InitModeule() { return new module(); } }; } // namespace aoce
22.246154
77
0.670124
msqljj
9b01091ed19e91701e87e18fd4691b40ac1c724e
856
cpp
C++
pico_src/conversion.cpp
Bambofy/pico
a26d853cca9e28170efa6ca694a9233f08f9b655
[ "MIT" ]
5
2020-03-03T16:02:28.000Z
2020-03-17T12:43:55.000Z
pico_src/conversion.cpp
Bambofy/pico
a26d853cca9e28170efa6ca694a9233f08f9b655
[ "MIT" ]
null
null
null
pico_src/conversion.cpp
Bambofy/pico
a26d853cca9e28170efa6ca694a9233f08f9b655
[ "MIT" ]
1
2020-03-04T12:16:05.000Z
2020-03-04T12:16:05.000Z
#include "../pico_inc/conversion.h" void Conversion_Uint_To_Char_Array(uint32_t inNumber, char * outDestinationPtrLocation, uint32_t outDestinationByteLength) { uintptr_t destPtr = reinterpret_cast<uintptr_t>(outDestinationPtrLocation); _Conversion_Uint_To_Char_Array(inNumber, destPtr, outDestinationByteLength); } void Conversion_Int_To_Char_Array(int32_t inNumber, char * outDestinationPtrLocation, uint32_t outDestinationByteLength) { uintptr_t destPtr = reinterpret_cast<uintptr_t>(outDestinationPtrLocation); _Conversion_Int_To_Char_Array(inNumber, destPtr, outDestinationByteLength); } int32_t Conversion_String_To_Int32(char * inCharArray, uint32_t inCharArrayPtrLength) { uintptr_t inCharArrayPtr = reinterpret_cast<uintptr_t>(inCharArray); return _Conversion_String_To_Int32(inCharArrayPtr, inCharArrayPtrLength); }
37.217391
122
0.83528
Bambofy
9b05d31c458571d55d4d9b0ae720162f60569b39
609
cpp
C++
2017.4.12/poj3176.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.4.12/poj3176.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.4.12/poj3176.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<string> #include<vector> #include<stack> #include<set> #include<map> #include<queue> #include<algorithm> using namespace std; int dp[355][355]; int a[355][355]; int main(){ int n,i,j; while(~scanf("%d",&n)){ for(i=1;i<=n;i++){ for(j=1;j<=i;j++){ scanf("%d",&a[i][j]); } } for(i=1;i<=n;i++){ dp[n][i]=a[n][i]; } for(i=n-1;i>=1;i--){ for(j=1;j<=i;j++){ dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+a[i][j]; } } printf("%d\n",dp[1][1]); memset(dp,0,sizeof(dp)); } return 0; }
16.459459
50
0.543514
1980744819
9b0a3563dab2a04ccc0e60408e3dab89439e70d4
3,269
cpp
C++
test/core/image_processing/hough_circle_transform.cpp
harsh-4/gil
6da59cc3351e5657275d3a536e0b6e7a1b6ac738
[ "BSL-1.0" ]
153
2015-02-03T06:03:54.000Z
2022-03-20T15:06:34.000Z
test/core/image_processing/hough_circle_transform.cpp
harsh-4/gil
6da59cc3351e5657275d3a536e0b6e7a1b6ac738
[ "BSL-1.0" ]
429
2015-03-22T09:49:04.000Z
2022-03-28T08:32:08.000Z
test/core/image_processing/hough_circle_transform.cpp
harsh-4/gil
6da59cc3351e5657275d3a536e0b6e7a1b6ac738
[ "BSL-1.0" ]
215
2015-03-15T09:20:51.000Z
2022-03-30T12:40:07.000Z
// Boost.GIL (Generic Image Library) - tests // // Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com> // // Use, modification and distribution are 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/core/lightweight_test.hpp> #include <boost/gil/image.hpp> #include <boost/gil/image_processing/hough_transform.hpp> #include <boost/gil/image_view.hpp> #include <boost/gil/typedefs.hpp> #include <cstddef> #include <iostream> #include <limits> #include <vector> namespace gil = boost::gil; template <typename Rasterizer> void exact_fit_test(std::ptrdiff_t radius, gil::point_t offset, Rasterizer rasterizer) { std::vector<gil::point_t> circle_points(rasterizer.point_count(radius)); rasterizer(radius, offset, circle_points.begin()); // const std::ptrdiff_t diameter = radius * 2 - 1; const std::ptrdiff_t width = offset.x + radius + 1; const std::ptrdiff_t height = offset.y + radius + 1; gil::gray8_image_t image(width, height); auto input = gil::view(image); for (const auto& point : circle_points) { input(point) = std::numeric_limits<gil::uint8_t>::max(); } using param_t = gil::hough_parameter<std::ptrdiff_t>; const auto radius_parameter = param_t{radius, 0, 1}; // const auto x_parameter = param_t::from_step_count(offset.x, neighborhood, half_step_count); // const auto y_parameter = param_t::from_step_count(offset.y, neighborhood, half_step_count); const auto x_parameter = param_t{offset.x, 0, 1}; const auto y_parameter = param_t{offset.y, 0, 1}; std::vector<gil::gray16_image_t> output_images( radius_parameter.step_count, gil::gray16_image_t(x_parameter.step_count, y_parameter.step_count)); std::vector<gil::gray16_view_t> output_views(radius_parameter.step_count); std::transform(output_images.begin(), output_images.end(), output_views.begin(), [](gil::gray16_image_t& img) { return gil::view(img); }); gil::hough_circle_transform_brute(input, radius_parameter, x_parameter, y_parameter, output_views.begin(), rasterizer); if (output_views[0](0, 0) != rasterizer.point_count(radius)) { std::cout << "accumulated value: " << static_cast<int>(output_views[0](0, 0)) << " expected value: " << rasterizer.point_count(radius) << "\n\n"; } BOOST_TEST(output_views[0](0, 0) == rasterizer.point_count(radius)); } int main() { const int test_dim_length = 20; for (std::ptrdiff_t radius = 5; radius < test_dim_length; ++radius) { for (std::ptrdiff_t x_offset = radius; x_offset < radius + test_dim_length; ++x_offset) { for (std::ptrdiff_t y_offset = radius; y_offset < radius + test_dim_length; ++y_offset) { exact_fit_test(radius, {x_offset, y_offset}, gil::midpoint_circle_rasterizer{}); exact_fit_test(radius, {x_offset, y_offset}, gil::trigonometric_circle_rasterizer{}); } } } return boost::report_errors(); }
38.916667
99
0.657693
harsh-4
9b10a45f76002112ed294a14d916e6f2af835d83
2,704
cpp
C++
src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
null
null
null
src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
null
null
null
src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
1
2022-03-11T00:12:20.000Z
2022-03-11T00:12:20.000Z
#include <unistd.h> #include <iomanip> #include <torch/utils.h> #include "../utils/Ch_18_util.h" #include "../matplotlibcpp.h" namespace plt = matplotlibcpp; using torch::indexing::Slice; using torch::indexing::None; // Statistical bias torch::Tensor stat_bias(float true_theta, torch::Tensor est_theta) { return(torch::mean(est_theta) - true_theta); } // Mean squared error torch::Tensor mse(torch::Tensor data, float true_theta) { return(torch::mean(torch::square(data - true_theta))); } int main() { std::cout << "Current path is " << get_current_dir_name() << '\n'; // Device auto cuda_available = torch::cuda::is_available(); torch::Device device(cuda_available ? torch::kCUDA : torch::kCPU); std::cout << (cuda_available ? "CUDA available. Training on GPU." : "Training on CPU.") << '\n'; torch::manual_seed(8675309); auto torch_pi = torch::acos(torch::zeros(1)) * 2; // define pi in torch // Sample datapoints and create y coordinate float epsilon = 0.1; auto xs = torch::randn({300}); std::cout << xs.size(0) << '\n'; std::vector<float> ys; for(int i = 0; i < xs.size(0); i++) { auto yi = torch::sum(torch::exp(-1*torch::pow((xs.index({Slice(None, i)}) - xs[i]), 2) / (2 * epsilon*epsilon))) / torch::sqrt(2*torch_pi*epsilon*epsilon) / xs.size(0); ys.push_back(yi.data().item<float>()); } // Compute true density auto xd = torch::arange(torch::min(xs).data().item<float>(), torch::max(xs).data().item<float>(), 0.01); auto yd = torch::exp(-1*torch::pow(xd, 2)/2) / torch::sqrt(2 * torch_pi); std::vector<float> xx(xs.data_ptr<float>(), xs.data_ptr<float>() + xs.numel()); std::vector<float> xxd(xd.data_ptr<float>(), xd.data_ptr<float>() + xd.numel()); std::vector<float> yyd(yd.data_ptr<float>(), yd.data_ptr<float>() + yd.numel()); plt::figure_size(700, 500); plt::plot(xxd, yyd, "b-"); plt::scatter(xx, ys); plt::plot({0.0,0.0}, {0.0, 0.5}, {{"color", "purple"}, {"linestyle", "--"}, {"lw", "2"}}); plt::xlabel("x"); plt::ylabel("density"); plt::title("sample mean: " + std::to_string(xs.mean().data().item<float>())); plt::show(); plt::close(); float theta_true = 1.0; float sigma = 4.0; int sample_len = 10000; auto samples = torch::normal(theta_true, sigma, {sample_len, 1}); auto theta_est = torch::mean(samples); std::cout << "theta_est: " << theta_est << '\n'; std::cout << "mse(samples, theta_true): " << mse(samples, theta_true) << '\n'; // Next, we calculate Var(θ^n)+[bias(θ^n)]2 as below. auto bias = stat_bias(theta_true, theta_est); std::cout << "torch::square(samples.std(false)) + torch::square(bias): " << torch::square(samples.std(false)) + torch::square(bias) <<'\n'; std::cout << "Done!\n"; }
31.811765
114
0.637574
jiamny
9b11201d895aebd1c232215dd1a6d43437170e38
4,093
cpp
C++
src/gamelib/editor/ui/Overlay.cpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
1
2020-02-17T09:53:36.000Z
2020-02-17T09:53:36.000Z
src/gamelib/editor/ui/Overlay.cpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
null
null
null
src/gamelib/editor/ui/Overlay.cpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
null
null
null
#include "gamelib/editor/ui/Overlay.hpp" #include "gamelib/editor/tools/ToolUtils.hpp" #include "gamelib/editor/EditorShared.hpp" #include "gamelib/core/ecs/Entity.hpp" #include "gamelib/core/geometry/flags.hpp" #include "gamelib/core/input/InputSystem.hpp" #include "gamelib/core/Game.hpp" #include "gamelib/core/rendering/CameraSystem.hpp" #include "gamelib/core/rendering/RenderSystem.hpp" #include "gamelib/components/geometry/Polygon.hpp" #include "gamelib/components/update/QPhysics.hpp" #include "imgui.h" namespace gamelib { Overlay::Overlay() : renderSolid(true), renderNormals(true), renderVel(true), showCoords(false), debugOverlay(true), debugOverlayMovable(true), renderCams(true) { } void Overlay::drawDebugOverlay() { if (debugOverlay) { if (!debugOverlayMovable) ImGui::SetNextWindowPos(ImVec2(0, 16)); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); if (ImGui::Begin("Stats overlay", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize)) { auto game = getSubsystem<Game>(); auto frametime = game->getFrametime(); ImGui::Text("FPS: %i", (int)(frametime != 0 ? 1.0 / frametime : 0)); ImGui::Text("Frametime: %i ms", (int)(frametime * 1000)); ImGui::Text("Real frametime: %i ms", (int)(game->getRealFrametime() * 1000)); ImGui::Text("Render time: %f ms", game->getRenderTime() * 1000); ImGui::Text("Update time: %f ms", game->getUpdateTime() * 1000); auto numrendered = getSubsystem<CameraSystem>()->getNumRendered(); if (!numrendered) numrendered = RenderSystem::getActive()->getNumObjectsRendered(); ImGui::Text("Objects rendered: %lu", numrendered); } ImGui::End(); ImGui::PopStyleColor(); } } void Overlay::drawGui() { auto input = getSubsystem<InputSystem>(); if (!input->isMouseConsumed() && showCoords) { auto mouse = EditorShared::isSnapEnabled() ? EditorShared::getMouseSnapped() : EditorShared::getMouse(); ImGui::BeginTooltip(); ImGui::SetTooltip("%i, %i", (int)mouse.x, (int)mouse.y); ImGui::EndTooltip(); } } void Overlay::render(sf::RenderTarget& target) { if (renderCams) { auto camsys = getSubsystem<CameraSystem>(); sf::Color col = sf::Color::Green; for (size_t i = 0; i < camsys->size(); ++i) { auto cam = camsys->get(i); const math::AABBf baserect(math::Point2f(), cam->getSize()); drawRectOutline(target, baserect, col, cam->getMatrix()); // if (!math::almostEquals(cam->getZoom(), 1.f)) // { // auto nozoomTransform = cam->getTransformation(); // nozoomTransform.scale.fill(1); // drawRectOutline(target, baserect, col, nozoomTransform.getMatrix()); // } } } const auto ent = EditorShared::getSelected(); if (!ent) return; if (renderSolid) drawCollisions(target, *ent, collision_solid); if (renderVel) { auto phys = ent->findByName<QPhysics>(); if (phys && !phys->vel.isZero()) { auto start = ent->getTransform().getBBox().getCenter(); auto end = start + phys->vel; drawArrow(target, start.x, start.y, end.x, end.y, sf::Color::Cyan); } } if (renderNormals) ent->findAllByName<PolygonCollider>([&](CompRef<PolygonCollider> pol) { if (pol->flags & collision_solid) drawNormals(target, pol->getGlobal()); return false; }); } }
36.221239
120
0.548986
mall0c
9b1409601663e4eec9f87a44ace803d145b51bfe
1,079
cc
C++
cpp/Codeforces/401-450/447A_DZY_Loves_Hash.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/401-450/447A_DZY_Loves_Hash.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/401-450/447A_DZY_Loves_Hash.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> #include <unordered_map> #include <stdint.h> #include <cmath> using namespace std; typedef int64_t Int; typedef uint64_t UInt; int main(int argc, char **argv) { UInt p = 0; UInt n = 0; // Read the first line string line = ""; if (getline(cin, line)) { stringstream ss(line); ss >> p >> n; } unordered_map<Int, Int> intMap; UInt lineIdx = 0; UInt insertionCount = 0; // Read the next n line while (getline(cin, line)) { stringstream ss(line); UInt value = 0; ss >> value; UInt key = value % p; unordered_map<Int, Int>::iterator iter = intMap.find(key); if (iter != intMap.end()) { break; } else { intMap.insert(make_pair(key, value)); ++insertionCount; } ++lineIdx; if (lineIdx == n) break; } if (insertionCount == n) cout << -1; else cout << insertionCount + 1; return 0; }
17.983333
66
0.533828
phongvcao
9b19915623890a71c6440137e1819b08795a6ab4
1,018
cpp
C++
engine/strings/source/RangedCombatTextKeys.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/strings/source/RangedCombatTextKeys.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/strings/source/RangedCombatTextKeys.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "RangedCombatTextKeys.hpp" using namespace std; // Ranged combat messages RangedCombatTextKeys::RangedCombatTextKeys() { } RangedCombatTextKeys::~RangedCombatTextKeys() { } const string RangedCombatTextKeys::RANGED_COMBAT_UNAVAILABLE_ON_WORLD_MAP = "RANGED_COMBAT_UNAVAILABLE_ON_WORLD_MAP"; const string RangedCombatTextKeys::RANGED_COMBAT_WEAPON_NOT_EQUIPPED = "RANGED_COMBAT_WEAPON_NOT_EQUIPPED"; const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_NOT_EQUIPPED = "RANGED_COMBAT_AMMUNITION_NOT_EQUIPPED"; const string RangedCombatTextKeys::RANGED_COMBAT_WEAPON_AMMUNITION_MISMATCH = "RANGED_COMBAT_WEAPON_AMMUNITION_MISMATCH"; const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_REQUIRES_RANGED_WEAPON = "RANGED_COMBAT_AMMUNITION_REQUIRES_RANGED_WEAPON"; const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_CURSED = "RANGED_COMBAT_AMMUNITION_CURSED"; const string RangedCombatTextKeys::RANGED_COMBAT_OVERBURDENED = "RANGED_COMBAT_OVERBURDENED";
50.9
135
0.852652
sidav
9b1d4f31caa5ccafbba94af952d5598e43d485ab
1,603
hpp
C++
rayt-cpp/utils.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
11
2020-07-04T13:35:10.000Z
2022-03-30T17:34:27.000Z
rayt-cpp/utils.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
null
null
null
rayt-cpp/utils.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
2
2021-03-02T06:31:43.000Z
2022-03-30T17:34:28.000Z
#ifndef UTILS_HPP #define UTILS_HPP //============================================================================== // Originally written in 2016 by Peter Shirley <ptrshrl@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy (see file COPYING.txt) of the CC0 Public // Domain Dedication along with this software. If not, see // <http://creativecommons.org/publicdomain/zero/1.0/>. //============================================================================== #include <cmath> #include <cstdlib> #include <limits> #include <memory> #include <random> // Usings using std::make_shared; using std::shared_ptr; using std::sqrt; // Constants const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; // Utility Functions inline double degrees_to_radians(double degrees) { return degrees * pi / 180; } inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } inline double random_double(double min, double max) { return min + (max - min) * random_double(); } inline int random_int(int min, int max) { return static_cast<int>(random_double(min, max + 1)); } inline double clamp(double x, double min, double max) { if (x < min) { return min; } if (x > max) { return max; } return x; } #endif
27.169492
80
0.65315
gkmngrgn
9b1e120f3f985b6e526ca03ec3955e648466096f
5,202
hh
C++
kenlm/include/util/mmap.hh
pokey/w2ldecode
03f9995a48c5c1043be309fe5b20c6126851a9ff
[ "BSD-3-Clause" ]
114
2015-01-11T05:41:03.000Z
2021-08-31T03:47:12.000Z
Part 02/001_LM/ngram_lm_lab/kenlm/include/util/mmap.hh
Kabongosalomon/AMMI-NLP
00a0e47399926ad1951b84a11cd936598a9c7c3b
[ "MIT" ]
29
2015-01-09T01:00:09.000Z
2019-09-25T06:04:02.000Z
Part 02/001_LM/ngram_lm_lab/kenlm/include/util/mmap.hh
Kabongosalomon/AMMI-NLP
00a0e47399926ad1951b84a11cd936598a9c7c3b
[ "MIT" ]
50
2015-02-13T13:48:39.000Z
2019-08-07T09:45:11.000Z
#ifndef UTIL_MMAP_H #define UTIL_MMAP_H // Utilities for mmaped files. #include <cstddef> #include <limits> #include <stdint.h> #include <sys/types.h> namespace util { class scoped_fd; long SizePage(); // (void*)-1 is MAP_FAILED; this is done to avoid including the mmap header here. class scoped_mmap { public: scoped_mmap() : data_((void*)-1), size_(0) {} scoped_mmap(void *data, std::size_t size) : data_(data), size_(size) {} ~scoped_mmap(); void *get() const { return data_; } const uint8_t *begin() const { return reinterpret_cast<uint8_t*>(data_); } const uint8_t *end() const { return reinterpret_cast<uint8_t*>(data_) + size_; } std::size_t size() const { return size_; } void reset(void *data, std::size_t size) { scoped_mmap other(data_, size_); data_ = data; size_ = size; } void reset() { reset((void*)-1, 0); } private: void *data_; std::size_t size_; scoped_mmap(const scoped_mmap &); scoped_mmap &operator=(const scoped_mmap &); }; /* For when the memory might come from mmap, new char[], or malloc. Uses NULL * and 0 for blanks even though mmap signals errors with (void*)-1). The reset * function checks that blank for mmap. */ class scoped_memory { public: typedef enum {MMAP_ALLOCATED, ARRAY_ALLOCATED, MALLOC_ALLOCATED, NONE_ALLOCATED} Alloc; scoped_memory(void *data, std::size_t size, Alloc source) : data_(data), size_(size), source_(source) {} scoped_memory() : data_(NULL), size_(0), source_(NONE_ALLOCATED) {} ~scoped_memory() { reset(); } void *get() const { return data_; } const char *begin() const { return reinterpret_cast<char*>(data_); } const char *end() const { return reinterpret_cast<char*>(data_) + size_; } std::size_t size() const { return size_; } Alloc source() const { return source_; } void reset() { reset(NULL, 0, NONE_ALLOCATED); } void reset(void *data, std::size_t size, Alloc from); // realloc allows the current data to escape hence the need for this call // If realloc fails, destroys the original too and get() returns NULL. void call_realloc(std::size_t to); private: void *data_; std::size_t size_; Alloc source_; scoped_memory(const scoped_memory &); scoped_memory &operator=(const scoped_memory &); }; typedef enum { // mmap with no prepopulate LAZY, // On linux, pass MAP_POPULATE to mmap. POPULATE_OR_LAZY, // Populate on Linux. malloc and read on non-Linux. POPULATE_OR_READ, // malloc and read. READ, // malloc and read in parallel (recommended for Lustre) PARALLEL_READ, } LoadMethod; extern const int kFileFlags; // Wrapper around mmap to check it worked and hide some platform macros. void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset = 0); void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out); void MapAnonymous(std::size_t size, scoped_memory &to); // Open file name with mmap of size bytes, all of which are initially zero. void *MapZeroedWrite(int fd, std::size_t size); void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file); // msync wrapper void SyncOrThrow(void *start, size_t length); // Forward rolling memory map with no overlap. class Rolling { public: Rolling() {} explicit Rolling(void *data) { Init(data); } Rolling(const Rolling &copy_from, uint64_t increase = 0); Rolling &operator=(const Rolling &copy_from); // For an actual rolling mmap. explicit Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount); // For a static mapping void Init(void *data) { ptr_ = data; current_end_ = std::numeric_limits<uint64_t>::max(); current_begin_ = 0; // Mark as a pass-through. fd_ = -1; } void IncreaseBase(uint64_t by) { file_begin_ += by; ptr_ = static_cast<uint8_t*>(ptr_) + by; if (!IsPassthrough()) current_end_ = 0; } void DecreaseBase(uint64_t by) { file_begin_ -= by; ptr_ = static_cast<uint8_t*>(ptr_) - by; if (!IsPassthrough()) current_end_ = 0; } void *ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size); // Returns base pointer void *get() const { return ptr_; } // Returns base pointer. void *CheckedBase(uint64_t index) { if (index >= current_end_ || index < current_begin_) { Roll(index); } return ptr_; } // Returns indexed pointer. void *CheckedIndex(uint64_t index) { return static_cast<uint8_t*>(CheckedBase(index)) + index; } private: void Roll(uint64_t index); // True if this is just a thin wrapper on a pointer. bool IsPassthrough() const { return fd_ == -1; } void *ptr_; uint64_t current_begin_; uint64_t current_end_; scoped_memory mem_; int fd_; uint64_t file_begin_; uint64_t file_end_; bool for_write_; std::size_t block_; std::size_t read_bound_; }; } // namespace util #endif // UTIL_MMAP_H
26.953368
122
0.662438
pokey
9b1ef61068f354d7463caaa27ecf5b7deb9a80a4
501
hpp
C++
ffl/include/pipeline/FFL_PipelineNodeParser.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/include/pipeline/FFL_PipelineNodeParser.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/include/pipeline/FFL_PipelineNodeParser.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * FFL_PipelineNodeParser.hpp * Created by zhufeifei(34008081@qq.com) on 2018/02/11 * https://github.com/zhenfei2016/FFL-v2.git * * Pipelin系统中通过脚本创建node的parser * */ #ifndef _FFL_PIPELINENODE_PARSER_HPP_ #define _FFL_PIPELINENODE_PARSER_HPP_ namespace FFL{ class PipelineNodeParser { public: PipelineNodeParser(); virtual ~PipelineNodeParser(); }; } #endif
17.892857
57
0.740519
zhenfei2016
9b22c51c017eac7389037e7adac6f8198921ebaf
1,740
cc
C++
sync/api/attachments/attachment_store.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
sync/api/attachments/attachment_store.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sync/api/attachments/attachment_store.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// 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 "sync/api/attachments/attachment_store.h" #include "base/bind.h" #include "base/callback.h" #include "base/location.h" #include "base/sequenced_task_runner.h" #include "base/thread_task_runner_handle.h" #include "sync/internal_api/public/attachments/attachment_store_handle.h" #include "sync/internal_api/public/attachments/in_memory_attachment_store.h" #include "sync/internal_api/public/attachments/on_disk_attachment_store.h" namespace syncer { AttachmentStoreBase::AttachmentStoreBase() {} AttachmentStoreBase::~AttachmentStoreBase() {} AttachmentStore::AttachmentStore() {} AttachmentStore::~AttachmentStore() {} scoped_refptr<AttachmentStore> AttachmentStore::CreateInMemoryStore() { // Both frontend and backend of attachment store will live on current thread. scoped_ptr<AttachmentStoreBase> backend( new InMemoryAttachmentStore(base::ThreadTaskRunnerHandle::Get())); return scoped_refptr<AttachmentStore>(new AttachmentStoreHandle( backend.Pass(), base::ThreadTaskRunnerHandle::Get())); } scoped_refptr<AttachmentStore> AttachmentStore::CreateOnDiskStore( const base::FilePath& path, const scoped_refptr<base::SequencedTaskRunner>& backend_task_runner, const InitCallback& callback) { scoped_ptr<OnDiskAttachmentStore> backend( new OnDiskAttachmentStore(base::ThreadTaskRunnerHandle::Get(), path)); scoped_refptr<AttachmentStore> attachment_store = new AttachmentStoreHandle(backend.Pass(), backend_task_runner); attachment_store->Init(callback); return attachment_store; } } // namespace syncer
37.021277
79
0.791379
kjthegod
9b23977b50d0add8801a8561d2bb08694a34cd37
1,233
hpp
C++
include/manala/selector/framemanagermostrecent.hpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
1
2019-05-10T02:50:50.000Z
2019-05-10T02:50:50.000Z
include/manala/selector/framemanagermostrecent.hpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2020-10-28T03:44:51.000Z
2021-01-18T19:49:33.000Z
include/manala/selector/framemanagermostrecent.hpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2018-08-31T14:02:47.000Z
2020-04-17T16:01:54.000Z
//--------------------------------------------------------------------------- // Framemanager sequential implementation. The frame are sent one by one // in the receiving order. // // Matthieu Dreher // Argonne National Laboratory // 9700 S. Cass Ave. // Argonne, IL 60439 // mdreher@anl.gov // //-------------------------------------------------------------------------- #ifndef DECAF_FRAMEMANAGER_RECENT #define DECAF_FRAMEMANAGER_RECENT #include <manala/selector/framemanager.hpp> #include <list> namespace decaf { class FrameManagerRecent : public FrameManager { public: FrameManagerRecent(CommHandle comm, TaskType role, unsigned int prod_freq_output); virtual ~FrameManagerRecent(); virtual bool sendFrame(unsigned int id); virtual void putFrame(unsigned int id); virtual FrameCommand getNextFrame(unsigned int* frame_id); virtual bool hasNextFrameId(); virtual bool hasNextFrame(); virtual void computeNextFrame(); protected: std::list<unsigned int> buffer_; bool received_frame_id_; bool received_frame_; int frame_to_send_; int previous_frame_; unsigned prod_freq_output_; }; } #endif
26.804348
90
0.609895
tpeterka
9b23a487cc1e235334005a4fd35d270a66e79f66
328
cpp
C++
chapter10/Proj1013.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
chapter10/Proj1013.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
chapter10/Proj1013.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
#include"head.h" bool func(const string &s); int main(){ vector<string> words{"fox","jumps","over","quick","red","quick","blow","slow","the","turtle"}; auto iter = partition(words.begin(),words.end(),func); for(const auto &e:words) cout<<e<<" "; cout<<endl; return 0; } bool func(const string &s){ return s.size()>=5; }
23.428571
95
0.631098
basstal
9b25946d853b291db8676fcd613c862454f7ef3e
1,719
cpp
C++
firmware/Heat controller/lib/NTC/src/NTC.cpp
atoomnetmarc/IoT12
7706f69758a800da70bf8034a91a331206706824
[ "Apache-2.0" ]
null
null
null
firmware/Heat controller/lib/NTC/src/NTC.cpp
atoomnetmarc/IoT12
7706f69758a800da70bf8034a91a331206706824
[ "Apache-2.0" ]
null
null
null
firmware/Heat controller/lib/NTC/src/NTC.cpp
atoomnetmarc/IoT12
7706f69758a800da70bf8034a91a331206706824
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021-2022 Marc Ketel SPDX-License-Identifier: Apache-2.0 */ #include <math.h> #include "NTC.h" /* Class which is able to calculate the temperature of a NTC given the voltage of a resistor divider. Simple schematic: resistorDividerVoltage---[resistorDividerResistance]---[NTC]---GND */ NTC::NTC(void) { } /** @param resistorDividerVoltage Voltage of the resistor divider. @param resistorDividerResistance The fixed resistance of the resistor divider. @param thermistorResistance Resistance of the NTC at thermistorTemperature. @param thermistorTemperature Temperature in Kelvin of the NTC at thermistorResistance. @param thermistorBValue β-value of the NTC in Kelvin. */ void NTC::SetParameters( float resistorDividerVoltage, float resistorDividerResistance, float thermistorResistance, float thermistorTemperature, float thermistorBValue) { this->resistorDividerVoltage = resistorDividerVoltage; this->resistorDividerResistance = resistorDividerResistance; this->thermistorResistance = thermistorResistance; this->thermistorTemperature = thermistorTemperature; this->thermistorBValue = thermistorBValue; } /** @return Temperature in Kelvin */ float NTC::GetTemperature(float voltage) { //Current though NTC. float I = (this->resistorDividerVoltage - voltage) / this->resistorDividerResistance; //NTC resistance. float Rntc = (voltage / I); //Apply Steinhart–Hart equation: https://en.wikipedia.org/wiki/Thermistor#B_or_%CE%B2_parameter_equation float temperature = (1 / ((log(Rntc / this->resistorDividerResistance) / this->thermistorBValue) + (1 / this->thermistorTemperature))); return temperature; }
28.180328
139
0.753345
atoomnetmarc
9b2a0aeeed97f88621425a9a0b549c20a5d110d2
1,065
hpp
C++
src/elona/serialization/std/bitset.hpp
nanbansenji/ElonaFoobar
ddbd6639db8698e89f09b2512526e855d8016e46
[ "MIT" ]
84
2018-03-03T02:44:32.000Z
2019-07-14T16:16:24.000Z
src/elona/serialization/std/bitset.hpp
AFB111/elonafoobar
da7a3c86dd45e68e6e490fb260ead1d67c9fff5e
[ "MIT" ]
685
2018-02-27T04:31:17.000Z
2019-07-12T13:43:00.000Z
src/elona/serialization/std/bitset.hpp
nanbansenji/ElonaFoobar
ddbd6639db8698e89f09b2512526e855d8016e46
[ "MIT" ]
23
2019-07-26T08:52:38.000Z
2021-11-09T09:21:58.000Z
#pragma once #include <bitset> #include "../concepts.hpp" namespace elona::serialization { template <size_t N, typename Archive> void serialize(std::bitset<N>& value, Archive& ar) { if constexpr (concepts::is_iarchive_v<Archive>) { if constexpr (N <= 32) { uint32_t tmp; ar.scalar(tmp); value = tmp; } else if constexpr (N <= 64) { uint64_t tmp; ar.scalar(tmp); value = tmp; } else { std::string tmp; ar.str(tmp); value = std::bitset<N>(tmp); } } else { if constexpr (N <= 32) { uint32_t tmp = value.to_ulong(); ar.scalar(tmp); } else if constexpr (N <= 64) { uint64_t tmp = value.to_ulong(); ar.scalar(tmp); } else { std::string tmp = value.to_string(); ar.str(tmp); } } } } // namespace elona::serialization
18.684211
51
0.449765
nanbansenji
9b2b78b9110a940be1ce88a548c6fadf5e412df8
6,835
cpp
C++
modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 The Android 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 "HidReport.h" #include "HidDefs.h" #include <cmath> #include <sstream> #include <iomanip> namespace HidUtil { HidReport::HidReport(uint32_t type, uint32_t data, const HidGlobal &global, const HidLocal &local) : mReportType(type), mFlag(data), mUsagePage(global.usagePage.get(0)), // default value 0 mUsage(local.getUsage(0)), mUsageVector(local.usage), mLogicalMin(global.logicalMin.get(0)), // default value 0 mLogicalMax(global.logicalMax.get(0)), mReportSize(global.reportSize), mReportCount(global.reportCount), mPhysicalMin(global.physicalMin), mPhysicalMax(global.physicalMax), mExponent(global.exponent), mUnit(global.unit), mReportId(global.reportId) { } std::string HidReport::getStringType() const { return reportTypeToString(mReportType); } std::string HidReport::reportTypeToString(int type) { using namespace HidDef::MainTag; switch(type) { case INPUT: return "INPUT"; case OUTPUT: return "OUTPUT"; case FEATURE: return "FEATURE"; default: return "<<UNKNOWN>>"; } } double HidReport::getExponentValue() const { if (!mExponent.isSet()) { return 1; } // default exponent is 0 int exponentInt = mExponent.get(0); if (exponentInt > 15 || exponentInt < 0) { return NAN; } return pow(10.0, static_cast<double>((exponentInt <= 7) ? exponentInt : exponentInt - 16)); } std::string HidReport::getExponentString() const { int exponentInt = mExponent.get(0); if (exponentInt > 15 || exponentInt < 0) { return "[error]"; } return std::string("x10^") + std::to_string((exponentInt <= 7) ? exponentInt : exponentInt - 16); } std::string HidReport::getUnitString() const { if (!mUnit.isSet()) { return "default"; } return "[not implemented]"; std::ostringstream ret; ret << std::hex << std::setfill('0') << std::setw(2) << mUnit.get(0); return ret.str(); } std::string HidReport::getFlagString() const { using namespace HidDef::ReportFlag; std::string ret; ret += (mFlag & DATA_CONST) ? "Const " : "Data "; ret += (mFlag & ARRAY_VARIABLE) ? "Variable " : "Array "; ret += (mFlag & WRAP) ? "Wrap " : ""; ret += (mFlag & NONLINEAR) ? "Nonlinear " : ""; ret += (mFlag & NO_PREFERRED) ? "NoPreferred " : ""; ret += (mFlag & NULL_STATE) ? "NullState " : ""; ret += (mFlag & VOLATILE) ? "Volatile " : ""; ret += (mFlag & BUFFERED_BYTES) ? "BufferedBytes " : ""; return ret; } // isArray() will return true for reports that may contains multiple values, e.g. keyboard scan // code, which can have multiple value, each denoting a key pressed down at the same time. It will // return false if repor represent a vector or matrix. // // This slightly deviates from HID's definition, it is more convenient this way as matrix/vector // input is treated similarly as variables. bool HidReport::isArray() const { using namespace HidDef::ReportFlag; return (mFlag & ARRAY_VARIABLE) == 0 && mIsCollapsed; } bool HidReport::isVariable() const { return !isArray(); } bool HidReport::isData() const { using namespace HidDef::ReportFlag; return (mFlag & DATA_CONST) == 0; } std::ostream& operator<<(std::ostream& os, const HidReport& h) { os << h.getStringType() << ", " << "usage: " << std::hex << h.getFullUsage() << std::dec << ", "; if (h.isData()) { auto range = h.getLogicalRange(); os << "logMin: " << range.first << ", " << "logMax: " << range.second << ", "; if (range == h.getPhysicalRange()) { os << "phy===log, "; } else { range = h.getPhysicalRange(); os << "phyMin: " << range.first << ", " << "phyMax: " << range.second << ", "; } if (h.isArray()) { os << "map: (" << std::hex; for (auto i : h.getUsageVector()) { os << i << ","; } os << "), " << std::dec; } os << "exponent: " << h.getExponentString() << ", " << "unit: " << h.getUnitString() << ", "; } else { os << "constant: "; } os << "size: " << h.getSize() << "bit x " << h.getCount() << ", " << "id: " << h.mReportId; return os; } std::pair<int64_t, int64_t> HidReport::getLogicalRange() const { int64_t a = mLogicalMin; int64_t b = mLogicalMax; if (a > b) { // might be unsigned a = a & ((static_cast<int64_t>(1) << getSize()) - 1); b = b & ((static_cast<int64_t>(1) << getSize()) - 1); if (a > b) { // bad hid descriptor return {0, 0}; } } return {a, b}; } std::pair<int64_t, int64_t> HidReport::getPhysicalRange() const { if (!(mPhysicalMin.isSet() && mPhysicalMax.isSet())) { // physical range undefined, use logical range return getLogicalRange(); } int64_t a = mPhysicalMin.get(0); int64_t b = mPhysicalMax.get(0); if (a > b) { a = a & ((static_cast<int64_t>(1) << getSize()) - 1); b = b & ((static_cast<int64_t>(1) << getSize()) - 1); if (a > b) { return {0, 0}; } } return {a, b}; } unsigned int HidReport::getFullUsage() const { return mUsage | (mUsagePage << 16); } size_t HidReport::getSize() const { return mReportSize; } size_t HidReport::getCount() const { return mReportCount; } unsigned int HidReport::getUnit() const { return mUnit.get(0); // default unit is 0 means default unit } unsigned HidReport::getReportId() const { // if report id is not specified, it defaults to zero return mReportId.get(0); } unsigned HidReport::getType() const { return mReportType; } void HidReport::setCollapsed(uint32_t fullUsage) { mUsage = fullUsage & 0xFFFF; mUsagePage = fullUsage >> 16; mIsCollapsed = true; } const std::vector<unsigned int>& HidReport::getUsageVector() const { return mUsageVector; } } // namespace HidUtil
29.717391
98
0.58654
lighthouse-os
9b2d7bdf8175e9af1324c8529f05ebc9298df440
4,713
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_DefineLazyClass.cpp // #include "smtc_DefineLazyClass.h" #include "smtc_ClassDefn.h" #include "smtc_ClassScope.h" #include "smtc_CreateLazyClass.h" #include "smtc_CreateLazyClassEntity.h" #include "smtc_CreateLazyClassScope.h" #include "smtc_CreateMbrInit.h" #include "smtc_CreateQualName.h" #include "smtc_CreateTmplLazyClass.h" #include "smtc_CreateTmplLazyClassEntity.h" #include "smtc_DeclareLazyClassObjParamSet.h" #include "smtc_FormTmplName.h" #include "smtc_GetNameLoc.h" #include "smtc_IsNameQual.h" #include "smtc_LazyBaseSpec.h" #include "smtc_LazyClass.h" #include "smtc_Message.h" #include "smtc_Ns.h" #include "smtc_NsScope.h" #include "smtc_ScopeVisitor.h" #include "smtc_TmplSpecScope.h" #include "smtc_TmplSpecToArgString.h" #define LZZ_INLINE inline namespace { using namespace smtc; } namespace { struct DefineLazyClass : ScopeVisitor { bool is_tmpl; TmplSpecPtrVector & tmpl_spec_set; gram::SpecSel const & spec_sel; ClassKey key; NamePtr const & name; bool is_dll_api; ParamPtrVector const & param_set; bool vararg; BaseSpecPtrVector const & base_spec_set; ScopePtr & res_scope; void visit (NsScope const & scope) const; void visit (ClassScope const & scope) const; void visit (TmplSpecScope const & scope) const; EntityPtr buildEntity (NamePtr const & encl_qual_name = NamePtr ()) const; public: explicit DefineLazyClass (bool is_tmpl, TmplSpecPtrVector & tmpl_spec_set, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set, ScopePtr & res_scope); ~ DefineLazyClass (); }; } namespace smtc { ScopePtr defineLazyClass (ScopePtr const & scope, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set) { ScopePtr res_scope; TmplSpecPtrVector tmpl_spec_set; scope->accept (DefineLazyClass (false, tmpl_spec_set, spec_sel, key, name, is_dll_api, param_set, vararg, base_spec_set, res_scope)); return res_scope; } } namespace { void DefineLazyClass::visit (NsScope const & scope) const { // build ns lazy class scope.getNs ()->addEntity (buildEntity ()); } } namespace { void DefineLazyClass::visit (ClassScope const & scope) const { // cannot be qualified if (isNameQual (name)) { msg::qualClassClassDefn (getNameLoc (name)); } // build mbr lazy class ClassDefnPtr const & class_defn = scope.getClassDefn (); class_defn->addEntity (buildEntity (class_defn->getQualName ())); } } namespace { void DefineLazyClass::visit (TmplSpecScope const & scope) const { // declare template class tmpl_spec_set.push_back (scope.getTmplSpec ()); scope.getParent ()->accept (DefineLazyClass (true, tmpl_spec_set, spec_sel, key, name, is_dll_api, param_set, vararg, base_spec_set, res_scope)); } } namespace { EntityPtr DefineLazyClass::buildEntity (NamePtr const & encl_qual_name) const { int flags = spec_sel.getFlags (); LazyClassPtr lazy_class = createLazyClass (flags, key, name, is_dll_api, param_set, vararg, base_spec_set); declareLazyClassObjParamSet (lazy_class, param_set, base_spec_set); // get qual name and entity NamePtr qual_name; EntityPtr entity; if (is_tmpl) { qual_name = formTmplName (name, tmplSpecToArgString (tmpl_spec_set.front ())); TmplLazyClassPtr tmpl_lazy_class = createTmplLazyClass (tmpl_spec_set, lazy_class); entity = createTmplLazyClassEntity (tmpl_lazy_class); } else { qual_name = name; entity = createLazyClassEntity (lazy_class); } if (encl_qual_name.isSet ()) { qual_name = createQualName (encl_qual_name, qual_name); } lazy_class->setQualName (qual_name); res_scope = createLazyClassScope (lazy_class); return entity; } } namespace { LZZ_INLINE DefineLazyClass::DefineLazyClass (bool is_tmpl, TmplSpecPtrVector & tmpl_spec_set, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set, ScopePtr & res_scope) : is_tmpl (is_tmpl), tmpl_spec_set (tmpl_spec_set), spec_sel (spec_sel), key (key), name (name), is_dll_api (is_dll_api), param_set (param_set), vararg (vararg), base_spec_set (base_spec_set), res_scope (res_scope) {} } namespace { DefineLazyClass::~ DefineLazyClass () {} } #undef LZZ_INLINE
34.152174
290
0.717165
SuperDizor
9b2fc253f49469923daac323b0bb90353b68c7fb
1,847
cpp
C++
uva/821 - Page Hopping floyed warshall .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
uva/821 - Page Hopping floyed warshall .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
uva/821 - Page Hopping floyed warshall .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; typedef long long ll; #define MX 60 int dist[105] [105]; int main() { int x, y; int n=100; int tc=1; int mp[105] = {0}; while(scanf("%d %d", &x, &y)==2) { if(x==0) break; for(int i=1; i<=n; i++) { for( int j=1; j<=n; j++) if(i!= j) dist[i][j] = (1<<10); } n=2; memset(mp, 0, sizeof mp); mp[x]=1; x=1; mp[y]=2; y=2; dist[x][y]=1; while(x!=0) { scanf("%d %d", &x, &y); if(x==0) break; if(!mp[x]) mp[x] = ++n; x = mp[x]; if(!mp[y]) mp[y] = ++n; y = mp[y]; dist[x][y]=1; //n = max(n, max(x, y)); } for(int k=1; k<=n; k++) { for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(dist[i][k]+dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k]+dist[k][j]; } } } double ans=0; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(dist[i][j] != (1<<10) ) { ans+= dist[i][j]; } //printf("i %d j %d dist %d\n", i, j, dist[i][j]); } } // cout<<ans/(n*(n-1))<<endl; // printf("nnn %d\n", n); // printf("ans %lf n %d\n", ans, n); printf("Case %d: average length between pages = %0.3lf clicks\n",tc++, ans/ (double)(n *(n-1))); } return 0; }
22.802469
105
0.30157
priojeetpriyom
9b36bf4ac6c6a7f412d25e45df5084a4df3baa41
530
cc
C++
pathtracer/src/scene_elements/serialized/lights/SpotLight.cc
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
pathtracer/src/scene_elements/serialized/lights/SpotLight.cc
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
pathtracer/src/scene_elements/serialized/lights/SpotLight.cc
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
#include "SpotLight.hh" float SpotLight::getAngle() const { return angle_; } void SpotLight::setAngle(float angle) { SpotLight::angle_ = angle; } const Vector3D<float> &SpotLight::getDirection() const { return direction_; } void SpotLight::setDirection(const Vector3D<float> &direction) { SpotLight::direction_ = direction; } const Vector3D<float> &SpotLight::getPosition() const { return position_; } void SpotLight::setPosition(const Vector3D<float> &position) { SpotLight::position_ = position; }
20.384615
64
0.720755
bjorn-grape
9b375c34a28ab4aee9774fa54acb33fb2ebd7fa8
8,869
cpp
C++
code/utils/encoding.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
307
2015-04-10T13:27:32.000Z
2022-03-21T03:30:38.000Z
code/utils/encoding.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
2,231
2015-04-27T10:47:35.000Z
2022-03-31T19:22:37.000Z
code/utils/encoding.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
282
2015-01-05T12:16:57.000Z
2022-03-28T04:45:11.000Z
// // #include "utils/encoding.h" #include "mod_table/mod_table.h" namespace util { Encoding guess_encoding(const SCP_string& content, bool assume_utf8) { if (content.size()>= 3 && !strncmp(content.c_str(), "\xEF\xBB\xBF", 3)) { // UTF-8 return Encoding::UTF8; } if (content.size()>= 4 && !strncmp(content.c_str(), "\x00\x00\xFE\xFF", 4)) { // UTF-32 big-endian return Encoding::UTF32BE; } if (content.size()>= 4 && !strncmp(content.c_str(), "\xFF\xFE\x00\x00", 4)) { // UTF-32 little-endian return Encoding::UTF32LE; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFE\xFF", 2)) { // UTF-16 big-endian return Encoding::UTF16BE; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFF\xFE", 2)) { // UTF-16 little-endian return Encoding::UTF16LE; } return assume_utf8 ? Encoding::UTF8 : Encoding::ASCII; } bool has_bom(const SCP_string& content) { if (content.size()>= 3 && !strncmp(content.c_str(), "\xEF\xBB\xBF", 3)) { // UTF-8 return true; } if (content.size()>= 4 && !strncmp(content.c_str(), "\x00\x00\xFE\xFF", 4)) { // UTF-32 big-endian return true; } if (content.size()>= 4 && !strncmp(content.c_str(), "\xFF\xFE\x00\x00", 4)) { // UTF-32 little-endian return true; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFE\xFF", 2)) { // UTF-16 big-endian return true; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFF\xFE", 2)) { // UTF-16 little-endian return true; } return false; } int check_encoding_and_skip_bom(CFILE* file, const char* filename, int* start_offset) { cfseek(file, 0, CF_SEEK_SET); // Read up to 10 bytes from the file to check if there is a BOM SCP_string probe; auto probe_size = (size_t)std::min(10, cfilelength(file)); probe.resize(probe_size); cfread(&probe[0], 1, (int) probe_size, file); cfseek(file, 0, CF_SEEK_SET); auto filelength = cfilelength(file); if (start_offset) { *start_offset = 0; } // Determine encoding. Assume UTF-8 if we are in unicode text mode auto encoding = util::guess_encoding(probe, Unicode_text_mode); if (Unicode_text_mode) { if (encoding != util::Encoding::UTF8) { //This is probably fatal, so let's abort right here and now. Error(LOCATION, "%s is in an Unicode/UTF format that cannot be read by FreeSpace Open. Please convert it to UTF-8\n", filename); } if (util::has_bom(probe)) { // The encoding has to be UTF-8 here so we know that the BOM is 3 Bytes long // This makes sure that the first byte we read will be the first actual text byte. cfseek(file, 3, SEEK_SET); filelength -= 3; if (start_offset) { *start_offset = 3; } } } else { if (encoding != util::Encoding::ASCII) { //This is probably fatal, so let's abort right here and now. Error(LOCATION, "%s is in Unicode/UTF format and cannot be read by FreeSpace Open without turning on Unicode mode. Please convert it to ASCII/ANSI\n", filename); } } return filelength; } // The following code is adapted from the uchardet library, the original licence of the file has been kept /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <cstdio> #define UDF 0 // undefined #define OTH 1 //other #define ASC 2 // ascii capital letter #define ASS 3 // ascii small letter #define ACV 4 // accent capital vowel #define ACO 5 // accent capital other #define ASV 6 // accent small vowel #define ASO 7 // accent small other #define CLASS_NUM 8 // total classes #define FREQ_CAT_NUM 4 static const unsigned char Latin1_CharToClass[] = { OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 00 - 07 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 08 - 0F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 10 - 17 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 18 - 1F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 20 - 27 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 28 - 2F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 30 - 37 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 38 - 3F OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 40 - 47 ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 48 - 4F ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 50 - 57 ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, // 58 - 5F OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 60 - 67 ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 68 - 6F ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 70 - 77 ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, // 78 - 7F OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, // 80 - 87 OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, // 88 - 8F UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 90 - 97 OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, // 98 - 9F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A0 - A7 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A8 - AF OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B0 - B7 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B8 - BF ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, // C0 - C7 ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, // C8 - CF ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, // D0 - D7 ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, // D8 - DF ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, // E0 - E7 ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, // E8 - EF ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, // F0 - F7 ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, // F8 - FF }; /* 0 : illegal 1 : very unlikely 2 : normal 3 : very likely */ static const unsigned char Latin1ClassModel[] = { /* UDF OTH ASC ASS ACV ACO ASV ASO */ /*UDF*/ 0, 0, 0, 0, 0, 0, 0, 0, /*OTH*/ 0, 3, 3, 3, 3, 3, 3, 3, /*ASC*/ 0, 3, 3, 3, 3, 3, 3, 3, /*ASS*/ 0, 3, 3, 3, 1, 1, 3, 3, /*ACV*/ 0, 3, 3, 3, 1, 2, 1, 2, /*ACO*/ 0, 3, 3, 3, 3, 3, 3, 3, /*ASV*/ 0, 3, 1, 3, 1, 1, 1, 3, /*ASO*/ 0, 3, 1, 3, 1, 1, 3, 3, }; bool guessLatin1Encoding(const char* aBuf, size_t aLen) { char mLastCharClass = OTH; uint32_t mFreqCounter[FREQ_CAT_NUM]; for (int i = 0; i < FREQ_CAT_NUM; i++) { mFreqCounter[i] = 0; } unsigned char charClass; unsigned char freq; for (size_t i = 0; i < aLen; i++) { charClass = Latin1_CharToClass[(unsigned char) aBuf[i]]; freq = Latin1ClassModel[mLastCharClass * CLASS_NUM + charClass]; if (freq == 0) { return false; } mFreqCounter[freq]++; mLastCharClass = charClass; } float confidence; uint32_t total = 0; for (int32_t i = 0; i < FREQ_CAT_NUM; i++) { total += mFreqCounter[i]; } if (!total) { confidence = 0.0f; } else { confidence = mFreqCounter[3] * 1.0f / total; confidence -= mFreqCounter[1] * 20.0f / total; } if (confidence < 0.0f) { confidence = 0.0f; } return confidence > .5f; } }
35.906883
140
0.597023
trgswe
9b37b184d2817217fb506c030d0f645051b8f56f
4,446
cpp
C++
ByteCamp/Day1/l.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
ByteCamp/Day1/l.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
ByteCamp/Day1/l.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <ctime> #include <vector> using namespace std; #define F first #define S second #define MP make_pair typedef long long ll; typedef long double ld; typedef pair <ld, ld> Point; const ld eps = 1e-7; const ld ERROR = 666666; const Point ERRORP = MP(ERROR, ERROR); bool if_same (ld a, ld b) { return -eps <= (a - b) && (a - b) <= eps; } bool if_same (Point a, Point b) { return if_same(a.F, b.F) && if_same(a.S, b.S); } struct Line { ld a, b, c; Line() {} Line(ld A, ld B, ld C) {a = A, b = B, c = C;} Point on_Line (ld x) { return MP(x, -(c + a * x) / b); } Point on_Line_y (ld y) { return MP(-(c + b * y) / a, y); } bool if_on (Point x) { return if_same (0, a * x.F + b * x.S + c); } }l[22]; Point cross_point (Line A, Line B) { // cerr << "calc cp: " << A.a << " " << A.b << " " << A.c << " , " << B.a << " " << B.b << " " << B.c << endl; if (if_same(0, A.a * B.b - B.a * A.b)) return ERRORP; return A.on_Line ((B.c * A.b - A.c * B.b) / (A.a * B.b - B.a * A.b)); } struct Curve { ld a, b, c; //ax^2+bx+c; Curve () {} Curve (ld aa, ld bb, ld cc) {a = aa, b = bb, c = cc;} ld delta() { ld ans = b*b-4*a*c; if (if_same(ans, 0)) return 0; return ans; } Point find_zero () { if (delta() < 0 - eps) return ERRORP; return MP((-b-sqrt(delta()))/(2*a), (-b+sqrt(delta()))/(2*a)); } }; struct Hypo { ld q0, q1, q2, q3, q4, q5; Point subs(bool tp, ld a, ld b) { if (tp == 0) { // x Curve c = Curve(q0 * a * a + q1 * a + q2, q0 * 2 * a * b + q1 * b + q3 * a + q4, q0 * b * b + q3 * b + q5); return c.find_zero(); } else { Curve c = Curve(q2 * a * a + q1 * a + q0, q2 * 2 * a * b + q1 * b + q4 * a + q3, q2 * b * b + q4 * b + q5); return c.find_zero(); } } ld delta () {return q1*q1-q0*q2;} bool if_on (Point p) { return if_same (0, q0 * p.F * p.F + q1 * p.F * p.S + q2 * p.S * p.S + q3 * p.F + q4 * p.S + q5); } }h; vector <Point> cps; int n; int e_num[22]; bool fake[22]; int main() { ios::sync_with_stdio(false); //freopen("1.in", "r", stdin); //freopen("1.out", "w", stdout); cin >> n; cin >> h.q0 >> h.q1 >> h.q2 >> h.q3 >> h.q4 >> h.q5; for (int i = 1; i <= n; i ++) { cin >> l[i].a >> l[i].b >> l[i].c; for (int j = 1; j < i; j ++) { if (if_same(0, l[i].a)) { if (if_same(0, l[j].a)) continue ; if (if_same(l[i].c / l[i].b, l[j].c / l[j].b)) { fake[i] = true; break; } } else { if (if_same(0, l[j].a)) continue ; ld X1 = l[i].c / l[i].a; ld Y1 = l[i].b / l[i].a; ld X2 = l[j].c / l[j].a; ld Y2 = l[j].b / l[j].a; if (if_same(X1, X2) && if_same (Y1, Y2)) { fake[i] = true; break; } } } // cerr << i << " : " << fake[i] << endl; } for (int i = 1; i <= n; i ++) for (int j = i + 1; j <= n; j ++) { if (fake[i] || fake[j]) continue ; Point cp = cross_point(l[i], l[j]); if (cp != ERRORP) { // cerr << "LL cp : " << cp.F << " " << cp.S << endl; cps.push_back(cp); } } for (int i = 1; i <= n; i ++) { if (fake[i]) continue ; if (h.delta() > 0 + eps) { if () } if (if_same(0, l[i].a)) { Point cp = h.subs(1, 0, -l[i].c / l[i].b); if (cp != ERRORP) { cps.push_back(l[i].on_Line(cp.F)); cps.push_back(l[i].on_Line(cp.S)); } } else { Point cp = h.subs(0, -l[i].b / l[i].a, -l[i].c / l[i].a); if (cp != ERRORP) { // cerr << "LH cp: " << cp.F << " " << cp.S << endl; cps.push_back(l[i].on_Line_y(cp.F)); cps.push_back(l[i].on_Line_y(cp.S)); } } } int p_num = 0; sort (cps.begin(), cps.end()); for (int i = 0; i < cps.size(); i ++) { if (i && if_same (cps[i], cps[i - 1])) continue ; // cerr << "a cp: " << cps[i].F << " " << cps[i].S << endl; p_num ++; for (int j = 1; j <= n; j ++) if (l[j].if_on(cps[i])) e_num[j] ++; if (h.if_on(cps[i])) e_num[0] ++; } // for (int i = 0; i <= n; i ++) // cerr << i << " : " << e_num[i] << endl; //v-e+f=1 int fans = 1; for (int i = 1; i <= n; i ++) { if (fake[i]) continue ; fans += e_num[i] + 1; } fans -= p_num; if (if_same (0, h.delta())) { // cerr << "should be here " << endl; fans += e_num[0] + 1; } else if (h.delta() < 0) { if (e_num[0] == 0) fans ++; else fans += e_num[0]; } else if (h.delta() > 0) { fans += e_num[0] + 2; } cout << fans << endl; return 0; }
22.683673
111
0.468961
JackBai0914
9b3addf69baf6396826baea1132848c4bea1126f
353
cpp
C++
Artemis/Source/Graphics/Artemis.Graphics.cpp
NoriyukiHiromoto/TinyGameEngine
ea683db3d498c1b8df91930a262a4c50a4e69b82
[ "MIT" ]
null
null
null
Artemis/Source/Graphics/Artemis.Graphics.cpp
NoriyukiHiromoto/TinyGameEngine
ea683db3d498c1b8df91930a262a4c50a4e69b82
[ "MIT" ]
null
null
null
Artemis/Source/Graphics/Artemis.Graphics.cpp
NoriyukiHiromoto/TinyGameEngine
ea683db3d498c1b8df91930a262a4c50a4e69b82
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- #include "Artemis.Local.hpp" #include "Artemis.Graphics.hpp" #if defined(ATS_API_DIRECTX11) #include "Platform/Artemis.Graphics.directx11.cpp" #endif//defined(ATS_API_DIRECTX11)
35.3
85
0.407932
NoriyukiHiromoto
9b3cc3cd55dd4d87adcbf4cab59dd62587a51248
3,360
cpp
C++
GraphAlgorithms/Monsters.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
2
2021-02-05T04:21:42.000Z
2021-02-10T14:24:38.000Z
GraphAlgorithms/Monsters.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
GraphAlgorithms/Monsters.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector<vector<char>>v(n,vector<char>(m)); vector<vector<int>>poss(n,vector<int>(m,-1)); queue<pair<int,int>>q; int xi,yi; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>v[i][j]; if(v[i][j]=='M') { q.push({i,j}); poss[i][j]=0; } if(v[i][j]=='A') { xi=i,yi=j; } } } vector<vector<int>>visited(n,vector<int>(m)); vector<pair<int,int>>pos={{1,0},{0,1},{-1,0},{0,-1}}; vector<char>pat={'D','R','U','L'}; while(!q.empty()) { pair<int,int>d=q.front(); q.pop(); for(int i=0;i<4;i++) { int x=pos[i].first+d.first; int y=pos[i].second+d.second; if(x>=0&&x<n&&y>=0&&y<m&&!visited[x][y]&&v[x][y]=='.') { visited[x][y]=1; q.push({x,y}); poss[x][y]=poss[d.first][d.second]+1; } // else if(x>=0&&x<n&&y>=0&&y<m&&v[x][y]=='.') // { // poss[x][y]=min(poss[x][y],poss[d.first][d.second]); // } } } q.push({xi,yi}); vector<vector<int>>vis(n,vector<int>(m)); vector<vector<int>>posss(n,vector<int>(m,-1)); vector<vector<char>>path(n,vector<char>(m)); posss[xi][yi]=0; vis[xi][yi]=1; if(poss[xi][yi]!=-1) { cout<<"NO"<<endl; return 0; } while(!q.empty()) { pair<int,int>d=q.front(); q.pop(); for(int i=0;i<4;i++) { int x=d.first+pos[i].first; int y=d.second+pos[i].second; if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&v[x][y]=='.') { vis[x][y]=1; if(poss[x][y]!=-1&&poss[x][y]<=posss[d.first][d.second]+1) { continue; } posss[x][y]=posss[d.first][d.second]+1; q.push({x,y}); path[x][y]=pat[i]; } } } int selx=-1,sely=-1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { // cout<<posss[i][j]<<" "; if(i==0||j==0||i==n-1||j==m-1) { if((v[i][j]=='.'||v[i][j]=='A')&&posss[i][j]!=-1) { selx=i,sely=j; break; } } } // cout<<endl; } if(selx==-1&&sely==-1) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; vector<char>res; path[xi][yi]='F'; while(path[selx][sely]!='F') { // cout<<selx<<" "<<sely<<endl; res.push_back(path[selx][sely]); if(path[selx][sely]=='L') { sely+=1; } else if(path[selx][sely]=='R') { sely-=1; } else if(path[selx][sely]=='U') { selx+=1; } else { selx-=1; } } reverse(res.begin(),res.end()); cout<<res.size()<<endl; for(char d:res) { cout<<d; } } return 0; }
24.347826
73
0.344048
su050300
9b3e2593d9ff36628dfe296383a498755d0df0e7
3,595
cpp
C++
src/main.cpp
shouxieai/kiwi-rknn
55c1a4ae2b664acf564b1218728b6ed85b9713aa
[ "MIT" ]
8
2022-03-02T08:51:21.000Z
2022-03-23T13:24:11.000Z
src/main.cpp
shouxieai/kiwi-rknn
55c1a4ae2b664acf564b1218728b6ed85b9713aa
[ "MIT" ]
3
2022-03-15T02:40:14.000Z
2022-03-29T03:25:17.000Z
src/main.cpp
shouxieai/kiwi-rknn
55c1a4ae2b664acf564b1218728b6ed85b9713aa
[ "MIT" ]
3
2022-03-03T07:46:21.000Z
2022-03-14T08:32:45.000Z
#include <stdio.h> #include <thread> #include <opencv2/opencv.hpp> #include "kiwi-logger.hpp" #include "kiwi-app-nanodet.hpp" #include "kiwi-app-scrfd.hpp" #include "kiwi-app-arcface.hpp" #include "kiwi-infer-rknn.hpp" using namespace cv; using namespace std; void test_pref(const char* model){ // 测试性能启用sync mode目的是尽可能的利用npu。实际使用如果无法掌握sync mode,尽量别用 // 你会发现sync mode的耗时会是非这个模式的80%左右,性能有提升,这与你实际推理时有区别,注意查看 auto infer = rknn::load_infer(model, true); infer->forward(); auto tic = kiwi::timestamp_now_float(); for(int i = 0; i < 100; ++i){ infer->forward(); } auto toc = kiwi::timestamp_now_float(); INFO("%s avg time: %f ms", model, (toc - tic) / 100); } void scrfd_demo(){ auto infer = scrfd::create_infer("scrfd_2.5g_bnkps.rknn", 0.4, 0.5); auto image = cv::imread("faces.jpg"); auto box_result = infer->commit(image).get(); auto tic = kiwi::timestamp_now_float(); for(int i = 0; i < 100; ++i){ infer->commit(image).get(); } auto toc = kiwi::timestamp_now_float(); INFO("scrfd time: %f ms", (toc - tic) / 100); for(auto& obj : box_result){ cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(0, 255, 0), 2); auto pl = obj.landmark; for(int i = 0; i < 5; ++i, pl += 2){ cv::circle(image, cv::Point(pl[0], pl[1]), 3, cv::Scalar(0, 0, 255), -1, 16); } } cv::imwrite("scrfd-result.jpg", image); } void nanodet_demo(){ auto infer = nanodet::create_infer("person_m416_plus_V15.rknn", 0.4, 0.5); auto image = cv::imread("faces.jpg"); auto box_result = infer->commit(image).get(); auto tic = kiwi::timestamp_now_float(); for(int i = 0; i < 100; ++i){ infer->commit(image).get(); } auto toc = kiwi::timestamp_now_float(); INFO("nanodet time: %f ms", (toc - tic) / 100); for(auto& obj : box_result){ cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(0, 255, 0), 2); } cv::imwrite("nanodet-result.jpg", image); } void arcface_demo(){ auto det = scrfd::create_infer("scrfd_2.5g_bnkps.rknn", 0.4, 0.5); auto ext = arcface::create_infer("w600k_r50_new.rknn"); auto a = cv::imread("library/2ys3.jpg"); auto b = cv::imread("library/male.jpg"); auto c = cv::imread("library/2ys5.jpg"); auto compute_sim = [](const cv::Mat& a, const cv::Mat& b){ auto c = cv::Mat(a * b.t()); return *c.ptr<float>(0); }; auto extract_feature = [&](const cv::Mat& image){ auto faces = det->commit(image).get(); if(faces.empty()){ INFOE("Can not detect any face"); return cv::Mat(); } auto max_face = std::max_element(faces.begin(), faces.end(), [](kiwi::Face& a, kiwi::Face& b){ return (a.right - a.left) * (a.bottom - a.top) > (b.right - b.left) * (b.bottom - b.top); }); auto out = arcface::face_alignment(image, max_face->landmark); return ext->commit(out, true).get(); }; auto fa = extract_feature(a); auto fb = extract_feature(b); auto fc = extract_feature(c); float ab = compute_sim(fa, fb); float ac = compute_sim(fa, fc); float bc = compute_sim(fb, fc); INFO("ab[differ] = %f, ac[same] = %f, bc[differ] = %f", ab, ac, bc); } int main(){ test_pref("person_m416_plus_V15.rknn"); test_pref("scrfd_2.5g_bnkps.rknn"); test_pref("w600k_r50_new.rknn"); // scrfd_demo(); // nanodet_demo(); arcface_demo(); return 0; }
30.726496
119
0.59249
shouxieai
9b41b65dac7fc919f5d55dae818426899396d8ba
22
cpp
C++
src/DlibDotNet.Native/dlib/image_saver/save_jpeg.cpp
ejoebstl/DlibDotNet
47436a573c931fc9c9107442b10cf32524805378
[ "MIT" ]
387
2017-10-14T23:08:59.000Z
2022-03-28T05:26:44.000Z
src/DlibDotNet.Native/dlib/image_saver/save_jpeg.cpp
ejoebstl/DlibDotNet
47436a573c931fc9c9107442b10cf32524805378
[ "MIT" ]
246
2017-10-09T11:40:20.000Z
2022-03-22T08:04:08.000Z
src/DlibDotNet.Native/dlib/image_saver/save_jpeg.cpp
ejoebstl/DlibDotNet
47436a573c931fc9c9107442b10cf32524805378
[ "MIT" ]
113
2017-10-18T12:04:53.000Z
2022-03-28T09:05:27.000Z
#include "save_jpeg.h"
22
22
0.772727
ejoebstl
9b48d5e4e8a9a8f65d4e01e68adc6cfac40bc6dc
4,261
hpp
C++
mllib/LogisticRegression.hpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
1
2019-01-23T02:10:10.000Z
2019-01-23T02:10:10.000Z
mllib/LogisticRegression.hpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
null
null
null
mllib/LogisticRegression.hpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
null
null
null
/* Edit by Christina */ #pragma once #include <limits> #include "mllib/Utility.hpp" #include "mllib/Instances.hpp" #include "lib/aggregator_factory.hpp" #include "mllib/Classifier.hpp" namespace husky{ namespace mllib{ /* MODE GLOBAL: global training LOCAL: training using local data */ enum class MODE {GLOBAL=0, LOCAL=1}; class LogisticRegression : public Classifier{ private: matrix_double param_matrix;//parameter matrix int max_iter; //Maximun iterations|pass through the data, default:5 double eta0; //The initial learning rate. The default value is 1. double alpha; //Constant that multuplies the regularization term, defualt: 0.0001. double trival_improve_th; //If weighted squared error improve is less than trival_improve_th, then this improve is trival. int max_trival_improve_iter; //If there are max_trival_improve_iter sequential iteration with trival_improve, then training will be stopped. MODE mode; //default: GLOBAL int class_num; //default: 2 /* Default settings maximize conditional log likelihood gradient descent update rule L2 penalty (least squares of 'param_vec'), a regularizer invscaling learning_rate : eta = eta0/pow(t, 0.5) NOTE: learning rate will only be updated when the loss increases, at the same time t will be increased by 1. */ /* Variables for extension std::string loss;//The loss function to be used. Defaults to "squared_loss". Only "Squared loss" is implemented in this stage. std::string penalty; //The penalty to be used. Defaults to "L2", second norm of 'param_vec', which is a standard regularizer. std::string learning_rate; //Type of learning rate to be used. Options include (1)'constant': eta = eta0;(2)'invscaling': eta = eta0/pow(t, 0.5); */ public: LogisticRegression(){ //default parameters max_iter = 5; eta0 = 1; alpha = 0.0001; trival_improve_th = 0.001; max_trival_improve_iter = 100; mode = MODE::GLOBAL; class_num = 2; } LogisticRegression(int m_iter, double e0, double al, double trival_im, double max_trival_im, MODE m, int classNum) : max_iter(m_iter), eta0(e0), alpha(al), trival_improve_th(trival_im), max_trival_improve_iter(max_trival_im), mode(m), class_num(classNum){} /* train a logistic regression model with even weighted instances. */ void fit(const Instances& instances); /* train model in global or local mode. */ void local_fit(const Instances& instances); void global_fit(const Instances& instances); void local_fit(const Instances& instances, std::string instance_weight_name); void global_fit(const Instances& instances, std::string instance_weight_name); /* train a logistic regression model using instance weight, which is specified as a attribute list of original_instances, name of which is 'instance_weight_name'. */ void fit(const Instances& instances, std::string instance_weight_name); AttrList<Instance, Prediction>& predict(const Instances& instances,std::string prediction_name="prediction"); Classifier* clone(int seed=0){ return new LogisticRegression(this->max_iter, this->eta0, this->alpha, this->trival_improve_th, this->max_trival_improve_iter, this->mode, this->class_num); } matrix_double get_parameters(){ return param_matrix; } }; } }
45.817204
273
0.574513
Christina-hshi
9b494df3b5e60407052fe5b8a93ae58a3c4bab6a
565
hpp
C++
include/MemeCore/TestRequest.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
include/MemeCore/TestRequest.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
include/MemeCore/TestRequest.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
#ifndef _ML_REQUEST_HPP_ #define _ML_REQUEST_HPP_ #include <MemeCore/IRequest.hpp> namespace ml { /* * * * * * * * * * * * * * * * * * * * */ class ML_CORE_API TestRequest : public IRequest { public: using LogFunc = void(*)(const ml::String &); public: TestRequest(); ~TestRequest(); public: void setValue(int32_t value); void setFunc(LogFunc value); public: void process() override; void finish() override; private: int32_t m_value; LogFunc m_func; }; /* * * * * * * * * * * * * * * * * * * * */ } #endif // !_ML_REQUEST_HPP_
15.694444
46
0.59469
Gurman8r
9b4d06272898ff03d5b0622f8eb060b9d8371e03
6,505
cc
C++
src/modular/lib/modular_config/modular_config.cc
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/modular/lib/modular_config/modular_config.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
src/modular/lib/modular_config/modular_config.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/modular/lib/modular_config/modular_config.h" #include <fcntl.h> #include <lib/syslog/cpp/macros.h> #include <rapidjson/document.h> #include <rapidjson/error/en.h> #include "src/lib/files/directory.h" #include "src/lib/files/file.h" #include "src/lib/files/path.h" #include "src/lib/fxl/strings/substitute.h" #include "src/modular/lib/fidl/clone.h" #include "src/modular/lib/fidl/json_xdr.h" #include "src/modular/lib/modular_config/modular_config_constants.h" #include "src/modular/lib/modular_config/modular_config_xdr.h" // Flags passed to RapidJSON that control JSON parsing behavior. // This is used to enable parsing non-standard JSON syntax, like comments. constexpr unsigned kModularConfigParseFlags = rapidjson::kParseCommentsFlag; namespace modular { namespace { rapidjson::Document GetSectionAsDoc(const rapidjson::Document& doc, const std::string& section_name) { rapidjson::Document section_doc; auto config_json = doc.FindMember(section_name); if (config_json != doc.MemberEnd()) { section_doc.CopyFrom(config_json->value, section_doc.GetAllocator()); } else { // |section_name| was not found; return an empty object section_doc.SetObject(); } return section_doc; } std::string StripLeadingSlash(std::string str) { if (str.find("/") == 0) return str.substr(1); return str; } } // namespace fit::result<fuchsia::modular::session::ModularConfig, std::string> ParseConfig( std::string_view config_json) { rapidjson::Document doc; doc.Parse<kModularConfigParseFlags>(config_json.data(), config_json.length()); if (doc.HasParseError()) { auto error = std::stringstream(); error << "Failed to parse JSON: " << rapidjson::GetParseError_En(doc.GetParseError()) << " (" << doc.GetErrorOffset() << ")"; return fit::error(error.str()); } fuchsia::modular::session::ModularConfig config; if (!XdrRead(&doc, &config, XdrModularConfig)) { return fit::error("Failed to read JSON as Modular configuration (does not follow schema?)"); } return fit::ok(std::move(config)); } // Returns the default Modular configuration. fuchsia::modular::session::ModularConfig DefaultConfig() { rapidjson::Document doc; doc.SetObject(); fuchsia::modular::session::ModularConfig config; auto ok = XdrRead(&doc, &config, XdrModularConfig); FX_DCHECK(ok); return config; } std::string ConfigToJsonString(const fuchsia::modular::session::ModularConfig& config) { std::string json; auto config_copy = CloneStruct(config); XdrWrite(&json, &config_copy, XdrModularConfig); return json; } ModularConfigReader::ModularConfigReader(fbl::unique_fd dir_fd) { FX_CHECK(dir_fd.get() >= 0); // 1. Figure out where the config file is. std::string config_path = files::JoinPath(StripLeadingSlash(modular_config::kOverriddenConfigDir), modular_config::kStartupConfigFilePath); if (!files::IsFileAt(dir_fd.get(), config_path)) { config_path = files::JoinPath(StripLeadingSlash(modular_config::kDefaultConfigDir), modular_config::kStartupConfigFilePath); } // 2. Read the file std::string config; if (!files::ReadFileToStringAt(dir_fd.get(), config_path, &config)) { FX_LOGS(ERROR) << "Failed to read file: " << config_path; UseDefaults(); return; } // 3. Parse the JSON ParseConfig(config, config_path); } ModularConfigReader::ModularConfigReader(std::string config) { constexpr char kPathForErrorStrings[] = "."; ParseConfig(config, kPathForErrorStrings); } // static ModularConfigReader ModularConfigReader::CreateFromNamespace() { return ModularConfigReader(fbl::unique_fd(open("/", O_RDONLY))); } // static std::string ModularConfigReader::GetOverriddenConfigPath() { return files::JoinPath(StripLeadingSlash(modular_config::kOverriddenConfigDir), modular_config::kStartupConfigFilePath); } // static bool ModularConfigReader::OverriddenConfigExists() { return files::IsFile(GetOverriddenConfigPath()); } void ModularConfigReader::ParseConfig(const std::string& config, const std::string& config_path) { rapidjson::Document doc; doc.Parse<kModularConfigParseFlags>(config); if (doc.HasParseError()) { FX_LOGS(ERROR) << "Failed to parse " << config_path << ": " << rapidjson::GetParseError_En(doc.GetParseError()) << " (" << doc.GetErrorOffset() << ")"; UseDefaults(); return; } // Parse the `basemgr` and `sessionmgr` sections out of the config. rapidjson::Document basemgr_doc = GetSectionAsDoc(doc, modular_config::kBasemgrConfigName); rapidjson::Document sessionmgr_doc = GetSectionAsDoc(doc, modular_config::kSessionmgrConfigName); if (!XdrRead(&basemgr_doc, &basemgr_config_, XdrBasemgrConfig)) { FX_LOGS(ERROR) << "Unable to parse 'basemgr' from " << config_path; } if (!XdrRead(&sessionmgr_doc, &sessionmgr_config_, XdrSessionmgrConfig)) { FX_LOGS(ERROR) << "Unable to parse 'sessionmgr' from " << config_path; } } void ModularConfigReader::UseDefaults() { rapidjson::Document doc; doc.SetObject(); XdrRead(&doc, &basemgr_config_, XdrBasemgrConfig); XdrRead(&doc, &sessionmgr_config_, XdrSessionmgrConfig); } fuchsia::modular::session::BasemgrConfig ModularConfigReader::GetBasemgrConfig() const { fuchsia::modular::session::BasemgrConfig result; basemgr_config_.Clone(&result); return result; } fuchsia::modular::session::SessionmgrConfig ModularConfigReader::GetSessionmgrConfig() const { fuchsia::modular::session::SessionmgrConfig result; sessionmgr_config_.Clone(&result); return result; } // static std::string ModularConfigReader::GetConfigAsString( fuchsia::modular::session::BasemgrConfig* basemgr_config, fuchsia::modular::session::SessionmgrConfig* sessionmgr_config) { std::string basemgr_json; std::string sessionmgr_json; XdrWrite(&basemgr_json, basemgr_config, XdrBasemgrConfig); XdrWrite(&sessionmgr_json, sessionmgr_config, XdrSessionmgrConfig); return fxl::Substitute(R"({ "$0": $1, "$2": $3 })", modular_config::kBasemgrConfigName, basemgr_json, modular_config::kSessionmgrConfigName, sessionmgr_json); } } // namespace modular
33.188776
100
0.713605
dahlia-os
9b4ea9f0b2be8e91eb8e1e8c5ad918940e0471a0
8,771
cc
C++
tce/src/applibs/ProGe/Netlist.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/ProGe/Netlist.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/ProGe/Netlist.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2009 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). 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 Netlist.cc * * Implementation of the Netlist class. * * @author Lasse Laasonen 2005 (lasse.laasonen-no.spam-tut.fi) * @author Otto Esko 2010 (otto.esko-no.spam-tut.fi) * @note rating: red */ #include <cstdlib> #include <string> #include "Netlist.hh" #include "NetlistPort.hh" #include "NetlistBlock.hh" #include "MapTools.hh" #include "Application.hh" #include "Conversion.hh" namespace ProGe { const std::string Netlist::INVERTER_MODULE = "util_inverter"; const std::string Netlist::INVERTER_INPUT = "data_in"; const std::string Netlist::INVERTER_OUTPUT = "data_out"; /** * The constructor. */ Netlist::Netlist() : coreEntityName_("") { } /** * The destructor. */ Netlist::~Netlist() { } /** * Partially connects two netlist ports. * * Connects two given subsets of bits of two netlist ports. The bit subsets * have equal cardinality and represent an ordered range of adjacent bits. * The bits are connected in the same order (the first bit of the subset of * the first port is connected to the first bit of the subset of the second * port). * * @param port1 The first port to connect. * @param port2 The second port to connect. * @param port1FirstBit The first bit of the first port to connect. * @param port2FirstBit The first bit of the second port to connect. * @param width The width of the connection. */ void Netlist::connectPorts( NetlistPort& port1, NetlistPort& port2, int port1FirstBit, int port2FirstBit, int width) { size_t port1Descriptor = descriptor(port1); size_t port2Descriptor = descriptor(port2); // create first edge PortConnectionProperty property1( port1FirstBit, port2FirstBit, width); boost::add_edge(port1Descriptor, port2Descriptor, property1, *this); // create the opposite edge PortConnectionProperty property2( port2FirstBit, port1FirstBit, width); boost::add_edge(port2Descriptor, port1Descriptor, property2, *this); } /** * Connects two netlist ports completely. * * Each bit of the first port is connected to a bit of the second port. The * bits are connected in the same order (the first bit of the first port is * connected to the first bit of the second port). * * @param port1 The first port to connect. * @param port2 The second port to connect. */ void Netlist::connectPorts( NetlistPort& port1, NetlistPort& port2) { size_t port1Descriptor = descriptor(port1); size_t port2Descriptor = descriptor(port2); PortConnectionProperty property; // create first edge boost::add_edge(port1Descriptor, port2Descriptor, property, *this); // create the opposite edge boost::add_edge(port2Descriptor, port1Descriptor, property, *this); } /** * TODO: partial connection version and support BIT_VECTOR length > 1 */ void Netlist::connectPortsInverted( NetlistPort& input, NetlistPort& output) { std::string instance = input.name() + "_" + INVERTER_MODULE; NetlistBlock* inverter = new NetlistBlock(INVERTER_MODULE, instance, *this); NetlistPort* inverterInput = new NetlistPort(INVERTER_INPUT, "1", 1, ProGe::BIT, HDB::IN, *inverter); NetlistPort* inverterOutput = new NetlistPort(INVERTER_OUTPUT, "1", 1, ProGe::BIT, HDB::OUT, *inverter); this->topLevelBlock().addSubBlock(inverter); this->connectPorts(input, *inverterInput, 0, 0, 1); this->connectPorts(output, *inverterOutput, 0, 0 ,1); } /** * Tells whether the netlist port is connected in this netlist instance * * @param port The netlist port * @return True if port is connected */ bool Netlist::isPortConnected(const NetlistPort& port) const { size_t vertDesc = descriptor(port); boost::graph_traits<Netlist>::degree_size_type edges = boost::out_degree(vertDesc, *this); return edges != 0; } /** * Tells whether the netlist is empty. * * @return True if the netlist is empty, otherwise false. */ bool Netlist::isEmpty() const { return boost::num_vertices(*this) == 0; } /** * Returns the top-level block in the netlist. * * @return The top-level block. * @exception InstanceNotFound If the netlist is empty. */ NetlistBlock& Netlist::topLevelBlock() const { if (isEmpty()) { throw InstanceNotFound(__FILE__, __LINE__, __func__); } boost::graph_traits<Netlist>::vertex_iterator iter = boost::vertices(*this).first; size_t vertexDescriptor = *iter; NetlistPort* port = (*this)[vertexDescriptor]; NetlistBlock* block = port->parentBlock(); while (block->hasParentBlock()) { block = &block->parentBlock(); } return *block; } /** * Maps the given descriptor for the given port. * * This method does not need to be called by clients. * * @param port The port. * @param descriptor The descriptor. */ void Netlist::mapDescriptor(const NetlistPort& port, size_t descriptor) { assert(!MapTools::containsKey(vertexDescriptorMap_, &port)); vertexDescriptorMap_.insert( std::pair<const NetlistPort*, size_t>(&port, descriptor)); } /** * Returns descriptor for the given port. * * @return Descriptor for the given port. */ size_t Netlist::descriptor(const NetlistPort& port) const { assert(MapTools::containsKey(vertexDescriptorMap_, &port)); return MapTools::valueForKey<size_t>(vertexDescriptorMap_, &port); } /** * Adds a parameter for the netlist. * * If the netlist already has a parameter with the given name, it is replaced * by the new parameter. * * @param name Name of the parameter. * @param type Type of the parameter. * @param value Value of the parameter. */ void Netlist::setParameter( const std::string& name, const std::string& type, const std::string& value) { if (hasParameter(name)) { removeParameter(name); } Parameter param = {name, type, value}; parameters_.push_back(param); } /** * Removes the given parameter from the netlist. * * @param name Name of the parameter. */ void Netlist::removeParameter(const std::string& name) { for (ParameterTable::iterator iter = parameters_.begin(); iter != parameters_.end(); iter++) { if (iter->name == name) { parameters_.erase(iter); break; } } } /** * Tells whether the netlist has the given parameter. * * @param name Name of the parameter. */ bool Netlist::hasParameter(const std::string& name) const { for (ParameterTable::const_iterator iter = parameters_.begin(); iter != parameters_.end(); iter++) { if (iter->name == name) { return true; } } return false; } /** * Returns the number of parameters in the netlist. * * @return The number of parameters. */ int Netlist::parameterCount() const { return parameters_.size(); } /** * Returns the parameter at the given position. * * @param index The position. * @exception OutOfRange If the given index is negative or not smaller than * the number of parameters. */ Netlist::Parameter Netlist::parameter(int index) const { if (index < 0 || index >= parameterCount()) { throw OutOfRange(__FILE__, __LINE__, __func__); } return parameters_[index]; } void Netlist::setCoreEntityName(TCEString coreEntityName) { coreEntityName_ = coreEntityName; } TCEString Netlist::coreEntityName() const { if (coreEntityName_ == "") return topLevelBlock().moduleName(); else return coreEntityName_; } }
26.498489
78
0.688063
kanishkan
9b52892eac05dc229e55bcbb9214c1db73817838
9,115
hpp
C++
libraries/protocol/include/scorum/protocol/betting/market.hpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
libraries/protocol/include/scorum/protocol/betting/market.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
libraries/protocol/include/scorum/protocol/betting/market.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#pragma once #include <fc/static_variant.hpp> #include <scorum/protocol/betting/wincase.hpp> #include <scorum/protocol/betting/market_kind.hpp> #include <scorum/protocol/config.hpp> #include <boost/range/algorithm/transform.hpp> namespace scorum { namespace protocol { template <market_kind kind, typename tag = void> struct over_under_market { int16_t threshold; template <bool site> using wincase = over_under_wincase<site, kind, tag>; using over = wincase<true>; using under = wincase<false>; static constexpr market_kind kind_v = kind; bool has_trd_state() const { return threshold % SCORUM_BETTING_THRESHOLD_FACTOR == 0; } }; template <market_kind kind, typename tag = void> struct score_yes_no_market { uint16_t home; uint16_t away; template <bool site> using wincase = score_yes_no_wincase<site, kind, tag>; using yes = wincase<true>; using no = wincase<false>; static constexpr market_kind kind_v = kind; bool has_trd_state() const { return false; } }; template <market_kind kind, typename tag = void> struct yes_no_market { template <bool site> using wincase = yes_no_wincase<site, kind, tag>; using yes = wincase<true>; using no = wincase<false>; static constexpr market_kind kind_v = kind; bool has_trd_state() const { return false; } }; struct home_tag; struct away_tag; struct draw_tag; struct both_tag; using result_home = yes_no_market<market_kind::result, home_tag>; using result_draw = yes_no_market<market_kind::result, draw_tag>; using result_away = yes_no_market<market_kind::result, away_tag>; using round_home = yes_no_market<market_kind::round>; using handicap = over_under_market<market_kind::handicap>; using correct_score_home = yes_no_market<market_kind::correct_score, home_tag>; using correct_score_draw = yes_no_market<market_kind::correct_score, draw_tag>; using correct_score_away = yes_no_market<market_kind::correct_score, away_tag>; using correct_score = score_yes_no_market<market_kind::correct_score>; using goal_home = yes_no_market<market_kind::goal, home_tag>; using goal_both = yes_no_market<market_kind::goal, both_tag>; using goal_away = yes_no_market<market_kind::goal, away_tag>; using total = over_under_market<market_kind::total>; using total_goals_home = over_under_market<market_kind::total_goals, home_tag>; using total_goals_away = over_under_market<market_kind::total_goals, away_tag>; using market_type = fc::static_variant<result_home, result_draw, result_away, round_home, handicap, correct_score_home, correct_score_draw, correct_score_away, correct_score, goal_home, goal_both, goal_away, total, total_goals_home, total_goals_away>; using wincase_type = fc::static_variant<result_home::yes, result_home::no, result_draw::yes, result_draw::no, result_away::yes, result_away::no, round_home::yes, round_home::no, handicap::over, handicap::under, correct_score_home::yes, correct_score_home::no, correct_score_draw::yes, correct_score_draw::no, correct_score_away::yes, correct_score_away::no, correct_score::yes, correct_score::no, goal_home::yes, goal_home::no, goal_both::yes, goal_both::no, goal_away::yes, goal_away::no, total::over, total::under, total_goals_home::over, total_goals_home::under, total_goals_away::over, total_goals_away::under>; std::pair<wincase_type, wincase_type> create_wincases(const market_type& market); wincase_type create_opposite(const wincase_type& wincase); market_type create_market(const wincase_type& wincase); bool has_trd_state(const market_type& market); bool match_wincases(const wincase_type& lhs, const wincase_type& rhs); market_kind get_market_kind(const wincase_type& wincase); template <typename T> std::set<market_kind> get_markets_kind(const T& markets) { std::set<market_kind> actual_markets; boost::transform(markets, std::inserter(actual_markets, actual_markets.begin()), [](const market_type& m) { return m.visit([&](const auto& market_impl) { return market_impl.kind_v; }); }); return actual_markets; } template <typename T> bool is_belong_markets(const wincase_type& wincase, const T& markets) { const auto wincase_market = create_market(wincase); for (const auto& market : markets) { if (wincase_market == market) return true; } return false; } } // namespace protocol } // namespace scorum #include <scorum/protocol/betting/wincase_comparison.hpp> #include <scorum/protocol/betting/market_comparison.hpp> namespace fc { using scorum::protocol::market_type; using scorum::protocol::wincase_type; template <> void to_variant(const wincase_type& wincase, fc::variant& variant); template <> void from_variant(const fc::variant& variant, wincase_type& wincase); template <> void to_variant(const market_type& market, fc::variant& var); template <> void from_variant(const fc::variant& var, market_type& market); } FC_REFLECT_EMPTY(scorum::protocol::result_home) FC_REFLECT_EMPTY(scorum::protocol::result_draw) FC_REFLECT_EMPTY(scorum::protocol::result_away) FC_REFLECT_EMPTY(scorum::protocol::round_home) FC_REFLECT(scorum::protocol::handicap, (threshold)) FC_REFLECT_EMPTY(scorum::protocol::correct_score_home) FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw) FC_REFLECT_EMPTY(scorum::protocol::correct_score_away) FC_REFLECT(scorum::protocol::correct_score, (home)(away)) FC_REFLECT_EMPTY(scorum::protocol::goal_home) FC_REFLECT_EMPTY(scorum::protocol::goal_both) FC_REFLECT_EMPTY(scorum::protocol::goal_away) FC_REFLECT(scorum::protocol::total, (threshold)) FC_REFLECT(scorum::protocol::total_goals_home, (threshold)) FC_REFLECT(scorum::protocol::total_goals_away, (threshold)) FC_REFLECT_EMPTY(scorum::protocol::result_home::yes) FC_REFLECT_EMPTY(scorum::protocol::result_home::no) FC_REFLECT_EMPTY(scorum::protocol::result_draw::yes) FC_REFLECT_EMPTY(scorum::protocol::result_draw::no) FC_REFLECT_EMPTY(scorum::protocol::result_away::yes) FC_REFLECT_EMPTY(scorum::protocol::result_away::no) FC_REFLECT_EMPTY(scorum::protocol::round_home::yes) FC_REFLECT_EMPTY(scorum::protocol::round_home::no) FC_REFLECT(scorum::protocol::handicap::over, (threshold)) FC_REFLECT(scorum::protocol::handicap::under, (threshold)) FC_REFLECT_EMPTY(scorum::protocol::correct_score_home::yes) FC_REFLECT_EMPTY(scorum::protocol::correct_score_home::no) FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::yes) FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::no) FC_REFLECT_EMPTY(scorum::protocol::correct_score_away::yes) FC_REFLECT_EMPTY(scorum::protocol::correct_score_away::no) FC_REFLECT(scorum::protocol::correct_score::yes, (home)(away)) FC_REFLECT(scorum::protocol::correct_score::no, (home)(away)) FC_REFLECT_EMPTY(scorum::protocol::goal_home::yes) FC_REFLECT_EMPTY(scorum::protocol::goal_home::no) FC_REFLECT_EMPTY(scorum::protocol::goal_both::yes) FC_REFLECT_EMPTY(scorum::protocol::goal_both::no) FC_REFLECT_EMPTY(scorum::protocol::goal_away::yes) FC_REFLECT_EMPTY(scorum::protocol::goal_away::no) FC_REFLECT(scorum::protocol::total::over, (threshold)) FC_REFLECT(scorum::protocol::total::under, (threshold)) FC_REFLECT(scorum::protocol::total_goals_home::over, (threshold)) FC_REFLECT(scorum::protocol::total_goals_home::under, (threshold)) FC_REFLECT(scorum::protocol::total_goals_away::over, (threshold)) FC_REFLECT(scorum::protocol::total_goals_away::under, (threshold))
40.691964
111
0.635765
scorum
9b58686529189be7eecc3c0c17292971a5e6f185
3,378
cpp
C++
tddd86-algorithms/life.cpp
AxelGard/university-projects
0c9a6e785f1918c6ed0fd365b2d419c9f52edb50
[ "MIT" ]
2
2022-01-30T17:53:33.000Z
2022-02-03T23:34:36.000Z
tddd86-algorithms/life.cpp
AxelGard/university-projects
0c9a6e785f1918c6ed0fd365b2d419c9f52edb50
[ "MIT" ]
null
null
null
tddd86-algorithms/life.cpp
AxelGard/university-projects
0c9a6e785f1918c6ed0fd365b2d419c9f52edb50
[ "MIT" ]
null
null
null
/* * Martin Gustafsson @margu424 && Axel Gard @axega544 * * The task was to crate a replication of the game of life. * * Soruces : * labb PM - https://www.ida.liu.se/~TDDD86/info/misc/labb1.pdf * C++ doc - http://www.cplusplus.com/doc/tutorial/files/ * StackOverFlow - https://stackoverflow.com/questions/25225948/how-to-check-if-a-file-exists-in-c-with-fstreamopen?rq=1 * */ #include <iostream> #include "grid.h" #include "lifeutil.h" #include <string> #include <fstream> /* Prints the given grid to the terminal */ void printGrid(const Grid<int>& grid){ for (int i = 0; i < grid.numRows(); i++){ for(int j = 0; j < grid.numCols(); j++){ if (grid.get(i,j)){ std::cout << "X"; } else{ std::cout << "-"; } } std::cout << std::endl; } } /* returns the number of neighbours in a given grid at pos row and col */ int getNeighbours(const Grid<int>& grid, int row, int col){ int neighbours = 0; for (int i = -1; i < 2; i++){ for (int j = -1; j < 2; j++){ if (i == 0 && j == 0) continue; if (!grid.inBounds(row+i, col+j)) continue; if (grid.get(row+i, col+j)) neighbours++; } } return neighbours; } /* Runs the game one genaration forward */ void tick(Grid<int>& grid){ Grid<int> newGrid = Grid<int>(grid.numRows(), grid.numCols()); for (int i = 0; i < grid.numRows(); i++){ for (int j = 0; j < grid.numCols(); j++){ if (getNeighbours(grid, i,j) == 2) newGrid.set(i,j,grid.get(i,j)); else if (getNeighbours(grid, i,j) == 3) newGrid.set(i,j,1); else newGrid.set(i,j, 0); } } grid = newGrid; } /* will run the game forever */ void animate(Grid<int>& grid){ while (true) { clearConsole(); printGrid(grid); pause(100); tick(grid); } } /* main function that handels user input */ int main() { std::cout << "Welcome to the TDDD86 Game of Life,\n" "a simulation of the lifecycle of a bacteria colony.\n" "Cells (X) live and die by the following rules:\n" " - A cell with 1 or fewer neighbours dies.\n" " - Locations with 2 neighbours remain stable.\n" " - Locations with 3 neighbours will create life. \n" " - A cell with 4 or more neighbours dies. \n\n"; std::string filename; std::cout << "Grid input file name? : "; std::cin >> filename; std::ifstream infile(filename); if (!infile.is_open()){ std::cout << "file not found : " << std::endl; return 1; } int rows; int coloums; infile >> rows; infile >> coloums; Grid<int> grid = Grid<int>(rows, coloums); // get given grid for (int i = 0; i < rows; i++){ std::string row; infile >> row; for (int j = 0; j < coloums; j++){ if (row[j] == 'X'){ grid.set(i, j, 1); } } } printGrid(grid); char choice; while (true) { std::cout << "a)nimate, t)ick, q)uit? "; std::cin >> choice; if (choice == 'a') animate(grid); else if (choice == 't'){ tick(grid); printGrid(grid); } else return 0; } }
25.78626
120
0.51717
AxelGard
9b64451c57a5c7befdabc8f310f8399877a8fad6
2,233
cpp
C++
src/Aims.cpp
weiboad/aidt
dabb0877675326f8bd80fdb450a4f3d7108ac5db
[ "Apache-2.0" ]
16
2017-07-06T04:54:06.000Z
2021-06-24T03:37:33.000Z
src/Aims.cpp
weiboad/aidt
dabb0877675326f8bd80fdb450a4f3d7108ac5db
[ "Apache-2.0" ]
1
2018-05-18T07:32:03.000Z
2018-05-18T10:02:24.000Z
src/Aims.cpp
weiboad/aidt
dabb0877675326f8bd80fdb450a4f3d7108ac5db
[ "Apache-2.0" ]
3
2017-07-11T03:43:30.000Z
2018-08-16T12:10:42.000Z
#include "Aims.hpp" // {{{ Aims::Aims() Aims::Aims(AimsContext* context) : _context(context) { _configure = _context->config; } // }}} // {{{ Aims::~Aims() Aims::~Aims() { } // }}} // {{{ void Aims::run() void Aims::run() { // 初始化 server init(); _kafkaProducerIn->start(); } // }}} // {{{ void Aims::init() void Aims::init() { initKafkaProducer(); } // }}} // {{{ void Aims::stop() void Aims::stop() { if (_kafkaProducerIn != nullptr) { _kafkaProducerIn->stop(); } if (_kafkaProducerCallbackIn != nullptr) { delete _kafkaProducerCallbackIn; _kafkaProducerCallbackIn = nullptr; } } // }}} // {{{ adbase::kafka::Producer* Aims::getProducer() adbase::kafka::Producer* Aims::getProducer() { return _kafkaProducerIn; } // }}} // {{{ void Aims::initKafkaProducer() void Aims::initKafkaProducer() { _kafkaProducerCallbackIn = new aims::kafka::ProducerIn(_context); std::unordered_map<std::string, std::string> configs; configs["metadata.broker.list"] = _configure->brokerListProducerIn; configs["debug"] = _configure->debugIn; configs["security.protocol"] = _configure->securityProtocol; configs["sasl.mechanisms"] = _configure->saslMechanisms; configs["sasl.kerberos.service.name"] = _configure->kerberosServiceName; configs["sasl.kerberos.principal"] = _configure->kerberosPrincipal; configs["sasl.kerberos.kinit.cmd"] = _configure->kerberosCmd; configs["sasl.kerberos.keytab"] = _configure->kerberosKeytab; configs["sasl.kerberos.min.time.before.relogin"] = _configure->kerberosMinTime; configs["sasl.username"] = _configure->saslUsername; configs["sasl.password"] = _configure->saslPassword; _kafkaProducerIn = new adbase::kafka::Producer(configs, _configure->queueLengthIn); _kafkaProducerIn->setSendHandler(std::bind(&aims::kafka::ProducerIn::send, _kafkaProducerCallbackIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); _kafkaProducerIn->setErrorHandler(std::bind(&aims::kafka::ProducerIn::errorCallback, _kafkaProducerCallbackIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); } // }}}
26.903614
85
0.670846
weiboad
9b64fe04440fda5b7bfc633eaf03e32d5e2ea0a8
1,259
cc
C++
deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc
jeffersQuan/greenworks
ab73a59574e4a15a1e97091334b384f6e84257eb
[ "MIT" ]
null
null
null
deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc
jeffersQuan/greenworks
ab73a59574e4a15a1e97091334b384f6e84257eb
[ "MIT" ]
null
null
null
deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc
jeffersQuan/greenworks
ab73a59574e4a15a1e97091334b384f6e84257eb
[ "MIT" ]
null
null
null
// Copyright (c) 2019, Entropy Game Global Limited. // All rights reserved. #include <stdint.h> #include "rail/sdk/base/rail_array.h" #include "thirdparty/gtest/gtest.h" struct Item { int32_t id; int32_t value; }; TEST(RailArray, size) { rail::RailArray<struct Item> array; EXPECT_EQ(0U, array.size()); array.resize(100); EXPECT_EQ(100U, array.size()); array.resize(0); EXPECT_EQ(0U, array.size()); struct Item item; item.id = 1; item.value = 100; array.push_back(item); EXPECT_EQ(1U, array.size()); EXPECT_EQ(100, array[0].value); array[0].value = 101; EXPECT_EQ(101, array[0].value); const struct Item& it = array[0]; EXPECT_EQ(101, it.value); struct Item item2; item2.id = 2; item2.value = 200; array.push_back(item2); EXPECT_EQ(2U, array.size()); rail::RailArray<char> str("Hello", 5); EXPECT_EQ(5U, str.size()); } TEST(RailArray, assign) { rail::RailArray<struct Item> array; Item items[5]; items[1].value = 100; array.assign(items, sizeof(items) / sizeof(Item)); EXPECT_EQ(5U, array.size()); EXPECT_EQ(100, array[1].value); } TEST(RailArray, buf) { rail::RailArray<int64_t> array; EXPECT_EQ(NULL, array.buf()); }
22.890909
54
0.631454
jeffersQuan
9b6caf18dd8e10d0f32bb9507f848b8ed7329c4f
1,552
hpp
C++
code/szen/inc/szen/System/SpriteBatch.hpp
Sonaza/scyori
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
[ "BSD-3-Clause" ]
null
null
null
code/szen/inc/szen/System/SpriteBatch.hpp
Sonaza/scyori
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
[ "BSD-3-Clause" ]
null
null
null
code/szen/inc/szen/System/SpriteBatch.hpp
Sonaza/scyori
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
[ "BSD-3-Clause" ]
null
null
null
#ifndef SZEN_SPRITEBATCH_HPP #define SZEN_SPRITEBATCH_HPP #include <SFML/Graphics.hpp> #include <functional> #include <map> #include <vector> #include <thor/Particles.hpp> namespace sz { class TextureAsset; class ShaderAsset; struct BatchData { BatchData() : texture(NULL), shader(NULL), particles(NULL) {} BatchData(size_t layer, const sf::Texture*, const sf::Shader*, sf::BlendMode); BatchData(size_t layer, thor::ParticleSystem*, const sf::Shader*, sf::BlendMode); BatchData(size_t layer, sf::Text*, sf::BlendMode); size_t layer; sf::VertexArray vertices; const sf::Texture* texture; const sf::Shader* shader; sf::BlendMode blendmode; thor::ParticleSystem* particles; sf::Text text; enum Type { Vertices, Particles, Text } type; }; typedef std::vector<BatchData> BatchDataList; class SpriteBatch { public: SpriteBatch(); ~SpriteBatch(); static void init(); static void clear(); //static void append(const sf::Vertex* quad, sf::Uint32 layer, TextureAsset* texture, ShaderAsset* shader, sf::BlendMode blendmode); static void append(const sf::Vertex* quad, sf::Uint32 layer, const sf::Texture* texture, ShaderAsset* shader, sf::BlendMode blendmode); static void append(thor::ParticleSystem* system, sf::Uint32 layer, ShaderAsset* shader, sf::BlendMode blendmode); static void append(sf::Text* text, sf::Uint32 layer, sf::BlendMode blendmode); static void draw(sf::RenderTarget&); private: static BatchDataList m_batchData; }; } #endif // SZEN_SPRITEBATCH_HPP
21.555556
137
0.717784
Sonaza
9b6d41b5fb0fc4f82fd71de1611c606f27f09f1f
8,171
cpp
C++
client_tools/lms/src/OPE_LMS/db.cpp
kgonyo/ope
a5b548ad7716e76f42af9bdd8f0079752760edee
[ "MIT" ]
null
null
null
client_tools/lms/src/OPE_LMS/db.cpp
kgonyo/ope
a5b548ad7716e76f42af9bdd8f0079752760edee
[ "MIT" ]
null
null
null
client_tools/lms/src/OPE_LMS/db.cpp
kgonyo/ope
a5b548ad7716e76f42af9bdd8f0079752760edee
[ "MIT" ]
null
null
null
#include "db.h" APP_DB::APP_DB(QQmlApplicationEngine *parent) : QObject(parent) { _db = QSqlDatabase::addDatabase("QSQLITE"); this->setParent(parent); // DEBUG STUFF QString crypt_pw = QCryptographicHash::hash(QString("abcd").toLocal8Bit(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); qDebug() << "TEST PW: " << crypt_pw; } /** * @brief DB::init_db - Connect to database and ensure that scheme is in place and/or migrated * @return true on success */ bool APP_DB::init_db() { bool ret = false; QQmlApplicationEngine *p = qobject_cast<QQmlApplicationEngine*>(this->parent()); p->rootContext()->setContextProperty("database", this); // Find DB path QDir d; d.setPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/"); d.mkpath(d.path()); QString db_file = d.path() + "/lms.db"; _db.setHostName(db_file); _db.setDatabaseName(db_file); _db.setPassword("TEST PW"); // TODO - doesn't do anything, need sqlite extetion to add encryption? ret = _db.open(); if (ret) { // Create and/or migrate tables QSqlQuery query; QString sql; //QSqlTableModel *model; GenericQueryModel *model; // Create student users table sql = "CREATE TABLE IF NOT EXISTS `students` ( \ `id` INTEGER PRIMARY KEY AUTOINCREMENT, \ `user_name` TEXT NOT NULL, \ `password` TEXT NOT NULL, \ `auth_cookie` TEXT NOT NULL DEFAULT '' \ );"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text(); ret = false; } // Add to the table models list model = new GenericQueryModel(this); //model->setTable("students"); //model->setEditStrategy(QSqlTableModel::OnManualSubmit); //model->select(); //model->setHeaderData(0, Qt::Horizontal, tr("id")); //model->setHeaderData(1, Qt::Horizontal, tr("user_name")); //model->setHeaderData(2, Qt::Horizontal, tr("password")); //model->setHeaderData(3, Qt::Horizontal, tr("auth_cookie")); _tables["students"] = model; // Expose this to QML p->rootContext()->setContextProperty("students_model", model); // Create the classes table sql = "CREATE TABLE IF NOT EXISTS `classes` ( \ `id` INTEGER PRIMARY KEY AUTOINCREMENT, \ `tid_student` INTEGER NOT NULL DEFAULT 0, \ `class_name` TEXT NOT NULL DEFAULT '', \ `class_code` TEXT NOT NULL DEFAULT '', \ `class_description` TEXT NOT NULL DEFAULT '' \ );"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text(); ret = false; } // Add to the table models list model = new GenericQueryModel(this); //model->select(); //model->setHeaderData(0, Qt::Horizontal, tr("id")); //model->setHeaderData(1, Qt::Horizontal, tr("tid_student")); //model->setHeaderData(2, Qt::Horizontal, tr("class_name")); //model->setHeaderData(3, Qt::Horizontal, tr("class_code")); //model->setHeaderData(4, Qt::Horizontal, tr("class_description")); _tables["classes"] = model; // Expose this to QML p->rootContext()->setContextProperty("classes_model", model); // Create the resources table sql = "CREATE TABLE IF NOT EXISTS `resources` ( \ `id` INTEGER PRIMARY KEY AUTOINCREMENT, \ `resource_name` TEXT NOT NULL DEFAULT '', \ `resource_url` TEXT NOT NULL DEFAULT '', \ `resource_description` TEXT NOT NULL DEFAULT '', \ `sort_order` INTEGER NOT NULL DEFAULT 0 \ );"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text(); ret = false; } // Add to the table models list model = new GenericQueryModel(this); model->setQuery("SELECT * FROM resources", _db); //model->select(); //model->setHeaderData(0, Qt::Horizontal, tr("id")); //model->setHeaderData(1, Qt::Horizontal, tr("resource_name")); //model->setHeaderData(2, Qt::Horizontal, tr("resource_url")); //model->setHeaderData(3, Qt::Horizontal, tr("resource_description")); //model->setHeaderData(4, Qt::Horizontal, tr("sort_order")); _tables["resources"] = model; // Expose this to QML p->rootContext()->setContextProperty("resources_model", model); // Make sure the default resource entries are in place add_resource("Start Here", "/start_here/index.html", "Getting started...", 0); // Make sure to commit and release locks _db.commit(); } return ret; } /** * @brief APP_DB::auth_student - Authenticate the student against the local database * @param user_name * @param password * @return true on success */ bool APP_DB::auth_student(QString user_name, QString password) { bool ret = false; // If the password is empty always return false if (password == "") { return false; } // Encode password QString crypt_pw = QCryptographicHash::hash(password.toLocal8Bit(), QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); // Query to see if the user exists QString sql = "SELECT COUNT(*) user_count FROM students WHERE user_name=:user_name and password=:password"; QSqlQuery q; q.prepare(sql); q.bindValue(":user_name", user_name); q.bindValue(":password", crypt_pw); q.exec(); int user_count = 0; while(q.next()) { user_count = q.value("user_count").toInt(); } if (user_count > 0) { ret = true; } return ret; } bool APP_DB::add_resource(QString resource_name, QString resource_url, QString resource_description, int sort_order) { bool ret = false; QString sql; QSqlQuery q; // Check if the resource exists sql = "SELECT count(*) as count FROM resources WHERE resource_name=:resource_name"; q.prepare(sql); q.bindValue(":resource_name", resource_name); q.exec(); int count = 0; while (q.next()) { count = q.value("count").toInt(); } if (count > 0) { // Already present return true; } // Not present, add it sql = "INSERT INTO resources (resource_name, resource_url, resource_description, sort_order) \ VALUES (:resource_name, :resource_url, :resource_description, :sort_order)"; q.prepare(sql); q.bindValue(":resource_name", resource_name); q.bindValue(":resource_url", resource_url); q.bindValue(":resource_description", resource_description); q.bindValue(":sort_order", sort_order); q.exec(); // Write changes to the db _db.commit(); // Refresh data after insert? TODO - should this be an emit signal instead? //_tables["resources"]->select(); ret = true; return ret; } GenericQueryModel::GenericQueryModel(QObject *parent) : QSqlQueryModel(parent) { } void GenericQueryModel::setQuery(const QString &query, const QSqlDatabase &db) { QSqlQueryModel::setQuery(query, db); generateRoleNames(); } void GenericQueryModel::setQuery(const QSqlQuery &query) { QSqlQueryModel::setQuery(query); generateRoleNames(); } QVariant GenericQueryModel::data(const QModelIndex &index, int role) const { QVariant value; if (role < Qt::UserRole) { value = QSqlQueryModel::data(index, role); } else { int columnIndex = role - Qt::UserRole -1; QModelIndex modelIndex = this->index(index.row(), columnIndex); value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole); } return value; } void GenericQueryModel::generateRoleNames() { m_roleNames.clear(); for(int i = 0; i < record().count(); i++) { m_roleNames.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8()); } }
31.548263
116
0.61241
kgonyo
9b724925d691a7781cd8a990a5556961f5e913fb
37,941
cpp
C++
src/Parser.cpp
MichaelMCE/LCDMisc
1d2a913d62fd4d940ad95b5f8463a5f06e683427
[ "CC-BY-4.0" ]
null
null
null
src/Parser.cpp
MichaelMCE/LCDMisc
1d2a913d62fd4d940ad95b5f8463a5f06e683427
[ "CC-BY-4.0" ]
null
null
null
src/Parser.cpp
MichaelMCE/LCDMisc
1d2a913d62fd4d940ad95b5f8463a5f06e683427
[ "CC-BY-4.0" ]
null
null
null
#include "Parser.h" #include "Tokenizer.h" #include "malloc.h" #include "config.h" //#include <stdio.h> //#include "string.h" #define REDUCE 0x20000000 #define SHIFT 0x40000000 #define ACCEPT 0x60000000 #define ACTION_MASK 0x60000000 struct Rule { ScriptTokenType result; NodeType nodeType; unsigned char numTerms:4; unsigned char operatorPos:4; ScriptTokenType terms[8]; }; const Rule rules[] = { {PARSER_SCRIPT, NODE_NONE, 2, 1, PARSER_FUNCTION_LIST, TOKEN_END}, {PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 2, 1, PARSER_FUNCTION, PARSER_FUNCTION_LIST}, {PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_FUNCTION}, {PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 2, 1, PARSER_STRUCT, PARSER_FUNCTION_LIST}, {PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_STRUCT}, //{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_RAW_STRUCT}, /* {PARSER_RAW_STRUCT, NODE_RAW_STRUCT, 6, 1, TOKEN_RAW, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, PARSER_RAW_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT}, {PARSER_RAW_STRUCT_LIST, NODE_RAW_STRUCT_LIST, 3, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_SEMICOLON, PARSER_STRUCT_LIST}, {PARSER_RAW_STRUCT_LIST, NODE_RAW_STRUCT_LIST, 2, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_SEMICOLON}, {PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 2, 0, PARSER_TYPE, TOKEN_IDENTIFIER}, {PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 3, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_COMMA, TOKEN_IDENTIFIER}, {PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 5, 0, PARSER_TYPE, TOKEN_ TOKEN_IDENTIFIER}, {PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 6, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_COMMA, TOKEN_IDENTIFIER}, {PARSER_TYPE, NODE_INT_TYPE, 1, 0, TOKEN_INT_TYPE}, {PARSER_TYPE, NODE_FLOAT_TYPE, 1, 0, TOKEN_FLOAT_TYPE}, {PARSER_TYPE, NODE_DOUBLE_TYPE, 1, 0, TOKEN_DOUBLE_TYPE}, {PARSER_TYPE, NODE_CHAR_TYPE, 1, 0, TOKEN_CHAR_TYPE}, {PARSER_TYPE, NODE_STRING_TYPE, 1, 0, TOKEN_STRING_TYPE}, //*/ {PARSER_STRUCT, NODE_STRUCT, 5, 0, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, PARSER_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT}, {PARSER_STRUCT, NODE_STRUCT, 7, 0, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_EXTENDS, PARSER_IDENTIFIER_LIST, TOKEN_OPEN_CODE, PARSER_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT}, //{PARSER_STRUCT, NODE_STRUCT, 4, 1, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, TOKEN_CLOSE_CODE}, {PARSER_STRUCT_LIST, NODE_STRUCT_LIST, 2, 1, PARSER_STRUCT_ENTRY, PARSER_STRUCT_LIST}, {PARSER_STRUCT_LIST, NODE_STRUCT_LIST, 1, 0, PARSER_STRUCT_ENTRY}, {PARSER_STRUCT_ENTRY, NODE_NONE, 3, 1, TOKEN_VAR, PARSER_STRUCT_VALUES, TOKEN_END_STATEMENT}, {PARSER_STRUCT_ENTRY, NODE_NONE, 1, 0, PARSER_FUNCTION}, {PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 1, 0, TOKEN_IDENTIFIER}, {PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 2, 1, TOKEN_MOD, TOKEN_IDENTIFIER}, {PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 3, 0, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_STRUCT_VALUES}, {PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 4, 1, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_STRUCT_VALUES}, {PARSER_FUNCTION, NODE_IGNORE, 1, 0, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_FUNCTION_ALIAS, 5, 3, TOKEN_ALIAS, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_END_STATEMENT}, //{PARSER_FUNCTION, NODE_DLL32, 4, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT}, //{PARSER_FUNCTION, NODE_DLL64, 4, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL32, 5, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_STRING, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL64, 5, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_STRING, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL32, 4, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL64, 4, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL_FUNCTION, 6, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL_FUNCTION, 7, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_STRING, PARSER_DLL_ARG_LIST, TOKEN_END_STATEMENT}, {PARSER_FUNCTION, NODE_DLL_FUNCTION_SIMPLE, 7, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_STRING, PARSER_DLL_ARG_LIST, TOKEN_END_STATEMENT}, // Hack to allow 0 element list. {PARSER_DLL_ARG_LIST, NODE_DLL_ARG, 2, 0, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN}, {PARSER_DLL_ARG_LIST, NODE_NONE, 3, 0, TOKEN_OPEN_PAREN, PARSER_DLL_ARGS, TOKEN_CLOSE_PAREN}, {PARSER_DLL_ARGS, NODE_DLL_ARGS, 1, 0, PARSER_DLL_ARG}, {PARSER_DLL_ARGS, NODE_DLL_ARGS, 3, 0, PARSER_DLL_ARG, TOKEN_COMMA, PARSER_DLL_ARGS}, {PARSER_DLL_ARG, NODE_DLL_ARG, 2, 0, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER}, {PARSER_DLL_ARG, NODE_DLL_ARG, 1, 0, TOKEN_IDENTIFIER}, {PARSER_FUNCTION, NODE_FUNCTION, 6, 0, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_IDENTIFIER_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK}, {PARSER_FUNCTION, NODE_FUNCTION, 5, 0, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK}, {PARSER_STRUCT_ENTRY, NODE_FUNCTION, 7, 0, TOKEN_FUNCTION, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_IDENTIFIER_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK}, {PARSER_STRUCT_ENTRY, NODE_FUNCTION, 6, 0, TOKEN_FUNCTION, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK}, //{PARSER_SIMPLE_EXPRESSION, NODE_FUNCTION_CALL, 3, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN}, {PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_REF_CALL, 8, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_CALL, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_REF_CALL, 6, 0, TOKEN_CALL, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_FUNCTION_CALL, 2, 0, TOKEN_IDENTIFIER, PARSER_VALUE_LIST}, {PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_FUNCTION_CALL, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST}, {PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_FUNCTION_CALL, 5, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_MOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST}, {PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_THIS_FUNCTION_CALL, 3, 0, TOKEN_MOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST}, //{PARSER_FUNCTION_CALL, NODE_FUNCTION_CALL, 4, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_LIST, TOKEN_CLOSE_PAREN}, {PARSER_VALUE_LIST, NODE_MAKE_COPY, 4, 0, TOKEN_OPEN_PAREN, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_VALUE_LIST, NODE_LIST_CREATE, 3, 0, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_VALUE_LIST, NODE_EMPTY_LIST, 2, 0, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN}, {PARSER_VALUE_LIST, NODE_LIST_ADD_NULL, 3, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_VALUE_LIST, NODE_LIST_ADD, 4, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_VALUE_LIST, NODE_APPEND, 5, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_LIST}, //{PARSER_LIST, NODE_LIST_ADD_NULL, 4, TOKEN_LIST, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN}, //{PARSER_LIST, NODE_LIST_CREATE, 4, TOKEN_LIST, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, //{PARSER_LIST, NODE_EMPTY_LIST, 3, TOKEN_LIST, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN}, // {PARSER_SIMPLE_EXPRESSION, NODE_DICT_TO_LIST, 4, 0, TOKEN_DICT_TO_LIST, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_LIST, NODE_NONE, 4, 0, TOKEN_OPEN_PAREN, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_LIST, NODE_LIST_ADD_NULL, 3, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_LIST, NODE_LIST_ADD, 4, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_LIST, NODE_APPEND, 5, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, //{PARSER_LIST, NODE_LIST_CREATE, 4, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, TOKEN_CLOSE_PAREN}, //{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 3, PARSER_LIST_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION}, {PARSER_LIST_EXPRESSION, NODE_LIST_ADD, 3, 0, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_COMMA}, {PARSER_LIST_EXPRESSION, NODE_LIST_ADD_NULL, 2, 0, PARSER_LIST_EXPRESSION, TOKEN_COMMA}, {PARSER_LIST_EXPRESSION, NODE_APPEND, 4, 0, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_COMMA}, {PARSER_LIST_EXPRESSION, NODE_LIST_CREATE_NULL, 1, 0, TOKEN_COMMA}, //{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 2, PARSER_EXPRESSION, TOKEN_COMMA}, {PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 2, 0, PARSER_EXPRESSION, TOKEN_COMMA}, {PARSER_LIST_EXPRESSION, NODE_NONE, 3, 0, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_COMMA}, {PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_DICT}, {PARSER_DICT, NODE_NONE, 4, 0, TOKEN_DICT, TOKEN_OPEN_PAREN, PARSER_DICT_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_DICT, NODE_NONE, 3, 0, TOKEN_OPEN_PAREN, PARSER_DICT_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_DICT, NODE_EMPTY_DICT, 3, 0, TOKEN_DICT, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN}, {PARSER_DICT_EXPRESSION, NODE_APPEND, 3, 0, PARSER_DICT_EXPRESSION, TOKEN_COMMA, PARSER_MINI_DICT_EXPRESSION}, {PARSER_DICT_EXPRESSION, NODE_NONE, 1, 0, PARSER_MINI_DICT_EXPRESSION}, {PARSER_MINI_DICT_EXPRESSION, NODE_DICT_CREATE, 3, 0, PARSER_EXPRESSION, TOKEN_COLON, PARSER_EXPRESSION}, {PARSER_MINI_DICT_EXPRESSION, NODE_MAKE_COPY, 2, 0, TOKEN_APPEND, PARSER_EXPRESSION}, {PARSER_SIMPLE_EXPRESSION, NODE_SIZE, 4, 0, TOKEN_SIZE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 3, 0, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_IDENTIFIER_LIST}, {PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 1, 0, TOKEN_IDENTIFIER}, {PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 4, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_IDENTIFIER_LIST}, {PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 2, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER}, {PARSER_STATEMENT_LIST, NODE_NONE, 1, 0, PARSER_STATEMENT}, {PARSER_STATEMENT_LIST, NODE_STATEMENT_LIST, 2, 0, PARSER_STATEMENT_LIST, PARSER_STATEMENT}, {PARSER_STATEMENT_BLOCK, NODE_NONE, 3, 0, TOKEN_OPEN_CODE, PARSER_STATEMENT_LIST, TOKEN_CLOSE_CODE}, {PARSER_STATEMENT_BLOCK, NODE_EMPTY, 2, 0, TOKEN_OPEN_CODE, TOKEN_CLOSE_CODE}, {PARSER_STATEMENT, NODE_DISCARD_LAST, 2, 0, PARSER_EXPRESSION, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_NONE, 1, 0, PARSER_STATEMENT_BLOCK}, //{PARSER_STATEMENT, NODE_DISCARD_FIRST, 1, PARSER_IF}, //{PARSER_STATEMENT, NODE_DISCARD_FIRST, 1, PARSER_IF_ELSE}, //{PARSER_STATEMENT, NODE_NONE, 1, PARSER_RETURN}, //{PARSER_RETURN, NODE_RETURN, 3, TOKEN_RETURN, PARSER_EXPRESSION, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_RETURN, 3, 0, TOKEN_RETURN, PARSER_EXPRESSION, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_RETURN, 2, 0, TOKEN_RETURN, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_BREAK, 2, 0, TOKEN_BREAK, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_CONTINUE, 2, 0, TOKEN_CONTINUE, TOKEN_END_STATEMENT}, {PARSER_STATEMENT, NODE_FOR, 7, 0, TOKEN_FOR, TOKEN_OPEN_PAREN, PARSER_FOR_PRE_STATEMENT_LIST, PARSER_EXPRESSION, PARSER_FOR_POST_STATEMENT_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT}, {PARSER_FOR_PRE_STATEMENT_LIST, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT}, {PARSER_FOR_POST_STATEMENT_LIST, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT}, {PARSER_FOR_PRE_STATEMENT_LIST, NODE_DISCARD_LAST, 2, 0, PARSER_FOR_SUB_STATEMENT_LIST, TOKEN_END_STATEMENT}, {PARSER_FOR_POST_STATEMENT_LIST, NODE_DISCARD_LAST, 2, 0, TOKEN_END_STATEMENT, PARSER_FOR_SUB_STATEMENT_LIST}, {PARSER_FOR_SUB_STATEMENT_LIST, NODE_NONE, 1, 0, PARSER_EXPRESSION}, {PARSER_FOR_SUB_STATEMENT_LIST, NODE_DISCARD_FIRST, 3, 0, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_FOR_SUB_STATEMENT_LIST}, {PARSER_STATEMENT, NODE_WHILE, 5, 0, TOKEN_WHILE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT}, {PARSER_STATEMENT, NODE_DO_WHILE, 7, 0, TOKEN_DO, PARSER_STATEMENT, TOKEN_WHILE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, TOKEN_END_STATEMENT}, //{PARSER_IF, NODE_IF, 5, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT}, //{PARSER_IF_ELSE, NODE_IF_ELSE, 7, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT, TOKEN_ELSE, PARSER_STATEMENT}, {PARSER_STATEMENT, NODE_IF, 5, 0, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT}, {PARSER_STATEMENT, NODE_IF_ELSE, 7, 0, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT, TOKEN_ELSE, PARSER_STATEMENT}, {PARSER_EXPRESSION, NODE_NONE, 1, 0, PARSER_ASSIGN_EXPRESSION}, //{PARSER_ASSIGN_EXPRESSION, NODE_ASSIGN, 3, PARSER_LOCAL_INDEX_EXPRESSION, TOKEN_ASSIGN, PARSER_ADD_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_CONCAT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_CONCATE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_MUL_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_MULE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_DIV_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_DIVE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_MOD_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_MODE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_ADD_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ADDE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_SUB_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_SUBE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_AND_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ANDE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_XOR_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_XORE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_OR_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ORE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_LSHIFT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_LSHIFTE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_RSHIFT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_RSHIFTE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_CONCAT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_CONCATE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_MUL_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_MULE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_DIV_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_DIVE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_MOD_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_MODE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_ADD_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ADDE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_SUB_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_SUBE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_AND_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ANDE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_XOR_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_XORE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_OR_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ORE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_LSHIFT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_LSHIFTE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_RSHIFT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_RSHIFTE, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ASSIGN, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ASSIGN, PARSER_ASSIGN_EXPRESSION}, {PARSER_ASSIGN_EXPRESSION, NODE_NONE, 1, 0, PARSER_APPEND_EXPRESSION}, {PARSER_APPEND_EXPRESSION, NODE_APPEND, 3, 1, PARSER_APPEND_EXPRESSION, TOKEN_APPEND, PARSER_BOOL_OR_EXPRESSION}, {PARSER_APPEND_EXPRESSION, NODE_NONE, 1, 0, PARSER_BOOL_OR_EXPRESSION}, {PARSER_BOOL_OR_EXPRESSION, NODE_BOOL_OR, 3, 1, PARSER_BOOL_OR_EXPRESSION, TOKEN_BOOL_OR, PARSER_BOOL_AND_EXPRESSION}, {PARSER_BOOL_OR_EXPRESSION, NODE_NONE, 1, 0, PARSER_BOOL_AND_EXPRESSION}, {PARSER_BOOL_AND_EXPRESSION, NODE_BOOL_AND, 3, 1, PARSER_BOOL_AND_EXPRESSION, TOKEN_BOOL_AND, PARSER_OR_EXPRESSION}, {PARSER_BOOL_AND_EXPRESSION, NODE_NONE, 1, 0, PARSER_OR_EXPRESSION}, {PARSER_OR_EXPRESSION, NODE_OR, 3, 1, PARSER_OR_EXPRESSION, TOKEN_OR, PARSER_XOR_EXPRESSION}, {PARSER_OR_EXPRESSION, NODE_NONE, 1, 0, PARSER_XOR_EXPRESSION}, {PARSER_XOR_EXPRESSION, NODE_XOR, 3, 1, PARSER_XOR_EXPRESSION, TOKEN_XOR, PARSER_AND_EXPRESSION}, {PARSER_XOR_EXPRESSION, NODE_NONE, 1, 0, PARSER_AND_EXPRESSION}, {PARSER_AND_EXPRESSION, NODE_AND, 3, 1, PARSER_AND_EXPRESSION, TOKEN_AND, PARSER_EQUALS_EXPRESSION}, {PARSER_AND_EXPRESSION, NODE_NONE, 1, 0, PARSER_EQUALS_EXPRESSION}, {PARSER_EQUALS_EXPRESSION, NODE_E, 3, 1, PARSER_EQUALS_EXPRESSION, TOKEN_E, PARSER_COMPARE_EXPRESSION}, {PARSER_EQUALS_EXPRESSION, NODE_NE, 3, 1, PARSER_EQUALS_EXPRESSION, TOKEN_NE, PARSER_COMPARE_EXPRESSION}, {PARSER_EQUALS_EXPRESSION, NODE_NONE, 1, 0, PARSER_COMPARE_EXPRESSION}, {PARSER_COMPARE_EXPRESSION, NODE_L, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_L, PARSER_COMPARE_STRING_EXPRESSION}, {PARSER_COMPARE_EXPRESSION, NODE_LE, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_LE, PARSER_COMPARE_STRING_EXPRESSION}, {PARSER_COMPARE_EXPRESSION, NODE_G, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_G, PARSER_COMPARE_STRING_EXPRESSION}, {PARSER_COMPARE_EXPRESSION, NODE_GE, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_GE, PARSER_COMPARE_STRING_EXPRESSION}, {PARSER_COMPARE_EXPRESSION, NODE_NONE, 1, 0, PARSER_COMPARE_STRING_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_E, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_NE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCINE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_L, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIL, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_LE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCILE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_G, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIG, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_GE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIGE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_S_E, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_S_NE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SNE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_S_L, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SL, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_S_LE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SLE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_S_G, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SG, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_S_GE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SGE, PARSER_CONCAT_EXPRESSION}, {PARSER_COMPARE_STRING_EXPRESSION, NODE_NONE, 1, 0, PARSER_CONCAT_EXPRESSION}, {PARSER_CONCAT_EXPRESSION, NODE_CONCAT_STRING, 3, 1, PARSER_CONCAT_EXPRESSION, TOKEN_CONCAT, PARSER_SHIFT_EXPRESSION}, {PARSER_CONCAT_EXPRESSION, NODE_NONE, 1, 0, PARSER_SHIFT_EXPRESSION}, {PARSER_SHIFT_EXPRESSION, NODE_LSHIFT, 3, 1, PARSER_SHIFT_EXPRESSION, TOKEN_LSHIFT, PARSER_ADD_EXPRESSION}, {PARSER_SHIFT_EXPRESSION, NODE_RSHIFT, 3, 1, PARSER_SHIFT_EXPRESSION, TOKEN_RSHIFT, PARSER_ADD_EXPRESSION}, {PARSER_SHIFT_EXPRESSION, NODE_NONE, 1, 0, PARSER_ADD_EXPRESSION}, {PARSER_ADD_EXPRESSION, NODE_ADD, 3, 1, PARSER_ADD_EXPRESSION, TOKEN_ADD, PARSER_MUL_EXPRESSION}, {PARSER_ADD_EXPRESSION, NODE_SUB, 3, 1, PARSER_ADD_EXPRESSION, TOKEN_SUB, PARSER_MUL_EXPRESSION}, {PARSER_ADD_EXPRESSION, NODE_NONE, 1, 0, PARSER_MUL_EXPRESSION}, {PARSER_MUL_EXPRESSION, NODE_MUL, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_MUL, PARSER_PREFIX_EXPRESSION}, {PARSER_MUL_EXPRESSION, NODE_MOD, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_MOD, PARSER_PREFIX_EXPRESSION}, {PARSER_MUL_EXPRESSION, NODE_DIV, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_DIV, PARSER_PREFIX_EXPRESSION}, {PARSER_MUL_EXPRESSION, NODE_NONE, 1, 0, PARSER_PREFIX_EXPRESSION}, {PARSER_PREFIX_EXPRESSION, NODE_NOT, 2, 0, TOKEN_NOT, PARSER_PREFIX_EXPRESSION}, {PARSER_PREFIX_EXPRESSION, NODE_NEG, 2, 0, TOKEN_SUB, PARSER_PREFIX_EXPRESSION}, {PARSER_PREFIX_EXPRESSION, NODE_BIN_NEG, 2, 0, TOKEN_TILDE, PARSER_PREFIX_EXPRESSION}, {PARSER_PREFIX_EXPRESSION, NODE_NONE, 2, 0, TOKEN_ADD, PARSER_PREFIX_EXPRESSION}, {PARSER_PREFIX_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_EXPRESSION}, //{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, PARSER_FUNCTION_CALL}, {PARSER_SIMPLE_EXPRESSION, NODE_INT, 1, 0, TOKEN_INT}, {PARSER_SIMPLE_EXPRESSION, NODE_DOUBLE, 1, 0, TOKEN_DOUBLE}, //{PARSER_SIMPLE_EXPRESSION, NODE_IDENTIFIER, 1, TOKEN_IDENTIFIER}, {PARSER_SIMPLE_EXPRESSION, NODE_STRING, 1, 0, TOKEN_STRING}, {PARSER_SIMPLE_EXPRESSION, NODE_NONE, 3, 1, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN}, {PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_POSTMOD_EXPRESSION}, //{PARSER_SIMPLE_EXPRESSION2, NODE_NONE, 1, 0, PARSER_SIMPLE_EXPRESSION}, {PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_PREMOD_EXPRESSION}, {PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_SIMPLE_POST_INC, 2, 1, PARSER_SIMPLE_POSTMOD_EXPRESSION, TOKEN_INC}, {PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_SIMPLE_POST_DEC, 2, 1, PARSER_SIMPLE_POSTMOD_EXPRESSION, TOKEN_DEC}, {PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_DEREFERENCE_EXPRESSION}, {PARSER_DEREFERENCE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_DEREFERENCE_EXPRESSION}, {PARSER_DEREFERENCE_EXPRESSION, NODE_DEREFERENCE, 1, 0, PARSER_IDENTIFIER_EXPRESSION}, {PARSER_DEREFERENCE_EXPRESSION, NODE_SUB_REFERENCE, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, {PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_DEREFERENCE, 1, 0, PARSER_IDENTIFIER_EXPRESSION}, {PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_SIMPLE_PRE_INC, 2, 0, TOKEN_INC, PARSER_SIMPLE_PREMOD_EXPRESSION}, {PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_SIMPLE_PRE_DEC, 2, 0, TOKEN_DEC, PARSER_SIMPLE_PREMOD_EXPRESSION}, //{PARSER_SIMPLE_EXPRESSION, NODE_DEREFERENCE, 1, PARSER_IDENTIFIER_EXPRESSION}, //{PARSER_INDEX_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_INDEX_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //{PARSER_SIMPLE_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //{PARSER_SIMPLE_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //{PARSER_ELEMENT_PREMOD_IDENTIFIER, NODE_NONE, 1, PARSER_SIMPLE_EXPRESSION}, //{PARSER_ELEMENT_PREPREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_ELEMENT_PREPREMOD_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //{PARSER_ELEMENT_PREPREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_ELEMENT_PREMOD_IDENTIFIER, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //{PARSER_ELEMENT_PREMOD_IDENTIFIER, NODE_DEREFERENCE, 1, PARSER_IDENTIFIER_EXPRESSION}, {PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, {PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_ELEMENT_PRE_INC, 2, 0, TOKEN_INC, PARSER_ELEMENT_PREMOD_EXPRESSION}, {PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_ELEMENT_PRE_DEC, 2, 0, TOKEN_DEC, PARSER_ELEMENT_PREMOD_EXPRESSION}, {PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_NONE, 1, 0, PARSER_ELEMENT_PREMOD_EXPRESSION}, {PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_ELEMENT_POST_INC, 2, 1, PARSER_ELEMENT_POSTMOD_EXPRESSION, TOKEN_INC}, {PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_ELEMENT_POST_DEC, 2, 1, PARSER_ELEMENT_POSTMOD_EXPRESSION, TOKEN_DEC}, {PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_ELEMENT_POSTMOD_EXPRESSION}, //{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_NONE, 1, PARSER_ELEMENT_PREPREMOD_EXPRESSION}, //{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //{SIMPLE_EXPRESSION, NODE_DEREFERENCE, 4, PARSER_IDENTIFIER_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, {PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 3, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER}, {PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 4, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_MOD, TOKEN_IDENTIFIER}, //{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 3, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER}, {PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_THIS_REFERENCE, 2, 0, TOKEN_MOD, TOKEN_IDENTIFIER}, {PARSER_IDENTIFIER_EXPRESSION, NODE_LOCAL_REFERENCE, 2, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER}, {PARSER_IDENTIFIER_EXPRESSION, NODE_GLOBAL_REFERENCE, 1, 0, TOKEN_IDENTIFIER}, //{PARSER_INDEX_EXPRESSION, NODE_REFERENCE, 4, PARSER_INDEX_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET}, //*/ }; #define NUM_RULES (sizeof(rules)/sizeof(Rule)) struct Item { int transition; int rule; int position; }; struct ItemSet { int numItems; Item items[1]; }; int CalcClosure(ItemSet **s, int *mem, int id) { int k = s[0]->numItems; int maxSize = k; int numCare = k; for (int j=0; j<numCare; j++) { int position = s[0]->items[j].position; const Rule *rule = &rules[s[0]->items[j].rule]; if (position >= rule->numTerms) continue; int term = rule->terms[position]; for (int i=1; i<NUM_RULES; i++) { if (term != rules[i].result) continue; if (mem[i] == id) break; if (k < maxSize || (srealloc(s[0], sizeof(ItemSet)+sizeof(Item)*(maxSize+16)) && (maxSize+=16))) { mem[i] = id; int q; for (q = 0; q<numCare; q++) { if (rules[s[0]->items[q].rule].terms[s[0]->items[q].position] == rules[i].terms[0]) { break; } } int out = k; if (q == numCare && rules[i].terms[0] > TOKEN_END) { s[0]->items[k] = s[0]->items[numCare]; out = numCare++; } s[0]->items[out].rule = i; s[0]->items[out].position = 0; s[0]->items[out].transition = -1; s[0]->numItems = ++k; } } } return 1; } void CleanupTree(ParseTree *t) { if (t->val) free(t->val); for (int i=0; i<t->numChildren; i++) { if (t->children[i]) CleanupTree(t->children[i]); } free(t); } void ParseError(Token *token) { errorPrintf(2, "Parse error, line %i:\r\n", token->line); errors++; DisplayErrorLine(token->start, token->pos); } int *actionTable = 0; ParseTree * ParseScript(Token *tokens, int numTokens) { int i; if (numTokens == 1) { CleanupTokens(tokens, numTokens); return 0; } if (!actionTable) { int numSets = 0; ItemSet **set = (ItemSet**) malloc(sizeof(ItemSet*)*1000); ItemSet **newSets = (ItemSet**) malloc(sizeof(ItemSet*)*1000); if (!set || !newSets) { free(set); free(newSets); return 0; } int changed = 1; int *followSets = (int*) calloc(1, PARSER_NONE * sizeof(int) * PARSER_NONE); int *firstSets = (int*) calloc(1, PARSER_NONE * sizeof(int) * PARSER_NONE); for (i=0; i<PARSER_SCRIPT; i++) { firstSets[PARSER_NONE*i+i] = 1; } while (changed) { changed = 0; for (int r = 0; r<NUM_RULES; r++) { int R = rules[r].result; int F = rules[r].terms[0]; for (i=0; i<PARSER_NONE;i++) { if (firstSets[F*PARSER_NONE+i] && !firstSets[R*PARSER_NONE+i]) { firstSets[R*PARSER_NONE+i] = 1; changed = 1; } } } } changed = 1; while (changed) { changed = 0; for (int r = 0; r<NUM_RULES; r++) { for (int p=0; p<rules[r].numTerms-1; p++) { ScriptTokenType F = rules[r].terms[p]; ScriptTokenType S = rules[r].terms[p+1]; for (i=0; i<PARSER_NONE;i++) { if (firstSets[S*PARSER_NONE+i] && !followSets[F*PARSER_NONE+i]) { followSets[F*PARSER_NONE+i] = 1; changed = 1; } } } ScriptTokenType F = rules[r].terms[rules[r].numTerms-1]; ScriptTokenType S = rules[r].result; for (i=0; i<PARSER_NONE;i++) { if (followSets[S*PARSER_NONE+i] && !followSets[F*PARSER_NONE+i]) { followSets[F*PARSER_NONE+i] = 1; changed = 1; } } } } set[numSets++] = (ItemSet *) malloc(sizeof(ItemSet)); set[0]->numItems = 1; set[0]->items[0].position = 0; set[0]->items[0].rule = 0; int closureId = 0; int closureNotes[sizeof(rules) / sizeof(Rule)]; for (i=0; i<sizeof(closureNotes)/sizeof(int);i++) closureNotes[i] = -1; //memset(closureNotes, -1, sizeof(closureNotes)); CalcClosure(&set[0], closureNotes, closureId++); for (i=0; i<numSets; i++) { int numNewSets = 0; int j; for (j=0; j<set[i]->numItems; j++) { set[i]->items[j].transition = -1; if (set[i]->items[j].position != rules[set[i]->items[j].rule].numTerms) { int q; for (q=0; q<numNewSets; q++) { if (rules[set[i]->items[j].rule].terms[set[i]->items[j].position] == rules[newSets[q]->items[0].rule].terms[newSets[q]->items[0].position-1]) { srealloc(newSets[q] , sizeof(ItemSet) + sizeof(Item) * newSets[q]->numItems); break; } } if (q==numNewSets) { newSets[q] = (ItemSet*) malloc(sizeof(ItemSet)); newSets[q]->numItems = 0; numNewSets++; } newSets[q]->items[newSets[q]->numItems].position = set[i]->items[j].position+1; newSets[q]->items[newSets[q]->numItems].rule = set[i]->items[j].rule; newSets[q]->items[newSets[q]->numItems].transition = j; newSets[q]->numItems++; } } for (j=0; j<numNewSets; j++) { CalcClosure(&newSets[j], closureNotes, closureId++); int q = 0; for (q = 0; q<numSets; q++) { int match = 0; if (set[q]->numItems == newSets[j]->numItems) while (match < newSets[j]->numItems) { int f; for (f = 0; f<set[q]->numItems; f++) { if (set[q]->items[f].rule == newSets[j]->items[match].rule && set[q]->items[f].position == newSets[j]->items[match].position) break; } if (f == set[q]->numItems) break; match++; } if (match == newSets[j]->numItems) break; } for (int w=0; w<newSets[j]->numItems; w++) if (newSets[j]->items[w].transition >= 0) set[i]->items[newSets[j]->items[w].transition].transition = q; if (q<numSets) { free(newSets[j]); } else { set[numSets++] = newSets[j]; } } } free(newSets); actionTable = (int*) malloc(sizeof(int) * numSets*PARSER_NONE); for (i=numSets*PARSER_NONE-1; i>=0;i--) { actionTable[i] = -1; } for (i=0; i<numSets; i++) { int reduce = 0; for (int w=0; w<set[i]->numItems; w++) { if (set[i]->items[w].position < rules[set[i]->items[w].rule].numTerms) { int term = rules[set[i]->items[w].rule].terms[set[i]->items[w].position]; if (actionTable[i*PARSER_NONE+term]>=0&& (actionTable[i*PARSER_NONE+term]&0xFFFFFF)-set[i]->items[w].transition !=0) { i=i; } actionTable[i*PARSER_NONE+term] = set[i]->items[w].transition; if (term < PARSER_SCRIPT) { if (term != TOKEN_END) actionTable[i*PARSER_NONE+term] |= SHIFT; else actionTable[i*PARSER_NONE+term] = ACCEPT; } /* if (rules[set[i]->items[w].rule].terms[set[i]->items[w].position] < S) { actionTable[i*PARSER_NONE+set[i]->items[w].rule] = set[i]->items[w].transition; else actionTable[i*PARSER_NONE+set[i]->items[w].rule] |= SHIFT; }//*/ } else { /*if (reduce && reduce != set[i]->items[w].rule) { reduce = reduce; } reduce = set[i]->items[w].rule; //*/ reduce = set[i]->items[w].rule; for (int x = 0; x<PARSER_SCRIPT; x++) { if (followSets[rules[reduce].result*PARSER_NONE+x]) { if (actionTable[x+i*PARSER_NONE] == -1) { actionTable[x+i*PARSER_NONE] = REDUCE | reduce; } else { i=i; } } } } } /*if (reduce) { for (int w = 0; w<PARSER_SCRIPT; w++) { if (actionTable[w+i*PARSER_NONE] == -1) { actionTable[w+i*PARSER_NONE] = REDUCE | reduce; } } }*/ } free(followSets); free(firstSets); for (i=0; i<numSets; i++) { free(set[i]); } free(set); } int maxStackSize = 1000; int *stack = (int*) malloc(sizeof(int) * 1000); //int output[1000]; stack[0] = 0; //int outputLen = 0; int stackSize = 1; int pos = 0; int accept = 0; int ParseTrees = 0; int maxParseTrees = 1000; ParseTree **tree = (ParseTree**) malloc(sizeof(ParseTree*) * 1000); int error = 0; while (pos < numTokens && stackSize > 0) { int row = stack[stackSize-1]; ScriptTokenType token = tokens[pos].type; int i = actionTable[token+row*PARSER_NONE]; if (i==-1) { if (pos && !tokens[pos].line) { ParseError(tokens+pos-1); } else { ParseError(tokens+pos); } error = 1; break; } else if ((i&ACTION_MASK) == SHIFT) { i &= ~SHIFT; if (stackSize == maxStackSize) { if (!srealloc(stack, sizeof(int) * (maxStackSize*=2))) { ParseError(tokens+pos); error = 1; break; } } if (ParseTrees == maxParseTrees) { if (!srealloc(tree, sizeof(ParseTree*) * (maxParseTrees*=2))) { ParseError(tokens+pos); error = 1; break; } } stack[stackSize++] = i; tree[ParseTrees] = (ParseTree*) calloc(1, sizeof(ParseTree)); if (!tree[ParseTrees]) { ParseError(tokens+pos); error = 1; break; } { tree[ParseTrees]->line = tokens[pos].line; tree[ParseTrees]->pos = tokens[pos].pos; tree[ParseTrees]->start = tokens[pos].start; } // Temporary node. Will be eaten by another. tree[ParseTrees]->type = NODE_LEAF; tree[ParseTrees]->numChildren = 0; tree[ParseTrees]->intVal = tokens[pos].intVal; tree[ParseTrees++]->val = tokens[pos].val; tokens[pos].val = 0; pos++; } else if ((i&ACTION_MASK) == REDUCE) { i &= ~REDUCE; // output[outputLen++] = i; ParseTree *children[5] = {0,0,0,0,0}; int numChildren = 0; int nline; unsigned char *npos; unsigned char *nstart; for (int j = 0; j<rules[i].numTerms; j++) { if (j == rules[i].operatorPos) { nline = tree[ParseTrees - rules[i].numTerms+j]->line; npos = tree[ParseTrees - rules[i].numTerms+j]->pos; nstart = tree[ParseTrees - rules[i].numTerms+j]->start; } if (rules[i].terms[j] <= TOKEN_IDENTIFIER || rules[i].terms[j]>=TOKEN_END) { children[numChildren++] = tree[ParseTrees - rules[i].numTerms+j]; } else { free(tree[ParseTrees - rules[i].numTerms+j]); tree[ParseTrees - rules[i].numTerms+j] = 0; } } ParseTrees -= rules[i].numTerms; if (rules[i].nodeType == NODE_NONE) { tree[ParseTrees] = children[0]; } else { if (numChildren && children[0]->type == NODE_LEAF) { tree[ParseTrees] = children[0]; } else { tree[ParseTrees] = (ParseTree*) calloc(1, sizeof(ParseTree)); if (!tree[ParseTrees]) { ParseError(tokens+pos); error = 1; break; } tree[ParseTrees]->children[0] = children[0]; } tree[ParseTrees]->numChildren = numChildren; tree[ParseTrees]->children[1] = children[1]; tree[ParseTrees]->children[2] = children[2]; tree[ParseTrees]->children[3] = children[3]; tree[ParseTrees]->children[4] = children[4]; tree[ParseTrees]->type = rules[i].nodeType; } tree[ParseTrees]->line = nline; tree[ParseTrees]->pos = npos; tree[ParseTrees]->start = nstart; ParseTrees++; stackSize -= rules[i].numTerms; if (stackSize <= 0) { ParseError(tokens+pos); error = 1; break; } else { int w = rules[i].result; int t = actionTable[stack[stackSize-1]*PARSER_NONE + w]; if (t >= 0 && t < 0x1000000) { stack[stackSize++] = t; } else { ParseError(tokens+pos); error = 1; break; } } } else if (i == ACCEPT) { accept = 1; break; } else { ParseError(tokens+pos); error = 1; break; } } free(stack); CleanupTokens(tokens, numTokens); if (error) { for (int i=0; i<ParseTrees; i++) { CleanupTree(tree[i]); } free(tree); return 0; } ParseTree *out = tree[0]; free(tree); return out; } void CleanupParser() { free(actionTable); actionTable = 0; }
49.791339
213
0.760048
MichaelMCE
9b73b78f9a528cba963dadd7c36bffc881a59b7f
4,198
cpp
C++
src/ossiarch/Katakros.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/ossiarch/Katakros.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/ossiarch/Katakros.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <UnitFactory.h> #include "ossiarch/Katakros.h" #include "OssiarchBonereaperPrivate.h" namespace OssiarchBonereapers { static const int g_basesize = 120; // x92 oval static const int g_wounds = 20; static const int g_pointsPerUnit = 470; bool Katakros::s_registered = false; Unit *Katakros::Create(const ParameterList &parameters) { auto legion = (Legion) GetEnumParam("Legion", parameters, g_legion[0]); auto general = GetBoolParam("General", parameters, false); return new Katakros(legion, general); } void Katakros::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { Katakros::Create, OssiarchBonereaperBase::ValueToString, OssiarchBonereaperBase::EnumStringToInt, Katakros::ComputePoints, { EnumParameter("Legion", g_legion[0], g_legion), BoolParameter("General") }, DEATH, {OSSIARCH_BONEREAPERS} }; s_registered = UnitFactory::Register("Orpheon Katakros", factoryMethod); } } Katakros::Katakros(Legion legion, bool isGeneral) : OssiarchBonereaperBase("Orpheon Katakros", 4, g_wounds, 10, 3, false, g_pointsPerUnit) { m_keywords = {DEATH, DEATHLORDS, OSSIARCH_BONEREAPERS, MORTIS_PRAETORIANS, LIEGE, HERO, KATAKROS}; m_weapons = {&m_indaKhaat, &m_shieldImmortis, &m_nadiriteDagger, &m_blades, &m_greatblade, &m_spiritDagger}; m_battleFieldRole = Role::Leader; setLegion(legion); setGeneral(isGeneral); auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_indaKhaat); model->addMeleeWeapon(&m_shieldImmortis); model->addMeleeWeapon(&m_nadiriteDagger); model->addMeleeWeapon(&m_blades); model->addMeleeWeapon(&m_greatblade); model->addMeleeWeapon(&m_spiritDagger); m_shieldImmortis.activate(false); addModel(model); } int Katakros::generateHits(int unmodifiedHitRoll, const Weapon *weapon, const Unit *unit) const { if ((unmodifiedHitRoll == 6) && ((weapon->name() == m_nadiriteDagger.name()) || (weapon->name() == m_blades.name()))) return 2; return OssiarchBonereaperBase::generateHits(unmodifiedHitRoll, weapon, unit); } void Katakros::onWounded() { OssiarchBonereaperBase::onWounded(); if (woundsTaken() >= 13) { m_shieldImmortis.activate(true); m_blades.activate(false); m_indaKhaat.setAttacks(4); } else if (woundsTaken() >= 8) { m_spiritDagger.activate(false); } else if (woundsTaken() >= 4) { m_greatblade.activate(false); m_indaKhaat.setAttacks(2); } else if (woundsTaken() >= 2) { m_nadiriteDagger.activate(false); } } Wounds Katakros::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const { // Deadly Combination if ((hitRoll == 6) && (weapon->name() == m_shieldImmortis.name())) { return {weapon->damage(), 2}; } return OssiarchBonereaperBase::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll); } int Katakros::ComputePoints(const ParameterList& /*parameters*/) { return g_pointsPerUnit; } void Katakros::onRestore() { OssiarchBonereaperBase::onRestore(); // Restore table-driven attributes onWounded(); // Defaults m_shieldImmortis.activate(false); m_blades.activate(true); m_indaKhaat.setAttacks(1); m_spiritDagger.activate(true); m_greatblade.activate(true); m_nadiriteDagger.activate(true); } } // namespace OssiarchBonereapers
35.576271
140
0.61696
rweyrauch
9b75f1f2214cae98acf730f268709fbce6f226cd
9,703
hpp
C++
redemption/src/core/RDP/tpdu_buffer.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/core/RDP/tpdu_buffer.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/core/RDP/tpdu_buffer.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Product name: redemption, a FLOSS RDP proxy * Copyright (C) Wallix 2013-2019 * Author(s): Jonathan Poelen */ #pragma once #include "core/buf64k.hpp" #include "utils/hexdump.hpp" #include "transport/transport.hpp" #include "core/RDP/x224.hpp" #include "utils/parse.hpp" namespace Extractors { enum { FASTPATH = 1, CR_TPDU = X224::CR_TPDU, // Connection Request 1110 xxxx CC_TPDU = X224::CC_TPDU, // Connection Confirm 1101 xxxx DR_TPDU = X224::DR_TPDU, // Disconnect Request 1000 0000 DT_TPDU = X224::DT_TPDU, // Data 1111 0000 (no ROA = No Ack) ER_TPDU = X224::ER_TPDU, // TPDU Error 0111 0000 }; struct HeaderResult { static HeaderResult fail() noexcept { return HeaderResult{}; } static HeaderResult ok(uint16_t n) noexcept { return HeaderResult{n}; } explicit operator bool () const noexcept { return this->is_extracted; } [[nodiscard]] uint16_t data_size() const noexcept { return this->len; } private: explicit HeaderResult() noexcept = default; explicit HeaderResult(uint16_t len) noexcept : is_extracted(true) , len(len) {} bool is_extracted{false}; uint16_t len; }; struct X224Extractor { HeaderResult read_header(Buf64k & buf) { // fast path header occupies 2 or 3 octets, but assume then data len at least 2 octets. if (buf.remaining() < 4) { return HeaderResult::fail(); } auto av = buf.av(4); uint16_t len; REDEMPTION_DIAGNOSTIC_PUSH() REDEMPTION_DIAGNOSTIC_CLANG_IGNORE("-Wcovered-switch-default") switch (FastPath::FASTPATH_OUTPUT(av[0] & 0x03)) { case FastPath::FASTPATH_OUTPUT_ACTION_FASTPATH: { len = av[1]; if (len & 0x80){ len = (len & 0x7F) << 8 | av[2]; // len -= 1; // buf.advance(1); } // len -= 1; // buf.advance(2); this->has_fast_path = true; this->type = Extractors::FASTPATH; } break; case FastPath::FASTPATH_OUTPUT_ACTION_X224: { len = Parse(av.subarray(2, 2).data()).in_uint16_be(); if (len < 6) { LOG(LOG_ERR, "Bad X224 header, length too short (length = %u)", len); throw Error(ERR_X224); } // len -= 4; // buf.advance(4); this->has_fast_path = false; } break; default: LOG(LOG_ERR, "Bad X224 header, unknown TPKT version (%.2x)", av[0]); throw Error(ERR_X224); } REDEMPTION_DIAGNOSTIC_POP() return HeaderResult::ok(len); } void prepare_data(Buf64k const & buf) { if (this->has_fast_path) { this->type = FASTPATH; return; } uint8_t tpdu_type = Parse(buf.sub(5, 1).data()).in_uint8(); switch (uint8_t(tpdu_type & 0xF0)) { case X224::CR_TPDU: // Connection Request 1110 xxxx this->type = Extractors::CR_TPDU; break; case X224::CC_TPDU: // Connection Confirm 1101 xxxx this->type = Extractors::CC_TPDU; break; case X224::DR_TPDU: // Disconnect Request 1000 0000 this->type = Extractors::DR_TPDU; break; case X224::DT_TPDU: // Data 1111 0000 (no ROA = No Ack) this->type = Extractors::DT_TPDU; break; case X224::ER_TPDU: // TPDU Error 0111 0000 this->type = Extractors::ER_TPDU; break; default: this->type = 0; LOG(LOG_ERR, "Bad X224 header, unknown TPDU type (code = %u)", tpdu_type); throw Error(ERR_X224); } } [[nodiscard]] uint8_t get_type() const noexcept { if (this->has_fast_path){ return Extractors::FASTPATH; } return this->type; } private: bool has_fast_path; uint8_t type; }; struct CreedsppExtractor { static HeaderResult read_header(Buf64k & buf) { if (buf.remaining() < 4) { return HeaderResult::fail(); } auto av = buf.av(4); if (av[1] <= 0x7F) { return HeaderResult::ok(av[1] + 2); } if (av[1] == 0x81) { return HeaderResult::ok(av[2] + 3); } if (av[1] == 0x82) { return HeaderResult::ok(((av[2] << 8) | av[3]) + 4); } throw Error(ERR_NEGO_INCONSISTENT_FLAGS); } static void prepare_data(Buf64k const & /*unused*/) {} }; } // namespace Extractors struct TpduBuffer { enum TpduType { PDU = 0, CREDSSP = 1, }; TpduBuffer() = default; void load_data(InTransport trans) { this->buf.read_from(trans); } [[nodiscard]] uint16_t remaining() const noexcept { return this->buf.remaining(); } u8_array_view remaining_data() noexcept { return this->buf.av(); } // Having two 'next' functions is a bit awkward. // Also it will work only if the buffer // knows how to consume the previous packet *and* the reader code // knows what the current packet type is (TPDU or CREDSSP) // Maybe something like below is possible: // bool next(TpduType packet) // { // switch (packet){ // case PACKET_TPDU: // return this->extract(this->extractors.x224); // case PACKET_CREDSSP: // return this->extract(this->extractors.credssp); // } // } // or fully extracting the knowledge of the Tpdu structure. // Write tests with both CredSSP and Tpdu and see how it looks. bool next(TpduType packet) { switch (packet){ case PDU: return this->extract(this->extractors.x224); case CREDSSP: return this->extract(this->extractors.credssp); } REDEMPTION_UNREACHABLE(); } // Works the same way for CREDSSP or PDU // We can use it to trace CREDSSP buffer writable_u8_array_view current_pdu_buffer() noexcept { assert(this->pdu_len); auto av = this->buf.av(this->pdu_len); if (this->trace_pdu){ ::hexdump_d(av); } return av; } [[nodiscard]] uint8_t current_pdu_get_type() const noexcept { assert(this->pdu_len); return this->extractors.x224.get_type(); } void consume_current_packet() noexcept { this->buf.advance(this->pdu_len); this->pdu_len = 0; } private: enum class StateRead : bool { Header, Data, }; struct Extractor // Extractor concept { Extractors::HeaderResult read_header(Buf64k& buf); void check_data(Buf64k const &) const; }; template<class Extractor> bool extract(Extractor & extractor) { if (this->data_ready){ this->data_ready = false; return true; } switch (this->state) { case StateRead::Header: this->consume_current_packet(); if (auto r = extractor.read_header(this->buf)) { this->pdu_len = r.data_size(); if (this->pdu_len <= this->buf.remaining()) { extractor.prepare_data(this->buf); return true; } this->state = StateRead::Data; } return false; case StateRead::Data: if (this->pdu_len <= this->buf.remaining()) { this->state = StateRead::Header; extractor.prepare_data(this->buf); return true; } return false; } } StateRead state = StateRead::Header; union U { Extractors::X224Extractor x224; Extractors::CreedsppExtractor credssp; char dummy; U():dummy() {} } extractors; uint16_t pdu_len = 0; Buf64k buf; bool data_ready = false; public: bool trace_pdu = false; };
28.622419
99
0.514068
DianaAssistant
9b78ede68f1cf46c0fa464ce85795cc3441fc52c
4,099
cpp
C++
libpandabase/tests/type_converter_tests.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
1
2021-09-09T03:17:23.000Z
2021-09-09T03:17:23.000Z
libpandabase/tests/type_converter_tests.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
null
null
null
libpandabase/tests/type_converter_tests.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
1
2021-09-13T11:21:57.000Z
2021-09-13T11:21:57.000Z
/* * 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 "utils/type_converter.h" #include <sstream> #include <random> #include <gtest/gtest.h> #ifndef PANDA_NIGHTLY_TEST_ON constexpr size_t ITERATION = 64; #else constexpr size_t ITERATION = 1024; #endif namespace panda::helpers::test { TEST(TimeTest, RandomTimeConverterTest) { std::mt19937 gen; std::uniform_int_distribution<time_t> distrib_nanos_right(0, 1e3 - 1); std::uniform_int_distribution<time_t> distrib_nanos_left(1, 23); for (size_t i = 0; i < ITERATION; i++) { uint64_t left_part_time = distrib_nanos_left(gen); uint64_t right_part_time = distrib_nanos_right(gen); ASSERT_NE(TimeConverter(left_part_time), ValueUnit(left_part_time, "ns")); ASSERT_NE(TimeConverter(right_part_time), ValueUnit(right_part_time, "ns")); ASSERT_EQ(TimeConverter(left_part_time), ValueUnit(static_cast<double>(left_part_time), "ns")); ASSERT_EQ(TimeConverter(right_part_time), ValueUnit(static_cast<double>(right_part_time), "ns")); double expected = left_part_time + right_part_time * 1e-3; uint64_t nanos = left_part_time * 1e3 + right_part_time; ASSERT_EQ(TimeConverter(nanos), ValueUnit(expected, "us")); ASSERT_EQ(TimeConverter(nanos * 1e3), ValueUnit(expected, "ms")); ASSERT_EQ(TimeConverter(nanos * 1e6), ValueUnit(expected, "s")); ASSERT_EQ(TimeConverter(nanos * 1e6 * 60), ValueUnit(expected, "m")); ASSERT_EQ(TimeConverter(nanos * 1e6 * 60 * 60), ValueUnit(expected, "h")); ASSERT_EQ(TimeConverter(nanos * 1e6 * 60 * 60 * 24), ValueUnit(expected, "day")); } } TEST(TimeTest, RoundTimeConverterTest) { ASSERT_EQ(TimeConverter(11'119'272), ValueUnit(11.119, "ms")); ASSERT_EQ(TimeConverter(11'119'472), ValueUnit(11.119, "ms")); ASSERT_EQ(TimeConverter(11'119'499), ValueUnit(11.119, "ms")); ASSERT_EQ(TimeConverter(11'119'500), ValueUnit(11.120, "ms")); ASSERT_EQ(TimeConverter(11'119'572), ValueUnit(11.120, "ms")); ASSERT_EQ(TimeConverter(11'119'999), ValueUnit(11.120, "ms")); } TEST(MemoryTest, RandomMemoryConverterTest) { std::mt19937 gen; std::uniform_int_distribution<uint64_t> distrib_bytes(1, 1023); for (size_t i = 0; i < ITERATION; i++) { uint64_t left_part_bytes = distrib_bytes(gen); uint64_t right_part_bytes = distrib_bytes(gen); ASSERT_NE(MemoryConverter(left_part_bytes), ValueUnit(left_part_bytes, "B")); ASSERT_NE(MemoryConverter(right_part_bytes), ValueUnit(right_part_bytes, "B")); ASSERT_EQ(MemoryConverter(left_part_bytes), ValueUnit(static_cast<double>(left_part_bytes), "B")); ASSERT_EQ(MemoryConverter(right_part_bytes), ValueUnit(static_cast<double>(right_part_bytes), "B")); double expected = left_part_bytes + right_part_bytes * 1e-3; uint64_t bytes = left_part_bytes * 1024 + right_part_bytes; ASSERT_EQ(MemoryConverter(bytes), ValueUnit(expected, "KB")); ASSERT_EQ(MemoryConverter(bytes * (1UL << 10)), ValueUnit(expected, "MB")); ASSERT_EQ(MemoryConverter(bytes * (1UL << 20)), ValueUnit(expected, "GB")); ASSERT_EQ(MemoryConverter(bytes * (1UL << 30)), ValueUnit(expected, "TB")); } } TEST(MemoryTest, RoundMemoryConverterTest) { ASSERT_EQ(MemoryConverter(11'119'272), ValueUnit(10.604, "MB")); ASSERT_EQ(MemoryConverter(11'120'149), ValueUnit(10.605, "MB")); ASSERT_EQ(MemoryConverter(11'121'092), ValueUnit(10.606, "MB")); } } // namespace panda::helpers::test
43.147368
108
0.706758
openharmony-gitee-mirror
9b7950992e4d849dbac86ca9d939085a949e337a
19,891
cpp
C++
cplus/libcfint/CFIntSubProjectEditObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntSubProjectEditObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntSubProjectEditObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
// Description: C++18 edit object instance implementation for CFInt SubProject. /* * org.msscf.msscf.CFInt * * Copyright (c) 2020 Mark Stephen Sobkow * * MSS Code Factory CFInt 2.13 Internet Essentials * * Copyright 2020-2021 Mark Stephen Sobkow * * This file is part of MSS Code Factory. * * MSS Code Factory is available under dual commercial license from Mark Stephen * Sobkow, or under the terms of the GNU General Public License, Version 3 * or later. * * MSS Code Factory is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MSS Code Factory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MSS Code Factory. If not, see <https://www.gnu.org/licenses/>. * * Donations to support MSS Code Factory can be made at * https://www.paypal.com/paypalme2/MarkSobkow * * Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing. * * Manufactured by MSS Code Factory 2.12 */ #include <cflib/ICFLibPublic.hpp> using namespace std; #include <cfint/ICFIntPublic.hpp> #include <cfintobj/ICFIntObjPublic.hpp> #include <cfintobj/CFIntSubProjectObj.hpp> #include <cfintobj/CFIntSubProjectEditObj.hpp> namespace cfint { const std::string CFIntSubProjectEditObj::CLASS_NAME( "CFIntSubProjectEditObj" ); CFIntSubProjectEditObj::CFIntSubProjectEditObj( cfint::ICFIntSubProjectObj* argOrig ) : ICFIntSubProjectEditObj() { static const std::string S_ProcName( "CFIntSubProjectEditObj-construct" ); static const std::string S_OrigBuff( "origBuff" ); orig = argOrig; cfint::CFIntSubProjectBuff* origBuff = orig->getBuff(); if( origBuff == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_OrigBuff ); } buff = dynamic_cast<cfint::CFIntSubProjectBuff*>( origBuff->clone() ); } CFIntSubProjectEditObj::~CFIntSubProjectEditObj() { orig = NULL; if( buff != NULL ) { delete buff; buff = NULL; } } const std::string& CFIntSubProjectEditObj::getClassName() const { return( CLASS_NAME ); } cfsec::ICFSecSecUserObj* CFIntSubProjectEditObj::getCreatedBy() { if( createdBy == NULL ) { createdBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getSubProjectBuff()->getCreatedByUserId() ); } return( createdBy ); } const std::chrono::system_clock::time_point& CFIntSubProjectEditObj::getCreatedAt() { return( getSubProjectBuff()->getCreatedAt() ); } cfsec::ICFSecSecUserObj* CFIntSubProjectEditObj::getUpdatedBy() { if( updatedBy == NULL ) { updatedBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getSubProjectBuff()->getUpdatedByUserId() ); } return( updatedBy ); } const std::chrono::system_clock::time_point& CFIntSubProjectEditObj::getUpdatedAt() { return( getSubProjectBuff()->getUpdatedAt() ); } void CFIntSubProjectEditObj::setCreatedBy( cfsec::ICFSecSecUserObj* value ) { createdBy = value; if( value != NULL ) { getSubProjectEditBuff()->setCreatedByUserId( value->getRequiredSecUserIdReference() ); } } void CFIntSubProjectEditObj::setCreatedAt( const std::chrono::system_clock::time_point& value ) { getSubProjectEditBuff()->setCreatedAt( value ); } void CFIntSubProjectEditObj::setUpdatedBy( cfsec::ICFSecSecUserObj* value ) { updatedBy = value; if( value != NULL ) { getSubProjectEditBuff()->setUpdatedByUserId( value->getRequiredSecUserIdReference() ); } } void CFIntSubProjectEditObj::setUpdatedAt( const std::chrono::system_clock::time_point& value ) { getSubProjectEditBuff()->setUpdatedAt( value ); } const classcode_t CFIntSubProjectEditObj::getClassCode() const { return( cfint::CFIntSubProjectBuff::CLASS_CODE ); } bool CFIntSubProjectEditObj::implementsClassCode( const classcode_t value ) const { if( value == cfint::CFIntSubProjectBuff::CLASS_CODE ) { return( true ); } else { return( false ); } } std::string CFIntSubProjectEditObj::toString() { static const std::string S_Space( " " ); static const std::string S_Preamble( "<CFIntSubProjectEditObj" ); static const std::string S_Postamble( "/>" ); static const std::string S_Revision( "Revision" ); static const std::string S_CreatedBy( "CreatedBy" ); static const std::string S_CreatedAt( "CreatedAt" ); static const std::string S_UpdatedBy( "UpdatedBy" ); static const std::string S_UpdatedAt( "UpdatedAt" ); static const std::string S_TenantId( "TenantId" ); static const std::string S_Id( "Id" ); static const std::string S_TopProjectId( "TopProjectId" ); static const std::string S_Name( "Name" ); static const std::string S_Description( "Description" ); std::string ret( S_Preamble ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_Revision, CFIntSubProjectEditObj::getRequiredRevision() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_CreatedBy, CFIntSubProjectEditObj::getCreatedBy()->toString() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_CreatedAt, CFIntSubProjectEditObj::getCreatedAt() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_UpdatedBy, CFIntSubProjectEditObj::getUpdatedBy()->toString() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_UpdatedAt, CFIntSubProjectEditObj::getUpdatedAt() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_TenantId, CFIntSubProjectEditObj::getRequiredTenantId() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_Id, CFIntSubProjectEditObj::getRequiredId() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_TopProjectId, CFIntSubProjectEditObj::getRequiredTopProjectId() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Name, CFIntSubProjectEditObj::getRequiredName() ) ); if( ! CFIntSubProjectEditObj::isOptionalDescriptionNull() ) { ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Description, CFIntSubProjectEditObj::getOptionalDescriptionValue() ) ); } ret.append( S_Postamble ); return( ret ); } int32_t CFIntSubProjectEditObj::getRequiredRevision() const { return( buff->getRequiredRevision() ); } void CFIntSubProjectEditObj::setRequiredRevision( int32_t value ) { getSubProjectEditBuff()->setRequiredRevision( value ); } std::string CFIntSubProjectEditObj::getObjName() { std::string objName( CLASS_NAME ); objName; objName.clear(); objName.append( getRequiredName() ); return( objName ); } const std::string CFIntSubProjectEditObj::getGenDefName() { return( cfint::CFIntSubProjectBuff::GENDEFNAME ); } cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getScope() { cfint::ICFIntTopProjectObj* scope = getRequiredContainerParentTPrj(); return( scope ); } cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getObjScope() { cfint::ICFIntTopProjectObj* scope = getRequiredContainerParentTPrj(); return( scope ); } cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getObjQualifier( const classcode_t* qualifyingClass ) { cflib::ICFLibAnyObj* container = this; if( qualifyingClass != NULL ) { while( container != NULL ) { if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) { break; } else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) { break; } else if( container->implementsClassCode( *qualifyingClass ) ) { break; } container = container->getObjScope(); } } else { while( container != NULL ) { if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) { break; } else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) { break; } container = container->getObjScope(); } } return( container ); } cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getNamedObject( const classcode_t* qualifyingClass, const std::string& objName ) { cflib::ICFLibAnyObj* topContainer = getObjQualifier( qualifyingClass ); if( topContainer == NULL ) { return( NULL ); } cflib::ICFLibAnyObj* namedObject = topContainer->getNamedObject( objName ); return( namedObject ); } cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getNamedObject( const std::string& objName ) { std::string nextName; std::string remainingName; cflib::ICFLibAnyObj* subObj = NULL; cflib::ICFLibAnyObj* retObj; int32_t nextDot = objName.find( '.' ); if( nextDot >= 0 ) { nextName = objName.substr( 0, nextDot ); remainingName = objName.substr( nextDot + 1 ); } else { nextName.clear(); nextName.append( objName ); remainingName.clear(); } if( subObj == NULL ) { subObj = dynamic_cast<ICFIntSchemaObj*>( getSchema() )->getMajorVersionTableObj()->readMajorVersionByLookupNameIdx( getRequiredTenantId(), getRequiredId(), nextName, false ); } if( remainingName.length() <= 0 ) { retObj = subObj; } else if( subObj == NULL ) { retObj = NULL; } else { retObj = subObj->getNamedObject( remainingName ); } return( retObj ); } std::string CFIntSubProjectEditObj::getObjQualifiedName() { const static std::string S_Dot( "." ); std::string qualName( getObjName() ); cflib::ICFLibAnyObj* container = getObjScope(); std::string containerName; std::string buildName; while( container != NULL ) { if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) { container = NULL; } else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) { container = NULL; } else if( container->implementsClassCode( cfsec::CFSecTenantBuff::CLASS_CODE ) ) { container = NULL; } else { containerName = container->getObjName(); buildName.clear(); buildName.append( containerName ); buildName.append( S_Dot ); buildName.append( qualName ); qualName.clear(); qualName.append( buildName ); container = container->getObjScope(); } } return( qualName ); } std::string CFIntSubProjectEditObj::getObjFullName() { const static std::string S_Dot( "." ); std::string fullName = getObjName(); cflib::ICFLibAnyObj* container = getObjScope(); std::string containerName; std::string buildName; while( container != NULL ) { if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) { container = NULL; } else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) { container = NULL; } else { containerName = container->getObjName(); buildName.clear(); buildName.append( containerName ); buildName.append( S_Dot ); buildName.append( fullName ); fullName.clear(); fullName.append( buildName ); container = container->getObjScope(); } } return( fullName ); } cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::realize() { // We realize this so that it's buffer will get copied to orig during realization cfint::ICFIntSubProjectObj* retobj = getSchema()->getSubProjectTableObj()->realizeSubProject( dynamic_cast<cfint::ICFIntSubProjectObj*>( this ) ); return( retobj ); } cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::read( bool forceRead ) { cfint::ICFIntSubProjectObj* retval = getOrigAsSubProject()->read( forceRead ); if( retval != orig ) { throw cflib::CFLibUsageException( CLASS_NAME, "read", "retval != orig" ); } copyOrigToBuff(); return( retval ); } cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::create() { cfint::ICFIntSubProjectObj* retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getSubProjectTableObj()->createSubProject( this ); // Note that this instance is usually discarded during the creation process, // and retobj now references the cached instance of the created object. return( retobj ); } cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::update() { getSchema()->getSubProjectTableObj()->updateSubProject( this ); return( NULL ); } cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::deleteInstance() { static const std::string S_MethodName( "deleteInstance" ); static const std::string S_CannotDeleteNewInstance( "Cannot delete a new instance" ); if( getIsNew() ) { throw cflib::CFLibUsageException( CLASS_NAME, S_MethodName, S_CannotDeleteNewInstance ); } getSchema()->getSubProjectTableObj()->deleteSubProject( this ); return( NULL ); } cfint::ICFIntSubProjectTableObj* CFIntSubProjectEditObj::getSubProjectTable() { return( orig->getSchema()->getSubProjectTableObj() ); } cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::getEdit() { return( this ); } cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::getSubProjectEdit() { return( (cfint::ICFIntSubProjectEditObj*)this ); } cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::beginEdit() { static const std::string S_ProcName( "beginEdit" ); static const std::string S_Message( "Cannot edit an edition" ); throw cflib::CFLibUsageException( CLASS_NAME, S_ProcName, S_Message ); } void CFIntSubProjectEditObj::endEdit() { orig->endEdit(); } cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::getOrig() { return( orig ); } cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::getOrigAsSubProject() { return( dynamic_cast<cfint::ICFIntSubProjectObj*>( orig ) ); } cfint::ICFIntSchemaObj* CFIntSubProjectEditObj::getSchema() { return( orig->getSchema() ); } cfint::CFIntSubProjectBuff* CFIntSubProjectEditObj::getBuff() { return( buff ); } void CFIntSubProjectEditObj::setBuff( cfint::CFIntSubProjectBuff* value ) { if( buff != value ) { if( ( buff != NULL ) && ( buff != value ) ) { delete buff; buff = NULL; } buff = value; } } cfint::CFIntSubProjectPKey* CFIntSubProjectEditObj::getPKey() { return( orig->getPKey() ); } void CFIntSubProjectEditObj::setPKey( cfint::CFIntSubProjectPKey* value ) { if( orig->getPKey() != value ) { orig->setPKey( value ); } copyPKeyToBuff(); } bool CFIntSubProjectEditObj::getIsNew() { return( orig->getIsNew() ); } void CFIntSubProjectEditObj::setIsNew( bool value ) { orig->setIsNew( value ); } const int64_t CFIntSubProjectEditObj::getRequiredTenantId() { return( getPKey()->getRequiredTenantId() ); } const int64_t* CFIntSubProjectEditObj::getRequiredTenantIdReference() { return( getPKey()->getRequiredTenantIdReference() ); } const int64_t CFIntSubProjectEditObj::getRequiredId() { return( getPKey()->getRequiredId() ); } const int64_t* CFIntSubProjectEditObj::getRequiredIdReference() { return( getPKey()->getRequiredIdReference() ); } const int64_t CFIntSubProjectEditObj::getRequiredTopProjectId() { return( getSubProjectBuff()->getRequiredTopProjectId() ); } const int64_t* CFIntSubProjectEditObj::getRequiredTopProjectIdReference() { return( getSubProjectBuff()->getRequiredTopProjectIdReference() ); } const std::string& CFIntSubProjectEditObj::getRequiredName() { return( getSubProjectBuff()->getRequiredName() ); } const std::string* CFIntSubProjectEditObj::getRequiredNameReference() { return( getSubProjectBuff()->getRequiredNameReference() ); } void CFIntSubProjectEditObj::setRequiredName( const std::string& value ) { if( getSubProjectBuff()->getRequiredName() != value ) { getSubProjectEditBuff()->setRequiredName( value ); } } bool CFIntSubProjectEditObj::isOptionalDescriptionNull() { return( getSubProjectBuff()->isOptionalDescriptionNull() ); } const std::string& CFIntSubProjectEditObj::getOptionalDescriptionValue() { return( getSubProjectBuff()->getOptionalDescriptionValue() ); } const std::string* CFIntSubProjectEditObj::getOptionalDescriptionReference() { return( getSubProjectBuff()->getOptionalDescriptionReference() ); } void CFIntSubProjectEditObj::setOptionalDescriptionNull() { if( ! getSubProjectBuff()->isOptionalDescriptionNull() ) { getSubProjectEditBuff()->setOptionalDescriptionNull(); } } void CFIntSubProjectEditObj::setOptionalDescriptionValue( const std::string& value ) { if( getSubProjectBuff()->isOptionalDescriptionNull() ) { getSubProjectEditBuff()->setOptionalDescriptionValue( value ); } else if( getSubProjectBuff()->getOptionalDescriptionValue() != value ) { getSubProjectEditBuff()->setOptionalDescriptionValue( value ); } } cfsec::ICFSecTenantObj* CFIntSubProjectEditObj::getRequiredOwnerTenant( bool forceRead ) { cfsec::ICFSecTenantObj* retobj = NULL; bool anyMissing = false; if( ! anyMissing ) { retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getTenantTableObj()->readTenantByIdIdx( getPKey()->getRequiredTenantId() ); } return( retobj ); } void CFIntSubProjectEditObj::setRequiredOwnerTenant( cfsec::ICFSecTenantObj* value ) { if( value != NULL ) { getPKey()->setRequiredTenantId ( value->getRequiredId() ); getSubProjectEditBuff()->setRequiredTenantId( value->getRequiredId() ); } } cfint::ICFIntTopProjectObj* CFIntSubProjectEditObj::getRequiredContainerParentTPrj( bool forceRead ) { cfint::ICFIntTopProjectObj* retobj = NULL; bool anyMissing = false; if( ! anyMissing ) { retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getTopProjectTableObj()->readTopProjectByIdIdx( getPKey()->getRequiredTenantId(), getSubProjectBuff()->getRequiredTopProjectId() ); } return( retobj ); } void CFIntSubProjectEditObj::setRequiredContainerParentTPrj( cfint::ICFIntTopProjectObj* value ) { if( value != NULL ) { getPKey()->setRequiredTenantId ( value->getRequiredTenantId() ); getSubProjectEditBuff()->setRequiredTenantId( value->getRequiredTenantId() ); getSubProjectEditBuff()->setRequiredTopProjectId( value->getRequiredId() ); } } std::vector<cfint::ICFIntMajorVersionObj*> CFIntSubProjectEditObj::getOptionalComponentsMajorVer( bool forceRead ) { std::vector<cfint::ICFIntMajorVersionObj*> retval; retval = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getMajorVersionTableObj()->readMajorVersionBySubProjectIdx( getPKey()->getRequiredTenantId(), getPKey()->getRequiredId(), forceRead ); return( retval ); } void CFIntSubProjectEditObj::copyPKeyToBuff() { cfint::CFIntSubProjectPKey* tablePKey = getPKey(); cfint::CFIntSubProjectBuff* tableBuff = getSubProjectEditBuff(); tableBuff->setRequiredTenantId( tablePKey->getRequiredTenantId() ); tableBuff->setRequiredId( tablePKey->getRequiredId() ); } void CFIntSubProjectEditObj::copyBuffToPKey() { cfint::CFIntSubProjectPKey* tablePKey = getPKey(); cfint::CFIntSubProjectBuff* tableBuff = getSubProjectBuff(); tablePKey->setRequiredTenantId( tableBuff->getRequiredTenantId() ); tablePKey->setRequiredId( tableBuff->getRequiredId() ); } void CFIntSubProjectEditObj::copyBuffToOrig() { cfint::CFIntSubProjectBuff* origBuff = getOrigAsSubProject()->getSubProjectEditBuff(); cfint::CFIntSubProjectBuff* myBuff = getSubProjectBuff(); if( origBuff != myBuff ) { *origBuff = *myBuff; } } void CFIntSubProjectEditObj::copyOrigToBuff() { cfint::CFIntSubProjectBuff* origBuff = getOrigAsSubProject()->getSubProjectBuff(); cfint::CFIntSubProjectBuff* myBuff = getSubProjectEditBuff(); if( origBuff != myBuff ) { *myBuff = *origBuff; } } }
34.413495
181
0.727062
msobkow
f926c57c62e11c0191895d80560b45d9e36323fa
19,255
cpp
C++
kernel/Scheduler.cpp
SmkViper/CranberryOS
ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6
[ "MIT" ]
null
null
null
kernel/Scheduler.cpp
SmkViper/CranberryOS
ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6
[ "MIT" ]
null
null
null
kernel/Scheduler.cpp
SmkViper/CranberryOS
ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6
[ "MIT" ]
null
null
null
#include "Scheduler.h" #include <cstring> #include <new> #include "ARM/SchedulerDefines.h" #include "IRQ.h" #include "MemoryManager.h" #include "Timer.h" // How the scheduler currently works: // // CopyProcess creates a new memory page and puts the task struct at the bottom of the page, with the stack pointer // pointing at a certain distance above it. // // 0xXXXXXXXX +--------------------+ ^ // | TaskStruct | | // +--------------------+ | One page // | | | // | Stack (grows up) | | // +--------------------+ | // | ProcessState | | // 0xXXXX1000 +--------------------+ v // // ScheduleImpl is called, either voluntarily or via timer // cpu_switch_to saves all callee-saved registers in the current task to the TaskStruct context member // cpu_switch_to "restores" all callee-saved registers for the new task, setting sp to 0xXXXX1000, the link register // to ret_from_create, x19 to the task's process function, and x20 to the process function parameter // cpu_switch_to returns, loading ret_from_create's address from the link register // ret_from_create reads from x19 and x20, and calls to the function in x19, passing it x20 // // Eventually a timer interrupt happens, saving all registers + elr_el1 and spsr_el1 to the bottom of the current // task's stack // // 0xXXXXXXXX +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xXXXX1000 +----------------------+ // // The current task is now handling an interrupt, and grows a little bit more on the stack to pick the task to resume // // 0xXXXXXXXX +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Stack (interrupt) | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xXXXX1000 +----------------------+ // // The interrupt picks a second new task to run, repeating the process performed for the first task to set up the // second new task. This task begins executing and growing its own stack. Note that execution is still in the timer // interrupt handler, but interrupts have been re-enabled at this point, so another timer can come in again. // // 0xXXXXXXXX +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Stack (interrupt) | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xXXXX1000 +----------------------+ // | ... | // 0xYYYYYYYY +----------------------+ // | TaskStruct | // +----------------------+ // | | // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xYYYY1000 +----------------------+ // // Another timer interrupt happens, and the process repeats to save off all the registers, elr_el1 and spsr_el1 at the // bottom of the second task's stack, and the interrupt stack for that task starts to grow // // 0xXXXXXXXX +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Stack (interrupt) | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xXXXX1000 +----------------------+ // | ... | // 0xYYYYYYYY +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Stack (interrupt) | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xYYYY1000 +----------------------+ // // ScheduleImpl is now called, and notes that both tasks have their counter at 0. It then sets the counters to their // priority and picks the first task to run again. (Though it could pick either if their priorities were the same) // cpu_switch_to is called and it restores all the callee-saved registers from the first task context. The link // register now points at the end of the SwitchTo function, since that's what it was the last time this task was // running. The stack pointer also is set to point at the bottom of the first task's interrupt stack. // The TimerTick function now resumes execution, disabling interrupts again and returns to the interrupt handler, // collapsing the interrupt stack to 0. // // 0xXXXXXXXX +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xXXXX1000 +----------------------+ // | ... | // 0xYYYYYYYY +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Stack (interrupt) | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xYYYY1000 +----------------------+ // // The interrupt cleans up, restoring all the regsters that were saved from the stack, including the elr_el1 and // spsr_el1 registers. elr_el1 now points somewhere in the middle of the process function (wherever the interrupt) // originally happened. And sp now points at the bottom of the task's original stack // // 0xXXXXXXXX +----------------------+ // | TaskStruct | // +----------------------+ // | | // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xXXXX1000 +----------------------+ // | ... | // 0xYYYYYYYY +----------------------+ // | TaskStruct | // +----------------------+ // | | // +----------------------+ // | Stack (interrupt) | // +----------------------+ // | Task saved registers | // +----------------------+ // | Stack (grows up) | // +----------------------+ // | ProcessState | // 0xYYYY1000 +----------------------+ // // The eret instruction is executed, using the saved elr_el1 register to jump back to whatever the first task was doing namespace { // SPSR_EL1 bits - See section C5.2.18 in the ARMv8 manual constexpr uint64_t PSRModeEL0tC = 0x00000000; struct CPUContext { // ARM calling conventions allow registers x0-x18 to be overwritten by a called function, // so we don't need to save those off // // #TODO: May need to save off additional registers (i.e. SIMD/FP registers?) uint64_t x19 = 0; uint64_t x20 = 0; uint64_t x21 = 0; uint64_t x22 = 0; uint64_t x23 = 0; uint64_t x24 = 0; uint64_t x25 = 0; uint64_t x26 = 0; uint64_t x27 = 0; uint64_t x28 = 0; uint64_t fp = 0; // x29 uint64_t sp = 0; uint64_t pc = 0; // x30 }; enum class TaskState : int64_t { Running, Zombie }; struct TaskStruct { CPUContext Context; TaskState State = TaskState::Running; int64_t Counter = 0; // decrements each timer tick. When reaches 0, another task will be scheduled int64_t Priority = 1; // copied to Counter when a task is scheduled, so higher priority will run for longer int64_t PreemptCount = 0; // If non-zero, task will not be preempted void* pStack = nullptr; // pointer to the stack root so it can be cleaned up if necessary uint64_t Flags = 0; }; // Expected to match what is put on the stack via the kernel_entry macro in the exception handler so it can // "restore" the processor state we want struct ProcessState { uint64_t Registers[31] = {0u}; uint64_t StackPointer = 0u; uint64_t ProgramCounter = 0u; uint64_t ProcessorState = 0u; }; static_assert(offsetof(TaskStruct, Context) == TASK_STRUCT_CONTEXT_OFFSET, "Unexpected offset of context in task struct"); } extern "C" { /** * Return to the newly created task (Defined in ExceptionVectors.S) */ extern void ret_from_create(); /** * Switch the CPU from running the previous task to the next task * * @param apPrev The previously running task * @param apNext The new task to resume */ extern void cpu_switch_to(TaskStruct* apPrev, TaskStruct* apNext); } namespace { constexpr auto TimerTickMSC = 200; // tick every 200ms constexpr auto ThreadSizeC = 4096; // 4k stack size (#TODO: Pull from page size?) constexpr auto NumberOfTasksC = 64u; TaskStruct InitTask; // task running kernel init TaskStruct* pCurrentTask = &InitTask; TaskStruct* Tasks[NumberOfTasksC] = {&InitTask, nullptr}; auto NumberOfTasks = 1; /** * Enable scheduler preemption in the current task */ void PreemptEnable() { // #TODO: Assert/error when we have it --pCurrentTask->PreemptCount; } /** * Disable scheduler preemption in the current task */ void PreemptDisable() { ++pCurrentTask->PreemptCount; } /** * Helper to disable scheduler preempting in the current scope */ struct DisablePreemptingInScope { /** * Constructor - disables scheduler preempting */ [[nodiscard]] DisablePreemptingInScope() { PreemptDisable(); } /** * Destructor - reenables scheduler preempting */ ~DisablePreemptingInScope() { PreemptEnable(); } // Disable copying DisablePreemptingInScope(const DisablePreemptingInScope&) = delete; DisablePreemptingInScope& operator=(const DisablePreemptingInScope&) = delete; }; /** * Switch from running the current task to the next task * * @param apNextTask The next task to run */ void SwitchTo(TaskStruct* const apNextTask) { if (pCurrentTask == apNextTask) { return; } const auto pprevTask = pCurrentTask; pCurrentTask = apNextTask; cpu_switch_to(pprevTask, apNextTask); } /** * Find and resume a running task */ void ScheduleImpl() { // Make sure we don't get called while we're in the middle of picking a task DisablePreemptingInScope disablePreempt; auto foundTask = false; auto taskToResume = 0u; while (!foundTask) { // Find the task with the largest counter value (i.e. the one that has the highest priority that has // not run in a while) auto largestCounter = -1ll; taskToResume = 0; for (auto curTask = 0u; curTask < NumberOfTasksC; ++curTask) { const auto ptask = Tasks[curTask]; if (ptask && (ptask->State == TaskState::Running) && (ptask->Counter > largestCounter)) { largestCounter = ptask->Counter; taskToResume = curTask; } } // If we don't find any running task with a non-zero counter, then we need to go and reset all their // counters according to their priority foundTask = (largestCounter > 0); if (!foundTask) { for (const auto pcurTask : Tasks) { if (pcurTask) { // Increment the counter by the priority, ensuring that we don't go above 2 * priority // So the longer the task has been waiting, the higher the counter should be. pcurTask->Counter = (pcurTask->Counter / 1) + pcurTask->Priority; } } } // If at least one task is running, then we should only loop around once. If all tasks are not running // then we keep looping until a task changes its state to running again (i.e. via an interrupt) } SwitchTo(Tasks[taskToResume]); } /** * Triggered by the timer interrupt to schedule a new task * * @param apParam The parameter registered for our callback */ void TimerTick(const void* /*apParam*/) { // Only switch task if the counter has run out and it hasn't been blocked --pCurrentTask->Counter; if ((pCurrentTask->Counter > 0) || (pCurrentTask->PreemptCount > 0)) { return; } pCurrentTask->Counter = 0; // Interrupts are disabled while handing one, so re-enable them for the schedule call because some tasks // might be waiting from an interrupt and we want them to be able to get them while the scheduler is trying // to find a task (otherwise we might just have all tasks waiting for interrupts and loop forever without // finding a task to run) enable_irq(); ScheduleImpl(); // And re-disable them before returning to the interrupt handler (which will deal with re-enabling them later) disable_irq(); } /** * Extract the state memory from the stack for the given task * * @param apTask Task to get the state for * @return The process state for the task */ void* GetTargetStateMemoryForTask(TaskStruct* apTask) { const auto state = reinterpret_cast<uintptr_t>(apTask) + ThreadSizeC - sizeof(ProcessState); return reinterpret_cast<void*>(state); } } extern "C" { /** * Called by assembly to finish any work up before staring the process call */ void schedule_tail() { PreemptEnable(); } } namespace Scheduler { void InitTimer() { // We're using a local timer instead of the global timer because it works on both QEMU and real hardware LocalTimer::RegisterCallback(TimerTickMSC, TimerTick, nullptr); } void Schedule() { pCurrentTask->Counter = 0; ScheduleImpl(); } int CreateProcess(const uint32_t aCreateFlags, ProcessFunctionPtr apProcessFn, const void* apParam, void* apStack) { // Make sure we don't get preempted in the middle of making a new task DisablePreemptingInScope disablePreempt; auto pmemory = reinterpret_cast<uint8_t*>(MemoryManager::GetFreePage()); if (pmemory == nullptr) { return -1; } auto pnewTask = new (pmemory) TaskStruct{}; const auto puninitializedState = reinterpret_cast<uint8_t*>(GetTargetStateMemoryForTask(pnewTask)); const auto pnewState = new (puninitializedState) ProcessState{}; if ((aCreateFlags & CreationFlags::KernelThreadC) == CreationFlags::KernelThreadC) { pnewTask->Context.x19 = reinterpret_cast<uint64_t>(apProcessFn); pnewTask->Context.x20 = reinterpret_cast<uint64_t>(apParam); } else { // extract and clone the current processor state const auto psourceState = reinterpret_cast<ProcessState*>(GetTargetStateMemoryForTask(pCurrentTask)); *pnewState = *psourceState; pnewState->Registers[0] = 0; // make sure ret_from_create knows this is the new user process pnewState->StackPointer = reinterpret_cast<uint64_t>(apStack) + ThreadSizeC; pnewTask->pStack = apStack; } pnewTask->Flags = aCreateFlags; pnewTask->Priority = pCurrentTask->Priority; pnewTask->Counter = pnewTask->Priority; pnewTask->PreemptCount = 1; // disable preemption until schedule_tail pnewTask->Context.pc = reinterpret_cast<uint64_t>(ret_from_create); pnewTask->Context.sp = reinterpret_cast<uint64_t>(pnewState); const auto processID = NumberOfTasks++; Tasks[processID] = pnewTask; return processID; } bool MoveToUserMode(UserModeFunctionPtr apUserModeFn) { const auto puninitializedState = reinterpret_cast<uint8_t*>(GetTargetStateMemoryForTask(pCurrentTask)); auto pstate = new (puninitializedState) ProcessState{}; static_assert(sizeof(UserModeFunctionPtr) == sizeof(uint64_t), "Unexpected pointer size"); pstate->ProgramCounter = reinterpret_cast<uint64_t>(apUserModeFn); pstate->ProcessorState = PSRModeEL0tC; const auto pstack = MemoryManager::GetFreePage(); if (pstack == nullptr) { pstate->~ProcessState(); return false; } pstate->StackPointer = reinterpret_cast<uint64_t>(pstack) + ThreadSizeC; pCurrentTask->pStack = pstack; return true; } void ExitProcess() { { // Make sure we don't get preempted in the middle of cleaning up the task DisablePreemptingInScope disablePreempt; // Flag the task as a zombie so it isn't rescheduled for (const auto pcurTask : Tasks) { if (pcurTask == pCurrentTask) { pcurTask->State = TaskState::Zombie; break; } } if (pCurrentTask->pStack) { MemoryManager::FreePage(pCurrentTask->pStack); } } // Won't ever return because a new task will be scheduled and this one is now flagged as a zombie Schedule(); } }
36.746183
126
0.513944
SmkViper
f9324ed31b1c1a246663744e94bbe6de7c2e2e05
1,525
cpp
C++
ip_protocol.cpp
folkertvanheusden/myip
374802136afad4bd7efafd5931cb04f67c0b4487
[ "Apache-2.0" ]
8
2021-08-14T11:12:53.000Z
2021-11-06T08:36:02.000Z
ip_protocol.cpp
folkertvanheusden/myip
374802136afad4bd7efafd5931cb04f67c0b4487
[ "Apache-2.0" ]
8
2021-08-22T11:34:10.000Z
2021-12-29T13:11:07.000Z
ip_protocol.cpp
folkertvanheusden/myip
374802136afad4bd7efafd5931cb04f67c0b4487
[ "Apache-2.0" ]
null
null
null
// (C) 2020 by folkert van heusden <mail@vanheusden.com>, released under Apache License v2.0 #include <chrono> #include "ip_protocol.h" #include "utils.h" constexpr size_t pkts_max_size { 512 }; ip_protocol::ip_protocol(stats *const s, const std::string & stats_name) { pkts = new fifo<const packet *>(s, stats_name, pkts_max_size); } ip_protocol::~ip_protocol() { delete pkts; } void ip_protocol::queue_packet(const packet *p) { if (!pkts->try_put(p)) DOLOG(warning, "IP-Protocol: packet dropped\n"); } uint16_t tcp_udp_checksum(const any_addr & src_addr, const any_addr & dst_addr, const bool tcp, const uint8_t *const tcp_payload, const int len) { uint16_t checksum { 0 }; if (dst_addr.get_len() == 16) { // IPv6 size_t temp_len = 40 + len + (len & 1); uint8_t *temp = new uint8_t[temp_len](); src_addr.get(&temp[0], 16); dst_addr.get(&temp[16], 16); temp[32] = len >> 24; temp[33] = len >> 16; temp[34] = len >> 8; temp[35] = len; temp[39] = tcp ? 0x06 : 0x11; memcpy(&temp[40], tcp_payload, len); checksum = ip_checksum((const uint16_t *)temp, temp_len / 2); delete [] temp; } else { // IPv4 size_t temp_len = 12 + len + (len & 1); uint8_t *temp = new uint8_t[temp_len](); src_addr.get(&temp[0], 4); dst_addr.get(&temp[4], 4); temp[9] = tcp ? 0x06 : 0x11; temp[10] = len >> 8; // TCP len temp[11] = len; memcpy(&temp[12], tcp_payload, len); checksum = ip_checksum((const uint16_t *)temp, temp_len / 2); delete [] temp; } return checksum; }
21.180556
144
0.645902
folkertvanheusden
f932855ce8ff9510153c6fba8ac23fd35798abfb
999
cpp
C++
videocodering/Encoder/Quantiser.cpp
FlashYoshi/UGentProjects
5561ce3bb73d5bc5bf31bcda2be7e038514c7072
[ "MIT" ]
null
null
null
videocodering/Encoder/Quantiser.cpp
FlashYoshi/UGentProjects
5561ce3bb73d5bc5bf31bcda2be7e038514c7072
[ "MIT" ]
null
null
null
videocodering/Encoder/Quantiser.cpp
FlashYoshi/UGentProjects
5561ce3bb73d5bc5bf31bcda2be7e038514c7072
[ "MIT" ]
1
2019-07-18T11:23:49.000Z
2019-07-18T11:23:49.000Z
#include "Quantiser.h" #include <math.h> #include <stdio.h> // Breng wijzigingen aan in onderstaande methode // Quantisatie van de luminanitie- en chrominantiecoefficienten. // De quantisatiestap qp moet bij het encoderen verschillend zijn van nul aangezien deling door nul niet is toegestaan. int Quantiser::sign(pixel i){ return (i > 0) ? 1 : -1; } void Quantiser::Quantise(Macroblock *mb, int qp) { //qp mag niet 0 zijn maar we willen wel Quantise uitvoeren qp++; //CB en CR zijn 8x8 matrices for(int i = 0; i < max; i++){ for(int j = 0; j < max; j++){ int cb = mb->cb[i][j]; int cr = mb->cr[i][j]; mb->cb[i][j] = (pixel) (sign(cb) * floor(abs(cb) / qp + 0.5)); mb->cr[i][j] = (pixel) (sign(cr) * floor(abs(cr) / qp + 0.5)); } } //Luma moeten we apart doen omdat het een 16x16 matrix is for (int i = 0; i < 2 * max; i++){ for (int j = 0; j < 2 * max; j++){ int luma = mb->luma[i][j]; mb->luma[i][j] = (pixel) (sign(luma) * floor(abs(luma) / qp + 0.5)); } } }
32.225806
119
0.608609
FlashYoshi
f9332c89d81651c0bce337bd11e78b7ec79d451c
4,546
cpp
C++
QMC2-crypto/qmc2-crypto/StreamCencrypt.cpp
jixunmoe/qmc2
4334a64abb4def3d44b1860ac7c34400e2ada85c
[ "MIT" ]
76
2021-12-12T19:07:30.000Z
2022-03-30T14:31:30.000Z
QMC2-crypto/qmc2-crypto/StreamCencrypt.cpp
jixunmoe/qmc2
4334a64abb4def3d44b1860ac7c34400e2ada85c
[ "MIT" ]
3
2021-12-27T09:21:17.000Z
2022-03-22T01:59:56.000Z
QMC2-crypto/qmc2-crypto/StreamCencrypt.cpp
jixunmoe/qmc2
4334a64abb4def3d44b1860ac7c34400e2ada85c
[ "MIT" ]
16
2021-12-12T19:23:46.000Z
2022-03-11T15:57:18.000Z
#include "qmc2-crypto/StreamCencrypt.h" #include <cassert> #include <cstring> #include <algorithm> void StreamCencrypt::StreamEncrypt(uint64_t offset, uint8_t *buf, size_t len) { if (N > 300) { ProcessByRC4(offset, buf, len); } else { for (size_t i = 0; i < len; i++) { buf[i] ^= mapL(offset + i); } } } void StreamCencrypt::StreamDecrypt(uint64_t offset, uint8_t *buf, size_t len) { this->StreamEncrypt(offset, buf, len); } void StreamCencrypt::SetKeyDec(KeyDec *key_dec) { Uninit(); rc4_key = nullptr; if (key_dec) { key_dec->GetKey(this->rc4_key, N); if (N > 300) { InitRC4KSA(); } } } void StreamCencrypt::Uninit() { // reset initial rc4 key if (rc4_key) { delete[] rc4_key; rc4_key = nullptr; } // reset sbox this->N = 0; if (S) { delete[] S; S = nullptr; } } #define FIRST_SEGMENT_SIZE (0x80) #define SEGMENT_SIZE (0x1400) void StreamCencrypt::ProcessByRC4(size_t offset, uint8_t *buf, size_t size) { uint8_t *orig_buf = buf; uint8_t *last_addr = orig_buf + size; auto len = size; // Initial segment if (offset < FIRST_SEGMENT_SIZE) { auto len_segment = std::min(size, FIRST_SEGMENT_SIZE - offset); EncFirstSegment(offset, buf, len_segment); len -= len_segment; buf += len_segment; offset += len_segment; } // FIXME: Move this as a private member? uint8_t *S = new uint8_t[N](); // Align segment if (offset % SEGMENT_SIZE != 0) { auto len_segment = std::min(SEGMENT_SIZE - (offset % SEGMENT_SIZE), len); EncASegment(S, offset, buf, len_segment); len -= len_segment; buf += len_segment; offset += len_segment; } // Batch process segments while (len > SEGMENT_SIZE) { auto len_segment = std::min(size_t{SEGMENT_SIZE}, len); EncASegment(S, offset, buf, len_segment); len -= len_segment; buf += len_segment; offset += len_segment; } // Last segment (incomplete segment) if (len > 0) { EncASegment(S, offset, buf, len); } assert(last_addr == buf + len); delete[] S; } uint64_t StreamCencrypt::GetSegmentKey(uint64_t id, uint64_t seed) { return uint64_t((double)this->key_hash / double((id + 1) * seed) * 100.0); } void StreamCencrypt::EncFirstSegment(size_t offset, uint8_t *buf, size_t len) { for (size_t i = 0; i < len; i++) { uint64_t key = uint64_t{this->rc4_key[offset % this->N]}; buf[i] ^= this->rc4_key[GetSegmentKey(offset, key) % this->N]; offset++; } } void StreamCencrypt::EncASegment(uint8_t *S, size_t offset, uint8_t *buf, size_t len) { if (rc4_key == nullptr) { // We need to initialise RC4 key first! return; } const auto N = this->N; // Initialise a new seedbox memcpy(S, this->S, N); // Calculate segment id int segment_id = (offset / SEGMENT_SIZE) & 0x1FF; // Calculate the number of bytes to skip. // The initial "key" derived from segment id, plus the current offset. auto skip_len = GetSegmentKey(offset / SEGMENT_SIZE, this->rc4_key[segment_id]) & 0x1FF; skip_len += offset % SEGMENT_SIZE; int j = 0; int k = 0; for (size_t i = 0; i < skip_len; i++) { j = (j + 1) % N; k = (S[j] + k) % N; std::swap(S[j], S[k]); } // Now we also manipulate the buffer: for (size_t i = 0; i < len; i++) { j = (j + 1) % N; k = (S[j] + k) % N; std::swap(S[j], S[k]); buf[i] ^= S[(S[j] + S[k]) % N]; } } void StreamCencrypt::InitRC4KSA() { if (!S) { S = new uint8_t[N](); } for (size_t i = 0; i < N; ++i) { S[i] = i & 0xFF; } int j = 0; for (size_t i = 0; i < N; ++i) { j = (S[i] + j + rc4_key[i % N]) % N; std::swap(S[i], S[j]); } GetHashBase(); } void StreamCencrypt::GetHashBase() { this->key_hash = 1; for (size_t i = 0; i < this->N; i++) { int32_t value = int32_t{this->rc4_key[i]}; // ignore if key char is '\x00' if (!value) continue; auto next_hash = this->key_hash * value; if (next_hash == 0 || next_hash <= this->key_hash) break; this->key_hash = next_hash; } } inline uint8_t rotate(uint8_t value, int bits) { int rotate = (bits + 4) % 8; auto left = value << rotate; auto right = value >> rotate; return uint8_t(left | right); } // Untested, this might be wrong. uint8_t StreamCencrypt::mapL(uint64_t offset) { if (offset > 0x7FFF) offset %= 0x7FFF; uint64_t key = (offset * offset + 71214) % this->N; uint8_t value = this->rc4_key[key]; return rotate(value, key & 0b0111); }
19.594828
90
0.602508
jixunmoe
f935d5845c9b02a9c2aca16f33c9703cce725ceb
1,475
cpp
C++
Deprecated/Debug/Debug.cpp
Theundeadwarrior/Casiope
f21b53b8e51adb9b341269471443b9dc0f61e9d8
[ "MIT" ]
3
2016-08-04T05:08:59.000Z
2018-03-28T04:40:43.000Z
Deprecated/Debug/Debug.cpp
Theundeadwarrior/Casiope
f21b53b8e51adb9b341269471443b9dc0f61e9d8
[ "MIT" ]
6
2016-08-05T17:57:51.000Z
2018-03-28T04:41:09.000Z
Deprecated/Debug/Debug.cpp
Theundeadwarrior/Casiope
f21b53b8e51adb9b341269471443b9dc0f61e9d8
[ "MIT" ]
1
2016-08-16T05:40:59.000Z
2016-08-16T05:40:59.000Z
#include "Debug.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include <string> #include <Windows.h> #include <iostream> namespace Atum { namespace Utilities { void OutputTrace(char* text, ...) { char buffer[256]; va_list args; va_start (args, text); vsprintf_s (buffer, text, args); OutputDebugString (buffer); va_end (args); } void OutputError(char* text, ...) { char buffer[256]; va_list args; va_start (args, text); vsprintf_s (buffer,text, args); perror (buffer); // Make crash? va_end (args); } void OutputAssert( const char* _condition, const char* _message, char* _filename, char* _line ) { std::string condition(_condition); std::string message(_message); std::string file(_filename); std::string line(_line); // Remove the path if there is a path int fileNameBeginPosition = file.find_last_of("\\"); if(fileNameBeginPosition != file.size()) { file.erase(0,fileNameBeginPosition + 1); file.erase(file.size() - 1, 1); } std::string errorMessage("[ASSERT] Condition: "); errorMessage.append(condition); errorMessage.append(" failed. "); errorMessage.append("Error in file "); errorMessage.append(file); errorMessage.append(" at line "); errorMessage.append(line); errorMessage.append(". "); errorMessage.append(message); OutputDebugString(errorMessage.c_str()); perror(errorMessage.c_str()); // make crash? } } }
22.014925
97
0.660339
Theundeadwarrior
f93cbce816eabe0acb98a508a6479f13f027ed1c
2,930
cpp
C++
Rasterizer/src/Light.cpp
litelawliet/ISARTRasterizer
329ed70ea830cfff286c01d8efa5e726276f1fcd
[ "MIT" ]
1
2020-03-23T14:36:02.000Z
2020-03-23T14:36:02.000Z
Rasterizer/src/Light.cpp
litelawliet/ISARTRasterizer
329ed70ea830cfff286c01d8efa5e726276f1fcd
[ "MIT" ]
null
null
null
Rasterizer/src/Light.cpp
litelawliet/ISARTRasterizer
329ed70ea830cfff286c01d8efa5e726276f1fcd
[ "MIT" ]
null
null
null
#include "Light.h" #include "Color.h" #include "Vertex.h" #include "Maths/Vec4.h" #include <iostream> #include <algorithm> using namespace Maths::Vector; //ADD LIGHTING HERE EVENTUALLY Light::Light(const Maths::Vector::Vec3 p_position, const float p_ambient, const float p_diffuse, const float p_specular) : m_position{ p_position }, m_ambientComponent{ p_ambient }, m_diffuseComponent{ p_diffuse }, m_specularComponent{ p_specular } {} Light::Light(const float p_x, const float p_y, const float p_z, const float p_ambient, const float p_diffuse, const float p_specular) : m_position{ p_x, p_y, p_z }, m_ambientComponent{ p_ambient }, m_diffuseComponent{ p_diffuse }, m_specularComponent{ p_specular } {} Vec3& Light::GetPosition() { return { m_position }; } float Light::GetAmbientComponent() const { return m_ambientComponent; } float Light::GetDiffuseComponent() const { return m_diffuseComponent; } float Light::GetSpecularComponent() const { return m_specularComponent; } void Light::SetPosition(const Vec3 & p_position) { m_position = p_position; } void Light::SetPosition(const float p_x, const float p_y, const float p_z) { m_position.m_x = p_x; m_position.m_y = p_x; m_position.m_z = p_z; } void Light::SetAmbientComponent(const float p_value) { m_ambientComponent = p_value; } void Light::SetDiffuseComponent(const float p_value) { m_diffuseComponent = p_value; } void Light::SetSpecularComponent(const float p_value) { m_specularComponent = p_value; } Color Light::CalculateColor(const Color p_color, const Vec3 p_surface, Vec4 p_vertex) { Vec3 normalSurface = p_surface; //normalSurface.Normalize(); Vec3 homogenizedVec = Vec3{ p_vertex.m_x / p_vertex.m_w, p_vertex.m_y / p_vertex.m_w, p_vertex.m_z / p_vertex.m_w }; Vec3 lightPosNormal = m_position - homogenizedVec; lightPosNormal.Normalize(); Vec3 reflectedLightVector = GetLightReflection(lightPosNormal, normalSurface); float specAngle = std::max(Vec3::GetDotProduct(reflectedLightVector, homogenizedVec), 0.0f); float lambertian = std::max(Vec3::GetDotProduct(normalSurface, lightPosNormal), 0.0f); float specular = std::powf(specAngle, 1.0); float r = (m_ambientComponent * p_color.m_r) + (m_diffuseComponent * lambertian * p_color.m_r) + (m_specularComponent * specular * p_color.m_r); float g = (m_ambientComponent * p_color.m_g) + (m_diffuseComponent * lambertian * p_color.m_g) + (m_specularComponent * specular * p_color.m_g); float b = (m_ambientComponent * p_color.m_b) + (m_diffuseComponent * lambertian * p_color.m_b) + (m_specularComponent * specular * p_color.m_b); return { Color { static_cast<unsigned char>(r), static_cast<unsigned char>(g), static_cast<unsigned char>(b), p_color.m_a} }; } Vec3 Light::GetLightReflection(Vec3 p_v0, Vec3 p_v1) { Vec3 negatedP0 = p_v0 * -1; float dotProductResult = Vec3::GetDotProduct(negatedP0, p_v1); return { negatedP0 - (p_v1 * (2 * dotProductResult)) }; }
30.206186
145
0.757679
litelawliet
f93ce1b91c54c5d7ea4614131913b4c31402e25f
2,445
cpp
C++
compiler-rt/test/tsan/signal_block2.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
compiler-rt/test/tsan/signal_block2.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
compiler-rt/test/tsan/signal_block2.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s // The test was reported to hang sometimes on Darwin: // https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20210517/917003.html // UNSUPPORTED: darwin #include "test.h" #include <signal.h> #include <string.h> #include <sys/time.h> int test; int done; int signals_handled; pthread_t main_thread; pthread_mutex_t mutex; pthread_cond_t cond; void timer_handler(int signum) { write(2, "timer_handler\n", strlen("timer_handler\n")); if (++signals_handled < 10) return; switch (test) { case 0: __atomic_store_n(&done, 1, __ATOMIC_RELEASE); (void)pthread_kill(main_thread, SIGUSR1); case 1: if (pthread_mutex_trylock(&mutex) == 0) { __atomic_store_n(&done, 1, __ATOMIC_RELEASE); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } case 2: __atomic_store_n(&done, 1, __ATOMIC_RELEASE); } } int main(int argc, char **argv) { main_thread = pthread_self(); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGUSR1); if (sigprocmask(SIG_BLOCK, &sigset, NULL)) exit((perror("sigprocmask"), 1)); struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = &timer_handler; if (sigaction(SIGALRM, &sa, NULL)) exit((perror("setitimer"), 1)); for (test = 0; test < 3; test++) { fprintf(stderr, "test %d\n", test); struct itimerval timer; timer.it_value.tv_sec = 0; timer.it_value.tv_usec = 50000; timer.it_interval = timer.it_value; if (setitimer(ITIMER_REAL, &timer, NULL)) exit((perror("setitimer"), 1)); switch (test) { case 0: while (__atomic_load_n(&done, __ATOMIC_ACQUIRE) == 0) { int signum; sigwait(&sigset, &signum); write(2, "sigwait\n", strlen("sigwait\n")); } case 1: pthread_mutex_lock(&mutex); while (__atomic_load_n(&done, __ATOMIC_ACQUIRE) == 0) { pthread_cond_wait(&cond, &mutex); write(2, "pthread_cond_wait\n", strlen("pthread_cond_wait\n")); } pthread_mutex_unlock(&mutex); case 2: while (__atomic_load_n(&done, __ATOMIC_ACQUIRE) == 0) { } } memset(&timer, 0, sizeof(timer)); if (setitimer(ITIMER_REAL, &timer, NULL)) exit((perror("setitimer"), 1)); done = 0; signals_handled = 0; } fprintf(stderr, "DONE\n"); } // CHECK: DONE
26.576087
81
0.643354
mkinsner
f93da586f7696291600bee410e128438d30e4fbf
15,828
cc
C++
ash/login/ui/login_bubble_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ash/login/ui/login_bubble_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ash/login/ui/login_bubble_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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 <memory> #include <utility> #include "ash/login/ui/login_bubble.h" #include "ash/login/ui/login_button.h" #include "ash/login/ui/login_menu_view.h" #include "ash/login/ui/login_test_base.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/test/event_generator.h" #include "ui/views/animation/test/ink_drop_host_view_test_api.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/widget/widget.h" namespace ash { namespace { // Total width of the bubble view. constexpr int kBubbleTotalWidthDp = 178; // Horizontal margin of the bubble view. constexpr int kBubbleHorizontalMarginDp = 14; // Top margin of the bubble view. constexpr int kBubbleTopMarginDp = 13; // Bottom margin of the bubble view. constexpr int kBubbleBottomMarginDp = 18; // Non zero size for the bubble anchor view. constexpr int kBubbleAnchorViewSizeDp = 100; std::vector<LoginMenuView::Item> PopulateMenuItems() { std::vector<LoginMenuView::Item> items; // Add one regular item. LoginMenuView::Item item1; item1.title = "Regular Item 1"; item1.is_group = false; item1.selected = true; items.push_back(item1); // Add one group item. LoginMenuView::Item item2; item2.title = "Group Item 2"; item2.is_group = true; items.push_back(item2); // Add another regular item. LoginMenuView::Item item3; item3.title = "Regular Item 2"; item3.is_group = false; items.push_back(item3); return items; } class LoginBubbleTest : public LoginTestBase { protected: LoginBubbleTest() = default; ~LoginBubbleTest() override = default; // LoginTestBase: void SetUp() override { LoginTestBase::SetUp(); container_ = new views::View(); container_->SetLayoutManager( std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical)); bubble_opener_ = new LoginButton(nullptr /*listener*/); other_view_ = new views::View(); bubble_opener_->SetFocusBehavior(views::View::FocusBehavior::ALWAYS); other_view_->SetFocusBehavior(views::View::FocusBehavior::ALWAYS); other_view_->SetPreferredSize( gfx::Size(kBubbleAnchorViewSizeDp, kBubbleAnchorViewSizeDp)); bubble_opener_->SetPreferredSize( gfx::Size(kBubbleAnchorViewSizeDp, kBubbleAnchorViewSizeDp)); container_->AddChildView(bubble_opener_); container_->AddChildView(other_view_); SetWidget(CreateWidgetWithContent(container_)); bubble_ = std::make_unique<LoginBubble>(); } void TearDown() override { bubble_.reset(); LoginTestBase::TearDown(); } void ShowUserMenu(base::OnceClosure on_remove_show_warning, base::OnceClosure on_remove) { bool show_remove_user = !on_remove.is_null(); bubble_->ShowUserMenu( base::string16() /*username*/, base::string16() /*email*/, user_manager::UserType::USER_TYPE_REGULAR, false /*is_owner*/, container_, bubble_opener_, show_remove_user, std::move(on_remove_show_warning), std::move(on_remove)); } void ShowSelectionMenu(const LoginMenuView::OnSelect& on_select) { LoginMenuView* view = new LoginMenuView(PopulateMenuItems(), container_, on_select); bubble_->ShowSelectionMenu(view, bubble_opener_); } // Owned by test widget view hierarchy. views::View* container_ = nullptr; // Owned by test widget view hierarchy. LoginButton* bubble_opener_ = nullptr; // Owned by test widget view hierarchy. views::View* other_view_ = nullptr; std::unique_ptr<LoginBubble> bubble_; private: DISALLOW_COPY_AND_ASSIGN(LoginBubbleTest); }; } // namespace // Verifies the base bubble settings. TEST_F(LoginBubbleTest, BaseBubbleSettings) { bubble_->ShowTooltip(base::string16(), bubble_opener_); EXPECT_TRUE(bubble_->IsVisible()); LoginBaseBubbleView* bubble_view = bubble_->bubble_view(); EXPECT_EQ(bubble_view->GetDialogButtons(), ui::DIALOG_BUTTON_NONE); EXPECT_EQ(bubble_view->width(), kBubbleTotalWidthDp); EXPECT_EQ(bubble_view->color(), SK_ColorBLACK); EXPECT_EQ(bubble_view->margins(), gfx::Insets(kBubbleTopMarginDp, kBubbleHorizontalMarginDp, kBubbleBottomMarginDp, kBubbleHorizontalMarginDp)); bubble_->Close(); } // Verifies the bubble handles key event correctly. TEST_F(LoginBubbleTest, BubbleKeyEventHandling) { EXPECT_FALSE(bubble_->IsVisible()); // Verifies that key event won't open the bubble. ui::test::EventGenerator& generator = GetEventGenerator(); other_view_->RequestFocus(); generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE); EXPECT_FALSE(bubble_->IsVisible()); // Verifies that key event on the bubble opener view won't close the bubble. ShowUserMenu(base::OnceClosure(), base::OnceClosure()); EXPECT_TRUE(bubble_->IsVisible()); bubble_opener_->RequestFocus(); generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that key event on the other view will close the bubble. other_view_->RequestFocus(); generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE); EXPECT_FALSE(bubble_->IsVisible()); } // Verifies the bubble handles mouse event correctly. TEST_F(LoginBubbleTest, BubbleMouseEventHandling) { EXPECT_FALSE(bubble_->IsVisible()); // Verifies that mouse event won't open the bubble. ui::test::EventGenerator& generator = GetEventGenerator(); generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_FALSE(bubble_->IsVisible()); // Verifies that mouse event on the bubble opener view won't close the bubble. ShowUserMenu(base::OnceClosure(), base::OnceClosure()); EXPECT_TRUE(bubble_->IsVisible()); generator.MoveMouseTo(bubble_opener_->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that mouse event on the bubble itself won't close the bubble. generator.MoveMouseTo( bubble_->bubble_view()->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that mouse event on the other view will close the bubble. generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_FALSE(bubble_->IsVisible()); } // Verifies the bubble handles gesture event correctly. TEST_F(LoginBubbleTest, BubbleGestureEventHandling) { EXPECT_FALSE(bubble_->IsVisible()); // Verifies that gesture event won't open the bubble. ui::test::EventGenerator& generator = GetEventGenerator(); generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint()); EXPECT_FALSE(bubble_->IsVisible()); // Verifies that gesture event on the bubble opener view won't close the // bubble. ShowUserMenu(base::OnceClosure(), base::OnceClosure()); EXPECT_TRUE(bubble_->IsVisible()); generator.GestureTapAt(bubble_opener_->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that gesture event on the bubble itself won't close the bubble. generator.GestureTapAt( bubble_->bubble_view()->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that gesture event on the other view will close the bubble. generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint()); EXPECT_FALSE(bubble_->IsVisible()); } // Verifies the ripple effects for the login button. TEST_F(LoginBubbleTest, LoginButtonRipple) { views::test::InkDropHostViewTestApi ink_drop_api(bubble_opener_); EXPECT_EQ(ink_drop_api.ink_drop_mode(), views::InkDropHostView::InkDropMode::ON); // Show the bubble to activate the ripple effect. ShowUserMenu(base::OnceClosure(), base::OnceClosure()); EXPECT_TRUE(bubble_->IsVisible()); EXPECT_TRUE(ink_drop_api.HasInkDrop()); EXPECT_EQ(ink_drop_api.GetInkDrop()->GetTargetInkDropState(), views::InkDropState::ACTIVATED); EXPECT_TRUE(ink_drop_api.GetInkDrop()->IsHighlightFadingInOrVisible()); // Close the bubble should hide the ripple effect. ui::test::EventGenerator& generator = GetEventGenerator(); generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_FALSE(bubble_->IsVisible()); // InkDropState::DEACTIVATED state will automatically transition to the // InkDropState::HIDDEN state. EXPECT_EQ(ink_drop_api.GetInkDrop()->GetTargetInkDropState(), views::InkDropState::HIDDEN); EXPECT_FALSE(ink_drop_api.GetInkDrop()->IsHighlightFadingInOrVisible()); } // Verifies that clicking remove user requires two clicks before firing the // callback. TEST_F(LoginBubbleTest, RemoveUserRequiresTwoActivations) { // Show the user menu. bool remove_warning_called = false; bool remove_called = false; ShowUserMenu( base::BindOnce( [](bool* remove_warning_called) { *remove_warning_called = true; }, &remove_warning_called), base::BindOnce([](bool* remove_called) { *remove_called = true; }, &remove_called)); EXPECT_TRUE(bubble_->IsVisible()); // Focus the remove user button. views::View* remove_user_button = bubble_->bubble_view()->GetViewByID( LoginBubble::kUserMenuRemoveUserButtonIdForTest); remove_user_button->RequestFocus(); EXPECT_TRUE(remove_user_button->HasFocus()); auto click = [&]() { EXPECT_TRUE(remove_user_button->HasFocus()); GetEventGenerator().PressKey(ui::KeyboardCode::VKEY_RETURN, 0); }; // First click calls remove warning. EXPECT_NO_FATAL_FAILURE(click()); EXPECT_TRUE(remove_warning_called); EXPECT_FALSE(remove_called); remove_warning_called = false; // Second click calls remove. EXPECT_NO_FATAL_FAILURE(click()); EXPECT_FALSE(remove_warning_called); EXPECT_TRUE(remove_called); } TEST_F(LoginBubbleTest, ErrorBubbleKeyEventHandling) { ui::test::EventGenerator& generator = GetEventGenerator(); EXPECT_FALSE(bubble_->IsVisible()); views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text")); bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagsNone); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that key event on a view other than error closes the error bubble. other_view_->RequestFocus(); generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE); EXPECT_FALSE(bubble_->IsVisible()); } TEST_F(LoginBubbleTest, ErrorBubbleMouseEventHandling) { ui::test::EventGenerator& generator = GetEventGenerator(); EXPECT_FALSE(bubble_->IsVisible()); views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text")); bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagsNone); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that mouse event on the bubble itself won't close the bubble. generator.MoveMouseTo( bubble_->bubble_view()->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that mouse event on the other view will close the bubble. generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_FALSE(bubble_->IsVisible()); } TEST_F(LoginBubbleTest, ErrorBubbleGestureEventHandling) { ui::test::EventGenerator& generator = GetEventGenerator(); EXPECT_FALSE(bubble_->IsVisible()); views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text")); bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagsNone); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that gesture event on the bubble itself won't close the bubble. generator.GestureTapAt( bubble_->bubble_view()->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that gesture event on the other view will close the bubble. generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint()); EXPECT_FALSE(bubble_->IsVisible()); } TEST_F(LoginBubbleTest, PersistentErrorBubbleEventHandling) { ui::test::EventGenerator& generator = GetEventGenerator(); EXPECT_FALSE(bubble_->IsVisible()); views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text")); bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagPersistent); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that mouse event on the bubble itself won't close the bubble. generator.MoveMouseTo( bubble_->bubble_view()->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that mouse event on the other view won't close the bubble. generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint()); generator.ClickLeftButton(); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that gesture event on the bubble itself won't close the bubble. generator.GestureTapAt( bubble_->bubble_view()->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that gesture event on the other view won't close the bubble. generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that key event on the other view won't close the bubble. other_view_->RequestFocus(); generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE); EXPECT_TRUE(bubble_->IsVisible()); // LoginBubble::Close should close the persistent error bubble. bubble_->Close(); EXPECT_FALSE(bubble_->IsVisible()); } TEST_F(LoginBubbleTest, TestShowSelectionMenu) { ui::test::EventGenerator& generator = GetEventGenerator(); EXPECT_FALSE(bubble_->IsVisible()); LoginMenuView::Item selected_item; bool selected = false; ShowSelectionMenu(base::BindLambdaForTesting([&](LoginMenuView::Item item) { selected_item = item; selected = true; })); EXPECT_TRUE(bubble_->IsVisible()); // Verifies that regular item 1 is selectable. LoginMenuView* menu_view = static_cast<LoginMenuView*>(bubble_->bubble_view()); LoginMenuView::TestApi test_api1(menu_view); EXPECT_TRUE(test_api1.contents()->child_at(0)->HasFocus()); generator.PressKey(ui::KeyboardCode::VKEY_RETURN, 0 /*flag*/); EXPECT_FALSE(bubble_->IsVisible()); EXPECT_EQ(selected_item.title, "Regular Item 1"); EXPECT_TRUE(selected); // Verfies that group item 2 is not selectable. selected = false; ShowSelectionMenu(base::BindLambdaForTesting([&](LoginMenuView::Item item) { selected_item = item; selected = true; })); EXPECT_TRUE(bubble_->IsVisible()); menu_view = static_cast<LoginMenuView*>(bubble_->bubble_view()); LoginMenuView::TestApi test_api2(menu_view); test_api2.contents()->child_at(1)->RequestFocus(); generator.PressKey(ui::KeyboardCode::VKEY_RETURN, 0 /*flag*/); EXPECT_TRUE(bubble_->IsVisible()); EXPECT_FALSE(selected); // Verifies up/down arrow key can navigate menu entries. generator.PressKey(ui::KeyboardCode::VKEY_UP, 0 /*flag*/); EXPECT_TRUE(test_api2.contents()->child_at(0)->HasFocus()); generator.PressKey(ui::KeyboardCode::VKEY_UP, 0 /*flag*/); EXPECT_TRUE(test_api2.contents()->child_at(0)->HasFocus()); generator.PressKey(ui::KeyboardCode::VKEY_DOWN, 0 /*flag*/); // Group item is skipped in up/down key navigation. EXPECT_TRUE(test_api2.contents()->child_at(2)->HasFocus()); generator.PressKey(ui::KeyboardCode::VKEY_DOWN, 0 /*flag*/); EXPECT_TRUE(test_api2.contents()->child_at(2)->HasFocus()); EXPECT_TRUE(bubble_->IsVisible()); bubble_->Close(); EXPECT_FALSE(bubble_->IsVisible()); } } // namespace ash
36.809302
80
0.740649
zipated
f93f1f10cc37eb7f4b1115bb7731d417a9b66855
481
cpp
C++
Matrici/el_pozitive.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
Matrici/el_pozitive.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
Matrici/el_pozitive.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <iostream> using namespace std; int main() { int a[30][30] ,nr, i, j, n, m ; cout<<"Numar de linii "; cin>>n; cout<<"Numar de coloane "; cin>>m; for(i=1; i<=n; i++) { for(j=1; j<=m; j++) {cout<<"a["<<i<<"]["<<j<<"] = "; cin>>a[i][j]; } if(a[i][j]>0) nr++; } cout<<"Numarul elemtelor pozitive: "<<nr; system("pause"); return 0 ; }
26.722222
64
0.37422
rusucosmin
f943654563d0575b5057d5468ba72d1f3e85fac9
8,700
cc
C++
src/main/c/zmq/zmq_pub.cc
bopopescu/hydra
ec0793f8c1f49ceb93bf1f1a9789085b68d55f08
[ "Apache-2.0" ]
10
2016-05-28T15:56:43.000Z
2018-01-03T21:30:58.000Z
src/main/c/zmq/zmq_pub.cc
bopopescu/hydra
ec0793f8c1f49ceb93bf1f1a9789085b68d55f08
[ "Apache-2.0" ]
17
2016-06-06T22:15:28.000Z
2020-07-22T20:28:12.000Z
src/main/c/zmq/zmq_pub.cc
bopopescu/hydra
ec0793f8c1f49ceb93bf1f1a9789085b68d55f08
[ "Apache-2.0" ]
5
2016-06-01T22:01:44.000Z
2020-07-22T20:12:49.000Z
#include <zmq.hpp> #include <stdio.h> #include <unistd.h> #include <string> #include <assert.h> #include <stdlib.h> #include <ctime> #include "hdaemon.pb.h" #include <iostream> class TestControl { public: TestControl() { publishing = start_publishing = false; test_duration = 5; msg_batch = 100; msg_requested_rate = 1000; msg_cnt = 0; } uint64_t start_test() { floatStats.clear(); intStats.clear(); uint64_t start_time = std::time(0); intStats["time:start"] = start_time; msg_cnt = 0; return start_time; } void stop_test() { // do stats calculation here intStats["time:end"] = std::time(0); uint64_t elapsed_time = intStats["time:end"] - intStats["time:start"]; floatStats["rate"] = 1.0 * msg_cnt / elapsed_time; intStats["msg_cnt"] = msg_cnt; } bool publishing; bool start_publishing; std::map <std::string, uint64_t> intStats; std::map <std::string, float> floatStats; uint32_t test_duration; uint32_t msg_batch; uint32_t msg_requested_rate; uint64_t msg_cnt; }; void process_message(const std::string& msg, TestControl* tctrl, std::string* resp) { hydra::CommandMessage cmsg; hydra::ResponseMessage rmsg; hydra::ResponseMessage_Resp* r; if (!cmsg.ParseFromString(msg)) { rmsg.set_status("error"); r = rmsg.add_resp(); r->set_name("__r"); r->set_strvalue("Unable to parse the protobuf string!!!"); printf("Unable to parse protbuf message received of size %d\n", (int)msg.size()); } else if (cmsg.type() == hydra::CommandMessage::SUBCMD && cmsg.has_cmd()) { std::string cmd_name = cmsg.cmd().cmd_name(); printf("Received a command [%s]\n", cmd_name.c_str()); fflush(NULL); if (cmd_name == "ping") { // PING - PONG. rmsg.set_status("ok"); r = rmsg.add_resp(); r->set_name("__r"); r->set_strvalue("pong"); } else if (cmd_name == "teststart") { // START of test. r = rmsg.add_resp(); r->set_name("__r"); if (tctrl->publishing || tctrl->start_publishing) { rmsg.set_status("error"); r->set_strvalue("test is still running, cant start."); } else { rmsg.set_status("ok"); r->set_strvalue("starting"); tctrl->start_publishing = true; } } else if (cmd_name == "teststatus") { // get test status rmsg.set_status("ok"); std::string tstatus; if (tctrl->publishing && tctrl->start_publishing) tstatus = "running"; else if (tctrl->publishing && !tctrl->start_publishing) tstatus = "stopping"; else if (!tctrl->publishing && tctrl->start_publishing) tstatus = "starting"; else tstatus = "stopped"; r = rmsg.add_resp(); r->set_name("__r"); r->set_strvalue(tstatus); printf("\t -> TestStatus:%s\n", tstatus.c_str()); } else if (cmd_name == "updateconfig") { // update test properties for (int i = 0; i < cmsg.cmd().argument_size(); ++i) { hydra::CommandMessage_CommandArgs arg = cmsg.cmd().argument(i); printf("\t -> name = %s [int:%d float:%d str:%d]\n", arg.name().c_str(), arg.has_intvalue(), arg.has_floatvalue(), arg.has_strvalue()); fflush(NULL); if (arg.name() == "test_duration") { assert(arg.has_intvalue()); tctrl->test_duration = arg.intvalue(); printf("\t -> updatedpub test_duration=%d\n", tctrl->test_duration); } else if (arg.name() == "msg_batch") { assert(arg.has_intvalue()); tctrl->msg_batch = arg.intvalue(); printf("\t -> updatedpub msg_batch=%d\n", tctrl->msg_batch); } else if (arg.name() == "msg_requested_rate") { assert(arg.has_intvalue() || arg.has_floatvalue()); if (arg.has_intvalue()) tctrl->msg_requested_rate = arg.intvalue(); else tctrl->msg_requested_rate = arg.floatvalue(); printf("\t -> updatedpub msg_requested_rate=%d\n", tctrl->msg_requested_rate); } } rmsg.set_status("ok"); } else if (cmd_name == "getstats") { rmsg.set_status("ok"); for (auto it = tctrl->intStats.begin(); it != tctrl->intStats.end(); ++it) { r = rmsg.add_resp(); r->set_name(it->first); r->set_intvalue(it->second); } for (auto it = tctrl->floatStats.begin(); it != tctrl->floatStats.end(); ++it) { r = rmsg.add_resp(); r->set_name(it->first); r->set_floatvalue(it->second); } } else { // INVALID COMMAND. rmsg.set_status("error"); r = rmsg.add_resp(); r->set_name("__r"); std::string m = "Did not find implemented for Command "; m += cmd_name; r->set_strvalue(m); } } else { rmsg.set_status("error"); r = rmsg.add_resp(); r->set_name("__r"); std::string m = "Did not find Command in the message or cmd type[" + std::to_string(cmsg.type()) + "] is incorrect"; r->set_strvalue(m); } printf(" -> Responding with status [%s]\n", rmsg.status().c_str()); fflush(NULL); assert(rmsg.SerializeToString(resp)); } // ping // start // get stats // test status // update pub metrics // parse protobuf // extract command // process command // create response // send reply int main (void) { GOOGLE_PROTOBUF_VERIFY_VERSION; zmq::context_t context(1); zmq::socket_t socket_rep(context, ZMQ_REP); zmq::socket_t socket_pub(context, ZMQ_PUB); if (0) { // with the watermark disabled // no drops will be there // however a slow client can cause the publisher to slow down. int hwm = 0; socket_pub.setsockopt(ZMQ_SNDHWM, &hwm, sizeof(hwm)); } { int ghwm; size_t ghwm_s = sizeof(ghwm); socket_pub.getsockopt(ZMQ_SNDHWM, &ghwm, &ghwm_s); printf("ZMQ SNDHWM is set to %d\n", ghwm); } std::string strPort = std::string(getenv("PORT0")); printf("Starting Rep Server on port %s\n", strPort.c_str()); fflush(NULL); socket_rep.bind("tcp://*:" + strPort); socket_pub.bind("tcp://*:15556"); TestControl tctrl; uint32_t cnt = 0; uint64_t start_time; char message_ch[120]; while(true) { zmq_pollitem_t items[] = { {static_cast<void *>(socket_rep), 0, ZMQ_POLLIN, 0} }; int rc = zmq_poll(items, 1, 0); if (rc == -1) { printf("ZMQ POLL had error \n"); break; } if (items[0].revents & ZMQ_POLLIN) { zmq::message_t request; socket_rep.recv(&request); std::string resp; process_message(std::string((char *)request.data(), request.size()), &tctrl, &resp); zmq::message_t reply(resp.c_str(), resp.size()); socket_rep.send(reply); } if (!tctrl.publishing && tctrl.start_publishing) { tctrl.publishing = true; start_time = tctrl.start_test(); cnt = 0; printf("Starting the test\n"); fflush(NULL); } else if (tctrl.publishing && !tctrl.start_publishing) { tctrl.publishing = false; tctrl.stop_test(); printf("Stopped the test\n"); fflush(NULL); } else if (!tctrl.publishing) { // to prevent spinning while test is idle sleep(1); } // Send the message to pub while (tctrl.publishing) { ++cnt; if (cnt >= (tctrl.msg_batch-1)) { // check cnt and delay if needed if (cnt == (tctrl.msg_batch - 1)) break; // break once before sleep to allow poll to // use up some of the delay if (cnt >= tctrl.msg_batch) { time_t duration = std::time(0) - start_time; double exp_time = (double) tctrl.msg_cnt / tctrl.msg_requested_rate; double delay = 0; if (duration > tctrl.test_duration) { tctrl.start_publishing = false; break; } if (exp_time > duration) delay = exp_time - duration; if (delay > 1) delay = 1; usleep(delay * 1e6); cnt = 0; } } // send some data //std::strig str_msgcnt = atoi(msg_cnt); //std::string msg = str_msgcnt + " msg" + str_msgcnt; snprintf(message_ch, sizeof(message_ch), "%ld msg%ld",tctrl.msg_cnt, tctrl.msg_cnt); zmq::message_t message(strlen(message_ch)); memcpy(message.data(), message_ch, strlen(message_ch)); //message.rebuild(message_ch, strlen(message_ch)); rc = socket_pub.send(message); if (!rc) printf(" ERROR Failed to send message %s\n", message_ch); ++tctrl.msg_cnt; } // while(publishing) } // while(true) return 0; }
32.222222
143
0.586667
bopopescu
f946696a7d0623b6cb4cc3138e4b97679ef3ab6d
8,891
hpp
C++
test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
17
2015-07-03T06:53:05.000Z
2021-05-15T20:55:12.000Z
test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
3
2015-02-20T12:48:17.000Z
2019-12-18T08:45:13.000Z
test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
15
2015-02-20T11:34:14.000Z
2021-05-15T20:55:13.000Z
/* * This is part of the fl library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2015 Max Planck Society, * Autonomous Motion Department, * Institute for Intelligent Systems * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_linear_vs_x_test_suite.hpp * \date July 2015 * \author Jan Issac (jan.issac@gmail.com) */ #include <gtest/gtest.h> #include "../typecast.hpp" #include <Eigen/Dense> #include <cmath> #include <iostream> #include <fl/util/math/linear_algebra.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/filter/gaussian/gaussian_filter_linear.hpp> #include <fl/model/transition/linear_transition.hpp> #include <fl/model/sensor/linear_gaussian_sensor.hpp> #include <fl/model/sensor/linear_decorrelated_gaussian_sensor.hpp> enum : signed int { DecorrelatedGaussianModel, GaussianModel }; static constexpr double epsilon = 0.1; template <typename TestType> class GaussianFilterLinearVsXTest : public ::testing::Test { protected: typedef typename TestType::Parameter Configuration; enum: signed int { StateDim = Configuration::StateDim, InputDim = Configuration::InputDim, ObsrvDim = Configuration::ObsrvDim, StateSize = fl::TestSize<StateDim, TestType>::Value, InputSize = fl::TestSize<InputDim, TestType>::Value, ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value }; enum ModelSetup { Random, Identity }; typedef Eigen::Matrix<fl::Real, StateSize, 1> State; typedef Eigen::Matrix<fl::Real, InputSize, 1> Input; typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv; typedef fl::IntegerTypeMap< fl::IntegerTypePair< DecorrelatedGaussianModel, fl::LinearDecorrelatedGaussianSensor<Obsrv, State> >, fl::IntegerTypePair< GaussianModel, fl::LinearGaussianSensor<Obsrv, State> > > SensorMap; typedef fl::LinearTransition<State, State, Input> LinearTransition; typedef typename SensorMap::template Select< Configuration::SelectedModel >::Type LinearSensor; typedef fl::GaussianFilter< LinearTransition, LinearSensor > KalmanFilter; typedef typename Configuration::template FilterDefinition< LinearTransition, LinearSensor > FilterDefinition; typedef typename FilterDefinition::Type Filter; GaussianFilterLinearVsXTest() : predict_steps_(200), predict_update_steps_(30) { } KalmanFilter create_kalman_filter() const { return KalmanFilter( LinearTransition(StateDim, InputDim), LinearSensor(ObsrvDim, StateDim)); } Filter create_filter() const { return Configuration::create_filter( LinearTransition(StateDim, InputDim), LinearSensor(ObsrvDim, StateDim)); } void setup_models( KalmanFilter& kalman_filter, Filter& other_filter, ModelSetup setup) { auto A = kalman_filter.transition().create_dynamics_matrix(); auto B = kalman_filter.transition().create_input_matrix(); auto Q = kalman_filter.transition().create_noise_matrix(); auto H = kalman_filter.sensor().create_sensor_matrix(); auto R = kalman_filter.sensor().create_noise_matrix(); Q.setZero(); R.setZero(); B.setZero(); switch (setup) { case Random: A.diagonal().setRandom(); H.diagonal().setRandom(); Q.diagonal().setRandom(); Q *= Q.transpose().eval(); R.diagonal().setRandom(); R *= R.transpose().eval(); break; case Identity: A.setIdentity(); H.setIdentity(); Q.setIdentity(); R.setIdentity(); break; } kalman_filter.transition().dynamics_matrix(A); kalman_filter.transition().input_matrix(B); kalman_filter.transition().noise_matrix(Q); kalman_filter.sensor().sensor_matrix(H); kalman_filter.sensor().noise_matrix(R); other_filter.transition().dynamics_matrix(A); other_filter.transition().input_matrix(B); other_filter.transition().noise_matrix(Q); other_filter.sensor().sensor_matrix(H); other_filter.sensor().noise_matrix(R); } State zero_state() { return State::Zero(StateDim); } Input zero_input() { return Input::Zero(InputDim); } Obsrv zero_obsrv() { return Obsrv::Zero(ObsrvDim); } State rand_state() { return State::Random(StateDim); } Input rand_input() { return Input::Random(InputDim); } Obsrv rand_obsrv() { return Obsrv::Random(ObsrvDim); } protected: int predict_steps_; int predict_update_steps_; }; TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest); //TYPED_TEST_P(GaussianFilterLinearVsXTest, predict) //{ // typedef TestFixture This; // auto other_filter = This::create_filter(); // auto kalman_filter = This::create_kalman_filter(); // This::setup_models(kalman_filter, other_filter, This::Random); // auto belief_other = other_filter.create_belief(); // auto belief_kf = kalman_filter.create_belief(); // for (int i = 0; i < This::predict_steps_; ++i) // { // other_filter.predict(belief_other, This::zero_input(), belief_other); // kalman_filter.predict(belief_kf, This::zero_input(), belief_kf); // if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon)) // { // std::cout << "i = " << i << std::endl; // PV(belief_kf.mean()); // PV(belief_other.mean()); // } // if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon)) // { // std::cout << "i = " << i << std::endl; // PV(belief_kf.covariance()); // PV(belief_other.covariance()); // } // ASSERT_TRUE( // fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon)); // ASSERT_TRUE( // fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon)); // } // PV(belief_kf.mean()); // PV(belief_other.mean()); // PV(belief_kf.covariance()); // PV(belief_other.covariance()); //} TYPED_TEST_P(GaussianFilterLinearVsXTest, predict_and_update) { typedef TestFixture This; auto other_filter = This::create_filter(); auto kalman_filter = This::create_kalman_filter(); This::setup_models(kalman_filter, other_filter, This::Random); auto belief_other = other_filter.create_belief(); auto belief_kf = kalman_filter.create_belief(); for (int i = 0; i < This::predict_update_steps_; ++i) { auto y = This::rand_obsrv(); kalman_filter.predict(belief_kf, This::zero_input(), belief_kf); other_filter.predict(belief_other, This::zero_input(), belief_other); // if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon)) // { // std::cout << "predict i = " << i << std::endl; // PV(belief_kf.mean()); // PV(belief_other.mean()); // } // if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon)) // { // std::cout << "predict i = " << i << std::endl; // PV(belief_kf.covariance()); // PV(belief_other.covariance()); // } kalman_filter.update(belief_kf, y, belief_kf); other_filter.update(belief_other, y, belief_other); // if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon)) // { // std::cout << "update i = " << i << std::endl; // PV(belief_kf.mean()); // PV(belief_other.mean()); // } // if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon)) // { // std::cout << "update i = " << i << std::endl; // PV(belief_kf.covariance()); // PV(belief_other.covariance()); // } ASSERT_TRUE( fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon)); ASSERT_TRUE( fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon)); } // PV(belief_kf.mean()); // PV(belief_other.mean()); // PV(belief_kf.covariance()); // PV(belief_other.covariance()); // std::cout << other_filter.name() << std::endl; } REGISTER_TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest, predict_and_update);
30.44863
91
0.614554
aeolusbot-tommyliu
f9489c7099d51b45affa6dae1069cc8b8267ccdf
780
cpp
C++
test/TestCommons.cpp
gtauzin/metaLBM
07291e085962f50848489fd36ece46ce412bdbb5
[ "MIT" ]
7
2019-10-19T22:58:30.000Z
2022-03-29T03:45:51.000Z
test/TestCommons.cpp
gtauzin/metaLBM
07291e085962f50848489fd36ece46ce412bdbb5
[ "MIT" ]
1
2022-02-04T14:08:45.000Z
2022-02-05T21:06:28.000Z
test/TestCommons.cpp
gtauzin/metaLBM
07291e085962f50848489fd36ece46ce412bdbb5
[ "MIT" ]
2
2021-02-05T23:52:14.000Z
2021-06-16T02:49:20.000Z
#define BOOST_TEST_MODULE "C++ Unit Tests for metaLBM" #include <boost/test/included/unit_test.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> namespace tt = boost::test_tools; #include <iostream> #define NPROCS 1 #include "Lattice.h" typedef double valueType; typedef lbm::Lattice<valueType, lbm::LatticeType::D1Q3> L; #include "Commons.h" #include "MathVector.h" using namespace lbm; BOOST_AUTO_TEST_SUITE(TestCommons) BOOST_AUTO_TEST_CASE(TestVTR) { constexpr CommonsType commonsType = CommonsType::Global; constexpr MathVector<int, 3> iP{{1}}; Commons<valueType, commonsType> commons(amplitude); BOOST_TEST(commons.write(iP)[d::X] == (valueType) 1, tt::tolerance(1e-15)); } BOOST_AUTO_TEST_SUITE_END()
25.16129
58
0.755128
gtauzin
f94e38df5799ef9f869a4654054e011cac6b46a3
13,307
hpp
C++
common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <string> #include <vector> #include "adstlog_cxx/p7_trace_wrapper.hpp" // clang-format off // Actor module registers all of these channels #define ADSTLOG_ACTOR_CH p7ActorCh_ #define ADSTLOG_MSG_TX_CH p7MsgTxCh_ #define ADSTLOG_MSG_RX_CH p7MsgRxCh_ #define ADSTLOG_GRPC_RX_CH p7GrpcRxCh_ #define ADSTLOG_GRPC_TX_CH p7GrpcTxCh_ #define ADSTLOG_GRPC_CH p7GrpcCh_ #define ADSTLOG_CORE_CH p7CoreCh_ // channel names to be used for set trace level on channels #define ADSTLOG_MSG_TX_CH_NAME "msg_tx" // message published internal dispatch #define ADSTLOG_MSG_RX_CH_NAME "msg_rx" // message consumed internal dispatch #define ADSTLOG_GRPC_RX_CH_NAME "grpc_rx" // message received between processes #define ADSTLOG_GRPC_TX_CH_NAME "grpc_tx" // message transmitted between processes #define ADSTLOG_GRPC_CH_NAME "grpc" // used in gRPC boarder actors debugging #define ADSTLOG_CORE_CH_NAME "core" // used by all framework classes #define ADSTLOG_ACTOR_CH_NAME "actor" // all user modules are on this channel // helper to be used in for loops to iterate over on channels. #define ADSTLOG_TRACE_CHANNELS \ ADSTLOG_MSG_TX_CH_NAME, \ ADSTLOG_MSG_RX_CH_NAME, \ ADSTLOG_GRPC_RX_CH_NAME, \ ADSTLOG_GRPC_TX_CH_NAME, \ ADSTLOG_GRPC_CH_NAME, \ ADSTLOG_CORE_CH_NAME, \ ADSTLOG_ACTOR_CH_NAME // the actual call for the trace function #define ADSTLOG_LOG_ON(OBJ, LVL, CHANNEL, MODULE, ...) \ OBJ->CHANNEL->getObj()->Trace(0, \ LVL, \ OBJ->MODULE, \ (tUINT16)__LINE__, \ (const char*)__FILE__, \ (const char*)__FUNCTION__, \ __VA_ARGS__) // then the logging is happening in a class where trace defined #define ADSTLOG_LOG(...) \ ADSTLOG_LOG_ON(this, __VA_ARGS__) // helper macros #define ADSTLOG_CH(CH) ADSTLOG_##CH##_CH #define ADSTLOG_CH_MOD(CH, MOD) p7_##CH##_##MOD##_ // Helper macros for define / declare traces in actor base #define ADSTLOG_GET_CH(CH) mutable adst::common::Logger::ChannelUPtr ADSTLOG_CH(CH) = \ std::make_unique<adst::common::ManageTraceObj<IP7_Trace>>(&P7_Get_Shared_Trace, \ ADSTLOG_##CH##_CH_NAME, &IP7_Trace::Release) #define ADSTLOG_DEFINE_CH(CH) mutable adst::common::Logger::ChannelUPtr ADSTLOG_CH(CH) = nullptr #define ADSTLOG_INIT_CH(CH) ADSTLOG_CH(CH) = \ std::make_unique<adst::common::ManageTraceObj<IP7_Trace>>(&P7_Get_Shared_Trace, \ ADSTLOG_##CH##_CH_NAME, &IP7_Trace::Release) #define ADSTLOG_REGISTER_MODULE(CH, MOD, NAME) \ mutable IP7_Trace::hModule ADSTLOG_CH_MOD(CH, MOD) = nullptr; \ tBOOL isNewModule_##CH##_##MOD = ADSTLOG_CH(CH)->getObj()->Register_Module(NAME, &ADSTLOG_CH_MOD(CH, MOD)) #define ADSTLOG_DEFINE_MODULE(CH, MOD) mutable IP7_Trace::hModule ADSTLOG_CH_MOD(CH, MOD) = nullptr #define ADSTLOG_INIT_MODULE(CH, MOD, NAME) ADSTLOG_CH(CH)->getObj()->Register_Module(NAME, &ADSTLOG_CH_MOD(CH, MOD)) #define TEST_HELPER_ADSTLOG_UNUSED(CH, MOD) \ mutable (void)isNewModule_##CH##_##MOD // public macros #define TEST_HELPER_ADSTLOG_UNUSED_ALL() \ TEST_HELPER_ADSTLOG_UNUSED(ACTOR, ACTOR); \ TEST_HELPER_ADSTLOG_UNUSED(MSG_TX, ACTOR); \ TEST_HELPER_ADSTLOG_UNUSED(MSG_RX, ACTOR); \ TEST_HELPER_ADSTLOG_UNUSED(GRPC_RX, ACTOR); \ TEST_HELPER_ADSTLOG_UNUSED(GRPC_TX, ACTOR); \ TEST_HELPER_ADSTLOG_UNUSED(GRPC, ACTOR); \ TEST_HELPER_ADSTLOG_UNUSED(CORE, ACTOR) /** * Generic trace macros can be used in ADST FW to log on non actor channel and non actor.name_ module. * The need for this is very rare. Normally, user shall not use these. * * They are used by the more restrictive trace macros like LOG_I(...), and LOG_CH_I(...), etc. */ #define LOG_CH_MOD_E(CH, MOD, ...) \ ADSTLOG_LOG(EP7TRACE_LEVEL_ERROR, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_W(CH, MOD, ...) \ ADSTLOG_LOG(EP7TRACE_LEVEL_WARNING, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_I(CH, MOD, ...) \ ADSTLOG_LOG(EP7TRACE_LEVEL_INFO, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_D(CH, MOD, ...) \ ADSTLOG_LOG(EP7TRACE_LEVEL_DEBUG, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_T(CH, MOD, ...) \ ADSTLOG_LOG(EP7TRACE_LEVEL_TRACE, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_E_ON(OBJ, CH, MOD, ...) \ ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_ERROR, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_W_ON(OBJ, CH, MOD, ...) \ ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_WARNING, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_I_ON(OBJ, CH, MOD, ...) \ ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_INFO, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_D_ON(OBJ, CH, MOD, ...) \ ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_DEBUG, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ #define LOG_CH_MOD_T_ON(OBJ, CH, MOD, ...) \ ADSTLOG_LOG(OBJ, EP7TRACE_LEVEL_TRACE, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */ /** * Log macro meant to be used within the ADST FW for tracing * on actor.name_ channel instead of actor or core. * * Mostly used in fw to log gRPC and dispatch message tx/rx. */ #define LOG_CH_E(CH, ...) LOG_CH_MOD_E(CH, ACTOR, __VA_ARGS__) #define LOG_CH_W(CH, ...) LOG_CH_MOD_W(CH, ACTOR, __VA_ARGS__) #define LOG_CH_I(CH, ...) LOG_CH_MOD_I(CH, ACTOR, __VA_ARGS__) #define LOG_CH_D(CH, ...) LOG_CH_MOD_D(CH, ACTOR, __VA_ARGS__) #define LOG_CH_T(CH, ...) LOG_CH_MOD_T(CH, ACTOR, __VA_ARGS__) #define LOG_CH_E_ON(OBJ, CH, ...) LOG_CH_MOD_E_ON((&OBJ), CH, ACTOR, __VA_ARGS__) #define LOG_CH_W_ON(OBJ, CH, ...) LOG_CH_MOD_W_ON((&OBJ), CH, ACTOR, __VA_ARGS__) #define LOG_CH_I_ON(OBJ, CH, ...) LOG_CH_MOD_I_ON((&OBJ), CH, ACTOR, __VA_ARGS__) #define LOG_CH_D_ON(OBJ, CH, ...) LOG_CH_MOD_D_ON((&OBJ), CH, ACTOR, __VA_ARGS__) #define LOG_CH_T_ON(OBJ, CH, ...) LOG_CH_MOD_T_ON((&OBJ), CH, ACTOR, __VA_ARGS__) /** * Logging macro meant to be used within the ADST FW for logging on core channel and on actor.name_ module * main macro used for tracing within the fw for debug */ #define LOG_C_E(...) LOG_CH_E(CORE, __VA_ARGS__) #define LOG_C_W(...) LOG_CH_W(CORE, __VA_ARGS__) #define LOG_C_I(...) LOG_CH_I(CORE, __VA_ARGS__) #define LOG_C_D(...) LOG_CH_D(CORE, __VA_ARGS__) // core trace TRACE_LEVEL very verbose and has performance penalty it is not compiled in by default. #ifdef ADSTLOG_TRACE_LEVEL_CORE_COMPILED_IN #define LOG_C_T(...) LOG_CH_T(CORE, __VA_ARGS__) #else #define LOG_C_T(...) #endif /** * Default logging macros. Shall be used by components and all code logic outside of ADST FW. Logs * on actor channel on Actor.name_ module */ #define LOG_E(...) LOG_CH_E(ACTOR, __VA_ARGS__) #define LOG_W(...) LOG_CH_W(ACTOR, __VA_ARGS__) #define LOG_I(...) LOG_CH_I(ACTOR, __VA_ARGS__) #define LOG_D(...) LOG_CH_D(ACTOR, __VA_ARGS__) #define LOG_T(...) LOG_CH_T(ACTOR, __VA_ARGS__) /** * Default logging macros. Shall be used by components and all code logic outside of ADST FW. Logs * on actor channel on Actor.name_ module */ #define LOG_E_ON(OBJ, ...) LOG_CH_E_ON(OBJ, ACTOR, __VA_ARGS__) #define LOG_W_ON(OBJ, ...) LOG_CH_W_ON(OBJ, ACTOR, __VA_ARGS__) #define LOG_I_ON(OBJ, ...) LOG_CH_I_ON(OBJ, ACTOR, __VA_ARGS__) #define LOG_D_ON(OBJ, ...) LOG_CH_D_ON(OBJ, ACTOR, __VA_ARGS__) #define LOG_T_ON(OBJ, ...) LOG_CH_T_ON(OBJ, ACTOR, __VA_ARGS__) // Every Class which works in actor context shall use this trace macro to enable tracing within the class /** * Only defines the member variables for tracing but does not initialize them this might be * necessary in case of template classes. * * If this macro is used, the constructor must call ADSTLOG_INIT_ACTOR_TRACE_MODULES. * *Before* considering to use this macro, make sure that ADSTLOG_DEF_DEC_ACTOR_TRACE_MODULES is not * suitable. */ #define ADSTLOG_DEF_ACTOR_TRACE_MODULES() \ ADSTLOG_DEFINE_CH(ACTOR); \ ADSTLOG_DEFINE_CH(MSG_TX); \ ADSTLOG_DEFINE_CH(MSG_RX); \ ADSTLOG_DEFINE_CH(GRPC_RX); \ ADSTLOG_DEFINE_CH(GRPC_TX); \ ADSTLOG_DEFINE_CH(GRPC); \ ADSTLOG_DEFINE_CH(CORE); \ ADSTLOG_DEFINE_MODULE(ACTOR, ACTOR); \ ADSTLOG_DEFINE_MODULE(MSG_TX, ACTOR); \ ADSTLOG_DEFINE_MODULE(MSG_RX, ACTOR); \ ADSTLOG_DEFINE_MODULE(GRPC_RX, ACTOR); \ ADSTLOG_DEFINE_MODULE(GRPC_TX, ACTOR); \ ADSTLOG_DEFINE_MODULE(GRPC, ACTOR); \ ADSTLOG_DEFINE_MODULE(CORE, ACTOR) /** * The macro is meant to used together with ADSTLOG_DEF_ACTOR_TRACE_MODULES. It shall be used in * class constructor when ADSTLOG_DEF_ACTOR_TRACE_MODULES was used in the class declaration. */ #define ADSTLOG_INIT_ACTOR_TRACE_MODULES(NAME) \ ADSTLOG_INIT_CH(ACTOR); \ ADSTLOG_INIT_CH(MSG_TX); \ ADSTLOG_INIT_CH(MSG_RX); \ ADSTLOG_INIT_CH(GRPC_RX); \ ADSTLOG_INIT_CH(GRPC_TX); \ ADSTLOG_INIT_CH(GRPC); \ ADSTLOG_INIT_CH(CORE); \ ADSTLOG_INIT_MODULE(ACTOR, ACTOR, NAME); \ ADSTLOG_INIT_MODULE(MSG_TX, ACTOR, NAME); \ ADSTLOG_INIT_MODULE(MSG_RX, ACTOR, NAME); \ ADSTLOG_INIT_MODULE(GRPC_RX, ACTOR, NAME); \ ADSTLOG_INIT_MODULE(GRPC_TX, ACTOR, NAME); \ ADSTLOG_INIT_MODULE(GRPC, ACTOR, NAME); \ ADSTLOG_INIT_MODULE(CORE, ACTOR, NAME) /** * Register threads used by ADST FW (user shall not create threads). */ #define ADSTLOG_REGISTER_THREAD(THREAD_ID, NAME) \ ADSTLOG_CH(ACTOR)->getObj()->Register_Thread(NAME, THREAD_ID); \ ADSTLOG_CH(MSG_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \ ADSTLOG_CH(MSG_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \ ADSTLOG_CH(GRPC_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \ ADSTLOG_CH(GRPC_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \ ADSTLOG_CH(GRPC)->getObj()->Register_Thread(NAME, THREAD_ID); \ ADSTLOG_CH(CORE)->getObj()->Register_Thread(NAME, THREAD_ID) #define ADSTLOG_REGISTER_THREAD_ON(OBJ, THREAD_ID, NAME) \ OBJ.ADSTLOG_CH(ACTOR)->getObj()->Register_Thread(NAME, THREAD_ID); \ OBJ.ADSTLOG_CH(MSG_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \ OBJ.ADSTLOG_CH(MSG_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \ OBJ.ADSTLOG_CH(GRPC_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \ OBJ.ADSTLOG_CH(GRPC_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \ OBJ.ADSTLOG_CH(GRPC)->getObj()->Register_Thread(NAME, THREAD_ID); \ OBJ.ADSTLOG_CH(CORE)->getObj()->Register_Thread(NAME, THREAD_ID) /** * Unregister threads used by ADST FW (user shall not create threads). */ #define ADSTLOG_UNREGISTER_THREAD(THREAD_ID) \ ADSTLOG_CH(ACTOR)->getObj()->Unregister_Thread(THREAD_ID); \ ADSTLOG_CH(MSG_TX)->getObj()->Unregister_Thread(THREAD_ID); \ ADSTLOG_CH(MSG_RX)->getObj()->Unregister_Thread(THREAD_ID); \ ADSTLOG_CH(GRPC_RX)->getObj()->Unregister_Thread(THREAD_ID); \ ADSTLOG_CH(GRPC_TX)->getObj()->Unregister_Thread(THREAD_ID); \ ADSTLOG_CH(GRPC)->getObj()->Unregister_Thread(THREAD_ID); \ ADSTLOG_CH(CORE)->getObj()->Unregister_Thread(THREAD_ID) // clang-format on #define ADSTLOG_UNREGISTER_THREAD_ON(OBJ, THREAD_ID) \ OBJ.ADSTLOG_CH(ACTOR)->getObj()->Unregister_Thread(THREAD_ID); \ OBJ.ADSTLOG_CH(MSG_TX)->getObj()->Unregister_Thread(THREAD_ID); \ OBJ.ADSTLOG_CH(MSG_RX)->getObj()->Unregister_Thread(THREAD_ID); \ OBJ.ADSTLOG_CH(GRPC_RX)->getObj()->Unregister_Thread(THREAD_ID); \ OBJ.ADSTLOG_CH(GRPC_TX)->getObj()->Unregister_Thread(THREAD_ID); \ OBJ.ADSTLOG_CH(GRPC)->getObj()->Unregister_Thread(THREAD_ID); \ OBJ.ADSTLOG_CH(CORE)->getObj()->Unregister_Thread(THREAD_ID) // clang-format on namespace adst::common { struct Config; /** * Only one single instance of logger shall exist in any ADST c++ process. */ class Logger { // not copyable or movable Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; Logger(Logger&&) = delete; Logger& operator=(Logger&&) = delete; public: using ClientUPtr = std::unique_ptr<ManageTraceObj<IP7_Client>>; using ChannelUPtr = std::unique_ptr<ManageTraceObj<IP7_Trace>>; Logger(const Config& config); // there is no flush is needed when the logger is recycled flush is called from the trance Object destructor. ~Logger() = default; private: std::string getClientConfigStr(const Config& config); ClientUPtr client_ = nullptr; std::vector<ChannelUPtr> channels_; }; } // namespace adst::common
46.044983
116
0.690915
csitarichie
f952d5cc45ae8b814c1940f16c5fc9eda719b50a
6,025
cpp
C++
src/SearchRange.cpp
emweb/aga
bd7ad699e901168fe1658bea7c3c5d53fa5938e5
[ "OML", "Naumen", "Condor-1.1", "MS-PL" ]
13
2017-10-12T10:10:55.000Z
2020-11-12T08:28:43.000Z
src/SearchRange.cpp
emweb/aga
bd7ad699e901168fe1658bea7c3c5d53fa5938e5
[ "OML", "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/SearchRange.cpp
emweb/aga
bd7ad699e901168fe1658bea7c3c5d53fa5938e5
[ "OML", "Naumen", "Condor-1.1", "MS-PL" ]
6
2018-09-13T04:49:10.000Z
2020-11-12T08:28:45.000Z
#include "SearchRange.h" #include "Cigar.h" SearchRangeItem::SearchRangeItem(Type aType, int aStartColumn, int anEndColumn, int aStartRow, int anEndRow) : type(aType), startRow(aStartRow), endRow(anEndRow), startColumn(aStartColumn), endColumn(anEndColumn) { } std::ostream& operator<<(std::ostream& o, const SearchRangeItem& sri) { switch (sri.type) { case SearchRangeItem::Rectangle: o << "rect Start=(" << sri.startColumn << "," << sri.startRow << ") " << "End=(" << sri.endColumn << "," << sri.endRow << ")"; break; case SearchRangeItem::Parallelogram: o << "para Start=(" << sri.startColumn << "," << sri.startRow << " - " << sri.endRow << ") " << "End=(" << sri.endColumn << "," << sri.startRow + (sri.endColumn - sri.startColumn) << " - " << sri.endRow + (sri.endColumn - sri.startColumn) << ")"; } return o; } SearchRange::SearchRange() : columns(0), rows(0) { } SearchRange::SearchRange(int aColumns, int aRows) : columns(aColumns), rows(aRows) { items.push_back(SearchRangeItem(SearchRangeItem::Rectangle, 0, columns, 0, rows)); } int SearchRange::startRow(int column) const { for (const auto& i : items) { if (column < i.endColumn) { switch (i.type) { case SearchRangeItem::Rectangle: return std::max(0, i.startRow); case SearchRangeItem::Parallelogram: return std::max(0, i.startRow + (column - i.startColumn)); } } } throw std::runtime_error("Incomplete search range not covering " + std::to_string(column)); } int SearchRange::endRow(int column) const { for (const auto& i : items) { if (column < i.endColumn) { switch (i.type) { case SearchRangeItem::Rectangle: return std::min(rows, i.endRow); case SearchRangeItem::Parallelogram: return std::min(rows, i.endRow + (column - i.startColumn)); } } } throw std::runtime_error("Incomplete search range not covering " + std::to_string(column)); } int SearchRange::maxRowCount() const { int result = 0; for (const auto& i : items) { int h = i.endRow - i.startRow; if (h > result) result = h; } return result; } long SearchRange::size() const { long result = 0; for (const auto& i : items) { long h = i.endRow - i.startRow; long w = i.endColumn - i.startColumn; result += h * w; } return result; } SearchRange getSearchRange(const Cigar& seed, int refSize, int querySize, int margin) { if (seed.empty()) return SearchRange(refSize + 1, querySize + 1); else { SearchRange result(refSize + 1, querySize + 1); result.items.clear(); SearchRangeItem::Type currentType = SearchRangeItem::Rectangle; int currentRefStart = 0; int currentQueryStart = 0; int refI = 1; int queryI = 1; const int MARGIN = margin; for (const auto& i : seed) { if (i.op() == CigarItem::RefSkipped || i.op() == CigarItem::QuerySkipped) { // terminate current aligned block if (currentType == SearchRangeItem::Parallelogram) { if (refI > currentRefStart && queryI > currentQueryStart) { int deviation = std::abs((queryI - currentQueryStart) - (refI - currentRefStart)); deviation += MARGIN; result.items.push_back (SearchRangeItem(currentType, currentRefStart, refI, currentQueryStart - deviation, currentQueryStart + deviation)); } currentType = SearchRangeItem::Rectangle; currentRefStart = refI; currentQueryStart = queryI - MARGIN; } if (i.op() == CigarItem::RefSkipped) refI += i.length(); else queryI += i.length(); } else { // terminate current non-aligned block if (currentType == SearchRangeItem::Rectangle) { if (result.items.empty()) { int s = refI - queryI - 10 * MARGIN; if (s > MARGIN) { result.items.push_back (SearchRangeItem(currentType, currentRefStart, s, currentQueryStart, 1)); currentRefStart = s; } } result.items.push_back (SearchRangeItem(currentType, currentRefStart, refI, currentQueryStart, queryI + MARGIN)); currentType = SearchRangeItem::Parallelogram; currentRefStart = refI; currentQueryStart = queryI; } switch (i.op()) { case CigarItem::Match: refI += i.length(); queryI += i.length(); break; case CigarItem::RefGap: queryI += i.length(); break; case CigarItem::QueryGap: refI += i.length(); break; default: break; } } refI = std::min(refI, refSize); queryI = std::min(queryI, querySize); } // Terminate last block if (currentType == SearchRangeItem::Parallelogram) { if (refI > currentRefStart && queryI > currentQueryStart) { int deviation = std::abs((queryI - currentQueryStart) - (refI - currentRefStart)); deviation += MARGIN; result.items.push_back (SearchRangeItem(currentType, currentRefStart, refI, currentQueryStart - deviation, currentQueryStart + deviation)); currentRefStart = refI; currentQueryStart = queryI - MARGIN; } } if (currentRefStart < refSize + 1) { int s = currentRefStart + (querySize - queryI + 10 * MARGIN); if (s < refSize + 1 - MARGIN) { result.items.push_back (SearchRangeItem(SearchRangeItem::Rectangle, currentRefStart, s, currentQueryStart, querySize + 1)); currentRefStart = s; currentQueryStart = querySize; } result.items.push_back (SearchRangeItem(SearchRangeItem::Rectangle, currentRefStart, refSize + 1, currentQueryStart, querySize + 1)); } return result; } } std::ostream& operator<<(std::ostream& o, const SearchRange& sr) { std::cerr << "SearchRange ["; bool first = true; for (const auto& i : sr.items) { if (!first) std::cerr << ","; std::cerr << std::endl << " " << i; first = false; } std::cerr << std::endl << "]" << std::endl; return o; }
23.720472
99
0.618257
emweb
f953fc44bb7d10293222e69195cbc3c3cdbb7bee
13,193
cpp
C++
samples/examples/imkRecognizeObject-file.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
samples/examples/imkRecognizeObject-file.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
samples/examples/imkRecognizeObject-file.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
/****************************************************************************** * Copyright (c) 2017 Johann Prankl * * 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 <float.h> #include <pcl/common/centroid.h> #include <pcl/common/time.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <v4r/config.h> #include <v4r/io/filesystem.h> #include <v4r/recognition/IMKRecognizer.h> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include <map> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <stdexcept> #include <v4r/keypoints/impl/PoseIO.hpp> #include <v4r/keypoints/impl/invPose.hpp> #include <v4r/keypoints/impl/toString.hpp> #include <v4r/reconstruction/impl/projectPointToImage.hpp> #include "pcl/common/transforms.h" //#include <v4r/features/FeatureDetector_KD_FAST_IMGD.h> #if HAVE_SIFTGPU #define USE_SIFT_GPU #include <v4r/features/FeatureDetector_KD_SIFTGPU.h> #else #include <v4r/features/FeatureDetector_KD_CVSIFT.h> #endif #include <pcl/common/time.h> using namespace std; namespace po = boost::program_options; void drawConfidenceBar(cv::Mat &im, const double &conf); cv::Point2f drawCoordinateSystem(cv::Mat &im, const Eigen::Matrix4f &pose, const cv::Mat_<double> &intrinsic, const cv::Mat_<double> &dist_coeffs, double size, int thickness); void convertImage(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, cv::Mat &image); //--------------------------- default configuration ------------------------------- void InitParameter(); void InitParameter() {} //------------------------------ helper methods ----------------------------------- // static void onMouse(int event, int x, int y, int flags, void *); void setup(int argc, char **argv); //----------------------------- data containers ----------------------------------- cv::Mat_<cv::Vec3b> image; cv::Mat_<cv::Vec3b> im_draw; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>); cv::Mat_<double> dist_coeffs; // = cv::Mat::zeros(4, 1, CV_64F); cv::Mat_<double> intrinsic = cv::Mat_<double>::eye(3, 3); Eigen::Matrix4f pose = Eigen::Matrix4f::Identity(); int ul_lr = 0; int start = 0, end_idx = 10; cv::Point track_win[2]; std::string cam_file; string filenames, base_dir, codebook_filename; std::vector<std::string> object_names; std::vector<v4r::triple<std::string, double, Eigen::Matrix4f>> objects; double thr_conf = 0; int live = -1; bool loop = false; /****************************************************************** * MAIN */ int main(int argc, char *argv[]) { int sleep = 0; char filename[PATH_MAX]; track_win[0] = cv::Point(0, 0); track_win[1] = cv::Point(640, 480); // config InitParameter(); setup(argc, argv); intrinsic(0, 0) = intrinsic(1, 1) = 525; intrinsic(0, 2) = 320, intrinsic(1, 2) = 240; if (cam_file.size() > 0) { cv::FileStorage fs(cam_file, cv::FileStorage::READ); fs["camera_matrix"] >> intrinsic; fs["distortion_coefficients"] >> dist_coeffs; } cv::namedWindow("image", CV_WINDOW_AUTOSIZE); // init recognizer v4r::IMKRecognizer::Parameter param; param.pnp_param.eta_ransac = 0.01; param.pnp_param.max_rand_trials = 10000; param.pnp_param.inl_dist_px = 2; param.pnp_param.inl_dist_z = 0.02; param.vc_param.cluster_dist = 40; #ifdef USE_SIFT_GPU param.cb_param.nnr = 1.000001; param.cb_param.thr_desc_rnn = 0.25; param.cb_param.max_dist = FLT_MAX; v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_SIFTGPU()); #else v4r::KeypointObjectRecognizer::Parameter param; param.cb_param.nnr = 1.000001; param.cb_param.thr_desc_rnn = 250.; param.cb_param.max_dist = FLT_MAX; v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_CVSIFT()); #endif // // -- test imgd -- // param.cb_param.nnr = 1.000001; // param.cb_param.thr_desc_rnn = 0.25; // param.cb_param.max_dist = FLT_MAX; // v4r::FeatureDetector_KD_FAST_IMGD::Parameter imgd_param(1000, 1.3, 4, 15); // v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_FAST_IMGD(imgd_param)); // // -- end -- v4r::IMKRecognizer recognizer(param, detector, detector); recognizer.setCameraParameter(intrinsic, dist_coeffs); recognizer.setDataDirectory(base_dir); if (!codebook_filename.empty()) recognizer.setCodebookFilename(codebook_filename); if (object_names.size() == 0) { // take all direcotry names from the base_dir object_names = v4r::io::getFoldersInDirectory(base_dir); } for (unsigned i = 0; i < object_names.size(); i++) recognizer.addObject(object_names[i]); std::cout << "Number of models: " << object_names.size() << std::endl; recognizer.initModels(); cv::VideoCapture cap; if (live != -1) { cap.open(live); cap.set(CV_CAP_PROP_FRAME_WIDTH, 640); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); loop = true; if (!cap.isOpened()) { cout << "Could not initialize capturing...\n"; return 0; } } // ---------------------- recognize object --------------------------- for (int i = start; i <= end_idx || loop; i++) { cout << "---------------- FRAME #" << i << " -----------------------" << endl; if (live != -1) { cap >> image; } else { snprintf(filename, PATH_MAX, filenames.c_str(), i); cout << filename << endl; image = cv::Mat_<cv::Vec3b>(); if (filenames.compare(filenames.size() - 3, 3, "pcd") == 0) { if (pcl::io::loadPCDFile(filename, *cloud) == -1) continue; convertImage(*cloud, image); } else { image = cv::imread(filename, 1); } } image.copyTo(im_draw); recognizer.dbg = im_draw; // cloud->clear(); // track { pcl::ScopeTime t("overall time"); if (cloud->width != (unsigned)image.cols || cloud->height != (unsigned)image.rows) { recognizer.recognize(image, objects); cout << "Use image only!" << endl; } else { recognizer.recognize(*cloud, objects); cout << "Use image and cloud!" << endl; } } //-- overall time -- // debug out draw // cv::addText( image, P::toString(1000./time)+std::string(" fps"), cv::Point(25,35), font); cout << "Confidence value threshold for visualization: " << thr_conf << endl; cout << "Found objects:" << endl; for (unsigned j = 0; j < objects.size(); j++) { cout << j << ": name= " << objects[j].first << ", conf= " << objects[j].second << endl; if (objects[j].second >= thr_conf) { cv::Point2f origin = drawCoordinateSystem(im_draw, objects[j].third, intrinsic, dist_coeffs, 0.1, 4); // cv::addText( im_draw, objects[i].first+std::string(" (")+v4r::toString(objects[i].second)<<std::string(")"), // origin+cv::Point(0,-10), font); std::string txt = v4r::toString(j) + std::string(": ") + objects[j].first + std::string(" (") + v4r::toString(objects[j].second) + std::string(")"); cv::putText(im_draw, txt, origin + cv::Point2f(0, 10), cv::FONT_HERSHEY_PLAIN, 1.5, CV_RGB(255, 255, 255), 2, CV_AA); } } cv::imshow("image", im_draw); int key = cv::waitKey(sleep); if (((char)key) == 27) break; if (((char)key) == 'r') sleep = 1; if (((char)key) == 's') sleep = 0; } cv::waitKey(0); return 0; } /******************************** SOME HELPER METHODS **********************************/ /* * static void onMouse(int event, int x, int y, int flags, void *) { if (x < 0 || x >= im_draw.cols || y < 0 || y >= im_draw.rows) return; if (event == CV_EVENT_LBUTTONUP && (flags & CV_EVENT_FLAG_LBUTTON)) { track_win[ul_lr % 2] = cv::Point(x, y); if (ul_lr % 2 == 0) cout << "upper left corner: " << track_win[ul_lr % 2] << endl; else cout << "lower right corner: " << track_win[ul_lr % 2] << endl; ul_lr++; } } */ /** * setup */ void setup(int argc, char **argv) { po::options_description general("General options"); general.add_options()("help,h", "show help message")("filenames,f", po::value<std::string>(&filenames)->default_value(filenames), "Input filename for recognition (printf-style)")( "base_dir,d", po::value<std::string>(&base_dir)->default_value(base_dir), "Object model directory")( "codebook_filename,c", po::value<std::string>(&codebook_filename), "Optional filename for codebook")( "object_names,n", po::value<std::vector<std::string>>(&object_names)->multitoken(), "Object names")( "start,s", po::value<int>(&start)->default_value(start), "start index")( "end,e", po::value<int>(&end_idx)->default_value(end_idx), "end index")( "cam_file,a", po::value<std::string>(&cam_file)->default_value(cam_file), "camera calibration files (opencv format)")("live,l", po::value<int>(&live)->default_value(live), "use live camera (OpenCV)")( "thr_conf,t", po::value<double>(&thr_conf)->default_value(thr_conf), "Confidence value threshold (visualization)"); po::options_description all(""); all.add(general); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(all).run(), vm); po::notify(vm); std::string usage = ""; if (vm.count("help")) { std::cout << usage << std::endl; std::cout << all; return; } return; } /** * drawConfidenceBar */ void drawConfidenceBar(cv::Mat &im, const double &conf) { int bar_start = 50, bar_end = 200; int diff = bar_end - bar_start; int draw_end = diff * conf; double col_scale = 255. / (double)diff; cv::Point2f pt1(0, 30); cv::Point2f pt2(0, 30); cv::Vec3b col(0, 0, 0); if (draw_end <= 0) draw_end = 1; for (int i = 0; i < draw_end; i++) { col = cv::Vec3b(255 - (i * col_scale), i * col_scale, 0); pt1.x = bar_start + i; pt2.x = bar_start + i + 1; cv::line(im, pt1, pt2, CV_RGB(col[0], col[1], col[2]), 8); } } cv::Point2f drawCoordinateSystem(cv::Mat &im, const Eigen::Matrix4f &_pose, const cv::Mat_<double> &_intrinsic, const cv::Mat_<double> &_dist_coeffs, double size, int thickness) { Eigen::Matrix3f R = _pose.topLeftCorner<3, 3>(); Eigen::Vector3f t = _pose.block<3, 1>(0, 3); Eigen::Vector3f pt0 = R * Eigen::Vector3f(0, 0, 0) + t; Eigen::Vector3f pt_x = R * Eigen::Vector3f(size, 0, 0) + t; Eigen::Vector3f pt_y = R * Eigen::Vector3f(0, size, 0) + t; Eigen::Vector3f pt_z = R * Eigen::Vector3f(0, 0, size) + t; cv::Point2f im_pt0, im_pt_x, im_pt_y, im_pt_z; if (!_dist_coeffs.empty()) { v4r::projectPointToImage(&pt0[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt0.x); v4r::projectPointToImage(&pt_x[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_x.x); v4r::projectPointToImage(&pt_y[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_y.x); v4r::projectPointToImage(&pt_z[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_z.x); } else { v4r::projectPointToImage(&pt0[0], &_intrinsic(0), &im_pt0.x); v4r::projectPointToImage(&pt_x[0], &_intrinsic(0), &im_pt_x.x); v4r::projectPointToImage(&pt_y[0], &_intrinsic(0), &im_pt_y.x); v4r::projectPointToImage(&pt_z[0], &_intrinsic(0), &im_pt_z.x); } cv::line(im, im_pt0, im_pt_x, CV_RGB(255, 0, 0), thickness); cv::line(im, im_pt0, im_pt_y, CV_RGB(0, 255, 0), thickness); cv::line(im, im_pt0, im_pt_z, CV_RGB(0, 0, 255), thickness); return im_pt0; } void convertImage(const pcl::PointCloud<pcl::PointXYZRGB> &_cloud, cv::Mat &_image) { _image = cv::Mat_<cv::Vec3b>(_cloud.height, _cloud.width); for (unsigned v = 0; v < _cloud.height; v++) { for (unsigned u = 0; u < _cloud.width; u++) { cv::Vec3b &cv_pt = _image.at<cv::Vec3b>(v, u); const pcl::PointXYZRGB &pt = _cloud(u, v); cv_pt[2] = pt.r; cv_pt[1] = pt.g; cv_pt[0] = pt.b; } } }
35.560647
119
0.612901
v4r-tuwien
f95623fc124c783cd96198949f96e5a69b54b9e0
1,560
cpp
C++
src/modes/mode_reprint_hbp.cpp
kliment-olechnovic/voronota
4e3063aa86b44f1f2e7b088ec9976f3e12047549
[ "MIT" ]
9
2019-08-23T10:46:18.000Z
2022-03-11T12:20:27.000Z
src/modes/mode_reprint_hbp.cpp
kliment-olechnovic/voronota
4e3063aa86b44f1f2e7b088ec9976f3e12047549
[ "MIT" ]
null
null
null
src/modes/mode_reprint_hbp.cpp
kliment-olechnovic/voronota
4e3063aa86b44f1f2e7b088ec9976f3e12047549
[ "MIT" ]
3
2020-09-17T19:07:47.000Z
2021-04-29T01:19:38.000Z
#include "../auxiliaries/program_options_handler.h" #include "../auxiliaries/atoms_io.h" #include "../auxiliaries/io_utilities.h" #include "../common/chain_residue_atom_descriptor.h" void reprint_hbp(const voronota::auxiliaries::ProgramOptionsHandler& poh) { voronota::auxiliaries::ProgramOptionsHandlerWrapper pohw(poh); pohw.describe_io("stdin", true, false, "hbplus output"); pohw.describe_io("stdout", false, true, "output"); if(!pohw.assert_or_print_help(false)) { return; } typedef voronota::common::ChainResidueAtomDescriptor CRAD; typedef voronota::common::ChainResidueAtomDescriptorsPair CRADsPair; std::set<CRADsPair> set_of_hbplus_crad_pairs; voronota::auxiliaries::AtomsIO::HBPlusReader::Data hbplus_file_data=voronota::auxiliaries::AtomsIO::HBPlusReader::read_data_from_file_stream(std::cin); if(!hbplus_file_data.hbplus_records.empty()) { for(std::vector<voronota::auxiliaries::AtomsIO::HBPlusReader::HBPlusRecord>::const_iterator it=hbplus_file_data.hbplus_records.begin();it!=hbplus_file_data.hbplus_records.end();++it) { const voronota::auxiliaries::AtomsIO::HBPlusReader::ShortAtomDescriptor& a=it->first; const voronota::auxiliaries::AtomsIO::HBPlusReader::ShortAtomDescriptor& b=it->second; const CRADsPair crads_pair(CRAD(CRAD::null_num(), a.chainID, a.resSeq, a.resName, a.name, "", ""), CRAD(CRAD::null_num(), b.chainID, b.resSeq, b.resName, b.name, "", "")); set_of_hbplus_crad_pairs.insert(crads_pair); } } voronota::auxiliaries::IOUtilities().write_set(set_of_hbplus_crad_pairs, std::cout); }
42.162162
184
0.771154
kliment-olechnovic
f9567c21e5efba5d8f92be3281a01b12c87beb69
485
cpp
C++
src/tema fisa for/ex 4 e/main.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
2
2021-11-27T18:29:32.000Z
2021-11-28T14:35:47.000Z
src/tema fisa for/ex 4 e/main.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
null
null
null
src/tema fisa for/ex 4 e/main.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int a,b,x,i=0,cx; cout<<"a= "; cin>>a; cout<<"b= "; cin>>b; x=a; cx=x; for(x; x<=b; x++) { cx=x; while(cx!=0) { if(cx%10==0) { i=i+1; cx=0; } else { cx=cx/10; } } } cout<<"Sunt "<<i<<" numere care contin cifra 0"; return 0; }
13.472222
52
0.31134
andrew-miroiu
f959c903e7d50b358684b12ef918d3179555705b
4,509
cpp
C++
unit_tests/main.cpp
obhi-d/hfn
692203a25a13214ba8a0e2feddb8d6e78275c860
[ "MIT" ]
null
null
null
unit_tests/main.cpp
obhi-d/hfn
692203a25a13214ba8a0e2feddb8d6e78275c860
[ "MIT" ]
null
null
null
unit_tests/main.cpp
obhi-d/hfn
692203a25a13214ba8a0e2feddb8d6e78275c860
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "hfn/config.hpp" #include "hfn/cxstring.hpp" #include "hfn/digest.hpp" #include "hfn/fnv1a.hpp" #include "hfn/murmur3.hpp" #include "hfn/rhid.hpp" #include "hfn/type_hash.hpp" #include "hfn/wyhash.hpp" #include "hfn/xxhash.hpp" #include <catch2/catch.hpp> #include <iostream> class type_name_test {}; TEST_CASE("Asserts", "[asserts]") { static_assert(sizeof(hfn::uhash128_t) == 16, "Size is incorrect"); CHECK(hfn::digest<std::uint64_t>(0) == "0"); CHECK(hfn::type_name<type_name_test>() == "class type_name_test"); constexpr std::uint32_t cth = hfn::type_hash<std::string_view>(); static_assert(cth == 787592100); CHECK(hfn::digest<std::uint64_t>(0xff64ffaadd41) == "1anlqvjcv7"); } TEST_CASE("Murmur3", "[murmur]") { std::string text = "The director instructed us to do batshit crazy things in the past."; std::string first = "First string."; std::string second = "Second string."; std::string combined = text + first + second; hfn::murmur3_32 hash32; hash32(text.c_str(), text.length()); CHECK(hash32() == hfn::murmur3::compute32(text.c_str(), text.length())); hfn::murmur3_128 hash128; hash128(text.c_str(), text.length()); CHECK(hash128() == hfn::murmur3::compute128(text.c_str(), text.length())); std::string_view conflict1 = "vertexColor"; std::string_view conflict2 = "userDefined"; CHECK(hfn::murmur3::compute32(conflict2.data(), conflict2.length()) != hfn::murmur3::compute32(conflict1.data(), conflict1.length())); hfn::cxstring s = "fixdStrinTest"; CHECK(s.hash() == hfn::murmur3::compute32(s.data(), s.size())); } TEST_CASE("Fnv1a", "[fnv1a]") { std::string text = "The director instructed us to do batshit crazy things in the past."; std::string first = "First string."; std::string second = "Second string."; std::string combined = text + first + second; hfn::fnv1a_32 hash32; hash32(text.c_str(), text.length()); CHECK(hash32() == hfn::fnv1a::compute32(text.c_str(), text.length())); hfn::fnv1a_64 hash64; hash64(text.c_str(), text.length()); CHECK(hash64() == hfn::fnv1a::compute64(text.c_str(), text.length())); hash32(first.c_str(), first.length()); hash32(second.c_str(), second.length()); CHECK(hash32() == hfn::fnv1a::compute32(combined.c_str(), combined.length())); hash64(first.c_str(), first.length()); hash64(second.c_str(), second.length()); CHECK(hash64() == hfn::fnv1a::compute64(combined.c_str(), combined.length())); } TEST_CASE("Wyhash", "[wyhash]") { std::string text = "The director instructed us to do batshit crazy things in the past."; hfn::wyhash_32 hash32; hash32(text.c_str(), text.length()); CHECK(hash32() == hfn::wyhash::compute32(text.c_str(), text.length())); hfn::wyhash_64 hash64; hash64(text.c_str(), text.length()); CHECK(hash64() == hfn::wyhash::compute64(text.c_str(), text.length())); hash32 = hfn::wyhash_32(); hash32(text.c_str(), 10); hash32(text.c_str() + 10, text.length() - 10); // CHECK(hash32() == hfn::wyhash::compute32(text.c_str(), text.length())); hash64 = hfn::wyhash_64(); hash64(text.c_str(), 10); hash64(text.c_str() + 10, text.length() - 10); // CHECK(hash64() == hfn::wyhash::compute64(text.c_str(), text.length())); } TEST_CASE("X3hash", "[xxhash]") { std::string text = "The director instructed us to do batshit crazy things in the past."; std::string first = "First string."; std::string second = "Second string."; std::string combined = text + first + second; hfn::xxhash_64 hash64; hash64(text.c_str(), text.length()); CHECK(hash64() == hfn::xxhash::compute64(text.c_str(), text.length())); hfn::xxhash_128 hash128; hash64(text.c_str(), text.length()); // CHECK(hash128() == hfn::xxhash::compute128(text.c_str(), text.length())); hash64(first.c_str(), first.length()); hash64(second.c_str(), second.length()); // CHECK(hash64() == hfn::xxhash::compute64(combined.c_str(), combined.length())); hash128(first.c_str(), first.length()); hash128(second.c_str(), second.length()); // CHECK(hash128() == hfn::xxhash::compute128(combined.c_str(), combined.length())); } TEST_CASE("RHID", "[rhid]") { std::string text = "The director instructed us to do batshit crazy things in the past."; std::string first = "First string."; std::string second = "Second string."; CHECK(hfn::rhid() == hfn::null_rhid); hfn::rhid rhid; rhid.update(text.c_str(), text.length()); CHECK((std::string)rhid == "mkjl131"); }
32.673913
92
0.664005
obhi-d
f959e804126995f18a040d22d82f3909666733f0
511
cpp
C++
Util/WebUrl.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
150
2015-01-14T15:06:38.000Z
2018-08-28T09:34:17.000Z
Util/WebUrl.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
28
2015-05-11T02:45:39.000Z
2018-08-24T11:43:17.000Z
Util/WebUrl.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
91
2015-05-04T09:52:41.000Z
2018-08-18T13:02:15.000Z
#include "WebUrl.h" using namespace std; WebUrl::WebUrl() {} WebUrl::~WebUrl() {} string WebUrl::CutParam(string url, string param) { int index = url.find("?" + param + "="); if (index < 0) { index = url.find("&" + param + "="); } if (index < 0) return string(); int index2 = index + 1 + (param + "=").length(); string substr = url.substr(index2); int endindex = substr.find("&"); if (endindex > 0) { string substr2 = substr.substr(0, endindex); return substr2; } else return substr; }
18.25
49
0.60274
SoftlySpoken
f9601f472091e6a18894fa6522a21e9160e64b8c
4,786
cpp
C++
PageRepository/Source/Page.cpp
DiplodocusDB/PhysicalStorage
9b110471d14300873a9067b25b0825727c178549
[ "MIT" ]
null
null
null
PageRepository/Source/Page.cpp
DiplodocusDB/PhysicalStorage
9b110471d14300873a9067b25b0825727c178549
[ "MIT" ]
19
2018-01-20T14:38:20.000Z
2018-01-26T22:58:52.000Z
PageRepository/Source/Page.cpp
DiplodocusDB/PhysicalStorage
9b110471d14300873a9067b25b0825727c178549
[ "MIT" ]
null
null
null
/* Copyright (c) 2018-2019 Xavier Leclercq 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 "Page.h" #include "PageFileRepository.h" #include "Ishiko/Errors/IOErrorExtension.h" #include <sstream> namespace DiplodocusDB { Page::Page(size_t index) : m_index(index), m_dataSize(0), m_availableSpace(sm_size - sm_startMarkerSize - sm_endMarkerSize), m_nextPage(0) { } void Page::init() { memset(m_buffer, 0, sm_size); } size_t Page::index() const { return m_index; } size_t Page::dataSize() const { return m_dataSize; } size_t Page::maxDataSize() const { return (sm_size - sm_startMarkerSize - sm_endMarkerSize); } size_t Page::availableSpace() const { return m_availableSpace; } size_t Page::nextPage() const { return m_nextPage; } void Page::setNextPage(size_t index) { m_nextPage = index; } void Page::get(char* buffer, size_t pos, size_t n, Ishiko::Error& error) const { if ((pos + n) <= m_dataSize) { memcpy(buffer, m_buffer + sm_startMarkerSize + pos, n); } else { std::stringstream message; message << "Page::get (m_index: " << m_index << ", pos:" << pos << ", n:" << n << ") exceeds data size (m_datasize: " << m_dataSize << ")"; error.fail(-1, message.str(), __FILE__, __LINE__); } } void Page::insert(const char* buffer, size_t bufferSize, size_t pos, Ishiko::Error& error) { if (bufferSize <= m_availableSpace) { char* p = (m_buffer + sm_startMarkerSize); if (pos != m_dataSize) { memmove(p + pos + bufferSize, p + pos, (m_dataSize - pos)); } memcpy(p + pos, buffer, bufferSize); m_dataSize += bufferSize; m_availableSpace -= bufferSize; } else { // TODO : add page details error.fail(-1, "Failed to insert page", __FILE__, __LINE__); } } void Page::erase(size_t pos, size_t n, Ishiko::Error& error) { memmove(m_buffer + sm_startMarkerSize + pos, m_buffer + sm_startMarkerSize + pos + n, m_dataSize + sm_endMarkerSize - pos - n); memset(m_buffer + sm_startMarkerSize + m_dataSize + sm_endMarkerSize - n, 0, n); m_dataSize -= n; m_availableSpace += n; } void Page::moveTo(size_t pos, size_t n, Page& targetPage, Ishiko::Error& error) { targetPage.insert(m_buffer + sm_startMarkerSize + pos, n, 0, error); if (!error) { erase(pos, n, error); } } void Page::write(std::ostream& output, Ishiko::Error& error) const { output.seekp(m_index * sm_size); Ishiko::IOErrorExtension::Fail(error, output, __FILE__, __LINE__); if (!error) { memcpy(m_buffer, "\xF0\x06\x00\x00\x00\x00", 6); *((uint16_t*)(m_buffer + 6)) = (uint16_t)m_dataSize; memcpy(m_buffer + sm_startMarkerSize + m_dataSize, "\xF1\x06\x00\x00\x00\x00\x00\x00", 8); *((uint32_t*)(m_buffer + sm_startMarkerSize + m_dataSize + 2)) = m_nextPage; output.write(m_buffer, sm_size); Ishiko::IOErrorExtension::Fail(error, output, __FILE__, __LINE__); } } void Page::read(std::istream& input, Ishiko::Error& error) { input.seekg(m_index * sm_size); Ishiko::IOErrorExtension::Fail(error, input, __FILE__, __LINE__); if (!error) { input.read(m_buffer, sm_size); Ishiko::IOErrorExtension::Fail(error, input, __FILE__, __LINE__); if (!error) { m_dataSize = *((uint16_t*)(m_buffer + 6)); m_availableSpace = sm_size - sm_startMarkerSize - sm_endMarkerSize - m_dataSize; uint32_t nextPage = *((uint32_t*)(m_buffer + sm_startMarkerSize + m_dataSize + 2)); m_nextPage = nextPage; } } } }
29.361963
117
0.649603
DiplodocusDB
f96c117a5b81a2b6b456ee21a20b141634852997
8,129
cpp
C++
d20/a.cpp
webdeveloperukraine/adventofcode2020
4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34
[ "MIT" ]
null
null
null
d20/a.cpp
webdeveloperukraine/adventofcode2020
4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34
[ "MIT" ]
null
null
null
d20/a.cpp
webdeveloperukraine/adventofcode2020
4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #include "../helpers/string_helpers.cpp" typedef long long int ll; struct Tile{ ll id; vector<string> pattern; int width, height; Tile(){ throw runtime_error("No Way!"); } Tile(ll id, vector<string> pattern) : id(id), pattern(pattern){ height = pattern.size(); width = pattern[0].size(); } void flipx(){ for(int i=0;i<height;i++){ for(int j=0;j<width/2;j++){ swap(pattern[i][j], pattern[i][width-j-1]); } } } void flipy(){ for(int i=0;i<height/2;i++){ swap(pattern[i], pattern[height-i-1]); } } void rotate() { vector<string> res; for(int i=0;i<width;i++){ string s; for(int j=0;j<height;j++){ s.push_back(pattern[j][i]); } reverse(s.begin(), s.end()); res.push_back(s); } pattern = res; } }; unordered_map<ll, Tile> input; void prepare() { string s; vector<string> pat; ll id; while(getline(cin, s)){ if(s[0] == 'T'){ string str = split_line(s, " ")[1]; id = stoll(str.substr(0, str.size()-1)); continue; } if(s == ""){ input.insert(make_pair(id, Tile(id, pat))); pat.resize(0); continue; } pat.push_back(s); } input.insert(make_pair(id, Tile(id, pat))); } string get_top_line(Tile& t) { return t.pattern[0]; } string get_left_line(Tile& t) { string s; for(int i=t.height-1;i>=0;i--){ s.push_back(t.pattern[i][0]); } return s; } string get_bottom_line(Tile& t) { string s = t.pattern[t.pattern.size()-1]; reverse(s.begin(), s.end()); return s; } string get_right_line(Tile& t) { string s; for(int i=0;i<t.height;i++){ s.push_back(t.pattern[i][9]); } return s; } ll line_to_num(string s) { ll n = 0; for(int i=0;i<s.size();i++){ if(s[i] == '#') n = n | 1; if(s.size()-1 != i) n <<= 1; } return n; } unordered_map<ll, ll> arr; unordered_map<ll, vector<int>> cnts; void prepare_other() { if(arr.size()) return; string s; for(auto& itt : input){ auto& it = itt.second; s = get_top_line(it); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); reverse(s.begin(), s.end()); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); s = get_bottom_line(it); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); reverse(s.begin(), s.end()); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); s = get_left_line(it); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); reverse(s.begin(), s.end()); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); s = get_right_line(it); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); reverse(s.begin(), s.end()); arr.insert(make_pair(line_to_num(s), it.id)); cnts[line_to_num(s)].push_back(it.id); } } ll first() { prepare_other(); unordered_map<ll, int> garr; for(auto& it : cnts){ if(it.second.size() == 1){ garr[arr[it.first]]++; } } ll res = 1; for(auto& it : garr){ if(it.second == 4){ res *= it.first; } } return res; } ////////////////////////////////////////////////////////// struct MT{ MT *top=nullptr, *right=nullptr, *bottom=nullptr, *left=nullptr; ll id; }; unordered_map<ll, MT*> mt_map; ll get_else_id(ll a, ll id) { auto& v = cnts[a]; if(v[0] == id) return v[1]; return v[0]; } void transform(ll id, ll a, string side) { Tile& t = input[id]; for(int i=0;i<8;i++){ ll b; if(side == "top") b = line_to_num(get_top_line(t)); if(side == "right") b = line_to_num(get_right_line(t)); if(side == "bottom") b = line_to_num(get_bottom_line(t)); if(side == "left") b = line_to_num(get_left_line(t)); if(b == a){ if(side == "top" || side == "bottom"){ t.flipx(); } else { t.flipy(); } return; } t.rotate(); if(i == 3){ t.flipx(); } } throw runtime_error("No Way!"); } unordered_set<ll> r_done; void req(MT* a) { if(!a) return; if(r_done.count(a->id)) return; r_done.insert(a->id); Tile& t = input[a->id]; ll top = line_to_num(get_top_line(t)); ll right = line_to_num(get_right_line(t)); ll bottom = line_to_num(get_bottom_line(t)); ll left = line_to_num(get_left_line(t)); MT *mt_top = nullptr, *mt_right = nullptr, *mt_bottom = nullptr, *mt_left = nullptr; if(cnts[top].size() > 1){ ll id = get_else_id(top, a->id); if(mt_map.count(id)){ a->top = mt_map[id]; } else { mt_top = new MT; mt_map[id] = mt_top; mt_top->id = id; a->top = mt_top; transform(id, top, "bottom"); } } if(cnts[right].size() > 1){ ll id = get_else_id(right, a->id); if(mt_map.count(id)){ a->right = mt_map[id]; } else { mt_right = new MT; mt_map[id] = mt_right; mt_right->id = id; a->right = mt_right; transform(id, right, "left"); } } if(cnts[bottom].size() > 1){ ll id = get_else_id(bottom, a->id); if(mt_map.count(id)){ a->bottom = mt_map[id]; } else { mt_bottom = new MT; mt_map[id] = mt_bottom; mt_bottom->id = id; a->bottom = mt_bottom; transform(id, bottom, "top"); } } if(cnts[left].size() > 1){ ll id = get_else_id(left, a->id); if(mt_map.count(id)){ a->left = mt_map[id]; } else { mt_left = new MT; mt_map[id] = mt_left; mt_left->id = id; a->left = mt_left; transform(id, left, "right"); } } req(a->top); req(a->right); req(a->bottom); req(a->left); } bool done[12][12]; char image[12*8][12*8]; void fill(Tile& t, int x, int y) { if(x > 11 || y > 11) throw runtime_error("No Way!"); for(int i=1;i<t.height-1;i++){ for(int j=1;j<t.width-1;j++){ image[y*8+i-1][x*8+j-1] = t.pattern[i][j]; } } } void req_build(MT* a, int x, int y) { if(!a) return; if(done[x][y]) return; done[x][y] = true; fill(input[a->id], x, y); req_build(a->right, x+1, y); req_build(a->bottom, x, y+1); } void print_image() { for(int i=0;i<12*8;i++){ cout << "_"; } cout << endl; for(int i=0;i<12*8;i++){ for(int j=0;j<12*8;j++){ cout << image[i][j]; } cout << endl; } } void rotate_image() { int W = 8*12; char new_image[W][W]; for(int i=0;i<W;i++){ for(int j=0;j<W;j++){ new_image[i][j] = image[j][i]; } for(int j=0;j<W/2;j++){ swap(new_image[i][j], new_image[i][W-j-1]); } } for(int i=0;i<W;i++){ for(int j=0;j<W;j++){ image[i][j] = new_image[i][j]; } } } void flip_image() { int W = 8*12; for(int i=0;i<W;i++){ for(int j=0;j<W/2;j++){ swap(image[i][j], image[i][W-j-1]); } } } vector<string> monster = { " # ", "# ## ## ###", " # # # # # # " }; int find_monsters() { int res = 0; int W = 8*12; int MW = monster[0].size(); int MH = monster.size(); for(int i=0;i<W;i++){ for(int j=0;j<W;j++){ if(W-i >= MH && W-j >= MW){ bool found = true; for(int ii=0;ii<MH;ii++){ for(int jj=0;jj<MW;jj++){ if(monster[ii][jj] == '#' && image[i+ii][j+jj] != '#'){ found = false; break; } } } if(found){ res++; for(int ii=0;ii<MH;ii++){ for(int jj=0;jj<MW;jj++){ if(monster[ii][jj] == '#'){ image[i+ii][j+jj] = 'O'; } } } } } } } return res; } ll second() { // preapre other things prepare_other(); // Build an image ll one_id = input.begin()->first; MT* part = new MT; part->id = one_id; mt_map[one_id] = part; req(part); // write image to array while(part->top){ part = part->top; } while(part->left){ part = part->left; } req_build(part,0,0); // Find monsters bool found = false; for(int i=0;i<10;i++){ if(find_monsters()){ found = true; break; } rotate_image(); if(i == 4) flip_image(); } if(!found){ throw runtime_error("Not Found Monsters :("); } int res = 0; for(int i=0;i<8*12;i++){ for(int j=0;j<8*12;j++){ if(image[i][j] == '#') res++; } } return res; } int main() { prepare(); cout << "First: " << first() << endl; cout << "Second: " << second() << endl; // Print image with monsters print_image(); return 0; }
17.905286
85
0.558986
webdeveloperukraine
f96c326286a20d184db4bb728848da1abf9f28fe
2,663
cpp
C++
source/line.cpp
Zylon-D-Lite/drawingPrototype
60caa86e72ad7fd36aed15679b003747c69e81c6
[ "MIT" ]
null
null
null
source/line.cpp
Zylon-D-Lite/drawingPrototype
60caa86e72ad7fd36aed15679b003747c69e81c6
[ "MIT" ]
null
null
null
source/line.cpp
Zylon-D-Lite/drawingPrototype
60caa86e72ad7fd36aed15679b003747c69e81c6
[ "MIT" ]
null
null
null
#include "./line.hpp" const png::rgba_pixel Line::WHITE_PIXEL = png::rgba_pixel(255, 255, 255, 255); const png::rgba_pixel Line::BLACK_PIXEL = png::rgba_pixel(0, 0, 0, 255); const png::rgba_pixel Line::TRANSPARENT_PIXEL = png::rgba_pixel(0, 0, 0, 0); const png::rgba_pixel Line::RED_PIXEL = png::rgba_pixel(255, 0, 0, 255); const png::rgba_pixel Line::GREEN_PIXEL = png::rgba_pixel(0, 255, 0, 255); const png::rgba_pixel Line::BLUE_PIXEL = png::rgba_pixel(0, 0, 255, 255); bool Line::isAdjacent(Coordinate i_curr, Coordinate i_adjacent) { if (abs(i_curr.x - i_adjacent.x) <= 1 && abs(i_curr.y - i_adjacent.y) <= 1) { return true; } return false; } std::pair<bool, std::string> Line::check(const png::image<png::rgba_pixel>& i_image, png::rgba_pixel i_on_pixel) { auto firstCheck = check(); bool noProblems = true; if (firstCheck.first == true) { return firstCheck; } std::string returnMessage{}; for (auto coordinate : lineData) { if (i_image[coordinate.y][coordinate.x].red != i_on_pixel.red || i_image[coordinate.y][coordinate.x].green != i_on_pixel.green || i_image[coordinate.y][coordinate.x].blue != i_on_pixel.blue) { returnMessage += "Pixel value mismatch at: x = " + std::to_string(coordinate.x) + ", y = " + std::to_string(coordinate.y) + "\n"; noProblems = false; } } if (!noProblems) return std::pair<bool, std::string>(false, firstCheck.second + returnMessage); return std::pair<bool, std::string>(true, "No problems detected"); } std::pair<bool, std::string> Line::check() { bool noProblems = true; std::string returnMessage{}; for (size_t i = 0; i < lineData.size() - 1; ++i) { if (!isAdjacent(lineData[i], lineData[i+1])) { returnMessage += "Discontinued line at: x1 = " + std::to_string(lineData[i].x) + ", y1 = " + std::to_string(lineData[i].y) + ", x2 = " + std::to_string(lineData[i + 1].x) + ", y2 = " + std::to_string(lineData[i + 1].y) + "\n"; noProblems = false; } } if (!noProblems) return std::pair<bool, std::string>(false, returnMessage); return std::pair<bool, std::string>(true, "No problems detected"); } inline void Line::insert(size_t offset, const Coordinate& input) { lineData.insert(lineData.begin() + offset, input); } void Line::append(const std::vector<Coordinate>::iterator& beg_it, const std::vector<Coordinate>::iterator& end_it) { lineData.insert(lineData.end(), beg_it, end_it); }
39.161765
86
0.607585
Zylon-D-Lite
f96d0aa3ae182e22ac149151167544afb5674954
15,323
cpp
C++
ppm_image.cpp
gulesh/pixmap-ops
573afdd349d7e4913d7dbc60f0b9d3edd33b39ca
[ "MIT" ]
null
null
null
ppm_image.cpp
gulesh/pixmap-ops
573afdd349d7e4913d7dbc60f0b9d3edd33b39ca
[ "MIT" ]
null
null
null
ppm_image.cpp
gulesh/pixmap-ops
573afdd349d7e4913d7dbc60f0b9d3edd33b39ca
[ "MIT" ]
null
null
null
#include "ppm_image.h" #include <string> #include <fstream> #include <iostream> #include <cmath> #include <algorithm> using namespace agl; using namespace std; ppm_image::ppm_image() { imageWidth = 0; imageHeight = 0; pixelArray= nullptr; } ppm_image::ppm_image(int w, int h) { imageWidth = w; imageHeight =h; //clear(); pixelArray = new ppm_pixel*[h]; for (int i =0; i<h ;i++) { pixelArray[i] = new ppm_pixel[w]; } } ppm_image::ppm_image(const ppm_image& orig) { //clear(); imageWidth = orig.imageWidth; imageHeight = orig.imageHeight; pixelArray = new ppm_pixel*[imageHeight]; for (int i =0; i<imageHeight ;i++) { pixelArray[i] = new ppm_pixel[imageWidth]; } for (int j = 0; j < imageHeight; j++) //rows { for (int k = 0; k < imageWidth; k++) //columns { pixelArray[j][k]= orig.pixelArray[j][k]; } } } ppm_image& ppm_image::operator=(const ppm_image& orig) { if (&orig == this) // protect against self-assignment { return *this; } //clear(); imageHeight = orig.imageHeight; imageWidth = orig.imageWidth; pixelArray = new ppm_pixel*[imageHeight]; for (int i =0; i<imageHeight ;i++) { pixelArray[i] = new ppm_pixel[imageWidth]; } for (int j = 0; j < imageHeight; j++) //rows { for (int k = 0; k < imageWidth; k++) //columns { pixelArray[j][k]= orig.pixelArray[j][k]; } } return *this; } void ppm_image::clear() { //pixelArray = nullptr; } ppm_image::~ppm_image() { for (int i = 0; i < imageHeight; i++) { delete[] pixelArray[i]; } delete[] pixelArray; } bool ppm_image::load(const std::string& filename) { ifstream file(filename); cout<<"filename " << filename <<endl; string p3; int value; if (!file) // true if the file is valid { cout << "Cannot load file: " << filename << endl; return 1; } file >> p3; //this will store "P3" file >> value; //width imageWidth = value; file >> value; //height imageHeight = value; file >> value; //this will give the number 255 //memory cleaning //clear(); pixelArray = new ppm_pixel*[imageHeight]; for (int i =0; i<imageHeight ;i++) { pixelArray[i] = new ppm_pixel[imageWidth]; } while(file) { for (int j = 0; j < imageHeight; j++) //rows { for (int k = 0; k < imageWidth; k++) //columns { ppm_pixel tempPixel; int pixel; //r value of the pixel file >> pixel ; tempPixel.r = (unsigned char) pixel; //g value of the pixel file >> pixel ; tempPixel.g = (unsigned char) pixel; //b value of the pixel file >> pixel ; tempPixel.b = (unsigned char) pixel; //pixel with r,g,b valus stored in the 2D array pixelArray[j][k]= tempPixel; } } return 0; } return 0; } bool ppm_image::save(const std::string& filename) const { ofstream file(filename); if(!file) { return 1; } string p3 = "P3"; file << p3 << endl; //this will store "P3" file << imageWidth << endl; //width file << imageHeight << endl; //height int value = 255; file << value << endl;//this will give the number 255 for (int j = 0; j < imageHeight; j++) //rows { for (int k = 0; k < imageWidth; k++) //columns { ppm_pixel tempPixel; tempPixel = pixelArray[j][k]; //r value of the pixel stored in the file file << (int) tempPixel.r <<endl; //cout << (int) tempPixel.r <<endl; //g value of the pixel stored in the file file << (int) tempPixel.g << endl; //cout << (int) tempPixel.g <<endl; //b value of the pixel stored in the file file << (int) tempPixel.b << endl; //cout << (int) tempPixel.b <<endl; } } file.close(); return 0; } ppm_image ppm_image::resize(int w, int h) const { int oldPixelC, oldPixelR; ppm_image result = ppm_image( w, h); for (int i = 0 ; i < h; i++) { for (int j = 0; j < w ;j++) { oldPixelR = floor( (i * (imageHeight - 1))/(h-1) ); oldPixelC = floor( (j * (imageWidth - 1))/(w-1) ); result.pixelArray[i][j].r = pixelArray[oldPixelR][oldPixelC].r; result.pixelArray[i][j].g = pixelArray[oldPixelR][oldPixelC].g; result.pixelArray[i][j].b = pixelArray[oldPixelR][oldPixelC].b; } } return result; } //got a unique image // ppm_image ppm_image::flip_horizontal() const // { // ppm_image result = ppm_image(imageWidth,imageHeight); // for (int i = 0 ; i <imageHeight; i++) // { // for (int j = 0 ; j < imageWidth ;j++) // { // result.pixelArray[i][j]= pixelArray[imageHeight - j - 1][j]; // } // } // return result; // } ppm_image ppm_image::flip_horizontal() const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i <imageHeight; i++) { for (int j = 0 ; j < imageWidth ;j++) { result.pixelArray[i][j]= pixelArray[imageHeight - i - 1][j]; } } return result; } ppm_image ppm_image::subimage(int startx, int starty, int w, int h) const { ppm_image result = ppm_image(w,h); for (int i = 0 ; i < h; i++) { for (int j = 0; j < w ;j++) { result.pixelArray[i][j].r = pixelArray[i+startx][j+starty].r; result.pixelArray[i][j].g = pixelArray[i+startx][j+starty].g; result.pixelArray[i][j].b = pixelArray[i+startx][j+starty].b; } } return result; } void ppm_image::replace(const ppm_image& image, int startx, int starty) { for (int i = 0 ; i < image.imageHeight; i++) { for (int j = 0; j < image.imageWidth ;j++) { pixelArray[i+starty][j+startx] = image.pixelArray[i][j]; } } } ppm_image ppm_image::alpha_blend(const ppm_image& other, float alpha) const { int blendedR, blendedG, blendedB; ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { blendedR = (int) ( ((float) (pixelArray[i][j].r )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].r)) * alpha ) ; blendedG = (int) ( ((float) (pixelArray[i][j].g )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].g)) * alpha ) ; blendedB = (int) ( ((float) (pixelArray[i][j].b )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].b)) * alpha ) ; //setting new pixel color result.pixelArray[i][j].r = (unsigned char) blendedR; result.pixelArray[i][j].g = (unsigned char) blendedG; result.pixelArray[i][j].b = (unsigned char) blendedB; } } return result; } ppm_image ppm_image::gammaCorrect(float gamma) const { int gCorrectedR, gCorrectedG, gCorrectedB; ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { gCorrectedR = 255 * pow(((float) pixelArray[i][j].r)/255, 1/gamma); gCorrectedG = 255 * pow(((float) pixelArray[i][j].g)/255, 1/gamma); gCorrectedB = 255 * pow(((float) pixelArray[i][j].b)/255, 1/gamma); //setting new pixel color result.pixelArray[i][j].r = (unsigned char) gCorrectedR; result.pixelArray[i][j].g = (unsigned char) gCorrectedG; result.pixelArray[i][j].b = (unsigned char) gCorrectedB; } } return result; } ppm_image ppm_image::grayscale() const { int r,g,b,weightedAvg; ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0 ; j < imageWidth ;j++) { ppm_pixel modifyingPixel = pixelArray[i][j]; r = modifyingPixel.r; g = modifyingPixel.g; b = modifyingPixel.b; weightedAvg = 0.3 * r + 0.59 * g + 0.11 * b; modifyingPixel.b = weightedAvg; modifyingPixel.g = weightedAvg; modifyingPixel.r = weightedAvg; result.pixelArray[i][j] = modifyingPixel; } } return result; } ppm_pixel ppm_image::get(int row, int col) const { return pixelArray[row][col]; } void ppm_image::set(int row, int col, const ppm_pixel& c) { pixelArray[row][col].r = c.r; pixelArray[row][col].g = c.g; pixelArray[row][col].b = c.b; } int ppm_image::height() const { return imageHeight; } int ppm_image::width() const { return imageWidth; } ppm_image ppm_image::swirlColors() const { ppm_pixel tempPixel; ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j] = pixelArray[i][j]; tempPixel.r = result.pixelArray[i][j].r ; result.pixelArray[i][j].r = result.pixelArray[i][j].g; result.pixelArray[i][j].g = result.pixelArray[i][j].b; result.pixelArray[i][j].b = tempPixel.r; } } return result; } ppm_image ppm_image::distortImage() const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { int distorted_j = (j + (int) (20*sin(i/10)) + imageWidth) % imageWidth; int distorted_i = (i + (int) (20*cos(j/10)) + imageHeight) % imageHeight; result.pixelArray[i][j] = pixelArray[distorted_i][distorted_j]; } } return result; } ppm_image ppm_image::invertColor() const { int modifiedR, modifiedG, modifiedB; ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { modifiedR = 255 - (int) pixelArray[i][j].r ; modifiedG = 255 - (int) pixelArray[i][j].g ; modifiedB = 255 - (int) pixelArray[i][j].b ; //setting new pixel color result.pixelArray[i][j].r = (unsigned char) modifiedR; result.pixelArray[i][j].g = (unsigned char) modifiedG; result.pixelArray[i][j].b = (unsigned char) modifiedB; } } return result; } ppm_image ppm_image::rotate90() const { int oldPixelC = 0; ppm_image result = ppm_image(imageHeight,imageWidth); for (int i = 0 ; i < imageWidth; i++) { int oldPixelR = imageHeight -1; for (int j = 0; j < imageHeight ;j++) { result.pixelArray[i][j] = pixelArray[oldPixelR][oldPixelC]; oldPixelR -= 1; } oldPixelC += 1; } return result; } ppm_image ppm_image::lightest(const ppm_image& other) const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = std::max(pixelArray[i][j].r, other.pixelArray[i][j].r); result.pixelArray[i][j].g = std::max(pixelArray[i][j].g, other.pixelArray[i][j].g); result.pixelArray[i][j].b = std::max(pixelArray[i][j].b, other.pixelArray[i][j].b); } } return result; } ppm_image ppm_image::darkest(const ppm_image& other) const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = std::min(pixelArray[i][j].r, other.pixelArray[i][j].r); result.pixelArray[i][j].g = std::min(pixelArray[i][j].g, other.pixelArray[i][j].g); result.pixelArray[i][j].b = std::min(pixelArray[i][j].b, other.pixelArray[i][j].b); } } return result; } ppm_image ppm_image::difference(const ppm_image& other) const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r); result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r); result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r); } } return result; } ppm_image ppm_image::multiply(const ppm_image& other) const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].r * other.pixelArray[i][j].r); result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].g * other.pixelArray[i][j].g); result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].b * other.pixelArray[i][j].b); } } return result; } ppm_image ppm_image::redOnly(const ppm_image& other) const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = std::max(pixelArray[i][j].r, other.pixelArray[i][j].r); } } return result; } //not working as expected need to edit ppm_image ppm_image::addBorder() const { int resultImageH = imageHeight+2; int resultImageW = imageWidth+2 ; ppm_pixel p{(unsigned char)255,(unsigned char) 255,(unsigned char) 255}; ppm_image result = ppm_image(resultImageW,resultImageH); for (int i = 0 ; i < resultImageH; i++) { if(i == 0 || i == resultImageH -1) { for (int j = 0; j < resultImageW ;j++) { result.pixelArray[i][j] = p; } } else { for (int j = 0; j < resultImageW ;j++) { if((j == 0) || (j == resultImageW-1)) { result.pixelArray[i][j] = p; } else { result.pixelArray[i][j] = pixelArray[i+1][j+1]; } } } } return result; } ppm_image ppm_image::redExtract() const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = pixelArray[i][j].r; result.pixelArray[i][j].g = 0; result.pixelArray[i][j].b = 0; } } return result; } ppm_image ppm_image::greenExtract() const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = result.pixelArray[i][j].g = pixelArray[i][j].g; result.pixelArray[i][j].b = 0; } } return result; } ppm_image ppm_image::blueExtract() const { ppm_image result = ppm_image(imageWidth,imageHeight); for (int i = 0 ; i < imageHeight; i++) { for (int j = 0; j < imageWidth ;j++) { result.pixelArray[i][j].r = 0; result.pixelArray[i][j].g = 0; result.pixelArray[i][j].b = pixelArray[i][j].b; } } return result; }
26.835377
125
0.559812
gulesh
f96f63c2c2a06f5743891f2fd243ece7b1615cb4
608
cpp
C++
server/src/extension_queue/queue.cpp
valmat/queueServer
6626e99cd4fccca6f2ae17b8cc33ef151b651b5d
[ "BSD-3-Clause" ]
4
2017-09-25T12:23:22.000Z
2019-02-19T14:15:46.000Z
server/src/extension_queue/queue.cpp
valmat/queueServer
6626e99cd4fccca6f2ae17b8cc33ef151b651b5d
[ "BSD-3-Clause" ]
1
2019-02-25T17:53:32.000Z
2019-02-27T06:57:35.000Z
server/src/extension_queue/queue.cpp
valmat/queueServer
6626e99cd4fccca6f2ae17b8cc33ef151b651b5d
[ "BSD-3-Clause" ]
1
2019-02-19T13:42:29.000Z
2019-02-19T13:42:29.000Z
/** * RocksServer plugin * https://github.com/valmat/queueServer */ #include "../include.h" #include "RequestMoveFirstPref.h" #include "RequestFirstPref.h" #include "RequestGetIncr.h" using namespace RocksServer; /* * Create plugin * * @param extension object of Extension * @param rdb wrapped object of RocksDB */ PLUGIN(Extension extension, RocksDBWrapper& rdb) { extension .bind("/get-incr", new RequestGetIncr(rdb)) .bind("/first-pref", new RequestFirstPref(rdb)) .bind("/move-fpref", new RequestMoveFirstPref(rdb)); ; }
20.266667
65
0.641447
valmat
f9711d8fdecf29560f186cbd4c4f86ee0342ff38
3,739
cpp
C++
Core-src/AnalyzeWindow.cpp
HaikuArchives/BeAE
b57860a81266dd465655ec98b7524406bfde27aa
[ "BSD-3-Clause" ]
6
2015-03-04T19:41:12.000Z
2022-03-27T09:44:25.000Z
Core-src/AnalyzeWindow.cpp
HaikuArchives/BeAE
b57860a81266dd465655ec98b7524406bfde27aa
[ "BSD-3-Clause" ]
20
2015-03-03T21:02:20.000Z
2021-08-02T13:26:59.000Z
Core-src/AnalyzeWindow.cpp
HaikuArchives/BeAE
b57860a81266dd465655ec98b7524406bfde27aa
[ "BSD-3-Clause" ]
8
2015-02-23T19:10:32.000Z
2020-10-26T08:03:00.000Z
/* Copyright (c) 2003, Xentronix Author: Frans van Nispen (frans@xentronix.com) 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 Xentronix nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Window.h> #include <View.h> #include <InterfaceKit.h> #include <stdlib.h> #include <stdio.h> #include "Globals.h" #include "AnalyzeWindow.h" #include "main.h" #define UPDATE 'updt' #define QUIT 'quit' #define SET 'setF' /******************************************************* * *******************************************************/ AnalyzeWindow::AnalyzeWindow(BRect r, const char *name) : BWindow(r,name, B_FLOATING_WINDOW_LOOK,B_FLOATING_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_AVOID_FOCUS) { // 25 frames per second by default m_frames = 25; m_count = 0; // set the playHook m_index = Pool.SetPlayHook( _PlayBuffer, PLAY_HOOKS/2, (void*)this); SetPulseRate(50000); Run(); Show(); } /******************************************************* * *******************************************************/ void AnalyzeWindow::PlayBuffer(float *buffer, size_t size) { } /******************************************************* * *******************************************************/ void AnalyzeWindow::_PlayBuffer(float *buffer, size_t size, void *cookie) { AnalyzeWindow *win = (AnalyzeWindow*)cookie; // cast to our own clas // process effect win->PlayBuffer(buffer, size); // update with frames/second win->m_count -= size; if (win->m_count <0){ win->m_count = (int)Pool.system_frequency*2/win->m_frames; win->PostMessage(UPDATE); } } /******************************************************* * *******************************************************/ int32 AnalyzeWindow::FramesPerSecond() { return m_frames; } void AnalyzeWindow::SetFramesPerSecond(int32 frames) { m_frames = frames; } /******************************************************* * *******************************************************/ bool AnalyzeWindow::QuitRequested(){ Pool.RemovePlayHook( _PlayBuffer, m_index ); return true; } /******************************************************* * *******************************************************/ void AnalyzeWindow::MessageReceived(BMessage* msg){ BView *view; switch(msg->what){ case UPDATE: view = ChildAt(0); if (view) view->Invalidate(); break; default: BWindow::MessageReceived(msg); } }
30.647541
101
0.61487
HaikuArchives
f972af1ee36532247bf190e9808e6e5d4a624d8e
708
hpp
C++
include/RadonFramework/IO/ConsoleUI/With.hpp
tak2004/RF_Console
b2a1114b4e948281c64b085eb407926704ecc7cb
[ "Apache-2.0" ]
null
null
null
include/RadonFramework/IO/ConsoleUI/With.hpp
tak2004/RF_Console
b2a1114b4e948281c64b085eb407926704ecc7cb
[ "Apache-2.0" ]
null
null
null
include/RadonFramework/IO/ConsoleUI/With.hpp
tak2004/RF_Console
b2a1114b4e948281c64b085eb407926704ecc7cb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <RadonFramework/IO/ConsoleUI/Component.hpp> #include <RadonFramework/IO/ConsoleUI/ComponentOperator.hpp> #include <RadonFramework/IO/ConsoleUI/State.hpp> namespace RadonFramework::IO::ConsoleUI { template <class T> struct With : public ComponentOperator { template <int N> With(char const (&CString)[N], T&& Value) : m_Temporary(Value), m_State(RF_HASH(CString)) { } void operator()(Component& Receiver) override { void* result; if(Receiver.States().Get(m_State, result)) { (*reinterpret_cast<State<T>*>(result)) = m_Temporary; } } const T m_Temporary; const RF_Type::UInt64 m_State; }; } namespace RF_CUI = RadonFramework::IO::ConsoleUI;
21.454545
60
0.710452
tak2004
f976e1c6bc0d2cac86d70e577b4df9a1003f5863
4,967
cc
C++
pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_cursor_delete2.cc
wc222/pmdk-examples
64aadc3a70471c469ac8e214eb1e04ff47cf18ff
[ "BSD-3-Clause" ]
11
2017-10-28T08:41:08.000Z
2021-06-24T07:24:21.000Z
pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_cursor_delete2.cc
WSCWDA/pmdk-examples
c3d079e52cd18b0e14836ef42bad9a995336bf90
[ "BSD-3-Clause" ]
1
2021-02-24T05:26:44.000Z
2021-02-24T05:26:44.000Z
pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_cursor_delete2.cc
isabella232/pmdk-examples
be7a5a18ba7bb8931e512f6d552eadf820fa2235
[ "BSD-3-Clause" ]
4
2017-09-07T09:33:26.000Z
2021-02-19T07:45:08.000Z
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /*====== This file is part of PerconaFT. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ---------------------------------------- PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. PerconaFT 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ======= */ #ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved." #include "test.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <memory.h> #include <errno.h> #include <sys/stat.h> #include <db.h> static DB_ENV *dbenv; static DB *db; static DB_TXN * txn; static void test_cursor_delete2 (void) { int r; DBT key,val; r = db_env_create(&dbenv, 0); CKERR(r); r = dbenv->open(dbenv, TOKU_TEST_FILENAME, DB_PRIVATE|DB_INIT_MPOOL|DB_CREATE|DB_INIT_TXN, 0); CKERR(r); r = db_create(&db, dbenv, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "primary.db", NULL, DB_BTREE, DB_CREATE, 0600); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->put(db, txn, dbt_init(&key, "a", 2), dbt_init(&val, "b", 2), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->del(db, txn, dbt_init(&key, "a", 2), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->del(db, txn, dbt_init(&key, "a", 2), DB_DELETE_ANY); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->put(db, txn, dbt_init(&key, "a", 2), dbt_init(&val, "c", 2), 0); CKERR(r); r = db->del(db, txn, dbt_init(&key, "a", 2), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->put(db, txn, dbt_init(&key, "a", 2), dbt_init(&val, "c", 2), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = dbenv->txn_begin(dbenv, 0, &txn, 0); CKERR(r); r = db->del(db, txn, dbt_init(&key, "a", 2), 0); CKERR(r); r = db->del(db, txn, dbt_init(&key, "a", 2), DB_DELETE_ANY); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->close(db, 0); CKERR(r); r = dbenv->close(dbenv, 0); CKERR(r); } int test_main(int argc, char *const argv[]) { parse_args(argc, argv); toku_os_recursive_delete(TOKU_TEST_FILENAME); toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); test_cursor_delete2(); return 0; }
45.154545
114
0.476545
wc222
f97a4336ab04e9446d773096c45ca5d954126da6
1,205
cpp
C++
Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
#include "../header.h" class Solution { public: vector<string> letterCombinations(string digits) { if (digits.length() == 0) { return {}; } unordered_map<char, string> m; m['2'] = "abc"; m['3'] = "def"; m['4'] = "ghi"; m['5'] = "jkl"; m['6'] = "mno"; m['7'] = "pqrs"; m['8'] = "tuv"; m['9'] = "wxyz"; vector<string> res; int d_index = 0; string current = ""; helper(digits, m, res, current, d_index); return res; } private: void helper(const string& digits, unordered_map<char, string>& m, vector<string>& res, string current, int d_index) { if (current.length() == digits.length()) { res.push_back(current); return; } string candidate = m[digits[d_index]]; for (int i = 0; i < candidate.size(); ++i) { current.push_back(candidate[i]); helper(digits, m, res, current, d_index+1); current.pop_back(); } } }; int main() { string digits; cin >> digits; vector<string> res = Solution().letterCombinations(digits); for (auto r: res) { cout << r << endl; } return 0; }
25.104167
121
0.509544
qiufengyu
f97d1a9270894f9dc0a87e4b98415bcd3e15cd13
2,071
hpp
C++
Libs/SceneGraph/PlantNode.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
Libs/SceneGraph/PlantNode.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
Libs/SceneGraph/PlantNode.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_TREE_NODE_HPP_INCLUDED #define CAFU_TREE_NODE_HPP_INCLUDED #include "Node.hpp" #include "Plants/Tree.hpp" struct PlantDescriptionT; class PlantDescrManT; namespace cf { namespace SceneGraph { class PlantNodeT : public GenericNodeT { public: /// The constructor. PlantNodeT(); /// Constructor for creating a PlantNodeT from parameters. PlantNodeT(const PlantDescriptionT* PlantDescription, unsigned long RandomSeed, const Vector3dT& Position, const Vector3fT& Angles); /// Named constructor. static PlantNodeT* CreateFromFile_cw(std::istream& InFile, aux::PoolT& Pool, LightMapManT& LMM, SHLMapManT& SMM, PlantDescrManT& PDM); /// The destructor. ~PlantNodeT(); // The NodeT interface. void WriteTo(std::ostream& OutFile, aux::PoolT& Pool) const; const BoundingBox3T<double>& GetBoundingBox() const; // void InitDrawing(); bool IsOpaque() const { return false; }; void DrawAmbientContrib(const Vector3dT& ViewerPos) const; //void DrawStencilShadowVolumes(const Vector3dT& LightPos, const float LightRadius) const; //void DrawLightSourceContrib(const Vector3dT& ViewerPos, const Vector3dT& LightPos) const; void DrawTranslucentContrib(const Vector3dT& ViewerPos) const; private: PlantNodeT(const PlantNodeT&); ///< Use of the Copy Constructor is not allowed. void operator = (const PlantNodeT&); ///< Use of the Assignment Operator is not allowed. TreeT m_Tree; unsigned long m_RandomSeed; Vector3dT m_Position; Vector3fT m_Angles; std::string m_DescrFileName; BoundingBox3dT m_Bounds; }; } } #endif
30.455882
146
0.633028
dns
f97f1b80cd830250828379c88056dfae3aa0c8f6
3,247
hpp
C++
modules/engine/include/randar/Render/Geometry.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
1
2016-11-12T02:43:29.000Z
2016-11-12T02:43:29.000Z
modules/engine/include/randar/Render/Geometry.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
modules/engine/include/randar/Render/Geometry.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
#ifndef RANDAR_RENDER_GEOMETRY_HPP #define RANDAR_RENDER_GEOMETRY_HPP #include <randar/Render/Primitive.hpp> #include <randar/Render/ShaderProgram.hpp> #include <randar/Render/VertexBuffer.hpp> namespace randar { class Geometry : public GraphicsContextResource { public: VertexBuffer vertices; IndexBuffer indices; /** * Primitive used by the geometry. * * Describes how vertices should be interpreted. */ Primitive primitive = randar::Primitive::Triangle; /** * Constructors. */ Geometry(); Geometry(GraphicsContext& context); /** * Assignment. */ Geometry(const Geometry& other); Geometry& operator =(const Geometry& other); Geometry copy(); /** * Destructor. */ ~Geometry(); /** * Identifies the Randar object type. */ std::string kind() const; /** * Initializes the geometry on a context. */ using GraphicsContextResource::initialize; virtual void initialize() override; /** * Uninitializes the geometry from a context. * * Nothing happens if the geometry is not initialized. No exceptions are * thrown upon failure. */ virtual void uninitialize() override; /** * Whether the geometry is initialized on a context. */ bool isInitialized(); /** * Syncs local data to OpenGL. */ void sync(); /** * Clears vertices and indices of the geometry. * * Primitive remains unchanged. */ void clear(); /** * Adds a vertex to the geometry's available vertices. * * Returns an index that identifies the vertex in this geometry's * available vertices, which is later used to construct a shape. * * If the vertex already exists in the available geometry, it is not * appended and the existing index is returned. * * This does not manipulate the shape of the geometry. * * In most cases, you can use the simplified append method instead. */ uint32_t useVertex(const Vertex& vertex); /** * Appends a vertex to the geometry shape. * * This method simply calls appendVertex, captures the index of the * vertex in this geometry's available vertices, and calls appendIndex * with it. * * This is the preferred way to append a vertex to geometry. */ void append(const Vertex& vertex); /** * Appends another geometry to this geometry. */ void append(Geometry& other); void append(Geometry& other, const Transform& transform); /** * Saves and loads the geometry from disk. */ void save(const randar::Path& filepath); void load(const randar::Path& filepath); }; /** * Node.js helper. */ #ifdef SWIG %newobject geometry; #endif Geometry* geometry(); } #endif
25.769841
80
0.558978
litty-studios
f97f4fbe581321f5293e8955e8f7d600fd259aba
13,240
cpp
C++
dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp
rudals0215/AR-streaming-with-MPEG-DASH
7c9f24a2eed7f756e51451670286a11351a6b877
[ "MIT" ]
null
null
null
dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp
rudals0215/AR-streaming-with-MPEG-DASH
7c9f24a2eed7f756e51451670286a11351a6b877
[ "MIT" ]
null
null
null
dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp
rudals0215/AR-streaming-with-MPEG-DASH
7c9f24a2eed7f756e51451670286a11351a6b877
[ "MIT" ]
1
2021-07-07T00:53:49.000Z
2021-07-07T00:53:49.000Z
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * <OWNER> = British Broadcasting Corporation (BBC). * <ORGANIZATION> = BBC. * <YEAR> = 2015 * * Copyright (c) 2015, BBC. * 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 <ORGANIZATION> 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. */ /*! ************************************************************************************* * \file DisplayGammaAdjustHLG.cpp * * \brief * DisplayGammaAdjustHLG class * This is an implementation of the display gamma normalization process * in BBC's Hybrid Log-Gamma system (HLG). * A complete documentation of this process is available in * the BBC's response to the MPEG call for evidence on HDR and WCG video coding * (document m36249, available at: * http://wg11.sc29.org/doc_end_user/documents/112_Warsaw/wg11/m36249-v2-m36249.zip) * * \author * - Matteo Naccari <matteo.naccari@bbc.co.uk> * - Manish Pindoria <manish.pindoria@bbc.co.uk> * ************************************************************************************* */ #include "Global.H" #include "DisplayGammaAdjustHLG.H" #include "ColorTransformGeneric.H" namespace hdrtoolslib { //----------------------------------------------------------------------------- // Constructor / destructor implementation //----------------------------------------------------------------------------- DisplayGammaAdjustHLG::DisplayGammaAdjustHLG(double gamma, double scale) { m_tfScale = 12.0; //19.6829249; // transfer function scaling - assuming super whites m_linScale = scale; m_gamma = gamma; m_transformY = NULL; } DisplayGammaAdjustHLG::~DisplayGammaAdjustHLG() { m_transformY = NULL; } void DisplayGammaAdjustHLG::setup(Frame *frame) { ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, (const double **) &m_transformY); } void DisplayGammaAdjustHLG::forward(double &comp0, double &comp1, double &comp2) { double vComp0, vComp1, vComp2; //vComp0 = comp0 / m_tfScale; //vComp1 = comp1 / m_tfScale; //vComp2 = comp2 / m_tfScale; vComp0 = comp0; vComp1 = comp1; vComp2 = comp2; double ySignal = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2); double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal; comp0 = (float) (vComp0 * yDisplay) ; comp1 = (float) (vComp1 * yDisplay) ; comp2 = (float) (vComp2 * yDisplay) ; } void DisplayGammaAdjustHLG::forward(const double iComp0, const double iComp1, const double iComp2, double *oComp0, double *oComp1, double *oComp2) { double vComp0, vComp1, vComp2; //vComp0 = iComp0 / m_tfScale; //vComp1 = iComp1 / m_tfScale; //vComp2 = iComp2 / m_tfScale; vComp0 = iComp0; vComp1 = iComp1; vComp2 = iComp2; double ySignal = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2); double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal; *oComp0 = (float) (vComp0 * yDisplay) ; *oComp1 = (float) (vComp1 * yDisplay) ; *oComp2 = (float) (vComp2 * yDisplay) ; } void DisplayGammaAdjustHLG::inverse(double &comp0, double &comp1, double &comp2) { // 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light // 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68) // 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white) // Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class. double vComp0, vComp1, vComp2; vComp0 = dMax(0.0, (double) comp0 / m_linScale); vComp1 = dMax(0.0, (double) comp1 / m_linScale); vComp2 = dMax(0.0, (double) comp2 / m_linScale); double yDisplay = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2); //double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma); double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma); comp0 = (float) (vComp0 * yDisplayGamma) ; comp1 = (float) (vComp1 * yDisplayGamma) ; comp2 = (float) (vComp2 * yDisplayGamma) ; } void DisplayGammaAdjustHLG::inverse(const double iComp0, const double iComp1, const double iComp2, double *oComp0, double *oComp1, double *oComp2) { // 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light // 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68) // 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white) // Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class. double vComp0, vComp1, vComp2; vComp0 = dMax(0.0, (double) iComp0 / m_linScale); vComp1 = dMax(0.0, (double) iComp1 / m_linScale); vComp2 = dMax(0.0, (double) iComp2 / m_linScale); double yDisplay = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2); //double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma); double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma); *oComp0 = (float) (vComp0 * yDisplayGamma) ; *oComp1 = (float) (vComp1 * yDisplayGamma) ; *oComp2 = (float) (vComp2 * yDisplayGamma) ; } void DisplayGammaAdjustHLG::forward(Frame *frame) { if (frame->m_isFloat == TRUE && frame->m_compSize[Y_COMP] == frame->m_compSize[Cb_COMP]) { if (frame->m_colorSpace == CM_RGB) { double vComp[3]; const double *transformY = NULL; ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, &transformY); for (int index = 0; index < frame->m_compSize[Y_COMP]; index++) { for(int component = 0; component < 3; component++) { //vComp[component] = frame->m_floatComp[component][index] / m_tfScale; vComp[component] = frame->m_floatComp[component][index]; } double ySignal = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]); double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal; for(int component = 0; component < 3; component++) { frame->m_floatComp[component][index] = (float) (vComp[component] * yDisplay) ; } } // reset the pointer (just for safety transformY = NULL; } } } void DisplayGammaAdjustHLG::forward(Frame *out, const Frame *inp) { if (inp->m_isFloat == TRUE && out->m_isFloat == TRUE && inp->m_size == out->m_size && inp->m_compSize[Y_COMP] == inp->m_compSize[Cb_COMP]) { if (inp->m_colorSpace == CM_RGB && out->m_colorSpace == CM_RGB) { double vComp[3]; const double *transformY = NULL; ColorTransformGeneric::setYConversion(inp->m_colorPrimaries, &transformY); for (int index = 0; index < inp->m_compSize[Y_COMP]; index++) { for(int component = 0; component < 3; component++) { //vComp[component] = inp->m_floatComp[component][index] / m_tfScale; vComp[component] = inp->m_floatComp[component][index]; } double ySignal = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]); double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal; for(int component = 0; component < 3; component++) { out->m_floatComp[component][index] = (float) (vComp[component] * yDisplay) ; } } // reset the pointer (just for safety transformY = NULL; } else { out->copy((Frame *) inp); } } else if (inp->m_isFloat == FALSE && out->m_isFloat == FALSE && inp->m_size == out->m_size && inp->m_bitDepth == out->m_bitDepth) { out->copy((Frame *) inp); } } void DisplayGammaAdjustHLG::inverse(Frame *frame) { // 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light // 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68) // 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white) // Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class. if (frame->m_isFloat == TRUE && frame->m_compSize[Y_COMP] == frame->m_compSize[Cb_COMP]) { if (frame->m_colorSpace == CM_RGB) { double vComp[3]; const double *transformY = NULL; ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, &transformY); for (int index = 0; index < frame->m_compSize[Y_COMP]; index++) { for(int component = 0; component < 3; component++) { vComp[component] = dMax(0.0, (double) frame->m_floatComp[component][index] / m_linScale); } double yDisplay = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]); //double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma); double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma); for(int component = 0; component < 3; component++) { frame->m_floatComp[component][index] = (float) (vComp[component] * yDisplayGamma) ; } } // reset the pointer (just for safety transformY = NULL; } } } void DisplayGammaAdjustHLG::inverse(Frame *out, const Frame *inp) { // 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light // 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68) // 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white) // Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class. if (inp->m_isFloat == TRUE && out->m_isFloat == TRUE && inp->m_size == out->m_size && inp->m_compSize[Y_COMP] == inp->m_compSize[Cb_COMP]) { if (inp->m_colorSpace == CM_RGB && out->m_colorSpace == CM_RGB) { double vComp[3]; const double *transformY = NULL; ColorTransformGeneric::setYConversion(inp->m_colorPrimaries, &transformY); for (int index = 0; index < inp->m_compSize[Y_COMP]; index++) { for(int component = 0; component < 3; component++) { vComp[component] = dMax(0.0, (double) inp->m_floatComp[component][index] / m_linScale); } double yDisplay = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]); //double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma); double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma); for(int component = 0; component < 3; component++) { out->m_floatComp[component][index] = (float) (vComp[component] * yDisplayGamma) ; } } // reset the pointer (just for safety transformY = NULL; } } else if (inp->m_isFloat == FALSE && out->m_isFloat == FALSE && inp->m_size == out->m_size && inp->m_bitDepth == out->m_bitDepth) { out->copy((Frame *) inp); } } } // namespace hdrtoolslib //----------------------------------------------------------------------------- // End of file //-----------------------------------------------------------------------------
43.84106
151
0.649245
rudals0215
f98335835b564975be345d5087b058a382845d32
5,545
cpp
C++
src/TransitionHandler.cpp
MacaroniDamage/FabulousNeopixelFirmware
4ebf638f9d053629dd2eb81039cc153755d55668
[ "MIT" ]
2
2021-06-05T15:26:29.000Z
2021-06-05T23:50:09.000Z
src/TransitionHandler.cpp
MacaroniDamage/FabulousNeopixelFirmware
4ebf638f9d053629dd2eb81039cc153755d55668
[ "MIT" ]
null
null
null
src/TransitionHandler.cpp
MacaroniDamage/FabulousNeopixelFirmware
4ebf638f9d053629dd2eb81039cc153755d55668
[ "MIT" ]
null
null
null
/** * @file TransitionHandler.cpp * @author MacaroniDamage * @brief Executes state machine that handel transitions to different * stages * @version 0.1 * @date 2020-12-18 * * */ #include "TransitionHandler.h" /** Configures the instace so that * it triggers the wished state machine **/ void TransitionHandler::playTransition(Transition transition, uint32_t targetColor) { this->targetColor = targetColor; this->currentColor = _pController->getCurrentColor(); this->currentBrightness = _pController->getCurrentBrightness(); this->transition = transition; this->transitionState = STATE_1; } //sets the target brightness and gets the current values from the controller void TransitionHandler::playTransition(uint8_t targetBrightness, Transition transition) { this->targetBrightness = targetBrightness; this->currentColor = _pController->getCurrentColor(); this->currentBrightness = _pController->getCurrentBrightness(); this->transition = transition; this->transitionState = STATE_1; } //Just sets the transition values and gets the current values from the controller void TransitionHandler::playTransition(Transition transition) { this->currentColor = _pController->getCurrentColor(); this->currentBrightness = _pController->getCurrentBrightness(); this->transition = transition; this->transitionState = STATE_1; Serial.println("Stage: " + String(transitionState)); } void TransitionHandler::setTransitionMode(TransitionMode transitionMode) { this->transitionMode = transitionMode; } TransitionState TransitionHandler::getCurrentTransitionState() { return this->transitionState; } //Sets the targetBrightness to the minimun value sets the new color //and set the targetBrigtness to the wished value void TransitionHandler::Fade() { switch (transitionState) { case STDBY: transitionState = STDBY; break; case STATE_1: //Fade_Out //temporaily saves the brightness to set it later. this->oldBrightness = this->currentBrightness; //turns the brightness of the stripe to minimal brightness this->targetBrightness = MIN_BRIGHTNESS; //changes the state transitionState = STATE_2; break; case STATE_2: //SET COLOR if (currentBrightness <= targetBrightness) { //Tells the Controller what color is now the current one //and dates the stripe up transitionState = STATE_3; //Dates the currentColor and currentBrightness up this->currentColor = this->targetColor; this->targetBrightness = this->oldBrightness; //Executes the changeColor function if transitionMode is in //a standart state so it won't be executed durig an animation if (transitionMode == STANDARD) _pController->changeColor(currentColor); } else { transitionState = STATE_2; } break; case STATE_3: //Fade IN if (currentBrightness < targetBrightness) { transitionState = STATE_3; } else { currentColor = targetColor; transitionState = STDBY; transitionisPlayed = false; } break; default: transitionState = STDBY; } } // change to a target brightness void TransitionHandler::gotoBrightness() { int16_t actBrightness = (int16_t)currentBrightness; if (brightnessUpdateTimer.isTimerReady()) { if (targetBrightness > currentBrightness) { actBrightness += BRIGHTNESS_STEP; if (actBrightness > targetBrightness) currentBrightness = targetBrightness; else currentBrightness = actBrightness; } else if (targetBrightness < currentBrightness) { actBrightness -= BRIGHTNESS_STEP; if (actBrightness < targetBrightness) currentBrightness = targetBrightness; else currentBrightness = (uint8_t)actBrightness; } //Refreshes the stripe _pController->changeBrightness(currentBrightness); //Refreshed the update timer brightnessUpdateTimer.startTimer(BRIGHTNESS_UPDATE); } } //Sets the targetBrightnes to the minimum brightness and waits until it is achieved //set the transition state then to Standby void TransitionHandler::FadeOut() { switch (transitionState) { case STATE_1: this->targetBrightness = MIN_BRIGHTNESS; this->transitionState = STATE_2; break; case STATE_2: if (currentBrightness <= targetBrightness) { this->transitionState = STDBY; } break; } } //Waits until the targetBrightness is equal or higher then the currentBrighness //and the set the TargetHandler to Standby void TransitionHandler::FadeIn() { switch (transitionState) { case STATE_1: //Will be modified so the changeBrightness method //refreshes the solid color this->transitionState = STATE_3; break; case STATE_3: if (currentBrightness >= targetBrightness) { this->transitionState = STDBY; } break; } } uint8_t TransitionHandler::getCurrentBrightness(){ return currentBrightness; } uint8_t TransitionHandler::getTargetBrightness(){ return targetBrightness; } void TransitionHandler::loop() { if (transitionState != STDBY) { switch (transition) { case FADE_TO: this->Fade(); this->gotoBrightness(); break; case FADE_OUT: this->FadeOut(); this->gotoBrightness(); break; case FADE_IN: this->FadeIn(); this->gotoBrightness(); break; default: _pController->changeColor(targetColor); this->transitionState = STDBY; break; } } }
25.911215
87
0.70532
MacaroniDamage
f9847bb79e52b2a28bc39127617f9544416c7709
7,076
cp
C++
Win32/Sources/Application/SMTP_Queue/CSMTPView.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Win32/Sources/Application/SMTP_Queue/CSMTPView.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Win32/Sources/Application/SMTP_Queue/CSMTPView.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Source for CSMTPView class #include "CSMTPView.h" #include "CFontCache.h" #include "CMailboxWindow.h" #include "CMbox.h" #include "CMulberryApp.h" #include "CMulberryCommon.h" #include "CPreferences.h" #include "CSMTPToolbar.h" #include "CSplitterView.h" #include "CToolbarView.h" // Static members BEGIN_MESSAGE_MAP(CSMTPView, CMailboxView) ON_WM_CREATE() ON_WM_DESTROY() END_MESSAGE_MAP() // C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S // Default constructor CSMTPView::CSMTPView() { mSender = NULL; } // Default destructor CSMTPView::~CSMTPView() { } // O T H E R M E T H O D S ____________________________________________________________________________ const int cTitleHeight = 16; int CSMTPView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMailboxView::OnCreate(lpCreateStruct) == -1) return -1; int width = lpCreateStruct->cx; int height = lpCreateStruct->cy; UINT focus_indent = Is3Pane() ? 3 : 0; // Create footer first so we get its scaled height mFooter.CreateDialogItems(IDD_SMTPFOOTER, &mFocusRing); mFooter.ModifyStyle(0, WS_CLIPSIBLINGS); mFooter.ModifyStyleEx(0, WS_EX_DLGMODALFRAME); CRect rect; mFooter.GetWindowRect(rect); mFooter.ExecuteDlgInit(MAKEINTRESOURCE(IDD_SMTPFOOTER)); mFooter.SetFont(CMulberryApp::sAppSmallFont); mFooter.MoveWindow(CRect(focus_indent, height - focus_indent - rect.Height(), width - focus_indent, height - focus_indent)); mFooter.ShowWindow(SW_SHOW); // Subclass footer controls for our use mTotalText.SubclassDlgItem(IDC_SMTPTOTALTXT, &mFooter); mTotalText.SetFont(CMulberryApp::sAppSmallFont); // Server table mSMTPTable.Create(NULL, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP, CRect(focus_indent, focus_indent + cTitleHeight, width - focus_indent, height - focus_indent - rect.Height()), &mFocusRing, IDC_MAILBOXTABLE); mSMTPTable.ModifyStyleEx(0, WS_EX_NOPARENTNOTIFY, 0); mSMTPTable.ResetFont(CFontCache::GetListFont()); mSMTPTable.SetColumnInfo(mColumnInfo); mSMTPTable.SetContextMenuID(IDR_POPUP_CONTEXT_MAILBOX); mSMTPTable.SetContextView(static_cast<CView*>(GetOwningWindow())); // Get titles mSMTPTitles.Create(NULL, NULL, WS_CHILD | WS_VISIBLE, CRect(focus_indent, focus_indent, width - focus_indent - 16, focus_indent + cTitleHeight), &mFocusRing, IDC_STATIC); mSMTPTitles.SetFont(CFontCache::GetListFont()); mFocusRing.AddAlignment(new CWndAlignment(&mSMTPTitles, CWndAlignment::eAlign_TopWidth)); PostCreate(&mSMTPTable, &mSMTPTitles); // Create alignment details mFocusRing.AddAlignment(new CWndAlignment(&mFooter, CWndAlignment::eAlign_BottomWidth)); mFocusRing.AddAlignment(new CWndAlignment(&mSMTPTable, CWndAlignment::eAlign_WidthHeight)); // Set status SetOpen(); return 0; } void CSMTPView::OnDestroy(void) { // Do standard close behaviour DoClose(); // Do default action now CMailboxView::OnDestroy(); } // Make a toolbar appropriate for this view void CSMTPView::MakeToolbars(CToolbarView* parent) { // Create a suitable toolbar CSMTPToolbar* tb = new CSMTPToolbar; mToolbar = tb; tb->InitToolbar(Is3Pane(), parent); // Toolbar must listen to view to get activate/deactive broadcast Add_Listener(tb); // Now give toolbar to its view as standard buttons parent->AddToolbar(tb, GetTable(), CToolbarView::eStdButtonsGroup); } // Set window state void CSMTPView::ResetState(bool force) { if (!GetMbox()) return; // Get name as cstr CString name(GetMbox()->GetAccountName()); // Get visible state bool visible = GetParentFrame()->IsWindowVisible(); // Get default state CMailboxWindowState* state = &CPreferences::sPrefs->mSMTPWindowDefault.Value(); // Do not set if empty CRect set_rect = state->GetBestRect(CPreferences::sPrefs->mSMTPWindowDefault.GetValue()); if (!set_rect.IsRectNull()) { // Clip to screen ::RectOnScreen(set_rect, NULL); // Reset bounds GetParentFrame()->SetWindowPos(nil, set_rect.left, set_rect.top, set_rect.Width(), set_rect.Height(), SWP_NOACTIVATE | SWP_NOZORDER | (visible ? 0 : SWP_NOREDRAW)); } // Prevent window updating while column info is invalid bool locked = GetParentFrame()->LockWindowUpdate(); // Adjust size of tables ResetColumns(state->GetBestColumnInfo(CPreferences::sPrefs->mServerWindowDefault.GetValue())); // Adjust menus SetSortBy(state->GetSortBy()); GetMbox()->ShowBy(state->GetShowBy()); // Sorting button //mSortBtn.SetPushed(state->GetShowBy() == cShowMessageDescending); if (force) SaveDefaultState(); if (locked) GetParentFrame()->UnlockWindowUpdate(); // Do zoom if (state->GetState() == eWindowStateMax) GetParentFrame()->ShowWindow(SW_SHOWMAXIMIZED); // Init the preview state once if we're in a window if (!Is3Pane() && !mPreviewInit) { mMessageView->ResetState(); mPreviewInit = true; } // Init splitter pos if (!Is3Pane() && (state->GetSplitterSize() != 0)) GetMailboxWindow()->GetSplitter()->SetRelativeSplitPos(state->GetSplitterSize()); if (!force) { if (!GetParentFrame()->IsWindowVisible()) GetParentFrame()->ActivateFrame(); RedrawWindow(); } else RedrawWindow(); } // Save current state as default void CSMTPView::SaveDefaultState(void) { // Only do this if a mailbox has been set if (!GetMbox()) return; // Get bounds CRect bounds; WINDOWPLACEMENT wp; GetParentFrame()->GetWindowPlacement(&wp); bool zoomed = (wp.showCmd == SW_SHOWMAXIMIZED); bounds = wp.rcNormalPosition; // Sync column widths for(int i = 0; i < mColumnInfo.size(); i++) mColumnInfo[i].column_width = GetTable()->GetColWidth(i + 1); // Get current match item CMatchItem match; // Check whether quitting bool is_quitting = CMulberryApp::sApp->IsQuitting(); // Add info to prefs CMailboxWindowState state(nil, &bounds, zoomed ? eWindowStateMax : eWindowStateNormal, &mColumnInfo, (ESortMessageBy) GetMbox()->GetSortBy(), (EShowMessageBy) GetMbox()->GetShowBy(), is_quitting ? NMbox::eViewMode_ShowMatch : NMbox::eViewMode_All, &match, Is3Pane() ? 0 : GetMailboxWindow()->GetSplitter()->GetRelativeSplitPos()); if (CPreferences::sPrefs->mSMTPWindowDefault.Value().Merge(state)) CPreferences::sPrefs->mSMTPWindowDefault.SetDirty(); }
30.110638
172
0.71368
mulberry-mail
f988503b86a58fce537ef8d81853b4f82278da5b
111,478
cpp
C++
src/newsview.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/newsview.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/newsview.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: newsview.cpp,v $ /* Revision 1.1 2010/07/21 17:14:57 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.3 2010/04/11 13:47:40 richard_wood /* FIXED - Export custom headers does not work, they are lost /* FIXED - Foreign month names cause crash /* FIXED - Bozo bin not being exported / imported /* FIXED - Watch & ignore threads not being imported / exported /* FIXED - Save article (append to existing file) missing delimiters between existing text in file and new article /* ADDED - Add ability to customise signature font size + colour /* First build for 2.9.15 candidate. /* /* Revision 1.2 2009/07/08 18:32:32 richard_wood /* Fixed lots of new installer bugs, spell checker dialog bug, updated the vcredist file to 2008 SP1 version, plus lots of other bug fixes. /* /* Revision 1.1 2009/06/09 13:21:29 richard_wood /* *** empty log message *** /* /* Revision 1.6 2009/01/29 17:22:35 richard_wood /* Tidying up source code. /* Removing dead classes. /* /* Revision 1.5 2009/01/02 13:34:33 richard_wood /* Build 6 : BETA release /* /* [-] Fixed bug in Follow up dialog - Quoted text should be coloured. /* [-] Fixed bug in New post/Follow up dialog - if more than 1 page of text /* and typing at or near top the text would jump around. /* /* Revision 1.4 2008/10/15 23:30:23 richard_wood /* Fixed bug in EMail reply dialog, if a ReplyTo header was present, the email field in the dialog picked up the address from the previous email sent. /* /* Revision 1.3 2008/09/19 14:51:35 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ // Newsview.cpp : implementation of the CNewsView class // // 4-18-96 amc When an article is destroyed by the DEL key, the Flatview // and the thread view update each other. I am no longer // using the odb callback stuff // #include "stdafx.h" #include "News.h" #include "Newsdoc.h" #include "Newsview.h" #include "mainfrm.h" #include "globals.h" #include "hints.h" #include "hourglas.h" #include "tmutex.h" #include "posttmpl.h" #include "custmsg.h" #include "tglobopt.h" #include "pobject.h" #include "names.h" #include "tasker.h" #include "nggenpg.h" #include "ngoverpg.h" // TNewsGroupOverrideOptions #include "ngfltpg.h" // TNewsGroupFilterPage #include "tsigpage.h" // TSigPage (per newsgroup sigs) #include "warndlg.h" #include "gotoart.h" #include "ngpurg.h" #include "ngutil.h" #include "tnews3md.h" // TNews3MDIChildWnd #include "mlayout.h" // TMdiLayout #include "artview.h" // TArticleFormView #include "statunit.h" // TStatusUnit #include "thrdlvw.h" // TThreadListView #include "utilrout.h" #include "rgbkgrnd.h" #include "rgwarn.h" #include "rgfont.h" #include "rgui.h" #include "rgswit.h" #include "log.h" #include "utilsize.h" //#include "hctldrag.h" #include "rules.h" // DoRuleSubstitution() #include "TAskFol.h" // how to handle "followup-to: poster" #include "fileutil.h" // UseProgramPath #include "genutil.h" // GetThreadView() #include "licutil.h" #include "nglist.h" // TNewsGroupUseLock #include "server.h" #include "newsdb.h" // gpStore #include "vfilter.h" // TViewFilter #include "utilerr.h" #include "servcp.h" // TServerCountedPtr #include "limithdr.h" // CPromptLimitHeaders #include "usrdisp.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif extern TGlobalOptions * gpGlobalOptions; extern TNewsTasker* gpTasker; const UINT CNewsView::idCaptionTimer = 32100; const UINT CNewsView::idSelchangeTimer = 32101; enum MessageType {MESSAGE_TYPE_BUG, MESSAGE_TYPE_SUGGESTION, MESSAGE_TYPE_SEND_TO_FRIEND}; MessageType giMessageType; // what type of message are we composing? #define FLATHDR_ID 9001 #define SCROLL_BMP_CX 15 #define BASE_CLASS CListView ///////////////////////////////////////////////////////////////////////////// // CNewsView IMPLEMENT_DYNCREATE(CNewsView, CListView) BEGIN_MESSAGE_MAP(CNewsView, BASE_CLASS) ON_WM_CREATE() ON_WM_SIZE() ON_COMMAND(IDR_NGPOPUP_OPEN, OnNgpopupOpen) ON_COMMAND(IDR_NGPOPUP_UNSUBSCRIBE, OnNewsgroupUnsubscribe) ON_COMMAND(IDR_NGPOPUP_CATCHUPALLARTICLES, OnNgpopupCatchupallarticles) ON_COMMAND(IDC_NGPOPUP_MANUAL_RULE, OnNgpopupManualRule) ON_COMMAND(ID_NEWSGROUP_POSTARTICLE, OnNewsgroupPostarticle) ON_COMMAND(ID_ARTICLE_FOLLOWUP, OnArticleFollowup) ON_COMMAND(ID_ARTICLE_REPLYBYMAIL, OnArticleReplybymail) ON_COMMAND(ID_ARTICLE_MAILTOFRIEND, OnArticleForward) ON_COMMAND(ID_FORWARD_SELECTED, OnForwardSelectedArticles) ON_UPDATE_COMMAND_UI(ID_ARTICLE_REPLYBYMAIL, OnUpdateArticleReplybymail) ON_UPDATE_COMMAND_UI(ID_FORWARD_SELECTED, OnUpdateForwardSelectedArticles) // ON_UPDATE_COMMAND_UI(ID_HELP_SENDBUGREPORT, OnUpdateHelpSendBugReport) // ON_UPDATE_COMMAND_UI(ID_HELP_SENDPRODUCTSUGGESTION, OnUpdateHelpSendSuggestion) ON_UPDATE_COMMAND_UI(ID_FILE_SEND_MAIL, OnUpdateSendToFriend) ON_WM_DESTROY() ON_UPDATE_COMMAND_UI(ID_ARTICLE_FOLLOWUP, OnUpdateArticleFollowup) ON_UPDATE_COMMAND_UI(ID_NEWSGROUP_POSTARTICLE, OnUpdateNewsgroupPostarticle) ON_COMMAND(IDR_NGPOPUP_PROPERTIES, OnNgpopupProperties) // ON_COMMAND(ID_HELP_SENDBUGREPORT, OnHelpSendBugReport) // ON_COMMAND(ID_HELP_SENDPRODUCTSUGGESTION, OnHelpSendSuggestion) ON_COMMAND(ID_FILE_SEND_MAIL, OnSendToFriend) ON_WM_TIMER() ON_MESSAGE (WMU_NEWSVIEW_GOTOARTICLE, GotoArticle) ON_MESSAGE (WMU_NEWSVIEW_PROCESS_MAILTO, ProcessMailTo) ON_MESSAGE (WMC_DISPLAY_ARTCOUNT, OnDisplayArtcount) ON_COMMAND (ID_ARTICLE_SAVE_AS, OnSaveToFile) ON_UPDATE_COMMAND_UI (ID_ARTICLE_SAVE_AS, OnUpdateSaveToFile) ON_COMMAND (ID_THREAD_CHANGETHREADSTATUSTO_READ, OnThreadChangeToRead) ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_CATCHUPALLARTICLES, OnUpdateNewsgroupCatchup) ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_UNSUBSCRIBE, OnUpdateNewsgroupUnsubscribe) ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_PROPERTIES, OnUpdateNewsgroupProperties) ON_UPDATE_COMMAND_UI (ID_THREAD_CHANGETHREADSTATUSTO_READ, OnUpdateThreadChangeToRead) ON_UPDATE_COMMAND_UI (IDC_VIEW_BINARY, OnUpdateDisable) ON_COMMAND(ID_CMD_TABAROUND, OnCmdTabaround) ON_COMMAND(ID_CMD_TABBACK, OnCmdTabBack) ON_COMMAND(ID_GETHEADERS_ALLGROUPS, OnGetheadersAllGroups) ON_UPDATE_COMMAND_UI(ID_GETHEADERS_ALLGROUPS, OnUpdateGetheadersAllGroups) ON_COMMAND(ID_GETHEADERS_MGROUPS, OnGetHeadersMultiGroup) ON_UPDATE_COMMAND_UI(ID_GETHEADERS_MGROUPS, OnUpdateGetHeadersMultiGroup) ON_COMMAND(ID_GETHEADER_LIMITED, OnGetheaderLimited) ON_UPDATE_COMMAND_UI(ID_GETHEADER_LIMITED, OnUpdateGetheaderLimited) ON_COMMAND(WMC_DISPLAYALL_ARTCOUNT, OnDisplayAllArticleCounts) ON_MESSAGE(WMU_MODE1_HDRS_DONE, OnMode1HdrsDone) ON_MESSAGE(WMU_NGROUP_HDRS_DONE, OnNewsgroupHdrsDone) ON_WM_CONTEXTMENU() ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateEditSelectAll) ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy) ON_MESSAGE(WMU_ERROR_FROM_SERVER, OnErrorFromServer) ON_MESSAGE(WMU_SELCHANGE_OPEN, OnSelChangeOpen) ON_UPDATE_COMMAND_UI(ID_ARTICLE_DELETE_SELECTED, OnUpdateDeleteSelected) ON_UPDATE_COMMAND_UI(IDC_NGPOPUP_MANUAL_RULE, OnUpdateNgpopupManualRule) ON_UPDATE_COMMAND_UI(IDR_NGPOPUP_OPEN, OnUpdateNgpopupOpen) ON_UPDATE_COMMAND_UI(ID_KEEP_SAMPLED, OnUpdateKeepSampled) ON_COMMAND(ID_KEEP_SAMPLED, OnKeepSampled) ON_UPDATE_COMMAND_UI(ID_KEEP_ALL_SAMPLED, OnUpdateKeepAllSampled) ON_COMMAND(ID_KEEP_ALL_SAMPLED, OnKeepAllSampled) ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll) ON_UPDATE_COMMAND_UI(ID_POST_SELECTED, OnUpdatePostSelected) ON_COMMAND(ID_POST_SELECTED, OnPostSelected) ON_COMMAND(ID_ARTICLE_DELETE_SELECTED, OnArticleDeleteSelected) ON_COMMAND(ID_VERIFY_HDRS, OnVerifyLocalHeaders) ON_COMMAND(ID_HELP_RESYNC_STATI, OnHelpResyncStati) ON_COMMAND(ID_NEWSGROUP_PINFILTER, OnNewsgroupPinfilter) ON_UPDATE_COMMAND_UI(ID_NEWSGROUP_PINFILTER, OnUpdateNewsgroupPinfilter) ON_UPDATE_COMMAND_UI(ID_ARTICLE_MORE, OnUpdateArticleMore) ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDisplayInfo) ON_NOTIFY_REFLECT(NM_CLICK, OnClick) ON_NOTIFY_REFLECT(NM_RETURN, OnReturn) ON_NOTIFY_REFLECT(NM_RCLICK, OnRclick) ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk) ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged) ON_WM_MOUSEWHEEL() ON_UPDATE_COMMAND_UI(IDM_GETTAGGED_FORGROUPS, OnUpdateGettaggedForgroups) ON_COMMAND(IDM_GETTAGGED_FORGROUPS, OnGettaggedForgroups) ON_WM_VKEYTOITEM() ON_WM_ERASEBKGND() ON_COMMAND(ID_THREADLIST_REFRESH, OnRefreshCurrentNewsgroup) ON_WM_LBUTTONDOWN() ON_COMMAND(ID_NV_FORWARD_SELECTED, OnForwardSelectedArticles) ON_UPDATE_COMMAND_UI(ID_THREADLIST_REPLYBYMAIL, OnUpdateArticleReplybymail) ON_UPDATE_COMMAND_UI(ID_THREADLIST_POSTFOLLOWUP, OnUpdateArticleFollowup) ON_UPDATE_COMMAND_UI(ID_THREADLIST_POSTNEWARTICLE, OnUpdateNewsgroupPostarticle) ON_UPDATE_COMMAND_UI (IDC_DECODE, OnUpdateDisable) ON_UPDATE_COMMAND_UI (IDC_MANUAL_DECODE, OnUpdateDisable) ON_UPDATE_COMMAND_UI(ID_VERIFY_HDRS, OnUpdateGetHeadersMultiGroup) ON_WM_MOUSEMOVE() ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnNeedText) END_MESSAGE_MAP() // --------------------------------------------------------------------------- // utility function void FreeGroupIDPairs (CPtrArray* pVec) { int tot = pVec->GetSize(); for (--tot; tot >= 0; --tot) delete ((TGroupIDPair*) pVec->GetAt(tot)); } ///////////////////////////////////////////////////////////////////////////// // CNewsView construction/destruction CNewsView::CNewsView() { InitializeCriticalSection(&m_dbCritSect); iLocalOpen = 0; m_ngPopupMenu.LoadMenu (IDR_NGPOPUP); m_imageList.Create (IDB_SCROLL, SCROLL_BMP_CX, // width of frame 1, // gro factor RGB(255,0,255) // transparent color (hot purple) ); // setup the 1st overlay image VERIFY(m_imageList.SetOverlayImage (6, 1)); m_curNewsgroupID = 0; m_pBrowsePaneHeader = 0; m_pBrowsePaneText = 0; m_fLoadFreshData = TRUE; m_hCaptionTimer = 0; m_hSelchangeTimer = 0; m_GotoArticle.m_articleNumber = -1; m_fPinFilter = FALSE; m_fTrackZoom = false; m_iOneClickInterference = 0; } ///////////////////////////////////////////////////////////////////////////// CNewsView::~CNewsView() { if (m_pBrowsePaneText) { delete m_pBrowsePaneText; m_pBrowsePaneText = 0; } DeleteCriticalSection(&m_dbCritSect); } ///////////////////////////////////////////////////////////////////////////// // CNewsView drawing void CNewsView::OnDraw(CDC* pDC) { CNewsDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); } ///////////////////////////////////////////////////////////////////////////// // CNewsView printing BOOL CNewsView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CNewsView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CNewsView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } #if defined(OLAY_CRAP) ///////////////////////////////////////////////////////////////////////////// // OLE Server support // The following command handler provides the standard keyboard // user interface to cancel an in-place editing session. Here, // the server (not the container) causes the deactivation. void CNewsView::OnCancelEditSrvr() { GetDocument()->OnDeactivateUI(FALSE); } #endif ///////////////////////////////////////////////////////////////////////////// // CNewsView diagnostics #ifdef _DEBUG void CNewsView::AssertValid() const { BASE_CLASS::AssertValid(); } void CNewsView::Dump(CDumpContext& dc) const { BASE_CLASS::Dump(dc); } CNewsDoc* CNewsView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CNewsDoc))); return (CNewsDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CNewsView message handlers int CNewsView::OnCreate(LPCREATESTRUCT lpCreateStruct) { LogString("Newsview start create"); if (BASE_CLASS::OnCreate(lpCreateStruct) == -1) return -1; SetupFont (); GetListCtrl().SetImageList (&m_imageList, LVSIL_SMALL); GetListCtrl().SetCallbackMask (LVIS_OVERLAYMASK); // Strip CS_HREDRAW and CS_VREDRAW. We don't need to repaint everytime we // are sized. (Tip from 'PC Magazine' May 6,1997) DWORD dwStyle = GetClassLong (m_hWnd, GCL_STYLE); SetClassLong (m_hWnd, GCL_STYLE, dwStyle & ~(CS_HREDRAW | CS_VREDRAW)); // OnInitialUpdate will Setup the columns in the header ctrl // after the size has settled down. // read from registry m_fPinFilter = gpGlobalOptions->GetRegUI()->GetPinFilter (); ((CMainFrame*) AfxGetMainWnd())->UpdatePinFilter ( m_fPinFilter ); LogString("Newsview end create"); return 0; } ///////////////////////////////////////////////////////////////////////////// void CNewsView::OnSize(UINT nType, int cx, int cy) { BASE_CLASS::OnSize(nType, cx, cy); Resize ( cx, cy ); } // called from OnSize, and OnInitialUpdate void CNewsView::Resize(int cx, int cy) { } // ------------------------------------------------------------------------ // void CNewsView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (VIEWHINT_SERVER_SWITCH == lHint) return; if (VIEWHINT_UNZOOM == lHint) { handle_zoom (false, pHint); return; } if (VIEWHINT_ZOOM == lHint) { handle_zoom (true, pHint); return; } if (VIEWHINT_SHOWARTICLE == lHint) return; if (VIEWHINT_SHOWGROUP == lHint) return; if (VIEWHINT_SHOWGROUP_NOSEL == lHint) return; if (VIEWHINT_EMPTY == lHint) { EmptyBrowsePointers (); GetDocument()->EmptyArticleStatusChange(); sync_caption(); return; } // if an article's status changes it means nothing to us if (VIEWHINT_STATUS_CHANGE == lHint || VIEWHINT_ERASE_OLDTHREADS == lHint) return; //if (VIEWHINT_NEWSVIEW_UNSUBSCRIBE == lHint) // { // Unsubscribing ((TNewsGroup*) pHint); // return; // } // remember selected group-id LONG iSelGroupID = GetSelectedGroupID(); CListCtrl & lc = GetListCtrl(); lc.DeleteAllItems (); TServerCountedPtr cpNewsServer; TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray(); TNewsGroupArrayReadLock ngMgr(vNewsGroups); int count = vNewsGroups->GetSize(); for (int j = 0; j < count; ++j) { TNewsGroup* pNG = vNewsGroups[j]; AddStringWithData ( pNG->GetBestname(), pNG->m_GroupID); } // restore selection if (iSelGroupID) { if (0 != SetSelectedGroupID (iSelGroupID)) SetOneSelection (0); } } // 5-8-96 change to fetch on zero void CNewsView::OnNgpopupOpen() { OpenNewsgroup( kFetchOnZero, kPreferredFilter ); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateNgpopupOpen(CCmdUI* pCmdUI) { pCmdUI->Enable (IsExactlyOneNewsgroupSelected()); } // ------------------------------------------------------------------------ // Returns -1 for failure int CNewsView::GetSelectedIndex () { CListCtrl & lc = GetListCtrl(); POSITION pos = lc.GetFirstSelectedItemPosition (); if (pos) return lc.GetNextSelectedItem (pos); int iMark = lc.GetSelectionMark (); if (-1 == iMark) return -1; return iMark; } // ------------------------------------------------------------------------ // Returns positive for success, 0 for failure LONG CNewsView::GetSelectedGroupID () { int idx = GetSelectedIndex (); if (-1 == idx) return 0; return (LONG) GetListCtrl().GetItemData (idx); } // ------------------------------------------------------------------------ // Input: a group id // Set the listbox selection to the newsgroup that has that id // Returns: 0 for success, non-zero for error int CNewsView::SetSelectedGroupID (int iGroupID) { CListCtrl & lc = GetListCtrl(); int idx = lc.GetItemCount(); for (--idx; idx >= 0; --idx) { if (iGroupID == (LONG) lc.GetItemData(idx)) { SetOneSelection (idx); return 0; } } return 1; } // ------------------------------------------------------------------------ void CNewsView::OnNgpopupManualRule () { AfxGetMainWnd ()->PostMessage (WM_COMMAND, ID_OPTIONS_MANUAL_RULE); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateNgpopupManualRule(CCmdUI* pCmdUI) { pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ()); } // ------------------------------------------------------------------------ void CNewsView::OnInitialUpdate() { CListCtrl & lc = GetListCtrl(); LogString("newsview start initial update"); CNewsApp* pNewsApp = (CNewsApp*) AfxGetApp(); pNewsApp->SetGlobalNewsDoc( GetDocument() ); CNewsDoc::m_pDoc = GetDocument(); CRect rct; GetClientRect( &rct ); // load the widths from the registry SetupReportColumns (rct.Width()); lc.SetExtendedStyle (LVS_EX_FULLROWSELECT); // the header control is too tall unless we do this Resize( rct.Width(), rct.Height() ); // setup columns before initial fill BASE_CLASS::OnInitialUpdate(); // setup tool tips VERIFY(m_sToolTips.Create (this, TTS_ALWAYSTIP)); VERIFY(m_sToolTips.AddTool (this, LPSTR_TEXTCALLBACK)); m_sToolTips.SetMaxTipWidth (SHRT_MAX); m_sToolTips.SetDelayTime (TTDT_AUTOPOP, 10000); // go away after 10 secs m_sToolTips.SetDelayTime (TTDT_INITIAL, 500); m_sToolTips.SetDelayTime (TTDT_RESHOW, 1000); // at this point the splash screen is gone and we are pretty much, // up and running and willing to load the VCR file from the cmdline CWnd::FromHandle(ghwndMainFrame)->PostMessage (WMU_READYTO_RUN); int lastGID = gpGlobalOptions->GetRegUI()->GetLastGroupID(); if (lastGID < 0) { if (lc.GetItemCount() > 0) lastGID = (int) lc.GetItemData( 0 ); } TServerCountedPtr cpNewsServer; // find it bool fFoundValidGroup = false; { BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, lastGID, &fUseLock, pNG); if (fUseLock) { fFoundValidGroup = true; // don't wait for mode-1 to load if (TNewsGroup::kNothing == UtilGetStorageOption (pNG)) fFoundValidGroup = false; } } if (fFoundValidGroup) { int tot = lc.GetItemCount(); for (--tot; tot >= 0; --tot) { if (lastGID == (int) lc.GetItemData( tot )) { if (gpGlobalOptions->GetRegUI()->GetOneClickGroup()) { SetOneSelection (tot); // LVN_ITEMCHANGED notification does the rest.... } else { SetOneSelection (tot); OpenNewsgroup( kOpenNormal, kPreferredFilter, lastGID ); } break; } } } LogString("newsview end initial update"); } /////////////////////////////////////////////////////////////////////////// void CNewsView::SetupReportColumns (int iParentWidth) { TRegUI* pRegUI = gpGlobalOptions->GetRegUI(); int riWidths[3]; if (0 != pRegUI->LoadUtilHeaders("NGPane", riWidths, ELEM(riWidths))) { int avgChar = LOWORD(GetDialogBaseUnits()); riWidths[1] = avgChar * 6; riWidths[2] = avgChar * 6; int remainder = iParentWidth -riWidths[1] -riWidths[2] -GetSystemMetrics(SM_CXVSCROLL); riWidths[0] = max(remainder, avgChar*6); } CString strNewsgroups; strNewsgroups.LoadString (IDS_HEADER_NEWSGROUPS); CString strLocal; strLocal.LoadString (IDS_HEADER_LOCAL); CString strServer; strServer.LoadString (IDS_HEADER_SERVER); CListCtrl & lc = GetListCtrl(); lc.InsertColumn (0, strNewsgroups, LVCFMT_LEFT, riWidths[0], 0); lc.InsertColumn (1, strLocal, LVCFMT_RIGHT, riWidths[1], 1); lc.InsertColumn (2, strServer, LVCFMT_RIGHT, riWidths[2], 2); } /////////////////////////////////////////////////////////////////////////// // CloseCurrentNewsgroup - this was factored out of OpenNewsgroup and // made public so that it could be used by // CMainFrame::OnDatePurgeAll /////////////////////////////////////////////////////////////////////////// void CNewsView::CloseCurrentNewsgroup () { BOOL fViewsEmptied = FALSE; fViewsEmptied = ShutdownOldNewsgroup (); gpUIMemory->SetLastGroup ( m_curNewsgroupID ); // the intent of this function is that there will be no // current group afterwards... SetCurNewsGroupID (0); if (!fViewsEmptied) { EmptyBrowsePointers (); // clear out TreeView, FlatView, ArtView GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); } } /////////////////////////////////////////////////////////////////////////// // OpenNewsgroup // eOpenMode - kFetchOnZero if you want to Try to GetHeaders // iInputGroupID - pass in a groupID, or function will use the cur Sel // // Changes: // 4-09-96 For the Dying NG, Empty the View and then Close it. // also call ::Empty to clean out the thread list // // 8-01-97 return 0 if loaded, 1 if started download, -1 for error // int CNewsView::OpenNewsgroup(EOpenMode eMode, EUseFilter eFilter, int iInputGroupID/*=-1*/) { int iFilterRC = 0; BOOL fViewsEmptied = FALSE; LONG newGroupID; if (iInputGroupID > 0) newGroupID = iInputGroupID; else { newGroupID = GetSelectedGroupID (); if (NULL == newGroupID) return -1; } fViewsEmptied = ShutdownOldNewsgroup (); SetCurNewsGroupID( newGroupID ); // set title on mdi-child if (0 == m_hCaptionTimer) m_hCaptionTimer = SetTimer (idCaptionTimer, 250, NULL); if (!fViewsEmptied) { EmptyBrowsePointers (); // clear out TreeView, FlatView, ArtView GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); fViewsEmptied = TRUE; } TServerCountedPtr cpNewsServer; { BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (fUseLock) { // open this guy for business protected_open ( pNG, TRUE ); if (kPreferredFilter == eFilter && (FALSE==m_fPinFilter)) { // newsgroup may have a default filter. hand off to the Filterbar int iWhatFilter = GetPreferredFilter ( pNG ); iFilterRC = ((CMainFrame*)AfxGetMainWnd())->SelectFilter ( iWhatFilter ); } else { // if we are using GotoArticle, skip the preferred filter, use current // if filters are pinned. Use current } // if the newsgrp is devoid of new articles, then Try downloading some if ((kFetchOnZero == eMode) && (TNewsGroup::kHeadersOnly == UtilGetStorageOption (pNG) || TNewsGroup::kStoreBodies == UtilGetStorageOption (pNG))) { pNG->UpdateFilterCount (true); TViewFilter * pVF = TNewsGroup::GetpCurViewFilter(); if (0 == pVF) return -1; TStatusUnit::ETriad eTri = pVF->GetNew(); if (TStatusUnit::kYes == eTri) { int iLocalNew, iServerNew, iLocalTotal; iLocalNew = iServerNew = 100; pNG->FormatNewArticles ( iLocalNew, iServerNew, iLocalTotal ); if (0 == iLocalNew) { // there's nothing in the DB to load - hit the server GetHeadersOneGroup (); return 1; } } if (TStatusUnit::kMaybe == eTri) { // they are viewing both New and Read if (0 == pNG->HdrRangeCount()) { // there's absolutely nothing in the newgroup - hit server GetHeadersOneGroup (); return 1; } } } // when re-creating a new layout, we just use the old data. if (m_fLoadFreshData) { // when in mode 1, do all rule substitution before loading articles // NOTE: This must be done before the hourglass icon is displayed // (below) if (pNG->GetStorageOption () == TNewsGroup::kNothing) ResetAndPerformRuleSubstitution (NULL /* psHeader */, pNG); // tell rules that an hourglass icon is going to appear, and not to // bring up any dialogs (it will queue them and display them later) RulesHourglassStart (); // user waits.... { CHourglass wait = this; pNG->LoadArticles(FALSE); } // now that the hourglass icon is gone, we can let rules display any // notification dialogs RulesHourglassEnd (); } } } // fill thread view please_update_views(); // allow the layout manager to see this action CFrameWnd * pDadFrame = GetParentFrame(); if (pDadFrame) pDadFrame->SendMessage (WMU_USER_ACTION, TGlobalDef::kActionOpenGroup); if (iFilterRC) AfxMessageBox (IDS_GRP_FILTERGONE); return 0; } /////////////////////////////////////////////////////////////////////////// // Return TRUE if the views have been Emptied // BOOL CNewsView::ShutdownOldNewsgroup (void) { // We can't shut down a group if the servers not alive if (!IsActiveServer()) return TRUE; // save off status of old? BOOL fViewsEmptied = FALSE; TServerCountedPtr cpNewsServer; LONG oldGroupID = m_curNewsgroupID; BOOL fUseLock; TNewsGroup* pOld = 0; TNewsGroupUseLock useLock(cpNewsServer, oldGroupID, &fUseLock, pOld); if (fUseLock) { TUserDisplay_UIPane sAutoDraw("Clear list..."); if (!fViewsEmptied) { // clear the threadview while the pointers are Valid EmptyBrowsePointers (); GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); fViewsEmptied = TRUE; } // if (pOld->GetDirty()) pOld->TextRangeSave(); // Try closing the newsgroup protected_open (pOld, FALSE); // this is new (4/9) Empty the threadlist pOld->Empty(); gpUserDisplay->SetCountFilter ( 0 ); gpUserDisplay->SetCountTotal ( 0 ); } return fViewsEmptied; } void CNewsView::please_update_views(void) { TUserDisplay_UIPane sAutoDraw("Loading list..."); // perform a broadcast directed at the threadlist view GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP); } //------------------------------------------------------------------------- // msg handler void CNewsView::OnRefreshCurrentNewsgroup () { RefreshCurrentNewsgroup ( ); } //------------------------------------------------------------------------- // Called by filter buttons, tmanrule.cpp void CNewsView::RefreshCurrentNewsgroup (bool fMoveSelection /* = true */) { TServerCountedPtr cpNewsServer; BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (fUseLock) { CWaitCursor wait; TSaveSelHint sSelHint; if (fMoveSelection) { // Try to restore selection after change (do this before Emptying) GetDocument()->UpdateAllViews (this, VIEWHINT_SAVESEL, &sSelHint); } if (true) { TUserDisplay_UIPane sAutoDraw("Emptying"); GetDocument()->UpdateAllViews (NULL, VIEWHINT_EMPTY); } // do not empty before reloading pNG->ReloadArticles (FALSE); TUserDisplay_UIPane sAutoDraw("Loading..."); if (fMoveSelection) { // perform a broadcast directed at the threadlist view GetDocument()->UpdateAllViews (this, VIEWHINT_SHOWGROUP); // restore selection GetDocument()->UpdateAllViews (this, VIEWHINT_SAVESEL, &sSelHint); } else { // perform a broadcast directed at the threadlist view GetDocument()->UpdateAllViews (this, VIEWHINT_SHOWGROUP_NOSEL); } } } //------------------------------------------------------------------------- void CNewsView::OnContextMenu(CWnd* pWnd, CPoint point) { //TRACE0("caught WM_CONTEXTMENU\n"); CPoint anchor(point); // weird coords if menu summoned with Shift-F10 if (-1 == anchor.x && -1 == anchor.y) { // do the best we can - top left corner of listbox anchor.x = anchor.y = 2; this->ClientToScreen( &anchor ); } context_menu( anchor ); } // ------------------------------------------------------------------------ // void CNewsView::context_menu(CPoint & ptScreen) { CListCtrl & lc = GetListCtrl(); // multiple selection is OK for everything except 'Properties...' if (lc.GetSelectedCount () <= 0) return; // get the group name so we can do the op... int idx = GetSelectedIndex (); if (idx < 0) return; TServerCountedPtr cpNewsServer; LONG id = (LONG) lc.GetItemData( idx ); BOOL fUseLock; TNewsGroup * pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG); if (!fUseLock) return; CMenu * pTrackMenu = m_ngPopupMenu.GetSubMenu ( 0 ); ProbeCmdUI (this, pTrackMenu); pTrackMenu->TrackPopupMenu( TPM_LEFTALIGN | TPM_RIGHTBUTTON, ptScreen.x, ptScreen.y, this); } // ------------------------------------------------------------------------ void CNewsView::UnsubscribeGroups (const CPtrArray &vec) { TServerCountedPtr cpNewsServer; TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray(); for (int i = 0; i < vec.GetSize(); i++) { TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]); bool fDemoted = false; // TRUE if lbx-string is deleted { BOOL fUseLock = FALSE; TNewsGroup* pNG; TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG); // kill any queued jobs if (fUseLock) fDemoted = demote_newsgroup ( pNG ); } // Try to get destroy lock on it if (0 == vNewsGroups.ReserveGroup (pPair->id)) { cpNewsServer->UnsubscribeGroup (pPair->id); } else { // yikes. add string back into listbox. if (fDemoted) AddStringWithData (pPair->ngName, pPair->id); CString pattern; pattern.LoadString (IDS_ERR_GROUP_IN_USE); CString msg; msg.Format (pattern, (LPCTSTR) pPair->ngName); NewsMessageBox (this, msg, MB_OK | MB_ICONSTOP); } } // find new selection, open next newsgroup etc... finish_unsubscribe(); } // ------------------------------------------------------------------------ void CNewsView::DoUnsubscribe (BOOL bAlwaysAsk) { CPtrArray vec; // hold data from _prelim function // confirm unsubscribe if (unsubscribe_prelim (&vec, bAlwaysAsk)) return; CWaitCursor cursor; UnsubscribeGroups (vec); FreeGroupIDPairs (&vec); } // ------------------------------------------------------------------------ void CNewsView::OnNewsgroupUnsubscribe() { DoUnsubscribe (FALSE /* bAlwaysAsk */); } // ------------------------------------------------------------------------ void CNewsView::OnArticleDeleteSelected() { DoUnsubscribe (TRUE /* bAlwaysAsk */); } // ------------------------------------------------------------------------ // TRUE indicates the lbx line was deleted bool CNewsView::demote_newsgroup ( TNewsGroup* pNG ) { extern TNewsTasker* gpTasker; CListCtrl & lc = GetListCtrl(); int total = lc.GetItemCount(); for (int i = 0; i < total; ++i) { if (pNG->m_GroupID == (int)lc.GetItemData(i)) { // kill any queued jobs. gpTasker->UnregisterGroup ( pNG ); // if we are killing the current newsgroup, open some // other group if (pNG->m_GroupID == m_curNewsgroupID) { m_curNewsgroupID = 0; } lc.DeleteItem ( i ); // figure out what to do with the selection int newsel; if (i == total - 1) newsel = i - 1; else newsel = i; if (newsel >= 0) SetOneSelection (newsel); return true; } } return false; } /////////////////////////////////////////////////////////////////////////// // // 4-24-96 amc Write changes to disk, reset title to Null // 11-01-96 amc Clear out views when going from Mode2(dead)->Mode1 int CNewsView::finish_unsubscribe (void) { int total; BOOL fEmptySync = TRUE; TServerCountedPtr cpNewsServer; TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray(); total = vNewsGroups->GetSize(); if (total > 0) { BOOL fOpenGroup = FALSE; LONG newGroupID; // Pull in newly selected newsgroup // iff we killed the current newsgroup if (0==m_curNewsgroupID) { // However... don't pull a newsgroup in // if it means doing a Mode-1 suck { newGroupID = GetSelectedGroupID (); if (NULL == newGroupID) return 0; BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, newGroupID, &fUseLock, pNG); if (!fUseLock) return 0; if (TNewsGroup::kHeadersOnly == UtilGetStorageOption(pNG) || TNewsGroup::kStoreBodies == UtilGetStorageOption(pNG)) fOpenGroup = TRUE; } if (fOpenGroup) { fEmptySync = FALSE; OpenNewsgroup(kOpenNormal, kPreferredFilter, newGroupID); } } } if (fEmptySync) { // empty all views GetDocument()->UpdateAllViews ( NULL, VIEWHINT_EMPTY ); sync_caption (); // "no newsgroup selected" } return 0; } // ------------------------------------------------------------------------ // gets info on multiselect int CNewsView::multisel_get (CPtrArray * pVec, int* piSel) { CListCtrl & lc = GetListCtrl(); int sel = lc.GetSelectedCount(); if (sel <= 0) return 1; int* pIdx = new int[sel]; auto_ptr<int> pDeleterIdx(pIdx); // get selected items int n = 0; POSITION pos = lc.GetFirstSelectedItemPosition (); while (pos) pIdx[n++] = lc.GetNextSelectedItem (pos); // get the names and the group-ids TServerCountedPtr cpNewsServer; TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray(); // get the each ng name and release for (int i = 0; i < sel; ++i) { int groupId = lc.GetItemData (pIdx[i]); BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, groupId, &fUseLock, pNG); if (fUseLock) pVec->Add ( new TGroupIDPair(groupId, pNG->GetBestname()) ); } *piSel = sel; return 0; } // ------------------------------------------------------------------------ // unsubscribe_prelim - Returns 0 for success. 1 for stop // Confirm that the user wants to unsubscribe from multiple newsgroups // Name and id pairs are returned in the PtrArray. Uses nickname if // it is set. int CNewsView::unsubscribe_prelim (CPtrArray *pVec, BOOL bAlwaysAsk) { int sel = 0; if (multisel_get (pVec, &sel)) return 1; int nProtectedArticles = 0; TServerCountedPtr cpNewsServer; for (int i = 0; i < pVec->GetSize(); i++) { TGroupIDPair * pPair = static_cast<TGroupIDPair*>(pVec->GetAt(i)); { BOOL fUseLock = FALSE; TNewsGroup* pNG; TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG); if (fUseLock) { int nProt = 0; pNG->StatusCountProtected ( nProt ); nProtectedArticles += nProt; } } } // see if they really want to kill these groups... if (gpGlobalOptions->WarnOnUnsubscribe() || bAlwaysAsk || (nProtectedArticles > 0)) { CString msg; CString strProtected; if (1 == sel) { if (pVec->GetSize () != 1) return 1; AfxFormatString1 (msg, IDS_WARNING_UNSUBSCRIBE, ((TGroupIDPair*)pVec->GetAt(0))->ngName); } else { char szCount[10]; _itoa (sel, szCount, 10); AfxFormatString1 (msg, IDS_WARN_UNSUBSCRIBE_MANY1, szCount); } if (nProtectedArticles > 0) { CString strProtected; strProtected.Format (IDS_WARNING_PROTCOUNT1, nProtectedArticles); msg += strProtected; } BOOL fDisableWarning = FALSE; if (WarnWithCBX (msg, &fDisableWarning, NULL /* pParentWnd */, FALSE /* iNotifyOnly */, FALSE /* bDefaultToNo */, bAlwaysAsk /* bDisableCheckbox */)) { if (fDisableWarning) { gpGlobalOptions->SetWarnOnUnsubscribe(FALSE); TRegWarn *pRegWarning = gpGlobalOptions->GetRegWarn (); pRegWarning->Save(); } return 0; // it's OK to go on } else { // free intermediate data FreeGroupIDPairs (pVec); return 1; } } return 0; // it's OK to go on } /* ---------------------------------------------------------------- Case 1: You are in Mode 1, and you are viewing New & Read messages. Catching up means marking things Read; After catching up, you do not want to reload the same headers over your PPP link (see Bug #68 part 2) 11-26-96 amc User can move to next group after catchup on this one ------------------------------------------------------------------- */ void CNewsView::OnNgpopupCatchupallarticles() { // holds a collection of (groupID, name) pairs CPtrArray vec; // get info on multisel and allow cancellation if (catchup_prelim (&vec)) return; int tot = vec.GetSize(); for (int i = 0; i < tot; i++) { BOOL fMoveNext = (i == tot-1); TGroupIDPair* pPair = static_cast<TGroupIDPair*>(vec[i]); CatchUp_Helper ( pPair->id, fMoveNext ); } // free intermediate data FreeGroupIDPairs (&vec); } // ------------------------------------------------------------------------ // Called from : // OnGetheaderGroup // OnNgpopupCatchupallarticles void CNewsView::CatchUp_Helper (int iGroupID, BOOL fAllowMoveNext) { TServerCountedPtr cpNewsServer; TNewsGroup * pNG = 0; BOOL fUseLock; // reacquire lock TNewsGroupUseLock useLock(cpNewsServer, iGroupID, &fUseLock, pNG); if (!fUseLock) return; BOOL fViewing = (pNG->m_GroupID == m_curNewsgroupID); if (TNewsGroup::kNothing == UtilGetStorageOption ( pNG )) { // Since this is Mode 1, avoid going out to the server again // marks everything as Read pNG->CatchUpArticles(); OnDisplayArtcount(pNG->m_GroupID, 0); if (fViewing) { int iNextGrpId = -1; int iNextIdx; // see if we are moving onward if (fAllowMoveNext && gpGlobalOptions->GetRegSwitch()->GetCatchUpLoadNext() && validate_next_newsgroup(&iNextGrpId, &iNextIdx)) { // clear out GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); // goto next ng AddOneClickGroupInterference(); SetOneSelection (iNextIdx); OpenNewsgroup (kOpenNormal, kPreferredFilter, iNextGrpId); } else { TViewFilter * pFilter = TNewsGroup::GetpCurViewFilter (); if (0 == pFilter) return; TStatusUnit::ETriad eTri = pFilter->GetNew (); switch (eTri) { case TStatusUnit::kMaybe: case TStatusUnit::kNo: // this will show the result (all articles marked as Read) GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP); break; case TStatusUnit::kYes: GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); break; } } } else { // catchup on a group that we are not viewing. No movement } } else { // this is Mode 2 or Mode 3 if (fViewing) // empty out TreeView, FlatView, ArtView GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); pNG->CatchUpArticles(); // newsview should redraw count of new articles (0) OnDisplayArtcount(pNG->m_GroupID, 0); if (fViewing) { int iNextGrpId = -1; int iNextIdx; // see if we are moving onward if (fAllowMoveNext && gpGlobalOptions->GetRegSwitch()->GetCatchUpLoadNext() && validate_next_newsgroup(&iNextGrpId, &iNextIdx)) { EmptyBrowsePointers (); // goto next ng AddOneClickGroupInterference(); SetOneSelection (iNextIdx); OpenNewsgroup (CNewsView::kOpenNormal, kPreferredFilter, iNextGrpId); } else { EmptyBrowsePointers (); // reload & update the display newsview_reload(pNG); } } } } // ----------------------------------------------------------------------- // Called from OnNgpopupCatchupallarticles void CNewsView::newsview_reload(TNewsGroup* pNG) { ASSERT(pNG); CWaitCursor wait; if (pNG) { SetCurNewsGroupID( pNG->m_GroupID ); // TRUE - empty thread list first, then load pNG->ReloadArticles(TRUE); // perform a broadcast directed at the threadlist view GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP); } } // -------------------------------------------------------------- int CNewsView::catchup_prelim (CPtrArray* pVec) { int sel = 0; if (multisel_get (pVec, &sel)) return 1; // see if they really want to catchup on these groups... if (gpGlobalOptions->WarnOnCatchup()) { CString msg; if (1 == sel) { if (pVec->GetSize () != 1) return 1; AfxFormatString1 (msg, IDS_WARNING_CATCHUP, ((TGroupIDPair*)pVec->GetAt(0))->ngName); } else { char szCount[10]; _itoa (sel, szCount, 10); AfxFormatString1 (msg, IDS_WARN_CATCHUP_MANY1, szCount); } BOOL fDisableWarning = FALSE; if (WarnWithCBX (msg, &fDisableWarning)) { if (fDisableWarning) { gpGlobalOptions->SetWarnOnCatchup(FALSE); TRegWarn *pRegWarning = gpGlobalOptions->GetRegWarn (); pRegWarning->Save(); } } else { // free intermediate data FreeGroupIDPairs (pVec); return 1; } } return 0; // it's OK to go on } // -------------------------------------------------------------- void CNewsView::OnUpdateNewsgroupPostarticle(CCmdUI* pCmdUI) { pCmdUI->Enable (IsNewsgroupDisplayed()); } // -------------------------------------------------------------- // OnNewsgroupPostarticle -- post an article to the open newsgroup void CNewsView::OnNewsgroupPostarticle () { if (!check_server_posting_allowed()) return; ASSERT (m_curNewsgroupID); TPostTemplate *pTemplate = gptrApp->GetPostTemplate (); pTemplate->m_iFlags = TPT_TO_NEWSGROUP | TPT_CANCEL_WARNING_ID | TPT_POST; pTemplate->m_NewsGroupID = GetCurNewsGroupID(); pTemplate->m_iCancelWarningID = IDS_WARNING_POSTCANCEL; pTemplate->Launch (GetCurNewsGroupID()); } // ------------------------------------------------------------------------ void CNewsView::OnUpdatePostSelected(CCmdUI* pCmdUI) { pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ()); } // ------------------------------------------------------------------------ void CNewsView::OnPostSelected() { CListCtrl & lc = GetListCtrl(); // check if posting is allowed to this server if (!check_server_posting_allowed()) return; // make template TPostTemplate *pTemplate = gptrApp->GetPostTemplate (); // get selected group IDs int iSel = lc.GetSelectedCount (); if (iSel <= 0) { ASSERT (0); return; } int * pIndices = new int [iSel]; auto_ptr<int> pDeleterIndices (pIndices); // get selected items int n = 0; POSITION pos = lc.GetFirstSelectedItemPosition (); while (pos) pIndices[n++] = lc.GetNextSelectedItem (pos); bool fCurGroupInSelection = false; pTemplate->m_rNewsgroups.RemoveAll (); for (int i = 0; i < iSel; i++) { LONG gid = lc.GetItemData (pIndices [i]); if (m_curNewsgroupID == gid) fCurGroupInSelection = true; pTemplate->m_rNewsgroups.Add (gid); } // utilize Per-Group e-mail address override w.r.t. which Group? if (1 == iSel) pTemplate->m_NewsGroupID = lc.GetItemData (pIndices[0]); else pTemplate->m_NewsGroupID = (fCurGroupInSelection) ? m_curNewsgroupID : 0 ; // fill in rest of template and launch pTemplate->m_iFlags = TPT_TO_NEWSGROUPS | TPT_CANCEL_WARNING_ID | TPT_POST; pTemplate->m_iCancelWarningID = IDS_WARNING_POSTCANCEL; pTemplate->Launch (pTemplate->m_NewsGroupID); } // ------------------------------------------------------------------------ void CNewsView::OnArticleFollowup () { TServerCountedPtr cpNewsServer; CString followUps; TArticleText * pArtText = static_cast<TArticleText*>(m_pBrowsePaneText); // get article on demand if we need it. I would like the TPostDoc to // get the article, but the check for "followup-to: poster" already // requires it early. if (true) { int stat; BOOL fUseLock; TNewsGroup * pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (!fUseLock) return; BOOL fMarkAsRead = gpGlobalOptions->GetRegSwitch()->GetMarkReadFollowup(); if (0 == pArtText) { TError sErrorRet; CPoint ptPartID(0,0); TArticleText * pReturnArticleText = 0; stat = fnFetchBody (sErrorRet, pNG, (TArticleHeader *) m_pBrowsePaneHeader, pReturnArticleText, ptPartID, fMarkAsRead, // mark-as-read TRUE); // Try from newsfeed if (0 == stat) { SetBrowseText ( pReturnArticleText ); pArtText = pReturnArticleText; } else { CString str; str.LoadString (IDS_ERR_COULD_NOT_RETRIEVE); NewsMessageBox ( this, str, MB_ICONSTOP | MB_OK ); return; } } else { // it's local TArticleHeader* pArtHdr = (TArticleHeader* ) m_pBrowsePaneHeader; if (pArtHdr && fMarkAsRead) pNG->ReadRangeAdd ( pArtHdr ); } } BOOL fPostWithCC = FALSE; // check for "followup-to: poster" pArtText->GetFollowup ( followUps ); followUps.TrimLeft(); followUps.TrimRight(); // Son-of-1036 indicates exact match if ("poster" == followUps) { TAskFollowup dlg(this); dlg.DoModal(); switch (dlg.m_eAction) { case TAskFollowup::kCancel: return; case TAskFollowup::kPostWithCC: fPostWithCC = TRUE; break; case TAskFollowup::kSendEmail: { OnArticleReplybymail (); return; } } } // Verify that server is "Posting Allowed". This check is down here since // Followup-To: poster can morph to an e-mail message if (!check_server_posting_allowed()) return; ASSERT (m_curNewsgroupID); TPostTemplate *pTemplate = gptrApp->GetFollowTemplate (); pTemplate->m_iFlags = TPT_TO_NEWSGROUP | TPT_INSERT_ARTICLE | TPT_READ_ARTICLE_HEADER | TPT_CANCEL_WARNING_ID | TPT_FOLLOWUP | TPT_INIT_SUBJECT | TPT_USE_FOLLOWUP_INTRO | TPT_POST; if (fPostWithCC) pTemplate->m_iFlags |= TPT_POST_CC_AUTHOR; pTemplate->m_NewsGroupID = m_curNewsgroupID; pTemplate->m_iCancelWarningID = IDS_WARNING_FOLLOWUPCANCEL; pTemplate->m_strSubjPrefix.LoadString (IDS_RE); // lock the group while the article header and text are being accessed BOOL fUseLock; TNewsGroup *pNG; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (!fUseLock) return; TSyncReadLock sync (pNG); // $$ MicroPlanet tech-support specific. Turn on CC if (gpGlobalOptions->GetRegSwitch()->m_fUsePopup && ("support" == pNG->GetName() || "suggest" == pNG->GetName() || "regstudio" == pNG->GetName())) pTemplate->m_iFlags |= TPT_POST_CC_AUTHOR; pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader; pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText; pTemplate->m_strSubject = ((TArticleHeader *) m_pBrowsePaneHeader)->GetSubject (); pTemplate->Launch (pTemplate->m_NewsGroupID); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateArticleFollowup(CCmdUI* pCmdUI) { // we must have a current article BOOL fEnable = FALSE; if (m_curNewsgroupID && m_pBrowsePaneHeader) { if (m_pBrowsePaneText) fEnable = TRUE; else { // the body is not here. But we can probably get it. fEnable = gpTasker->IsConnected(); } } pCmdUI->Enable ( fEnable ); } // ------------------------------------------------------------------------ void fnNewsView_ReplyTo (CString& strTo, CString& strFrom, TArticleText* pText) { // use the 'Reply-To' field if present CString fldReplyTo; if (pText->GetReplyTo (fldReplyTo) && !fldReplyTo.IsEmpty()) { // RLW : 16/10/08 : The effect of these #ifdefs and // DecodeElectronicAddress being commented out meant that // ReplyTo: was being ignored, and the email was getting // the email of the pervious email sent!! // So I have removed #ifdef and ASSERT... //#if defined(_DEBUG) //ASSERT(0); // RLW : 16/10/08 : removed commenting from this func... // this function will handle the rfc2047 encoding TArticleHeader::DecodeElectronicAddress (fldReplyTo, strTo); // RLW : 16/10/08 : removed #endif to implement correct behaviour. //#endif } else strTo = strFrom; } /////////////////////////////////////////////////////////////////////////// // amc 4-2-97 Fix a deadlock problem. If you are replying to something // you haven't read, the Pump gets it on the fly and then // blocks on a WriteLock as it tries to mark the article // Read. Solution - release the ReadLock we acquired in this // function void CNewsView::OnArticleReplybymail() { TServerCountedPtr cpNewsServer; TPostTemplate *pTemplate = gptrApp->GetReplyTemplate (); pTemplate->m_iFlags = TPT_TO_STRING | TPT_INSERT_ARTICLE | TPT_READ_ARTICLE_HEADER | TPT_CANCEL_WARNING_ID | TPT_INIT_SUBJECT | TPT_USE_REPLY_INTRO | TPT_MAIL; pTemplate->m_iCancelWarningID = IDS_WARNING_REPLYCANCEL; pTemplate->m_strSubjPrefix.LoadString (IDS_RE); pTemplate->m_NewsGroupID = m_curNewsgroupID; // lock the group while the article header and text are being accessed BOOL fUseLock; TNewsGroup *pNG; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (!fUseLock) return; // protects the header object pNG->ReadLock (); pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader; // copy the From field CString strFrom = pTemplate->m_pArtHdr->GetFrom (); pTemplate->m_strSubject = pTemplate->m_pArtHdr->GetSubject (); pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText; if (pTemplate->m_pArtText) { pNG->UnlockRead (); } else { TError sErrorRet; CPoint ptPartID(0,0); TArticleHeader tmpHdr(*pTemplate->m_pArtHdr); TArticleText * pReturnArticleText = 0; // fMarkRead will need a WriteLock !! Give it up. pNG->UnlockRead (); BOOL fMarkAsRead = gpGlobalOptions->GetRegSwitch()->GetMarkReadReply(); int stat = fnFetchBody ( sErrorRet, pNG, &tmpHdr, pReturnArticleText, ptPartID, fMarkAsRead /* fMarkRead */, TRUE /* Try newsfeed */ ); if (stat) { NewsMessageBox (this, IDS_ERR_COULD_NOT_RETRIEVE, MB_ICONSTOP | MB_OK); return; } SetBrowseText ( pReturnArticleText ); pTemplate->m_pArtText = pReturnArticleText; } // setup the 'To:' field. Use the 'Reply-To' field if present fnNewsView_ReplyTo ( pTemplate->m_strTo, strFrom, pTemplate->m_pArtText ); // proceed pTemplate->Launch (pTemplate->m_NewsGroupID); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateArticleReplybymail(CCmdUI* pCmdUI) { if (!IsActiveServer()) { pCmdUI->Enable (FALSE); return; } TServerCountedPtr cpNewsServer; BOOL fArticleBody = m_pBrowsePaneText ? TRUE : gpTasker->IsConnected(); pCmdUI->Enable ( !cpNewsServer->GetSmtpServer ().IsEmpty () && m_curNewsgroupID && m_pBrowsePaneHeader && fArticleBody ); } //////////////////////////////////////////////////////////////// static BOOL gbForwardingSelected; // forwarding all selected articles? void CNewsView::OnArticleForward () { TServerCountedPtr cpNewsServer; TPostTemplate *pTemplate = gptrApp->GetForwardTemplate (); pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_MAIL; pTemplate->m_NewsGroupID = m_curNewsgroupID; pTemplate->m_iCancelWarningID = IDS_WARNING_FORWARDCANCEL; pTemplate->m_strSubjPrefix.LoadString (IDS_FWD); pTemplate->m_iFlags |= gbForwardingSelected ? (TPT_INSERT_SELECTED_ARTICLES | TPT_INIT_SUBJECT) : (TPT_READ_ARTICLE_HEADER | TPT_INSERT_ARTICLE | TPT_INIT_SUBJECT); // put this newsgroup's name in the template's "extra text file" field { BOOL fUseLock; TNewsGroup *pNG; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (!fUseLock) return; pTemplate->m_strExtraTextFile = pNG->GetName (); } // when forwarding, don't wrap, don't quote, ignore the line limit, and // insert the special prefix message pTemplate->m_iFlags |= TPT_DONT_WRAP | TPT_DONT_QUOTE | TPT_IGNORE_LINE_LIMIT | TPT_USE_FORWARD_INTRO; if (!gbForwardingSelected) { // lock the group while the article header and text are being accessed BOOL fUseLock; TNewsGroup *pNG; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (!fUseLock) return; TSyncReadLock sync (pNG); pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader; pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText; pTemplate->m_strSubject = ((TArticleHeader *) m_pBrowsePaneHeader)->GetSubject (); } else { // get the subject from the first selected article TThreadListView *pView = GetThreadView (); ASSERT (pView); TArticleHeader *pHeader = NULL; pView->GetFirstSelectedHeader ((TPersist822Header *&) pHeader); ASSERT (pHeader); pTemplate->m_strSubject = pHeader->GetSubject (); } pTemplate->Launch (pTemplate->m_NewsGroupID); gbForwardingSelected = FALSE; } //////////////////////////////////////////////////////////////// void CNewsView::OnForwardSelectedArticles () { gbForwardingSelected = TRUE; OnArticleForward (); } void CNewsView::OnUpdateForwardSelectedArticles (CCmdUI* pCmdUI) { TServerCountedPtr cpNewsServer; const CString & host = cpNewsServer->GetSmtpServer(); if (!host.IsEmpty() && m_curNewsgroupID && m_pBrowsePaneHeader && m_pBrowsePaneText) pCmdUI->Enable (TRUE); else pCmdUI->Enable (FALSE); } /////////////////////////////////////////////////// void CNewsView::SetBrowseText(TPersist822Text* pText) { delete m_pBrowsePaneText; m_pBrowsePaneText = pText; } TPersist822Text * CNewsView::GetBrowseText(void) { //ASSERT(m_pBrowsePaneArticle); return m_pBrowsePaneText; } /////////////////////////////////////////////////// void CNewsView::SetBrowseHeader(TPersist822Header* pHdr) { m_pBrowsePaneHeader = pHdr; } TPersist822Header * CNewsView::GetBrowseHeader(void) { //ASSERT(m_pBrowsePaneArticle); return m_pBrowsePaneHeader; } /////////////////////////////////////////////////// void CNewsView::SetCurNewsGroupID(LONG id) { m_curNewsgroupID = id; } LONG CNewsView::GetCurNewsGroupID(void) { return m_curNewsgroupID; } void CNewsView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView) { // TODO: Add your specialized code here and/or call the base class if (bActivate) { SetFocus (); // let the mdichild window know that we have the focus ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->PostMessage ( WMU_CHILD_FOCUS, 0, 0L ); } // IMHO this vvv is bullshit -al //BASE_CLASS::OnActivateView(bActivate, pActivateView, pDeactiveView); } // This is public, so the threadView can route msgs through us BOOL CNewsView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { // TODO: Add your specialized code here and/or call the base class return BASE_CLASS::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } //////////////////////////////////////////////////////////////////// // Note: the Deregister also happens when we destroy & recreate the // layout configuration void CNewsView::OnDestroy() { // save off status before we shut down { if (IsActiveServer()) { TServerCountedPtr cpNewsServer; BOOL fUseLock; TNewsGroup* pOld = 0; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pOld); if (fUseLock) { if (pOld && (pOld->GetDirty()) ) pOld->TextRangeSave(); // close the current newsgroup if (pOld->IsOpen()) pOld->Close(); } } } SaveColumnSettings(); // m_fPinFilter doesn't need to be written. it is saved immediately on Toggl BASE_CLASS::OnDestroy(); } //------------------------------------------------------------------------- // PropertyPage void CNewsView::OnNgpopupProperties() { int idx = GetSelectedIndex (); if (idx < 0) return; LONG id = (LONG)GetListCtrl().GetItemData(idx); TServerCountedPtr cpNewsServer; BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG); if (!fUseLock) return; TNewsGroup::EStorageOption eOldStorage = UtilGetStorageOption (pNG); TNewGroupGeneralOptions pgGeneral; TPurgePage pgPurge; TNewsGroupOverrideOptions pgOverride; TNewsGroupFilterPage pgFilter; TSigPage pgSignature; pgGeneral.m_kStorageOption = pgGeneral.m_iOriginalMode = (int) eOldStorage; pNG->GetServerBounds ( pgGeneral.m_iServerLow, pgGeneral.m_iServerHi ); int iHiRead = 0; if (pNG->GetHighestReadArtInt (&iHiRead)) pgGeneral.m_iHighestArticleRead = iHiRead; pgGeneral.m_lowWater = pNG->GetLowwaterMark(); pgGeneral.m_nickname = pNG->GetNickname (); pgGeneral.m_bSample = pNG->IsSampled (); pgGeneral.m_fInActive = pNG->IsActiveGroup() ? FALSE : TRUE ; //pgGeneral.m_fUseGlobalStorageOptions = pNG->UseGlobalStorageOptions (); pgGeneral.m_fCustomNGFont = FALSE; pgGeneral.m_strGroupName = pNG->GetName (); if (gpGlobalOptions->IsCustomNGFont()) { CopyMemory (&pgGeneral.m_ngFont, gpGlobalOptions->GetNewsgroupFont(), sizeof(LOGFONT)); pgGeneral.m_newsgroupColor = gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor(); pgGeneral.m_fCustomNGFont = TRUE; } else CopyMemory (&pgGeneral.m_ngFont, &gpGlobalOptions->m_defNGFont, sizeof(LOGFONT)); TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors (); pgGeneral.m_newsgroupBackground = pBackgrounds->GetNewsgroupBackground(); pgGeneral.m_fDefaultBackground = gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG(); pgPurge.m_fOverride = pNG->IsPurgeOverride(); pgPurge.m_fPurgeRead = UtilGetPurgeRead(pNG); pgPurge.m_iReadLimit = UtilGetPurgeReadLimit(pNG); pgPurge.m_fPurgeUnread = UtilGetPurgeUnread(pNG); pgPurge.m_iUnreadLimit = UtilGetPurgeUnreadLimit(pNG); pgPurge.m_fOnHdr = UtilGetPurgeOnHdrs(pNG); pgPurge.m_iDaysHdrPurge= UtilGetPurgeOnHdrsEvery(pNG); pgPurge.m_fShutdown = UtilGetCompactOnExit(pNG); pgPurge.m_iShutCompact = UtilGetCompactOnExitEvery(pNG); pgOverride.m_bOverrideCustomHeaders = pNG->GetOverrideCustomHeaders (); pgOverride.m_bOverrideEmail = pNG->GetOverrideEmail (); pgOverride.m_bOverrideFullName = pNG->GetOverrideFullName (); pgOverride.m_bOverrideDecodeDir = pNG->GetOverrideDecodeDir (); pgOverride.m_fOverrideLimitHeaders = pNG->GetOverrideLimitHeaders (); pgOverride.m_strDecodeDir = pNG->GetDecodeDir (); pgOverride.m_strEmail = pNG->GetEmail (); pgOverride.m_strFullName = pNG->GetFullName (); CopyCStringList (pgOverride.m_sCustomHeaders, pNG->GetCustomHeaders ()); pgOverride.m_iHeaderLimit = pNG->GetHeadersLimit (); // newsgroup filter page pgFilter.m_iFilterID = pNG->GetFilterID(); pgFilter.m_fOverrideFilter = pgFilter.m_iFilterID != 0; // newsgroup signature page pgSignature.m_fCustomSig = pNG->GetUseSignature(); pgSignature.m_strShortName = pNG->GetSigShortName(); CPropertySheet newsgroupProperties(pNG->GetName ()); int iRC; newsgroupProperties.AddPage (&pgGeneral); newsgroupProperties.AddPage (&pgPurge); newsgroupProperties.AddPage (&pgOverride); newsgroupProperties.AddPage (&pgFilter); newsgroupProperties.AddPage (&pgSignature); iRC = newsgroupProperties.DoModal (); if (IDOK == iRC) { #if defined(_DEBUG) && defined(VERBOSE) CString msg; msg.Format("SrHi= %d; SrLo= %d; HiRead=%d", pgGeneral.m_iServerHi, pgGeneral.m_iServerLow, pgGeneral.m_iHighestArticleRead); MessageBox (msg); #endif pNG->SetNickname (pgGeneral.m_nickname); pNG->Sample (pgGeneral.m_bSample); sync_caption(); if (pgGeneral.m_iHighestArticleRead != pgGeneral.m_iHighestArticleRead0) { // user has chosen to go back! int iLowWater = pNG->GetLowwaterMark (); if (pgGeneral.m_iHighestArticleRead < iLowWater) pNG->SetLowwaterMark (pgGeneral.m_iHighestArticleRead); pNG->ResetHighestArticleRead (pgGeneral.m_iHighestArticleRead, pgGeneral.m_iHighestArticleRead0); // if user changed the GoBack, then we should save this cpNewsServer->SaveReadRange (); } pNG->SetStorageOption (TNewsGroup::EStorageOption(pgGeneral.m_kStorageOption)); pNG->SetUseGlobalStorageOptions (/*pgGeneral.m_fUseGlobalStorageOptions*/FALSE); gpGlobalOptions->CustomNGFont (pgGeneral.m_fCustomNGFont); gpGlobalOptions->GetRegSwitch()->SetDefaultNGBG(pgGeneral.m_fDefaultBackground); pBackgrounds->SetNewsgroupBackground(pgGeneral.m_newsgroupBackground); gpGlobalOptions->GetRegFonts()->SetNewsgroupFontColor( pgGeneral.m_newsgroupColor ); if (pgGeneral.m_fCustomNGFont) gpGlobalOptions->SetNewsgroupFont ( &pgGeneral.m_ngFont ); pNG->SetActiveGroup (!pgGeneral.m_fInActive); pNG->SetPurgeOverride(pgPurge.m_fOverride); pNG->SetPurgeRead(pgPurge.m_fPurgeRead); pNG->SetPurgeReadLimit(pgPurge.m_iReadLimit); pNG->SetPurgeUnread(pgPurge.m_fPurgeUnread); pNG->SetPurgeUnreadLimit(pgPurge.m_iUnreadLimit); pNG->SetPurgeOnHdrs(pgPurge.m_fOnHdr); pNG->SetPurgeOnHdrsEvery(pgPurge.m_iDaysHdrPurge); pNG->SetCompactOnExit(pgPurge.m_fShutdown); pNG->SetCompactOnExitEvery(pgPurge.m_iShutCompact); pNG->SetOverrideCustomHeaders (pgOverride.m_bOverrideCustomHeaders); pNG->SetOverrideEmail (pgOverride.m_bOverrideEmail); pNG->SetOverrideFullName (pgOverride.m_bOverrideFullName); pNG->SetOverrideDecodeDir (pgOverride.m_bOverrideDecodeDir); pNG->SetOverrideLimitHeaders (pgOverride.m_fOverrideLimitHeaders); pNG->SetDecodeDir (pgOverride.m_strDecodeDir); pNG->SetEmail (pgOverride.m_strEmail); pNG->SetFullName (pgOverride.m_strFullName); pNG->SetCustomHeaders (pgOverride.m_sCustomHeaders); pNG->SetHeadersLimit (pgOverride.m_iHeaderLimit); // destroy stuff if we transition from (Mode 2,3)->(Mode 1) if ((TNewsGroup::kHeadersOnly == eOldStorage || TNewsGroup::kStoreBodies == eOldStorage) && TNewsGroup::kNothing == UtilGetStorageOption (pNG)) { if (pNG->m_GroupID == m_curNewsgroupID) { // probably lots of articles have been removed EmptyBrowsePointers (); GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY); // empty out thread list pNG->Empty (); } // destroy headers for which there are no bodies // -- what do we have to lock down? pNG->StorageTransition (eOldStorage); } // associated filter if (pgFilter.m_fOverrideFilter) pNG->SetFilterID (pgFilter.m_iFilterID); else pNG->SetFilterID (0); pNG->SetUseSignature (pgSignature.m_fCustomSig); pNG->SetSigShortName (pgSignature.m_strShortName); // if user changed the GoBack, then we should save this // "this is done above" cpNewsServer->SaveReadRange (); // make it last cpNewsServer->SaveIndividualGroup ( pNG ); gpStore->SaveGlobalOptions (); CMDIChildWnd * pMDIChild; CMDIFrameWnd * pMDIFrame = (CMDIFrameWnd*) AfxGetMainWnd(); // note this is only 1 of the mdi children. could be more. // we aren't handling them. pMDIChild = pMDIFrame->MDIGetActive(); // apply the new ng font pMDIChild->PostMessage ( WMU_NEWSVIEW_NEWFONT ); GetListCtrl().DeleteItem (idx); // use name or nickname if (0==AddStringWithData (pNG->GetBestname(), pNG->m_GroupID, &idx)) SetOneSelection (idx); } // IDOK == DoModal() } // ------------------------------------------------------------------------- static void MicroplanetDoesntLikeSpamBlockingAddresses () { TServerCountedPtr pServer; CString strAddress = pServer->GetEmailAddress (); strAddress.MakeUpper (); if (strAddress.Find ("SPAM") >= 0 || strAddress.Find ("REMOVE") >= 0 || strAddress.Find ("DELETE") >= 0) MsgResource (IDS_MICROPLANET_DOESNT_LIKE_SPAM); } // ------------------------------------------------------------------------- void CNewsView::ComposeMessage () { // if mailing to microplanet, check the from address for spam-blocking if (giMessageType == MESSAGE_TYPE_SUGGESTION || giMessageType == MESSAGE_TYPE_BUG) MicroplanetDoesntLikeSpamBlockingAddresses (); TPostTemplate *pTemplate = giMessageType == MESSAGE_TYPE_BUG ? gptrApp->GetBugTemplate () : (giMessageType == MESSAGE_TYPE_SUGGESTION ? gptrApp->GetSuggestionTemplate () : gptrApp->GetSendToFriendTemplate ()); pTemplate->m_strSubjPrefix = ""; pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_INIT_SUBJECT | TPT_MAIL; switch (giMessageType) { case MESSAGE_TYPE_BUG: pTemplate->m_iFlags |= TPT_TO_STRING | TPT_INSERT_MACHINEINFO; pTemplate->m_iCancelWarningID = IDS_WARNING_BUGCANCEL; pTemplate->m_strSubject.LoadString (IDS_BUG_REPORT); #if defined(KISS) || defined(KISS_TRIAL) pTemplate->m_strTo.LoadString (IDS_SUPPORT_KISS); #else pTemplate->m_strTo.LoadString (IDS_SUPPORT_ADDR); #endif break; case MESSAGE_TYPE_SUGGESTION: pTemplate->m_iFlags |= TPT_TO_STRING; pTemplate->m_iCancelWarningID = IDS_WARNING_SUGGESTCANCEL; pTemplate->m_strSubject.LoadString (IDS_NEWS32_SUGGESTION); pTemplate->m_strTo.LoadString (IDS_SUGGEST_ADDR); break; case MESSAGE_TYPE_SEND_TO_FRIEND: { TPath appFilespec; CString & infoFilename = pTemplate->m_strExtraTextFile; pTemplate->m_iCancelWarningID = IDS_WARNING_MESSAGECANCEL; pTemplate->m_strSubject.LoadString (IDS_NEWS32_INFORMATION); pTemplate->m_iFlags |= TPT_INSERT_FILE; // look in the App's directory infoFilename.LoadString (IDS_INFO_FILE); TFileUtil::UseProgramPath(infoFilename, appFilespec); pTemplate->m_strExtraTextFile = appFilespec; break; } default: ASSERT (0); break; } pTemplate->Launch ( 0 /* newsgroupID */); } // ------------------------------------------------------------------------ //void CNewsView::OnHelpSendBugReport() //{ // giMessageType = MESSAGE_TYPE_BUG; // ComposeMessage (); //} // ------------------------------------------------------------------------ //void CNewsView::OnUpdateHelpSendBugReport (CCmdUI* pCmdUI) //{ // TServerCountedPtr cpNewsServer; // // const CString & host = cpNewsServer->GetSmtpServer(); // if (!host.IsEmpty()) // pCmdUI->Enable (TRUE); // else // pCmdUI->Enable (FALSE); //} // ------------------------------------------------------------------------ //void CNewsView::OnHelpSendSuggestion() //{ // giMessageType = MESSAGE_TYPE_SUGGESTION; // ComposeMessage (); //} // //// ------------------------------------------------------------------------ //void CNewsView::OnUpdateHelpSendSuggestion (CCmdUI* pCmdUI) //{ // OnUpdateHelpSendBugReport(pCmdUI); //} // ------------------------------------------------------------------------ void CNewsView::OnSendToFriend() { giMessageType = MESSAGE_TYPE_SEND_TO_FRIEND; ComposeMessage (); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateSendToFriend (CCmdUI* pCmdUI) { TServerCountedPtr cpNewsServer; const CString & host = cpNewsServer->GetSmtpServer(); if (!host.IsEmpty()) pCmdUI->Enable (TRUE); else pCmdUI->Enable (FALSE); } // ------------------------------------------------------------------------ // Keep trying to set the Caption on the mdichild void CNewsView::OnTimer(UINT nIDEvent) { if (idCaptionTimer == nIDEvent) { if (sync_caption()) { KillTimer ( m_hCaptionTimer ); m_hCaptionTimer = 0; } } else if (CNewsView::idSelchangeTimer == nIDEvent) { // this is related to 1-click open NG stop_selchange_timer (); //TRACE("SelchangeTimer popped\n"); PostMessage (WMU_SELCHANGE_OPEN); } BASE_CLASS::OnTimer(nIDEvent); } /////////////////////////////////////////////////////////////////////////// // Get the name of the current NG and set the CDocument title. This // will set the caption on the MDI window. // BOOL CNewsView::sync_caption() { TNewsGroup* pNG = 0; LONG id = m_curNewsgroupID; CString title; TServerCountedPtr cpNewsServer; TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray(); TNewsGroupArrayReadLock ngMgr(vNewsGroups); if (0 == vNewsGroups->GetSize() || (0==id)) { title.Empty (); } else { BOOL fUseLock; TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG); if (!fUseLock) { title.Empty (); } else { title = cpNewsServer->GetNewsServerName() + "/" + pNG->GetBestname(); } } // Documents have titles too! GetDocument()->SetTitle ( title ); return TRUE; } ///////////////////////////////////////////////////////////////////// // GotoArticle - Jump to a specific group/article pair. // // return 0 if loaded, 1 if started download // LRESULT CNewsView::GotoArticle (WPARAM wParam, LPARAM lParam) { CListCtrl & lc = GetListCtrl (); TServerCountedPtr cpNewsServer; // find the newsgroup in the listbox, set selection, and // call OpenNewsgroup int iOpenRet = 0; TGotoArticle *pGoto = (TGotoArticle *) lParam; BOOL fOpened = FALSE; int iRet = -1; int count = lc.GetItemCount (); for (int i = 0; i < count; i++) { if (pGoto->m_groupNumber == (int)lc.GetItemData (i)) { #if 1 // the search dialog has logic to force a filter change (via // WMU_FORCE_FILTER_CHANGE #else // set the view filter to the least restrictive one... ???? don't need // to restrict filter if article is compatible with current filter set gpUIMemory->SetViewFilter (0); #endif // ???? might need to optimize for newsgroup is current one somehow // potentially by passing in the status of the message so // that it can be compared against the current filter // if we need to jump to a different NG, or we are about to utilize // the 'All Articles' filter, then Open the newsgroup if (m_curNewsgroupID != pGoto->m_groupNumber || pGoto->m_byOpenNG) { if (pGoto->m_byDownloadNG) { // this is useful for newsurl support. DL a newly subscribed NG. iRet = iOpenRet = OpenNewsgroup ( kFetchOnZero, kCurrentFilter, pGoto->m_groupNumber); } else iRet = iOpenRet = OpenNewsgroup ( kOpenNormal, kCurrentFilter, pGoto->m_groupNumber); } if (iRet >= 0) { this->AddOneClickGroupInterference (); SetOneSelection (i); } else { SetOneSelection (i); } break; } } BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG); if (fUseLock) { switch (UtilGetStorageOption ( pNG )) { case TNewsGroup::kNothing: m_GotoArticle = *pGoto; break; case TNewsGroup::kHeadersOnly: case TNewsGroup::kStoreBodies: EmptyBrowsePointers (); GetDocument()->UpdateAllViews(this, VIEWHINT_GOTOARTICLE, pGoto); break; default: ASSERT(0); break; } } return iOpenRet; } ///////////////////////////////////////////////////////////////////// // ProcessMailTo - Send mail to somebody. ///////////////////////////////////////////////////////////////////// LRESULT CNewsView::ProcessMailTo (WPARAM wParam, LPARAM lParam) { TPostTemplate *pTemplate = gptrApp->GetMailToTemplate (); pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_MAIL | TPT_TO_STRING; pTemplate->m_iCancelWarningID = IDS_WARNING_MESSAGECANCEL; pTemplate->m_strTo = (LPCTSTR) lParam; pTemplate->Launch (GetCurNewsGroupID()); return FALSE; } // --------------------------------------------------------------------- // handles WMU_NEWSVIEW_NEWFONT void CNewsView::ApplyNewFont(void) { TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors (); if (!gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG()) { CListCtrl &lc = GetListCtrl(); lc.SetBkColor ( pBackgrounds->GetNewsgroupBackground() ); lc.SetTextBkColor ( pBackgrounds->GetNewsgroupBackground() ); } GetListCtrl().SetTextColor ( gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor() ); LOGFONT lfCurrent; // check against current font. CFont* pCurCFont = GetFont(); if (pCurCFont) pCurCFont->GetObject (sizeof(LOGFONT), &lfCurrent); else { // we should always have an explicit font set. ASSERT(0); } const LOGFONT* plfFontNew; BOOL fCustom = gpGlobalOptions->IsCustomNGFont(); if (fCustom) plfFontNew = gpGlobalOptions->GetNewsgroupFont(); else plfFontNew = &gpGlobalOptions->m_defNGFont; // Only if the newfont is different, do we apply it. // 9-15-95 this may not work due to non-match on precision, // clipping and fine points like that if (memcmp (plfFontNew, &lfCurrent, sizeof(LOGFONT))) { if (m_font.m_hObject) { m_font.DeleteObject (); // i pray this does the detach m_font.m_hObject = NULL; } m_font.CreateFontIndirect ( plfFontNew ); SetFont (&m_font, TRUE); // m_font is cleaned up by CFont destructor. } } LRESULT CNewsView::OnDisplayArtcount (WPARAM wParam, LPARAM lParam) { int iGroupID = (int) wParam; if (iGroupID <= 0) { // redraw all this->Invalidate (); } else { // redraw to show the Total number of new articles RedrawByGroupID ( iGroupID ); } return 0; } /////////////////////////////////////////////////////////////////////////// // The MDI window does the 4 way routing. If we really do have the focus // save the article shown is the view pane. void CNewsView::OnSaveToFile () { BOOL fMax; TNews3MDIChildWnd *pMDI = (TNews3MDIChildWnd *) ((CMainFrame*) AfxGetMainWnd ())->MDIGetActive (&fMax); TMdiLayout *pLayout = pMDI->GetLayoutWnd (); TArticleFormView *pArtView = pLayout->GetArtFormView(); pArtView->SendMessage (WM_COMMAND, ID_ARTICLE_SAVE_AS); } void CNewsView::OnUpdateSaveToFile (CCmdUI* pCmdUI) { BOOL fValid = (GetBrowseHeader () && GetBrowseText ()); pCmdUI->Enable (fValid); } // ------------------------------------------------------------------------- void CNewsView::OnUpdateThreadChangeToRead (CCmdUI* pCmdUI) { pCmdUI->Enable (FALSE); } // ------------------------------------------------------------------------- // this should always be disabled when the NewsView pane has focus void CNewsView::OnThreadChangeToRead () { // ChangeThreadStatusTo (TStatusUnit::kNew, FALSE); } void CNewsView::EmptyBrowsePointers () { SetBrowseHeader (NULL); SetBrowseText (NULL); } // ------------------------------------------------------------------------- // a newsgroup's headers are displayed BOOL CNewsView::IsNewsgroupDisplayed () { return m_curNewsgroupID ? TRUE : FALSE; } // ------------------------------------------------------------------------- // True if exactly one bool CNewsView::IsExactlyOneNewsgroupSelected () { return GetListCtrl().GetSelectedCount() == 1; } // ------------------------------------------------------------------------- bool CNewsView::IsOneOrMoreNewsgroupSelected () { return GetListCtrl().GetSelectedCount() > 0; } // ------------------------------------------------------------------------- void CNewsView::OnUpdateNewsgroupUnsubscribe (CCmdUI* pCmdUI) { pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ()); } // ------------------------------------------------------------------------- // 4-19-96 amc Changed catchup alot. So I can use any selected NG. void CNewsView::OnUpdateNewsgroupCatchup (CCmdUI* pCmdUI) { pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ()); } // ------------------------------------------------------------------------- void CNewsView::OnUpdateNewsgroupProperties (CCmdUI* pCmdUI) { pCmdUI->Enable (IsExactlyOneNewsgroupSelected ()); } void CNewsView::OnUpdateDisable(CCmdUI* pCmdUI) { pCmdUI->Enable (FALSE); } // ------------------------------------------------------------------------- // this is a real accelerator void CNewsView::OnCmdTabaround() { ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()-> PostMessage (WMU_CHILD_TAB, FALSE, 0); } // ------------------------------------------------------------------------- // this is a real accelerator void CNewsView::OnCmdTabBack() { ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()-> PostMessage (WMU_CHILD_TAB, TRUE, 0); } /////////////////////////////////////////////////////////////////////////// // Get articles for all subscribed newsgroups // void CNewsView::OnGetheadersAllGroups() { // get headers, (force the retrieve cycle, fUserAction) CNewsDoc::DocGetHeadersAllGroups (true, true); } void CNewsView::OnUpdateGetheadersAllGroups(CCmdUI* pCmdUI) { BOOL fEnable = FALSE; if (gpTasker) fEnable = gpTasker->CanRetrieveCycle (); pCmdUI->Enable ( fEnable ); } /////////////////////////////////////////////////////////////////////////// // Get article headers for one group. Function does NOT map to a menu-item // void CNewsView::GetHeadersOneGroup() { if (0 == gpTasker) return; BOOL fCatchUp = gpGlobalOptions->GetRegSwitch()->GetCatchUpOnRetrieve(); int iGroupId = GetSelectedGroupID (); if (LB_ERR != iGroupId) get_header_worker (iGroupId, fCatchUp, TRUE /* get all */, 0); } // ------------------------------------------------------------------------ // also used by ID_VERIFY_HDRS void CNewsView::OnUpdateGetHeadersMultiGroup(CCmdUI* pCmdUI) { pCmdUI->Enable (gpTasker ? IsOneOrMoreNewsgroupSelected () : false); } // ------------------------------------------------------------------------ // Request headers for 1 or more groups void CNewsView::OnGetHeadersMultiGroup () { // call worker function get_header_multigroup_worker (TRUE /* fGetAllHdrs */, 0); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateGetheaderLimited(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here OnUpdateGetHeadersMultiGroup( pCmdUI); } // ------------------------------------------------------------------------ // Get 'X' headers void CNewsView::OnGetheaderLimited() { CPromptLimitHeaders sDlg (AfxGetMainWnd()); if (IDOK == sDlg.DoModal()) { get_header_multigroup_worker (FALSE, sDlg.m_iCount); } } // ------------------------------------------------------------------------ int CNewsView::get_header_multigroup_worker (BOOL fGetAll, int iHdrsLimit) { if (0 == gpTasker) return 1; BOOL fCatchUp = gpGlobalOptions->GetRegSwitch()->GetCatchUpOnRetrieve(); CPtrArray vec; int iSelCount = 0; // get info on multi selection if (multisel_get (&vec, &iSelCount)) return 1; for (int i = 0; i < vec.GetSize(); i++) { TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]); get_header_worker (pPair->id, fCatchUp, fGetAll, iHdrsLimit); } FreeGroupIDPairs (&vec); return 0; } // ------------------------------------------------------------------------ // int CNewsView::get_header_worker (int iGroupId, BOOL fCatchUp, BOOL fGetAll, int iHdrsLimit) { if (LB_ERR == iGroupId) return 1; BOOL fConnected = gpTasker->IsConnected(); if (!fConnected) return 1; TServerCountedPtr cpNewsServer; BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, iGroupId, &fUseLock, pNG); if (!fUseLock) return 1; if (fCatchUp) { CatchUp_Helper ( iGroupId, FALSE ); } // before downloading headers Purge via Date criteria // Master Plan: // purge // get headers // refresh ui. // If we are't connected then don't purge either [2-12-97 amc] if (fConnected && pNG->NeedsPurge()) pNG->PurgeByDate(); gpTasker->PrioritizeNewsgroup ( pNG->GetName(), fGetAll, iHdrsLimit ); return 0; } // ------------------------------------------------------------------------ // OnVerifyLocalHeaders -- see if all local headers still exist on the // server. If any have been expired, remove them from the display (reload) void CNewsView::OnVerifyLocalHeaders () { try { CPtrArray vec; int iSelCount = 0; // get info on multi selection if (multisel_get (&vec, &iSelCount)) return; TServerCountedPtr cpNewsServer; for (int i = 0; i < vec.GetSize(); i++) { TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]); BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG); if (fUseLock && TNewsGroup::kNothing != UtilGetStorageOption (pNG)) gpTasker->VerifyLocalHeaders (pNG); } FreeGroupIDPairs (&vec); } catch(...) { /* trap all errors */ } } void CNewsView::OnDisplayAllArticleCounts(void) { // for listctrl redraw it all Invalidate (); } /////////////////////////////////////////////////////////////////////////// // Created 3-24-96 // Once all the headers have been saved - re-open the newsgroup. // 1 - this saves the user the effort of opening the NG himself // 2 - after purging articles (during hdr retrieve) we sorta haveto // repaint, (some articles showing in the LBX may be gone) // LRESULT CNewsView::OnNewsgroupHdrsDone(WPARAM wParam, LPARAM lParam) { TServerCountedPtr cpNewsServer; LONG grpID = (LONG) wParam; BOOL fUserAction = (BOOL) lParam; if (grpID == m_curNewsgroupID) { BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, grpID, &fUseLock, pNG); if (fUseLock) { if (fUserAction) OpenNewsgroup (kOpenNormal, kPreferredFilter, grpID); } } return 0; } //------------------------------------------------------------------------- // LRESULT CNewsView::OnMode1HdrsDone(WPARAM wParam, LPARAM lParam) { LONG grpID = (LONG) wParam; BOOL fOld = (lParam & 0x1) ? TRUE : FALSE; BOOL fNew = (lParam & 0x2) ? TRUE : FALSE; TServerCountedPtr cpNewsServer; if (grpID == m_curNewsgroupID) { BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, grpID, &fUseLock, pNG); if (fUseLock) { if (TNewsGroup::kNothing == UtilGetStorageOption(pNG)) { // mode 1 - Don't call OpenNewsgroup this would be an infinite loop pNG->Mode1_Thread (fOld, fNew); please_update_views (); // 'GOTO' article from Search Window if (m_GotoArticle.m_articleNumber >= 0) { EmptyBrowsePointers (); GetDocument()->UpdateAllViews(this, VIEWHINT_GOTOARTICLE, &m_GotoArticle); m_GotoArticle.m_articleNumber = -1; } return 0; } } } return 0; } // There are no objects in the newsview you can copy void CNewsView::OnUpdateEditCopy(CCmdUI* pCmdUI) { pCmdUI->Enable( FALSE ); } // ------------------------------------------------------------------------ // subthread forces UI to show a message box LRESULT CNewsView::OnErrorFromServer (WPARAM wParam, LPARAM lParam) { ASSERT(wParam); if (wParam) { PTYP_ERROR_FROM_SERVER psErr = (PTYP_ERROR_FROM_SERVER)(void*)(wParam); // Response from Server: %s CString strReason; strReason.Format (IDS_UTIL_SERVRESP, psErr->iRet, LPCTSTR(psErr->serverString)); TNNTPErrorDialog sDlg(this); sDlg.m_strWhen = psErr->actionDesc; sDlg.m_strReason = strReason; // show fairly polished dlg box sDlg.DoModal (); delete psErr; } return TRUE; } void CNewsView::protected_open(TNewsGroup* pNG, BOOL fOpen) { TEnterCSection enter(&m_dbCritSect); int iCount = 10; if (fOpen) { TUserDisplay_UIPane sAutoDraw("Open group"); pNG->Open (); ++ iLocalOpen; } else { TUserDisplay_UIPane sAutoDraw("Close group"); ASSERT(iLocalOpen > 0); if (iLocalOpen > 0) { pNG->Close (); -- iLocalOpen; } } } ////////////////////////////////////////////////////////////////////////// // Called from OnLbxSelChange(void) LRESULT CNewsView::OnSelChangeOpen(WPARAM wParam, LPARAM lParam) { //TRACE0("Start from SelChange Open\n"); OpenNewsgroup( kFetchOnZero, kPreferredFilter ); //TRACE0("Returning from SelChange Open\n"); return 0; } //------------------------------------------------------------------------- // return TRUE to continue, FALSE to abort BOOL CNewsView::check_server_posting_allowed() { TServerCountedPtr cpNewsServer; if (cpNewsServer->GetPostingAllowed()) return TRUE; CString msg; AfxFormatString1(msg, IDS_WARN_SERVER_NOPOSTALLOWED, (LPCTSTR) cpNewsServer->GetNewsServerName()); // are you sure you want to continue? return (IDYES == NewsMessageBox(this, msg, MB_YESNO | MB_ICONQUESTION)); } //------------------------------------------------------------------------- // validate_connection -- Suppose the normal pump is busy downloading a // binary. As the user switches to a mode-1 NG, the emergency-pump // should be used, since the n-pump is busy. Start it up and it should // be running when the ArticleBank needs it. It would be GROSS to // move the connection code to when the ArticleBank calls // gpTasker->GetRangeFor() BOOL CNewsView::validate_connection () { TServerCountedPtr cpNewsServer; if (FALSE == gpTasker->IsConnected()) return TRUE; else { // ok we are connected if (FALSE == gpTasker->NormalPumpBusy()) return TRUE; int iTry; BOOL fConnected; BOOL fContinueConnect = FALSE; fConnected = gpTasker->SecondIsConnected ( &fContinueConnect ); if (fConnected) return TRUE; else { // since the norm-pump is running, we should have permission to // start the e-pump if (!fContinueConnect) return FALSE; iTry = gpTasker->SecondConnect ( cpNewsServer->GetNewsServerAddress() ); if (0 != iTry) return FALSE; return TRUE; } } } // ------------------------------------------------------------------------ // used for CatchUp and Move to Next newsgroup. Returns grpid. BOOL CNewsView::validate_next_newsgroup (int * pGrpId, int * pIdx) { TServerCountedPtr cpNewsServer; CListCtrl & lc = GetListCtrl (); int iNext = -1; int tot = lc.GetItemCount(); for (int i = 0; i < tot; ++i) { // hunt for a newsgroup we can open if (0 == iNext) { int iGrpID = (int) lc.GetItemData(i); BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, iGrpID, &fUseLock, pNG); if (fUseLock) { if (TNewsGroup::kNothing == UtilGetStorageOption (pNG)) { // if we are not connected keep going if (gpTasker->IsConnected()) { *pGrpId = iGrpID; *pIdx = i; return TRUE; } } else { *pGrpId = iGrpID; *pIdx = i; return TRUE; } } } // find our current guy if (m_curNewsgroupID == (int) lc.GetItemData(i)) iNext = 0; } return FALSE; } // ------------------------------------------------------------------------ // A real public func void CNewsView::OpenNewsgroupEx(CNewsView::EOpenMode eMode) { // open the selected one! OpenNewsgroup ( eMode, kPreferredFilter ); } // ------------------------------------------------------------------------ int CNewsView::NumSelected () { return GetListCtrl().GetSelectedCount(); } // ------------------------------------------------------------------------ // GetSelectedIDs -- takes a pointer to an integer array, and returns the // group IDs for the selected groups void CNewsView::GetSelectedIDs (int *piIDs, int iSize) { // first, fill dest array with zeros int i = 0; for (i = 0; i < iSize; i++) piIDs [i] = 0; int iNumSelected = NumSelected (); if (iNumSelected <= 0) return; CListCtrl & lc = GetListCtrl(); int * piIndices = new int [iNumSelected]; auto_ptr <int> pIndicesDeleter(piIndices); int n = 0; POSITION pos = lc.GetFirstSelectedItemPosition (); while (pos) piIndices[n++] = lc.GetNextSelectedItem (pos); for (i = 0; i < iNumSelected && i < iSize; i++) piIDs [i] = lc.GetItemData (piIndices [i]); } // ------------------------------------------------------------------------ // OnUpdateKeepSampled -- enabled if any selected group is sampled void CNewsView::OnUpdateKeepSampled(CCmdUI* pCmdUI) { TServerCountedPtr cpNewsServer; BOOL bEnable = FALSE; CPtrArray sPairs; // holds a collection of (groupID, name) pairs int iNum = 0; if (multisel_get (&sPairs, &iNum)) { pCmdUI->Enable (FALSE); return; } iNum = sPairs.GetSize(); for (int i = 0; i < iNum; i++) { // get pNG TGroupIDPair *pPair = static_cast <TGroupIDPair*> (sPairs [i]); TNewsGroup *pNG; BOOL fUseLock; TNewsGroupUseLock useLock (cpNewsServer, pPair->id, &fUseLock, pNG); if (!fUseLock) break; // check it if (pNG->IsSampled ()) { bEnable = TRUE; break; } } FreeGroupIDPairs (&sPairs); pCmdUI->Enable (bEnable); } // ------------------------------------------------------------------------ void CNewsView::OnKeepSampled() { TServerCountedPtr cpNewsServer; CPtrArray sPairs; // holds a collection of (groupID, name) pairs int iNum = 0; if (multisel_get (&sPairs, &iNum)) return; iNum = sPairs.GetSize(); for (int i = 0; i < iNum; i++) { // get pNG TGroupIDPair *pPair = static_cast <TGroupIDPair*> (sPairs [i]); TNewsGroup *pNG; BOOL fUseLock; TNewsGroupUseLock useLock (cpNewsServer, pPair->id, &fUseLock, pNG); if (!fUseLock) break; // keep the group pNG->Sample (FALSE); } FreeGroupIDPairs (&sPairs); // redraw all Invalidate (); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateKeepAllSampled(CCmdUI* pCmdUI) { TServerCountedPtr cpNewsServer; BOOL bEnable = FALSE; TNewsGroupArray &vNewsGroups = cpNewsServer->GetSubscribedArray (); int iNum = vNewsGroups->GetSize (); for (int i = 0; i < iNum; i++) { TNewsGroup *pNG = vNewsGroups [i]; if (pNG->IsSampled ()) bEnable = TRUE; } pCmdUI->Enable (bEnable); } // ------------------------------------------------------------------------ void CNewsView::OnKeepAllSampled() { TServerCountedPtr cpNewsServer; TNewsGroupArray &vNewsGroups = cpNewsServer->GetSubscribedArray (); int iNum = vNewsGroups->GetSize (); for (int i = 0; i < iNum; i++) { TNewsGroup *pNG = vNewsGroups [i]; pNG->Sample (FALSE); } // redraw all Invalidate (); } // ------------------------------------------------------------------------ void CNewsView::OnEditSelectAll() { GetListCtrl().SetItemState (-1, LVIS_SELECTED, LVIS_SELECTED); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateEditSelectAll(CCmdUI* pCmdUI) { pCmdUI->Enable (GetListCtrl().GetItemCount () > 0); } // ------------------------------------------------------------------------ void CNewsView::EmptyListbox () { GetListCtrl().DeleteAllItems (); } // ------------------------------------------------------------------------ void CNewsView::OnUpdateDeleteSelected(CCmdUI* pCmdUI) { pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ()); } // --------------------------------------------------- void CNewsView::OnHelpResyncStati() { //TRACE0("Resyncing...\n"); TServerCountedPtr cpNewsServer; LONG nGID = GetCurNewsGroupID(); BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, nGID, &fUseLock, pNG); if (!fUseLock) return; { TAutoClose sCloser(pNG); CWaitCursor cursor; pNG->ValidateStati (); } // redraw all Invalidate (); } // Pindown view filter void CNewsView::OnNewsgroupPinfilter() { m_fPinFilter = !m_fPinFilter; // save immediately gpGlobalOptions->GetRegUI()->SetPinFilter( m_fPinFilter ); gpGlobalOptions->GetRegUI()->Save (); ((CMainFrame*)AfxGetMainWnd())->UpdatePinFilter ( m_fPinFilter ); } void CNewsView::OnUpdateNewsgroupPinfilter(CCmdUI* pCmdUI) { pCmdUI->SetCheck ( m_fPinFilter ); } // ------------------------------------------------------------------------- // Returns 0 for success. On success return the group-id we found. // int CNewsView::GetNextGroup (EJmpQuery eQuery, int * pGroupID) { CListCtrl & lc = GetListCtrl (); // depends on the 'sort' order, so we have to ask the UI. ick! int curGID = GetCurNewsGroupID(); bool fFound = false; int nextI = 0; for (int i = 0; i < lc.GetItemCount(); i++) { if (lc.GetItemData (i) == curGID) { nextI = i + 1; break; } } if (nextI >= lc.GetItemCount() || 0==nextI) return 1; TServerCountedPtr cpNewsServer; // smart pointer for (; nextI < lc.GetItemCount(); nextI++) { int gid = lc.GetItemData (nextI); BOOL fUseLock; TNewsGroup * pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG); if (pNG) { if (pNG->QueryExistArticle (eQuery)) { *pGroupID = gid; return 0; } } } return 1; // no matching group found } BOOL CNewsView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Add your specialized code here and/or call the base class cs.style &= ~(LVS_ICON | LVS_SMALLICON | LVS_LIST); cs.style |= LVS_REPORT | LVS_NOSORTHEADER | LVS_SORTASCENDING | LVS_SHOWSELALWAYS; return BASE_CLASS::PreCreateWindow(cs); } // ------------------------------------------------------------------------ int CNewsView::AddStringWithData (const CString & groupName, LONG lGroupID, int * pIdxAt /* =NULL */) { CListCtrl & lc = GetListCtrl(); int idx; LVITEM lvi; ZeroMemory (&lvi, sizeof(lvi)); lvi.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; lvi.iItem = lc.GetItemCount(); lvi.iSubItem = 0; lvi.iImage = I_IMAGECALLBACK; lvi.pszText = LPTSTR(LPCTSTR(groupName)); // lvi.state |= INDEXTOOVERLAYMASK(1); // lvi.stateMask = LVIS_OVERLAYMASK; lvi.lParam = lGroupID; if (-1 == (idx = lc.InsertItem ( &lvi))) return 1; //fail // local count, server count lc.SetItemText (idx, 1, LPSTR_TEXTCALLBACK); lc.SetItemText (idx, 2, LPSTR_TEXTCALLBACK); if (pIdxAt) *pIdxAt = idx; return 0; // success } // ------------------------------------------------------------------------ int CNewsView::SetOneSelection (int idx) { CListCtrl & lc = GetListCtrl(); // note: in case the SELCHANGE notification is hooked, do not // - turn off selection on all // - turn on selection on the index we want. (It may cause a // one-click group to re-open) for (int i = 0; i < lc.GetItemCount(); i++) { if (i == idx) { // select this guy lc.SetItemState (idx, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); } else { // deselect all lc.SetItemState (i, 0, LVIS_SELECTED | LVIS_FOCUSED); } } // this useful thing is provided by MFC lc.EnsureVisible (idx, TRUE /* fPartialOK */); // success return 0; } // --------------------------------------------------------------------- // called from OnCreate void CNewsView::SetupFont () { TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors (); COLORREF ngCR = pBackgrounds->GetNewsgroupBackground(); if (!gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG()) { CListCtrl &lc = GetListCtrl(); lc.SetBkColor ( pBackgrounds->GetNewsgroupBackground() ); lc.SetTextBkColor ( pBackgrounds->GetNewsgroupBackground() ); } ngCR = gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor(); GetListCtrl().SetTextColor (ngCR); if (0 == gpGlobalOptions->m_defNGFont.lfFaceName[0]) { // show this info in the config dialog box gpVariableFont->GetObject ( sizeof (LOGFONT), &gpGlobalOptions->m_defNGFont ); } if (m_font.m_hObject) { m_font.DeleteObject (); // i pray this does the detach m_font.m_hObject = NULL; } if (gpGlobalOptions->IsCustomNGFont()) m_font.CreateFontIndirect ( gpGlobalOptions->GetNewsgroupFont() ); else { // default to microplanet defined small font LOGFONT info; gpVariableFont->GetObject ( sizeof (info), &info ); m_font.CreateFontIndirect ( &info ); } SetFont ( &m_font ); } // -------------------------------------------------------------------------- void CNewsView::OnGetDisplayInfo(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO * pDispInfo = (LV_DISPINFO*)pNMHDR; if (!IsActiveServer()) { *pResult = 0; return; } LVITEM & lvi = pDispInfo->item; TServerCountedPtr cpNewsServer; TNewsGroup * pNG = 0; BOOL fUseLock; LONG gid = LONG(GetListCtrl().GetItemData (lvi.iItem)); TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG); if (fUseLock) { if (lvi.mask & LVIF_IMAGE) { switch (pNG->GetStorageOption()) { case TNewsGroup::kNothing: lvi.iImage = 0; break; case TNewsGroup::kHeadersOnly: lvi.iImage = 1; break; case TNewsGroup::kStoreBodies: lvi.iImage = 2; break; } if (pNG->IsSampled ()) lvi.iImage += 3; } if (lvi.mask & LVIF_STATE) { if (!pNG->IsActiveGroup()) lvi.state |= INDEXTOOVERLAYMASK(1); } if (lvi.mask & LVIF_TEXT) { int iLocalNew, iServerNew, nTotal; pNG->FormatNewArticles ( iLocalNew, iServerNew , nTotal); if (1 == lvi.iSubItem) wsprintf (lvi.pszText, "%d", iLocalNew); else if (2 == lvi.iSubItem) wsprintf (lvi.pszText, "%d", iServerNew); // data eventuall is displayed in status bar pane if (GetCurNewsGroupID() == gid) gpUserDisplay->SetCountTotal ( nTotal ); } } *pResult = 0; } /////////////////////////////////////////////////////////////////////////// // Depends on user preference - single click/selchange opens a newsgroup // void CNewsView::OnClick (NMHDR* pNMHDR, LRESULT* pResult) { //TRACE0("On Click\n"); if (gpGlobalOptions->GetRegUI()->GetOneClickGroup() && (1 == GetListCtrl().GetSelectedCount())) { // turn off delayed activation. Actually this is futile, since // NM_ITEMCHANGE will start the timer again stop_selchange_timer(); AddOneClickGroupInterference(); PostMessage (WMU_SELCHANGE_OPEN); } *pResult = 0; } /////////////////////////////////////////////////////////////////////////// void CNewsView::AddOneClickGroupInterference () { if (gpGlobalOptions->GetRegUI()->GetOneClickGroup()) { m_iOneClickInterference ++; } } /////////////////////////////////////////////////////////////////////////// // Substitute for LBN_SELCHANGE, // void CNewsView::OnItemChanged (NMHDR* pNMHDR, LRESULT* pResult) { *pResult = 1; LPNMLISTVIEW pnmlv = (LPNMLISTVIEW) pNMHDR; BOOL fNewSelect = (pnmlv->uNewState & LVIS_SELECTED); BOOL fOldSelect = (pnmlv->uOldState & LVIS_SELECTED); if ( fNewSelect && !fOldSelect ) { //TRACE0("OnItemChanged\n"); if (gpGlobalOptions->GetRegUI()->GetOneClickGroup() && (1 == GetListCtrl().GetSelectedCount())) { if (m_iOneClickInterference > 0) { *pResult = 0; // do not start timer! --m_iOneClickInterference; } else { // this will pop unless: // a: another selchange comes // b: this turns out to be a right click // start_selchange_timer (); // OnTimer will call // PostMessage (WMU_SELCHANGE_OPEN); // 5-25-96 Rather than calling OpenNewsgroup() directly, // post a message to myself. That way the processing // can finish before we start the big fat OpenNewsgroup function *pResult = 0; } } } } /////////////////////////////////////////////////////////////////////////// void CNewsView::OnReturn(NMHDR* pNMHDR, LRESULT* pResult) { // We got an VK_RETURN, so open the newsgroup OpenNewsgroup ( kFetchOnZero, kPreferredFilter ); *pResult = 0; } // ------------------------------------------------------------------------ void CNewsView::OnRclick(NMHDR* pNMHDR, LRESULT* pResult) { // seems to set selection on Right click // this is so we can right click on a newsgroup, an put selection on it // with out actually opening the newsgroup via 1-click stop_selchange_timer (); //TRACE("Rclik stopped selchange action\n"); *pResult = 0; } /////////////////////////////////////////////////////////////////////////// // Depends on user preference - double click opens a newsgroup // void CNewsView::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult) { if (FALSE == gpGlobalOptions->GetRegUI()->GetOneClickGroup()) OpenNewsgroup( kFetchOnZero, kPreferredFilter ); *pResult = 0; } // ------------------------------------------------------------------------ void CNewsView::RedrawByGroupID (int iGroupID) { CListCtrl & lc = GetListCtrl(); RECT rct; int n = lc.GetItemCount(); for (--n; n >= 0; --n) { if (iGroupID == (int) lc.GetItemData (n)) { lc.GetItemRect (n, &rct, LVIR_BOUNDS); // we only need to redraw the counters InvalidateRect (&rct); break; } } } // ------------------------------------------------------------------------ void CNewsView::SaveColumnSettings() { SaveColumnSettingsTo (m_fTrackZoom ? "NGPaneZ" : "NGPane"); } // ------------------------------------------------------------------------ void CNewsView::SaveColumnSettingsTo (const CString & strLabel) { TRegUI* pRegUI = gpGlobalOptions->GetRegUI(); int riWidths[3]; riWidths[0] = GetListCtrl().GetColumnWidth (0); riWidths[1] = GetListCtrl().GetColumnWidth (1); riWidths[2] = GetListCtrl().GetColumnWidth (2); pRegUI->SaveUtilHeaders(strLabel, riWidths, ELEM(riWidths)); } // ------------------------------------------------------------------------ // tnews3md.cpp does the real work. Each active view must have a // handler for this // void CNewsView::OnUpdateArticleMore (CCmdUI* pCmdUI) { CWnd* pMdiChild = ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame(); BOOL fOK = ((TNews3MDIChildWnd*) pMdiChild)->CanArticleMore(); pCmdUI->Enable (fOK); } // ------------------------------------------------------------------------ BOOL CNewsView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { // let the mdi-child decide which pane will handle this CWnd* pMdiChild = ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame(); if (!pMdiChild) return FALSE; if (((TNews3MDIChildWnd*) pMdiChild)->handleMouseWheel(nFlags, zDelta, pt)) return TRUE; else return handleMouseWheel (nFlags, zDelta, pt); } // ------------------------------------------------------------------------ // called from MDI child BOOL CNewsView::handleMouseWheel(UINT nFlags, short zDelta, CPoint pt) { return BASE_CLASS::OnMouseWheel (nFlags, zDelta, pt); } // ------------------------------------------------------------------------ // zoom mode has its own set of column widths void CNewsView::handle_zoom (bool fZoom, CObject* pHint) { int riWidths[3]; bool fApply = false; TRegUI* pRegUI = gpGlobalOptions->GetRegUI(); if (fZoom) { if (pHint == this) { // The roles are the same, but the widths can be different // save off normal SaveColumnSettings (); if (0 != pRegUI->LoadUtilHeaders("NGPaneZ", riWidths, ELEM(riWidths))) return; fApply = true; m_fTrackZoom = true; // passive variable, as a convenienence } } else { TUnZoomHintInfo * pUnZoom = static_cast<TUnZoomHintInfo *>(pHint); if (pUnZoom->m_pTravelView == this) { m_fTrackZoom = false; // save zoomed SaveColumnSettingsTo ("NGPaneZ"); // load Normal if (0 != pRegUI->LoadUtilHeaders("NGPane", riWidths, ELEM(riWidths))) return; fApply = true; } } if (fApply) { GetListCtrl().SetColumnWidth (0, riWidths[0]); GetListCtrl().SetColumnWidth (1, riWidths[1]); GetListCtrl().SetColumnWidth (2, riWidths[2]); } } // pCmdUI for ID_GETTAGGED_FOR_GROUPS void CNewsView::OnUpdateGettaggedForgroups(CCmdUI* pCmdUI) { pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ()); } // ---------------------------------------------------------- // Retrieve Tagged articles only for the selected groups void CNewsView::OnGettaggedForgroups() { // holds a collection of (groupID, name) pairs CPtrArray vecPairs; int sel = 0; // get info on multisel if (multisel_get (&vecPairs, &sel)) return; int tot = vecPairs.GetSize(); // build up CDWordArray that only contains GroupIDs CDWordArray vecIDs; for (int i = 0; i < tot; i++) { TGroupIDPair* pPair = static_cast<TGroupIDPair*>(vecPairs[i]); vecIDs.Add (pPair->id); } FreeGroupIDPairs (&vecPairs); TServerCountedPtr cpServer; cpServer->GetPersistentTags().RetrieveTagged (false, vecIDs); } // ------------------------------------------------------------------------- BOOL CNewsView::PreTranslateMessage(MSG* pMsg) { if (::IsWindow (m_sToolTips.m_hWnd) && pMsg->hwnd == m_hWnd) { switch (pMsg->message) { case WM_LBUTTONDOWN: case WM_MOUSEMOVE: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONUP: m_sToolTips.RelayEvent (pMsg); break; } } return BASE_CLASS::PreTranslateMessage(pMsg); } // ------------------------------------------------------------------------- void CNewsView::OnMouseMove(UINT nFlags, CPoint point) { if (!(nFlags & MK_LBUTTON) || 0 == GetListCtrl().GetSelectedCount ()) { HandleToolTips (point); BASE_CLASS::OnMouseMove (nFlags, point); return; } BASE_CLASS::OnMouseMove(nFlags, point); } // ------------------------------------------------------------------------- BOOL CNewsView::OnNeedText (UINT, NMHDR *pNMHdr, LRESULT *) { // make sure the cursor is in the client area, because the mainframe also // wants these messages to provide tooltips for the toolbar CPoint sCursorPoint; VERIFY (::GetCursorPos (&sCursorPoint)); ScreenToClient (&sCursorPoint); CRect sClientRect; GetClientRect (&sClientRect); if (sClientRect.PtInRect (sCursorPoint)) { TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *) pNMHdr; pTTT->lpszText = (LPTSTR)(LPCTSTR) m_strToolTip; return TRUE; } return FALSE; } // ------------------------------------------------------------------------- void CNewsView::HandleToolTips (CPoint &point) { static bool fDisplayed = false; static int iDisplayedIndex; if (!::IsWindow (m_sToolTips.m_hWnd)) return; // get index of item under mouse int iIndex = GetListCtrl().HitTest ( point ); if (fDisplayed) { if (iIndex != iDisplayedIndex) { m_sToolTips.Activate (FALSE); m_strToolTip.Empty(); fDisplayed = false; } } if (!fDisplayed && iIndex >= 0) { try { TServerCountedPtr cpNewsServer; TNewsGroup * pNG = 0; BOOL fUseLock; LONG gid = LONG(GetListCtrl().GetItemData (iIndex)); TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG); if (fUseLock) { int nNewHdrs, nServer, nTotalHdrs; pNG->FormatNewArticles ( nNewHdrs, nServer, nTotalHdrs ); m_strToolTip.Format ("%s\nLocal Unread: %d\nLocal Total: %d\nServer: %d", GetListCtrl().GetItemText (iIndex, 0), nNewHdrs, nTotalHdrs, nServer ); } else m_strToolTip = GetListCtrl().GetItemText (iIndex, 0); } catch(...) { m_strToolTip.Empty(); } m_sToolTips.Activate (TRUE); iDisplayedIndex = iIndex; fDisplayed = true; } } // ------------------------------------------------------------------------- void CNewsView::start_selchange_timer () { stop_selchange_timer (); m_hSelchangeTimer = SetTimer (CNewsView::idSelchangeTimer, 333, NULL); } // ------------------------------------------------------------------------- void CNewsView::stop_selchange_timer () { // kill any timer currently running if (m_hSelchangeTimer) KillTimer (m_hSelchangeTimer); m_hSelchangeTimer = 0; } // ------------------------------------------------------------------------- int CNewsView::GetPreferredFilter (TNewsGroup * pNG) { int iWhatFilter = pNG->GetFilterID(); if (0 == iWhatFilter) { TAllViewFilter * pAllFilters = gpStore->GetAllViewFilters(); iWhatFilter = pAllFilters->GetGlobalDefFilterID(); } return iWhatFilter; }
28.222278
152
0.61866
taviso
f98a0cdf5f2a3eee6a87ac19dbb2e18e2198ddcd
1,283
cpp
C++
Tree/BalancedTree/BalancedTree.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Tree/BalancedTree/BalancedTree.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Tree/BalancedTree/BalancedTree.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. Constraints: 1<= N <= 10^4 Approach: To check if a tree is height-balanced, get the height of left and right subtrees. Return true if difference between heights is not more than 1 and left and right subtrees are balanced, otherwise return false. Calculate the height in the same recursion rather than calling a height() function separately. Time complexity – O(n) */ bool isBalancedUtil(Node *root, int *height) { int leftHeight = 0, rightHeight = 0; bool leftBalanced = 0, rightBalanced = 0; if(root == NULL) { *height = 0; return 1; } leftBalanced = isBalancedUtil(root->left, &leftHeight); rightBalanced = isBalancedUtil(root->right, &rightHeight); *height = max(leftHeight,rightHeight) + 1; if( abs(leftHeight - rightHeight) >= 2 || !leftBalanced || !rightBalanced) return 0; return 1; } // This function should return tree if passed tree // is balanced, else false. bool isBalanced(Node *root) { int height = 0; return isBalancedUtil(root,&height); }
27.891304
163
0.681216
PrachieNaik
f98b56f403871a3056dd8284deee2b49b92ca23d
4,718
cpp
C++
src/model_loading/model.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/model_loading/model.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/model_loading/model.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
// // model.cpp // // Created by Clsrfish on 08/10/2020 // #include "./model.h" #include "../gl/gl_utils.h" model_loading::Model::Model(const std::string &modelPath) { loadModel(modelPath); } void model_loading::Model::Draw(const Shader &shader) { for (unsigned int i = 0; i < Meshes.size(); i++) { Meshes[i].Draw(shader); } } void model_loading::Model::loadModel(const std::string &modelPath) { Assimp::Importer importer; const aiScene *scene = importer.ReadFile(modelPath.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs); if (scene == nullptr || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || scene->mRootNode == nullptr) { LOG_E("ASSMIP::%s", importer.GetErrorString()); return; } directory = modelPath.substr(0, modelPath.find_last_of('/')); processNode(scene->mRootNode, scene); } void model_loading::Model::processNode(aiNode *node, const aiScene *scene) { for (unsigned int i = 0; i < node->mNumMeshes; i++) { aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; Meshes.push_back(processMesh(mesh, scene)); } for (unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } model_loading::Mesh model_loading::Model::processMesh(aiMesh *mesh, const aiScene *scene) { std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<Texture> textures; for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; glm::vec3 pos; pos.x = mesh->mVertices[i].x; pos.y = mesh->mVertices[i].y; pos.z = mesh->mVertices[i].z; vertex.Position = pos; glm::vec3 normal; normal.x = mesh->mNormals[i].x; normal.y = mesh->mNormals[i].y; normal.z = mesh->mNormals[i].z; vertex.Normal = normal; if (mesh->mTextureCoords[0]) { glm::vec2 texCoord; texCoord.x = mesh->mTextureCoords[0][i].x; texCoord.y = mesh->mTextureCoords[0][i].y; vertex.TexCoords = texCoord; } else { vertex.TexCoords = glm::vec2(0.0f, 0.0f); } vertices.push_back(vertex); } for (unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (unsigned int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } if (mesh->mMaterialIndex >= 0) { // process all materials aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; // 1. diffuse maps std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "u_TextureDiffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // 2. specular maps std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "u_TextureSpecular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // 3. normal maps std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_NORMALS, "u_TextureNormal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // 4. height maps std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "u_TextureHeight"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); } return model_loading::Mesh(vertices, indices, textures); } std::vector<model_loading::Texture> model_loading::Model::loadMaterialTextures(aiMaterial *material, aiTextureType texType, const std::string &typeName) { std::vector<model_loading::Texture> textures; for (unsigned int i = 0; i < material->GetTextureCount(texType); ++i) { aiString str; material->GetTexture(texType, i, &str); auto file = std::string(str.C_Str()); bool useCache = false; for (unsigned int j = 0; j < loadedTextures.size(); j++) { if (file.compare(loadedTextures[j].path) == 0) { LOG_I("Texture loaded preciously: %s", file.c_str()); textures.push_back(loadedTextures[j]); useCache = true; break; } } if (!useCache) { model_loading::Texture texture; texture.id = TextureFromFile(file, directory); texture.type = typeName; texture.path = file; textures.push_back(texture); loadedTextures.push_back(texture); } } return textures; }
31.453333
152
0.602798
clsrfish
f98fc6fe889504295cefaf5aa7436bc071f81e98
7,042
hpp
C++
src/Utilities/NMatrix/NLine.hpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
src/Utilities/NMatrix/NLine.hpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
src/Utilities/NMatrix/NLine.hpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
/** * \file NLine.hpp * \author fcaillaud * \version 1.0 * \date 2 Avril 2014 * \brief Fichier décrivant la classe NLine. * \details Classe utilisée pour représenter une ligne ou colonne de matrice (plus ou moins un vecteur). * \todo Réfléchir à une meilleure approche pour toute la classe. */ #ifndef NMATRIX_NLINE #define NMATRIX_NLINE #include <vector> #include <stdlib.h> /** * \namespace alg * \brief Nom de domaine tertiaire, partie utilitaire. * \todo Migrer vers le namespace gu. */ namespace alg { /** * \enum LineState * \brief Type de vecteur, soit ligne, soit colonne. */ enum LineState { LS_ROW, /*!< Vecteur de type ligne. */ LS_COLUMN /*!< Vecteur de type colonne. */ }; /** * \class NLine * \brief Classe représentant un vecteur de matrice (soit ligne, soit colonne). * \details Classe template avec le type Mtype qui sera le type des valeurs contenues dans le vecteur. */ template<class MType = double> class NLine { public: /** * Constructeur par défaut. * \details Construit un vecteur de taille 0. */ NLine(): mSize(), mLine(), mHasToBeAllDeleted(false) { //EMPTY } /** * Constructeur paramétré. * \param pSize La taille du vecteur voulu. * \details Construit un vecteur de taille pSize. */ NLine(unsigned int pSize): mSize(pSize), mLine(new MType *[pSize]), mHasToBeAllDeleted(true) { for(unsigned int i = 0; i < mSize; ++i) mLine[i] = new MType(); } /** * Constructeur par copie. * \param pLine Le vecteur à copier. */ NLine(const NLine & pLine): mSize(pLine.mSize), mLine(new MType *[pLine.mSize]), mHasToBeAllDeleted(false) { for(unsigned int i = 0; i < mSize; ++i) mLine[i] = pLine.mLine[i]; } /** * Constructeur par copie. * \param pMatrixData La matrice cotenant le vecteur à copier. * \param pInd L'indice de la ligne ou de la colonne dans la matrice. * \param pSize Les dimensions de la matrice à copier. * \param pLineState Le type de vecteur à copier (ligne ou colonne). * \todo Enlever pSize, pas besoin, utiliser les dimensions de la matrice à copier. */ NLine(MType * pMatrixData, int pInd, std::pair<unsigned int, unsigned int> pSize, LineState pLineState): mSize(), mLine(), mHasToBeAllDeleted(false) { if(pLineState == LS_ROW){ mSize = pSize.first; mLine = new MType *[mSize]; for(unsigned int i = 0; i < mSize; ++i) mLine[i] = pMatrixData + (pInd * pSize.first + i); }else{ mSize = pSize.second; mLine = new MType *[mSize]; for(unsigned int i = 0; i < mSize; ++i) mLine[i] = pMatrixData + (i * pSize.first + pInd); } } /** * Destructeur * \details Si mHasToBeAllDeleted est à false, il n'efface pas les pointeurs * sur les valeurs stockées. */ ~NLine() { if(mHasToBeAllDeleted) for(unsigned int i = 0; i < mSize; ++i) delete mLine[i]; delete [] mLine; } /** * Récupération de la valeur à l'indice souhaité. * \param pInd L'indice de la valeur à récupérer dans le vecteur. * \return La valeur à l'indice pInd dans le vecteur. */ const MType GetAt(int pInd) { return *mLine[pInd]; } /** * Change la valeur à l'indice souhaité. * \param pInd L'indice de la valeur à changer dans le vecteur. * \param pData La nouvelle valeur. */ void SetAt(int pInd, MType pData) { *mLine[pInd] = pData; } /** * Récupération de la valeur à l'indice souhaité. * \param pInd L'indice de la valeur à récupérer dans le vecteur. * \return La valeur à l'indice pInd dans le vecteur. */ MType operator[] (int pInd) { return *mLine[pInd]; } /** * Addition de deux vecteurs. * \param pLine L'autre vecteur à additionner. * \return Le vecteur résultant de l'addition. * \details Additionne valeur par valeur. */ NLine operator+ (NLine pLine) { if(mSize != pLine.mSize){ std::cerr << "ERROR : In NLine +, the addition between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl; exit(-1); } NLine<MType> vLine(mSize); for(unsigned int i = 0; i < mSize; ++i) *(vLine.mLine[i]) = *mLine[i] + pLine[i]; return vLine; } /** * Soustraction de deux vecteurs. * \param pLine Le vecteur que l'on soustrait. * \return Le vecteur résultant de la soustraction. * \details Soustrait valeur par valeur. */ NLine operator- (NLine pLine) { if(mSize != pLine.mSize){ std::cerr << "ERROR : In NLine -, the substraction between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl; exit(-1); } NLine<MType> vLine(mSize); for(unsigned int i = 0; i < mSize; ++i) *(vLine.mLine[i]) = *mLine[i] - pLine[i]; return vLine; } /** * Multiplication de deux vecteurs. * \param pLine L'autre vecteur à multiplier. * \return Le vecteur résultant de la multiplication. * \details Multiplie valeur par valeur. */ double operator* (NLine pLine) { unsigned int vSize = pLine.mSize; double vRes = 0.0; if(mSize != vSize){ std::cerr << "ERROR : In NLine *, the substraction between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl; exit(-1); } for(unsigned int i = 0; i < vSize; ++i) vRes += (*mLine[i]) * (*(pLine.mLine[i])); return vRes; } /** * Récupère la taille du vecteur. * \return La taille du vecteur. * \todo Changer le nom de la fonction pour GetSize(), plus cohérent. */ unsigned int Size() { return mSize; } /** * Récupère le pointeur sur les éléments du vecteur. * \return Le pointeur sur les éléments du vecteur. */ MType ** SData() { return mLine; } /** * Ajout d'un pointeur sur valeur dans le vecteur. * \param pData Le pointeur sur valeur à ajouter. * \details Le vecteur s'agrandit et sa taille s'incrémente. */ void Add(MType * pData) { mSize++; mLine = (MType *) realloc(mLine, mSize * sizeof(MType *)); mLine[mSize - 1] = pData; } /** * Affichage du vecteur. * \details Affiche sur la sortie standard les valeurs du vecteur. * \todo Utiliser Msg (dans les autres fonction également) ET * différencier l'affichage en colonne et en ligne. */ void Print() { for(unsigned int i = 0; i < mSize; ++i) std::cout << *mLine[i] << " "; } private: /** * \brief Taille du vecteur. */ unsigned int mSize; /** * \brief Tableau des pointeurs sur les valeurs. */ MType ** mLine; /** * \brief État de suppression des pointeurs sur les valeurs. */ bool mHasToBeAllDeleted; }; } #endif
24.883392
164
0.598268
fcaillaud
f9950c4c127eed8eb765a4f79dff18707a5a927e
1,141
cpp
C++
libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 <sge/charconv/fcppt_string_to_utf8.hpp> #include <sge/charconv/fcppt_string_to_utf8_file.hpp> #include <sge/charconv/utf8_string.hpp> #include <fcppt/string.hpp> #include <fcppt/cast/size.hpp> #include <fcppt/cast/to_char_ptr.hpp> #include <fcppt/cast/to_signed.hpp> #include <fcppt/config/external_begin.hpp> #include <filesystem> #include <fstream> #include <ios> #include <fcppt/config/external_end.hpp> bool sge::charconv::fcppt_string_to_utf8_file( fcppt::string const &_string, std::filesystem::path const &_path) { std::ofstream file(_path); if (!file.is_open()) { return false; } sge::charconv::utf8_string const result(sge::charconv::fcppt_string_to_utf8(_string)); return !file.write( fcppt::cast::to_char_ptr<char const *>(result.c_str()), fcppt::cast::size<std::streamsize>(fcppt::cast::to_signed(result.size()))) .fail(); }
31.694444
92
0.69851
cpreh
f995a5ef4619ff65e37e0210dd58371372442922
158
cpp
C++
MathTools/Point.cpp
richardchien/math-tools-ios
956b77d91afd7bb78dd02a5027180de72d9d6a29
[ "MIT" ]
null
null
null
MathTools/Point.cpp
richardchien/math-tools-ios
956b77d91afd7bb78dd02a5027180de72d9d6a29
[ "MIT" ]
null
null
null
MathTools/Point.cpp
richardchien/math-tools-ios
956b77d91afd7bb78dd02a5027180de72d9d6a29
[ "MIT" ]
null
null
null
// // Point.cpp // MathTools // // Created by Richard Chien on 14-1-31. // Copyright (c) 2014年 Richard Chien. All rights reserved. // #include "Point.h"
15.8
59
0.64557
richardchien
f99ccbcf7cb99a16654eacebaf9f4850000193f9
1,233
cpp
C++
src/QBtAuxFunctions.cpp
ftylitak/QBluetoothZero
3e4a018a5e62705b62fa2cbc64a27c3f66059982
[ "Apache-2.0" ]
2
2018-02-05T13:22:49.000Z
2019-01-19T12:04:20.000Z
src/QBtAuxFunctions.cpp
ftylitak/QBluetoothZero
3e4a018a5e62705b62fa2cbc64a27c3f66059982
[ "Apache-2.0" ]
1
2018-02-04T18:37:50.000Z
2018-02-05T23:16:31.000Z
src/QBtAuxFunctions.cpp
ftylitak/QBluetoothZero
3e4a018a5e62705b62fa2cbc64a27c3f66059982
[ "Apache-2.0" ]
3
2018-05-24T02:35:43.000Z
2019-02-28T16:38:52.000Z
#include "QBtAuxFunctions.h" #ifdef Q_OS_WIN32 bool QBtAuxFunctions::InitBthSdk() { if ( sdkInitializationCounter == 0) /* not connected with BlueSoleil */ { if (Btsdk_Init() != BTSDK_OK) return false; if (Btsdk_IsBluetoothReady() == BTSDK_FALSE) Btsdk_StartBluetooth(); BTUINT16 discoveryFlags = BTSDK_CONNECTABLE | BTSDK_PAIRABLE | BTSDK_GENERAL_DISCOVERABLE; Btsdk_SetDiscoveryMode(discoveryFlags); Btsdk_SetLocalDeviceClass(BTSDK_COMPCLS_DESKTOP); } sdkInitializationCounter++; return true; } void QBtAuxFunctions::DeinitBthSdk() { if(Btsdk_IsSDKInitialized() && sdkInitializationCounter > 0) { sdkInitializationCounter--; if(sdkInitializationCounter == 0) Btsdk_Done(); } } BTDEVHDL QBtAuxFunctions::GetDeviceHandle(const QBtAddress& address) { //get device handle BTDEVHDL devHandle = BTSDK_INVALID_HANDLE; BTUINT8 btAddr [6]= {0}; QByteArray btAddrQt = address.toReversedByteArray(); memcpy(btAddr, btAddrQt.constData(), btAddrQt.size()); devHandle = Btsdk_GetRemoteDeviceHandle(btAddr); return devHandle; } #endif //WIN32
27.4
99
0.665856
ftylitak
f9a02a599df97e56a3b57d258939f6fc32e01d64
610
cpp
C++
source/343.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
2
2017-02-28T11:39:13.000Z
2019-12-07T17:23:20.000Z
source/343.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
source/343.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
// // 343.cpp // LeetCode // // Created by Narikbi on 23.02.17. // Copyright © 2017 app.leetcode.kz. All rights reserved. // #include <stdio.h> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <deque> #include <queue> #include <set> #include <map> #include <stack> #include <cmath> using namespace std; int integerBreak(int n) { vector <int> dp(n+1, 0); dp[1] = 0; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { dp[i] = max(dp[i], max(j, dp[j]) * max(i-j, dp[i-j])); } } return dp[n]; }
16.052632
66
0.539344
narikbi
f9a413b98940eca59f60296c27675bf0b29f1a73
1,456
cpp
C++
pico-cnn/layers/pooling/pooling.cpp
ekut-es/pico-cnn
18ef2ae0afd7ac9c0e18c293f2f2478a5f78c66c
[ "BSD-3-Clause" ]
43
2019-06-18T13:53:24.000Z
2021-12-24T17:37:56.000Z
pico-cnn/layers/pooling/pooling.cpp
ekut-es/pico-cnn
18ef2ae0afd7ac9c0e18c293f2f2478a5f78c66c
[ "BSD-3-Clause" ]
12
2020-06-01T00:54:37.000Z
2022-02-10T01:40:23.000Z
pico-cnn/layers/pooling/pooling.cpp
ekut-es/pico-cnn
18ef2ae0afd7ac9c0e18c293f2f2478a5f78c66c
[ "BSD-3-Clause" ]
6
2020-11-02T19:58:55.000Z
2021-12-24T17:38:02.000Z
#include "pooling.h" pico_cnn::naive::Pooling::Pooling(std::string name, uint32_t id, pico_cnn::op_type op, uint32_t *kernel_size, uint32_t *stride, uint32_t *padding) : Layer(name, id, op) { if (kernel_size) { kernel_size_ = new uint32_t[2](); std::memcpy(kernel_size_, kernel_size, 2 * sizeof(uint32_t)); } else { kernel_size_ = kernel_size; } if (stride) { stride_ = new uint32_t[2](); std::memcpy(stride_, stride, 2 * sizeof(uint32_t)); } else { stride_ = stride; } if (padding) { padding_ = new uint32_t[4](); std::memcpy(padding_, padding, 4 * sizeof(uint32_t)); } else { padding_ = padding; } } pico_cnn::naive::Pooling::~Pooling() { delete [] kernel_size_; delete [] stride_; delete [] padding_; } void pico_cnn::naive::Pooling::run(pico_cnn::naive::Tensor *input, pico_cnn::naive::Tensor *output) { if (input->num_dimensions() == 4 || input->num_dimensions() == 3) { Tensor *input_tensor; if (padding_) { input_tensor = input->expand_with_padding(padding_); } else { input_tensor = input; } this->pool(input_tensor, output); if (padding_) { delete input_tensor; } } else { PRINT_ERROR_AND_DIE("Not implemented for Tensor with num_dims: " << input->num_dimensions()); } }
26.962963
109
0.574176
ekut-es
f9a62c668e2250f899b7b3e209bda4e68f8183bc
2,605
cpp
C++
droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
#include "swarmAgentInterface.h" #include "RvizInteractiveMarkerDisplay.h" SwarmAgentInterface::SwarmAgentInterface(int idDrone_in) { idDrone = idDrone_in; return; } SwarmAgentInterface::~SwarmAgentInterface() { return; } void SwarmAgentInterface::open(ros::NodeHandle &nIn) { n = nIn; localizer_pose_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_POSE_SUBSCRIPTION, 1, &SwarmAgentInterface::localizerPoseCallback, this); mission_planner_mission_point_reference_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_TRAJECTORY_ABS_REF_CMD_SUBSCRIPTION, 1, &SwarmAgentInterface::missionPointCallback, this); trajectory_planner_trajectory_reference_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_TRAJECTORY_ABS_REF_CMD_SUBSCRIPTION, 1, &SwarmAgentInterface::trajectoryAbsRefCmdCallback, this); obstacle_processor_obstacle_list_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_OBSTACLE_LIST_SUBSCRIPTION, 1, &SwarmAgentInterface::obstacleListCallback, this); // this_drone_society_pose_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_SOCIETY_POSE_SUBSCRIPTION, 1, &SwarmAgentInterface::societyPoseSubCallback, this); return; } void SwarmAgentInterface::localizerPoseCallback(const droneMsgsROS::dronePose &pose_euler) { Drone.PoseCallback(pose_euler, idDrone); } void SwarmAgentInterface::missionPointCallback(const droneMsgsROS::dronePositionTrajectoryRefCommand &point) { if (idDrone == Drone.ActiveDroneId()) { Drone.MissionPointPubCallback(point, idDrone); } } void SwarmAgentInterface::trajectoryAbsRefCmdCallback(const droneMsgsROS::dronePositionTrajectoryRefCommand &trajectory) { if (idDrone == Drone.ActiveDroneId()) { Drone.TrajectoryPubCallback(trajectory, idDrone); } } void SwarmAgentInterface::obstacleListCallback(const droneMsgsROS::obstaclesTwoDim &obstacles) { //ROS_INFO("Drone ID %i", Drone.ActiveDroneId()); if (idDrone == Drone.ActiveDroneId()) { Drone.ObstaclesPubCallback(obstacles, idDrone); } } void SwarmAgentInterface::societyPoseSubCallback(const droneMsgsROS::societyPose::ConstPtr &msg) { //std::cout << "SwarmAgentInterface::societyPoseSubCallback drone:" << idDrone << std::endl; }
30.290698
250
0.761996
MorS25
f9a85337ac0427c6189842eb22ef8534aa49fb95
6,279
cpp
C++
MakeBuild/MakeBuild/CMakeFile.cpp
mooming/make_builder
e5aa68d4c922b3343cb032c0201126b9ed85ae37
[ "MIT" ]
1
2018-09-29T01:36:18.000Z
2018-09-29T01:36:18.000Z
MakeBuild/MakeBuild/CMakeFile.cpp
mooming/make_builder
e5aa68d4c922b3343cb032c0201126b9ed85ae37
[ "MIT" ]
null
null
null
MakeBuild/MakeBuild/CMakeFile.cpp
mooming/make_builder
e5aa68d4c922b3343cb032c0201126b9ed85ae37
[ "MIT" ]
null
null
null
// // CMakeFile.cpp // mbuild // // Created by mooming on 2016. 8. 15.. // // #include "CMakeFile.h" #include "StringUtil.h" #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; using namespace Builder; namespace { void AddFrameworks(ostream& os, string projName, const vector<string>& frameworks) { os << "if (APPLE)" << endl; os << "include_directories ( /System/Library/Frameworks )" << endl; os << "endif (APPLE)" << endl << endl; if (!frameworks.empty()) { for (const auto& element : frameworks) { if (Util::EqualsIgnoreCase(element, "opengl")) { os << "find_package (OpenGL)" << endl << endl; os << "if (OPENGL_FOUND)" << endl; os << "include_directories (${OPENGL_INCLUDE_DIR})" << endl; os << "target_link_libraries (" << projName << " ${OPENGL_gl_LIBRARY})" << endl; os << "endif (OPENGL_FOUND)" << endl << endl; os << "if (OPENGL_GLU_FOUND)" << endl; os << "target_link_libraries (" << projName << " ${OPENGL_glu_LIBRARY})" << endl; os << "endif (OPENGL_GLU_FOUND)" << endl << endl; } else { string libName = element; libName.append("_LIBRARY"); os << "find_library(" << libName << " " << element << ")" << endl << endl; os << "if (" << libName << ")" << endl; os << "target_link_libraries (" << projName << " ${" << libName << "})" << endl; os << "endif (" << libName << ")" << endl << endl; } } } } } namespace CMake { CMakeFile::CMakeFile(const Build& build, const ProjectDir& targetDir) : build(build), dir(targetDir) { } void CMakeFile::Make() { const BuildType buildType = dir.GetBuildType(); const char* basePath = "${CMAKE_SOURCE_DIR}"; using namespace Util; string filePath(dir.path); string projName(PathToName(dir.path)); filePath.append("/CMakeLists.txt"); cout << "Creating: " << filePath.c_str() << "(" << BuildTypeStr(buildType) << ")" << endl; ofstream ofs (filePath.c_str(), ofstream::out); ofs << "cmake_minimum_required (VERSION 2.6)" << endl; ofs << "project (" << projName << ")" << endl; ofs << endl; ofs << "if(CMAKE_COMPILER_IS_GNUCXX)" << endl; ofs << " set(CMAKE_CXX_FLAGS \"${ CMAKE_CXX_FLAGS } -Wall -Werror\")" << endl; ofs << "endif(CMAKE_COMPILER_IS_GNUCXX)" << endl; auto& definesList = dir.DefinitionsList(); if (!definesList.empty()) { ofs << "add_definitions ("; for (auto& def : definesList) { ofs << def << " "; } ofs << ")" << endl; } ofs << endl; ofs << "include_directories ("; ofs << " " << basePath << endl; ofs << " " << basePath << "/include" << endl; for (const auto& element : build.includeDirs) { ofs << " " << TranslatePath(element) << endl; } ofs << " )" << endl; ofs << endl; if (buildType != HEADER_ONLY) { ofs << "link_directories (" << basePath << "/lib)" << endl; ofs << endl; } ofs << endl; for (const auto& subDir : dir.ProjDirList()) { if (!subDir.SrcFileList().empty()) { ofs << "add_subdirectory (" << PathToName(subDir.path.c_str()) << ")" << endl; } } ofs << endl; switch(buildType) { case EXECUTABLE: ofs << "add_executable (" << projName.c_str() << endl; for (const auto& element : dir.SrcFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } for (const auto& element : dir.HeaderFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } ofs << ")" << endl << endl; AddFrameworks(ofs, projName, dir.FrameworkList()); ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/bin)" << endl; break; case STATIC_LIBRARY: ofs << "add_library (" << projName.c_str() << " STATIC " << endl; for (const auto& element : dir.SrcFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } for (const auto& element : dir.HeaderFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } ofs << ")" << endl << endl; AddFrameworks(ofs, projName, dir.FrameworkList()); ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/lib)" << endl; break; case SHARED_LIBRARY: ofs << "add_library (" << projName.c_str() << " SHARED " << endl; for (const auto& element : dir.SrcFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } for (const auto& element : dir.HeaderFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } ofs << ")" << endl << endl; AddFrameworks(ofs, projName, dir.FrameworkList()); ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/bin)" << endl; break; case HEADER_ONLY: ofs << "add_library (" << projName.c_str() << " INTERFACE)" << endl; ofs << "target_sources (" << projName.c_str() << " INTERFACE " << endl; for (const auto& element : dir.HeaderFileList()) { ofs << " " << PathToName(element.path.c_str()) << endl; } ofs << ")" << endl; break; default: break; }; ofs << endl << endl; auto& dependencyList = dir.DependencyList(); auto& libList = dir.LibraryList(); if (!dependencyList.empty() || !libList.empty()) { ofs << "target_link_libraries (" << projName; for (const auto& dependency : dependencyList) { if (dependency.empty()) continue; ofs << " " << dependency; } for (const auto& library : libList) { if (library.empty()) continue; ofs << " " << library; } ofs << ")" << endl << endl; for (const auto& dependency : dependencyList) { if (dependency.empty()) continue; ofs << "add_dependencies (" << projName.c_str() << " " << dependency << ")" << endl; } ofs << endl; } ofs << endl; ofs.close(); } string CMakeFile::TranslatePath(string path) { using namespace Util; path = TrimPath(path); if (StartsWithIgnoreCase(path, build.baseDir.path)) { string newPath = string("${CMAKE_SOURCE_DIR}"); newPath.append(path.substr(build.baseDir.path.length())); return newPath; } return path; } }
23.965649
93
0.563306
mooming