blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
0a9301789a18d0eeea1a3a3844e0c78a5c30c61d
C++
jezhiggins/stiX
/c++/chapter_3/6_archive/archive_file.cpp
UTF-8
1,722
2.921875
3
[ "MIT" ]
permissive
#include "archive_file.hpp" #include <iostream> #include <stdexcept> #include <algorithm> std::string const HEADER_TAG = "-h- "; stiX::archive_file stiX::parse_header(std::string const& header) { if (header.find(HEADER_TAG) != 0) throw std::logic_error("Not a header line"); auto lastspace = header.find_last_of(' '); auto namelength = lastspace-4; auto name = header.substr(4, namelength); auto size = header.substr(lastspace+1); return { name, std::stoul(size) }; } // parse_header std::ostream& operator<<(std::ostream& os, stiX::archive_file const& af) { os << HEADER_TAG << af.name << ' ' << af.filesize << '\n'; return os; } // operator<< void stiX::skip_entry( std::istream& archive_in, stiX::archive_file const& header ) { archive_in.seekg(header.filesize, std::ios_base::cur); } // skip_entry bool stiX::of_interest( std::vector<std::string> const& files_to_remove, stiX::archive_file const& name ) { return std::find(files_to_remove.begin(), files_to_remove.end(), name.name) != files_to_remove.end(); } // of_interest void stiX::copy_contents( std::istream& archive_in, stiX::archive_file const& header, std::ostream& archive_out ) { std::copy_n( std::istreambuf_iterator<char>(archive_in), header.filesize, std::ostreambuf_iterator<char>(archive_out) ); archive_in.get(); } // copy_contents void stiX::read_archive( std::istream& archive_in, stiX::ArchiveReader reader ) { archive_in.peek(); while(archive_in && !archive_in.eof()) { auto header_line = getline(archive_in); auto header = parse_header(header_line); reader(archive_in, header); archive_in.peek(); } // while ... } // read_archive
true
e5dd5a0922c34d62025d787e7daf4137fd1d7254
C++
ji-one/algorithm-study
/baekjoon_study_wook/bfs,dfs 탐색/13549_dw.cpp
UTF-8
953
2.9375
3
[]
no_license
// 13549 숨바꼭질 3 #include <iostream> #include <queue> using namespace std; int n,k; int visit[100001]; int pos[100001]; bool isInside(int x) { return x>=0 && x<=100000; } int bfs() { priority_queue<pair<int, int> > pq; pq.push({0,n}); visit[n] = 1; while(!pq.empty()) { int ct = -pq.top().first; int cx = pq.top().second; pq.pop(); if(cx == k) { return ct; } if(isInside(cx-1) && visit[cx-1] == 0) { pq.push({-(ct+1), cx-1}); visit[cx-1] = ct+1; } if(isInside(cx+1) && visit[cx+1] == 0) { pq.push({-(ct+1), cx+1}); visit[cx+1] = ct+1; } if(cx != 0 && isInside(cx*2) && (visit[cx*2] == 0 || visit[cx*2] > ct)) { pq.push({-ct, cx*2}); visit[cx*2] = ct; } } } int main(){ cin >> n >> k; cout << bfs(); return 0; }
true
42dba5154616c5b5ae6a796ec9346c4cc9a04ac3
C++
aminnezarat/build
/Hardwrae_Architecture.h
UTF-8
659
2.515625
3
[]
no_license
/** @file Hardware_Architecture.h * Definition of enum for Hardware and architecture type of kernel arguments. */ #pragma once namespace ktt { /** @enum ArgumentDataType * Enum for hardware type and architecture model for DLNezarat searcher */ //enum class Hardware_Architecture //{ enum HARDWARE { Vega56 = 1, TitanV, P100, Mic5110P, K20, Gtx2080Ti, Gtx1070, Gtx750, Gtx680 }; enum ARCHITECTURE { Vega56 = 7, //Radeoon TitanV = 5, //Volta P100 = 2, //Pascal Mic5110P = 6, //XeonPhi K20 = 4, //Kepler Gtx2080Ti = 3, //Turing Gtx1070 = 2, //Pascal Gtx750 = 1, //Maxwell Gtx680 = 4 //Kepler }; } // namespace ktt
true
075eb5aeedbfd63284865b3139533729a5f7207a
C++
hallgeirl/cse272-raytracer
/Texture.h
UTF-8
5,788
3.015625
3
[]
no_license
#ifndef _TEXTURE_H_ #define _TEXTURE_H_ #define NO_FREEIMAGE #include "Phong.h" #include <Perlin.h> #include <string> #include <iostream> #include <vector> #include <list> #include <stdlib.h> #ifndef NO_FREEIMAGE #include <FreeImage.h> #endif #include <Worley.h> #include <cstdlib> #include <cmath> #include "Utility.h" //Generate turbulent perlin noise at (x,y,z). //The returned number is between -1 and 1. //frequencyIncrease indicates how quickly the frequency increases over multiple turbulence iterations. //amplitudeFalloff indicates how quickly the amplitude of the higher frequency noise values decrease. //iterations determines the number of iterations to use for turbulence. inline float generateNoise(float x, float y, float z, float initialFrequency, float frequencyIncrease, float amplitudeFalloff, int iterations) { float amplitude = 1; float frequency = initialFrequency; float value = 0; float max_val = 0; for (int i = 0; i < iterations; i++) { value += amplitude * PerlinNoise::noise(x*frequency, y*frequency, z*frequency); max_val += amplitude; frequency *= frequencyIncrease; amplitude *= amplitudeFalloff; } return value/max_val; } //Used for the grid in cellular textures typedef struct gridcell_s { std::vector<tex_coord2d_t> points; void addPoint(tex_coord2d_t point) { points.push_back(point); } } gridcell_t; class Grid { public: Grid(int gridWidth, int gridHeight); void addPoint(tex_coord2d_t point); const std::vector<tex_coord2d_t> &getPoints(int cellI, int cellJ) const { return m_grid[cellI][cellJ].points; } int getWidth() const { return m_gridWidth; } int getHeight() const { return m_gridHeight; } private: gridcell_t ** m_grid; int m_gridWidth, m_gridHeight; }; class Texture { public: virtual float bumpHeight2D(const tex_coord2d_t & coords) const { return 0; } virtual float bumpHeight3D(const tex_coord3d_t & coords) const { return 0; } virtual LookupCoordinates GetLookupCoordinates() const = 0; virtual Vector3 lookup2D(const tex_coord2d_t & coords) const { return Vector3(0,0,0); } // Look up the color value for a specified position virtual Vector3 lookup3D(const tex_coord3d_t & coords) const { return Vector3(0,0,0); } // For 3D textures virtual Vector3 lowresLookup2D(const tex_coord2d_t & coords) const { return lookup2D(coords); } virtual Vector3 lowresLookup3D(const tex_coord2d_t & coords) const { return lookup2D(coords); } }; class Texture2D : public Texture { public: virtual LookupCoordinates GetLookupCoordinates() const {return UV; } }; class Texture3D : public Texture { public: virtual LookupCoordinates GetLookupCoordinates() const {return UVW; } }; class CellularTexture2D : public Texture2D { public: CellularTexture2D(int points, int gridWidth, int gridHeight); float * getClosestDistances(const tex_coord2d_t &point, int n) const; //Get the n closest distances from a given point //Populate the grid with grid points. Override to control distribution of points. virtual void populateGrid(int points); //Typically, this function combines the values gotten from getClosestDistances() and maps it to a color value. virtual Vector3 lookup2D(const tex_coord2d_t & coords) const; protected: std::vector<tex_coord2d_t> m_points; Grid m_grid; }; class CheckerBoardTexture : public Texture2D { protected: float m_scale; Vector3 m_color1, m_color2; public: CheckerBoardTexture(Vector3 color1 = Vector3(1), Vector3 color2 = Vector3(0), float scale=1) { m_color1 = color1; m_color2 = color2; m_scale = scale; } virtual Vector3 lookup2D(const tex_coord2d_t & coords) const { float u = std::abs(m_scale*(coords.u)); float v = std::abs(m_scale*(coords.v)); if (coords.u < 0) u += m_scale; if (coords.v < 0) v += m_scale; return ((int)((int)u+(int)v) % 2 == 0 ? m_color1 : m_color2); } }; #ifndef NO_FREEIMAGE //Texture loaded from a file class LoadedTexture : public Texture2D { public: LoadedTexture(std::string filename); ~LoadedTexture(); Vector3 lookup(const tex_coord2d_t & coords, bool lowres) const; Vector3 lookup2D(const tex_coord2d_t & coords) const { return lookup(coords, false); } Vector3 lowresLookup2D(const tex_coord2d_t & coords) const { return lookup(coords, true); } protected: static Vector3 getPixel(FIBITMAP* bm, int x, int y); //Get the tonemapped pixel static void setPixel(FIBITMAP* bm, Vector3& value, int x, int y); float tonemapValue(float val) const; FIBITMAP* m_bitmap; FIBITMAP* m_lowres; static const int LOWRES_WIDTH = 24; float m_maxIntensity; }; #endif //Shading model that also does textures class TexturedPhong : public Phong { public: TexturedPhong(Texture * texture, const Vector3 & specularColor = Vector3(0), //Reflectivity for each color. 1 is fully reflective, 0 is fully non-reflective. const Vector3 & transparentColor = Vector3(0), //Transparency for each color. 1 is fully transparent (refracting according to refractIndex), 0 is fully opaque. const float shinyness = 1.0f, const float refractIndex = 1); virtual LookupCoordinates GetLookupCoordinates() const { return m_texture->GetLookupCoordinates(); } virtual Vector3 diffuse2D(const tex_coord2d_t & texture_coords) const; virtual Vector3 diffuse3D(const tex_coord3d_t & texture_coords) const; virtual float bumpHeight2D(const tex_coord2d_t & texture_coords) const; virtual float bumpHeight3D(const tex_coord3d_t & texture_coords) const; protected: Texture * m_texture; }; #endif
true
0dfbc7f8e2a0dfe51461915ec6d19b1514dce5c0
C++
moreclassy/algospot
/rep2/ROUTING.cpp
UTF-8
1,124
2.8125
3
[]
no_license
#include <vector> #include <iostream> #include <unordered_map> #include <queue> #include <climits> using namespace std; void solve() { int n; cin>>n; vector<vector<pair<int, double>>> edge(n); vector<double> cost(n, 1); int m; cin>>m; for (int i = 0; i < m; i++) { int s; cin>>s; int e; cin>>e; double w; cin>>w; edge[s].push_back({e, w}); edge[e].push_back({s, w}); } priority_queue<pair<double, int>> pq; pq.push({-1.0, 0}); while (!pq.empty()) { int curNode = pq.top().second; double curCost = pq.top().first; pq.pop(); if (cost[curNode] < 0.5) continue; cost[curNode] = curCost; for (auto e : edge[curNode]) { int nextNode = e.first; double nextCost = curCost * e.second; if (cost[nextNode] > 0.5) pq.push({nextCost, nextNode}); } } cout<<-cost.back()<<endl; } int main() { cout<<fixed; cout.precision(10); int c; cin>>c; for (int i = 0; i < c; i++) solve(); return 0; }
true
a53865b74aa4ba5185c24e759973972e0be233c4
C++
congthanh97/LTNC
/bai tap C/c++codeblock/point.cpp
UTF-8
1,067
3.078125
3
[]
no_license
#include <iostream> #include <conio.h> #include <stdio.h> using namespace std; class point { private: int x, y; public: void InputPoint() { cout<<"\nNhap toa do A (x,y) "<<endl; cout<<"\nInput the value of x = "; cin>>x; cout<<"\nInput the value of y = "; cin>>y; } void Tinhtien() { float data_x,data_y; cout<<"\nnhap toa do tinh tien x = "; cin>> data_x; cout<<"\nnhap toa do tinh tien y = "; cin>>data_y; cout<<"\n\nToa do moi: ("<<x+data_x<<","<<y+data_y<<") "; } void DisplayPoint() { cout<<"Toa Do: ("<<x<<","<<y<<") "<<endl; } point operator-(point a) { a.x=-1*a.x; a.y=-1*a.y; return a; } }; int main() { point a,b; cout<<"\t\t\tChuong trinh nhap dien tinh tien diem\n"; cout<<"\n\t\tHo ten: Bui Van Cong \t\t\tLop:AT13CLC01\n"; a.InputPoint(); a.DisplayPoint(); a.Tinhtien(); //diem doi xung; b=b-a; cout<<"\n\n\nDiem doi xung"<<endl; b.DisplayPoint(); }
true
94305fd1e4c12855bfb12df8ae56744844073d37
C++
ZhuoerFeng/2019-OOP
/Final/01reload/bracket.cpp
UTF-8
422
3.5
4
[]
no_license
#include <iostream> using namespace std; class Test { public: int operator() (int a, int b) { cout << "operator() called. " << a << ' ' << b << endl; return a + b; } }; int main() { Test sum; int s = sum(3, 4); /// sum􀀇􀀍􀀋􀀂􀀆􀀍􀀊􀀁􀀃􀀅􀀉􀀎􀀈􀀄􀀌􀀏􀀅􀀉􀀇􀀍􀀐 cout << "a + b = " << s << endl; int t = sum.operator()(5, 6); return 0; }
true
c17a0e8ad860e4936a1ddadd26ca0cc011fcf632
C++
MyGUI/mygui
/MyGUIEngine/src/MyGUI_UString.cpp
UTF-8
54,864
2.703125
3
[ "MIT" ]
permissive
/* * This source file is part of MyGUI. For the latest info, see http://mygui.info/ * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "MyGUI_Precompiled.h" #include "MyGUI_UString.h" namespace MyGUI { //-------------------------------------------------------------------------- void UString::_base_iterator::_seekFwd(size_type c) { mIter += c; } //-------------------------------------------------------------------------- void UString::_base_iterator::_seekRev(size_type c) { mIter -= c; } //-------------------------------------------------------------------------- void UString::_base_iterator::_become(const _base_iterator& i) { mIter = i.mIter; mString = i.mString; } //-------------------------------------------------------------------------- bool UString::_base_iterator::_test_begin() const { return mIter == mString->mData.begin(); } //-------------------------------------------------------------------------- bool UString::_base_iterator::_test_end() const { return mIter == mString->mData.end(); } //-------------------------------------------------------------------------- UString::size_type UString::_base_iterator::_get_index() const { return mIter - mString->mData.begin(); } //-------------------------------------------------------------------------- void UString::_base_iterator::_jump_to(size_type index) { mIter = mString->mData.begin() + index; } //-------------------------------------------------------------------------- UString::unicode_char UString::_base_iterator::_getCharacter() const { size_type current_index = _get_index(); return mString->getChar(current_index); } //-------------------------------------------------------------------------- int UString::_base_iterator::_setCharacter(unicode_char uc) { size_type current_index = _get_index(); int change = mString->setChar(current_index, uc); _jump_to(current_index); return change; } //-------------------------------------------------------------------------- void UString::_base_iterator::_moveNext() { _seekFwd(1); // move 1 code point forward if (_test_end()) return; // exit if we hit the end if (_utf16_surrogate_follow(mIter[0])) { // landing on a follow code point means we might be part of a bigger character // so we test for that code_point lead_half = 0; //NB: we can't possibly be at the beginning here, so no need to test lead_half = mIter[-1]; // check the previous code point to see if we're part of a surrogate pair if (_utf16_surrogate_lead(lead_half)) { _seekFwd(1); // if so, then advance 1 more code point } } } //-------------------------------------------------------------------------- void UString::_base_iterator::_movePrev() { _seekRev(1); // move 1 code point backwards if (_test_begin()) return; // exit if we hit the beginning if (_utf16_surrogate_follow(mIter[0])) { // landing on a follow code point means we might be part of a bigger character // so we test for that code_point lead_half = 0; lead_half = mIter[-1]; // check the previous character to see if we're part of a surrogate pair if (_utf16_surrogate_lead(lead_half)) { _seekRev(1); // if so, then rewind 1 more code point } } } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- UString::_fwd_iterator& UString::_fwd_iterator::operator++() { _seekFwd(1); return *this; } //-------------------------------------------------------------------------- UString::_fwd_iterator UString::_fwd_iterator::operator++(int) { _fwd_iterator tmp(*this); _seekFwd(1); return tmp; } //-------------------------------------------------------------------------- UString::_fwd_iterator& UString::_fwd_iterator::operator--() { _seekRev(1); return *this; } //-------------------------------------------------------------------------- UString::_fwd_iterator UString::_fwd_iterator::operator--(int) { _fwd_iterator tmp(*this); _seekRev(1); return tmp; } //-------------------------------------------------------------------------- UString::_fwd_iterator UString::_fwd_iterator::operator+(difference_type n) { _fwd_iterator tmp(*this); if (n < 0) tmp._seekRev(-n); else tmp._seekFwd(n); return tmp; } //-------------------------------------------------------------------------- UString::_fwd_iterator UString::_fwd_iterator::operator-(difference_type n) { _fwd_iterator tmp(*this); if (n < 0) tmp._seekFwd(-n); else tmp._seekRev(n); return tmp; } //-------------------------------------------------------------------------- UString::_fwd_iterator& UString::_fwd_iterator::operator+=(difference_type n) { if (n < 0) _seekRev(-n); else _seekFwd(n); return *this; } //-------------------------------------------------------------------------- UString::_fwd_iterator& UString::_fwd_iterator::operator-=(difference_type n) { if (n < 0) _seekFwd(-n); else _seekRev(n); return *this; } //-------------------------------------------------------------------------- UString::value_type& UString::_fwd_iterator::operator*() const { return *mIter; } //-------------------------------------------------------------------------- UString::value_type& UString::_fwd_iterator::operator[](difference_type n) const { _fwd_iterator tmp(*this); tmp += n; return *tmp; } //-------------------------------------------------------------------------- UString::_fwd_iterator& UString::_fwd_iterator::moveNext() { _moveNext(); return *this; } //-------------------------------------------------------------------------- UString::_fwd_iterator& UString::_fwd_iterator::movePrev() { _movePrev(); return *this; } //-------------------------------------------------------------------------- UString::unicode_char UString::_fwd_iterator::getCharacter() const { return _getCharacter(); } //-------------------------------------------------------------------------- int UString::_fwd_iterator::setCharacter(unicode_char uc) { return _setCharacter(uc); } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- UString::_const_fwd_iterator::_const_fwd_iterator() = default; //-------------------------------------------------------------------------- UString::_const_fwd_iterator::_const_fwd_iterator(const _fwd_iterator& i) { _become(i); } //-------------------------------------------------------------------------- UString::_const_fwd_iterator& UString::_const_fwd_iterator::operator++() { _seekFwd(1); return *this; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator UString::_const_fwd_iterator::operator++(int) { _const_fwd_iterator tmp(*this); _seekFwd(1); return tmp; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator& UString::_const_fwd_iterator::operator--() { _seekRev(1); return *this; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator UString::_const_fwd_iterator::operator--(int) { _const_fwd_iterator tmp(*this); _seekRev(1); return tmp; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator UString::_const_fwd_iterator::operator+(difference_type n) { _const_fwd_iterator tmp(*this); if (n < 0) tmp._seekRev(-n); else tmp._seekFwd(n); return tmp; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator UString::_const_fwd_iterator::operator-(difference_type n) { _const_fwd_iterator tmp(*this); if (n < 0) tmp._seekFwd(-n); else tmp._seekRev(n); return tmp; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator& UString::_const_fwd_iterator::operator+=(difference_type n) { if (n < 0) _seekRev(-n); else _seekFwd(n); return *this; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator& UString::_const_fwd_iterator::operator-=(difference_type n) { if (n < 0) _seekFwd(-n); else _seekRev(n); return *this; } //-------------------------------------------------------------------------- const UString::value_type& UString::_const_fwd_iterator::operator*() const { return *mIter; } //-------------------------------------------------------------------------- const UString::value_type& UString::_const_fwd_iterator::operator[](difference_type n) const { _const_fwd_iterator tmp(*this); tmp += n; return *tmp; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator& UString::_const_fwd_iterator::moveNext() { _moveNext(); return *this; } //-------------------------------------------------------------------------- UString::_const_fwd_iterator& UString::_const_fwd_iterator::movePrev() { _movePrev(); return *this; } //-------------------------------------------------------------------------- UString::unicode_char UString::_const_fwd_iterator::getCharacter() const { return _getCharacter(); } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- UString::_rev_iterator& UString::_rev_iterator::operator++() { _seekRev(1); return *this; } //-------------------------------------------------------------------------- UString::_rev_iterator UString::_rev_iterator::operator++(int) { _rev_iterator tmp(*this); _seekRev(1); return tmp; } //-------------------------------------------------------------------------- UString::_rev_iterator& UString::_rev_iterator::operator--() { _seekFwd(1); return *this; } //-------------------------------------------------------------------------- UString::_rev_iterator UString::_rev_iterator::operator--(int) { _rev_iterator tmp(*this); _seekFwd(1); return tmp; } //-------------------------------------------------------------------------- UString::_rev_iterator UString::_rev_iterator::operator+(difference_type n) { _rev_iterator tmp(*this); if (n < 0) tmp._seekFwd(-n); else tmp._seekRev(n); return tmp; } //-------------------------------------------------------------------------- UString::_rev_iterator UString::_rev_iterator::operator-(difference_type n) { _rev_iterator tmp(*this); if (n < 0) tmp._seekRev(-n); else tmp._seekFwd(n); return tmp; } //-------------------------------------------------------------------------- UString::_rev_iterator& UString::_rev_iterator::operator+=(difference_type n) { if (n < 0) _seekFwd(-n); else _seekRev(n); return *this; } //-------------------------------------------------------------------------- UString::_rev_iterator& UString::_rev_iterator::operator-=(difference_type n) { if (n < 0) _seekRev(-n); else _seekFwd(n); return *this; } //-------------------------------------------------------------------------- UString::value_type& UString::_rev_iterator::operator*() const { return mIter[-1]; } //-------------------------------------------------------------------------- UString::value_type& UString::_rev_iterator::operator[](difference_type n) const { _rev_iterator tmp(*this); tmp -= n; return *tmp; } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- UString::_const_rev_iterator::_const_rev_iterator() = default; UString::_const_rev_iterator::_const_rev_iterator(const _rev_iterator& i) { _become(i); } //-------------------------------------------------------------------------- UString::_const_rev_iterator& UString::_const_rev_iterator::operator++() { _seekRev(1); return *this; } //-------------------------------------------------------------------------- UString::_const_rev_iterator UString::_const_rev_iterator::operator++(int) { _const_rev_iterator tmp(*this); _seekRev(1); return tmp; } //-------------------------------------------------------------------------- UString::_const_rev_iterator& UString::_const_rev_iterator::operator--() { _seekFwd(1); return *this; } //-------------------------------------------------------------------------- UString::_const_rev_iterator UString::_const_rev_iterator::operator--(int) { _const_rev_iterator tmp(*this); _seekFwd(1); return tmp; } //-------------------------------------------------------------------------- UString::_const_rev_iterator UString::_const_rev_iterator::operator+(difference_type n) { _const_rev_iterator tmp(*this); if (n < 0) tmp._seekFwd(-n); else tmp._seekRev(n); return tmp; } //-------------------------------------------------------------------------- UString::_const_rev_iterator UString::_const_rev_iterator::operator-(difference_type n) { _const_rev_iterator tmp(*this); if (n < 0) tmp._seekRev(-n); else tmp._seekFwd(n); return tmp; } //-------------------------------------------------------------------------- UString::_const_rev_iterator& UString::_const_rev_iterator::operator+=(difference_type n) { if (n < 0) _seekFwd(-n); else _seekRev(n); return *this; } //-------------------------------------------------------------------------- UString::_const_rev_iterator& UString::_const_rev_iterator::operator-=(difference_type n) { if (n < 0) _seekRev(-n); else _seekFwd(n); return *this; } //-------------------------------------------------------------------------- const UString::value_type& UString::_const_rev_iterator::operator*() const { return mIter[-1]; } //-------------------------------------------------------------------------- const UString::value_type& UString::_const_rev_iterator::operator[](difference_type n) const { _const_rev_iterator tmp(*this); tmp -= n; return *tmp; } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- UString::UString() { _init(); } //-------------------------------------------------------------------------- UString::UString(const UString& copy) { _init(); mData = copy.mData; } //-------------------------------------------------------------------------- UString::UString(size_type length, const code_point& ch) { _init(); assign(length, ch); } //-------------------------------------------------------------------------- UString::UString(const code_point* str) { _init(); assign(str); } //-------------------------------------------------------------------------- UString::UString(const code_point* str, size_type length) { _init(); assign(str, length); } //-------------------------------------------------------------------------- UString::UString(const UString& str, size_type index, size_type length) { _init(); assign(str, index, length); } //-------------------------------------------------------------------------- #if MYGUI_IS_NATIVE_WCHAR_T UString::UString(const wchar_t* w_str) { _init(); assign(w_str); } //-------------------------------------------------------------------------- UString::UString(const wchar_t* w_str, size_type length) { _init(); assign(w_str, length); } #endif //-------------------------------------------------------------------------- UString::UString(const std::wstring& wstr) { _init(); assign(wstr); } //-------------------------------------------------------------------------- UString::UString(const char* c_str) { _init(); assign(c_str, std::strlen(c_str)); } //-------------------------------------------------------------------------- UString::UString(const char* c_str, size_type length) { _init(); assign(c_str, length); } //-------------------------------------------------------------------------- UString::UString(const std::string& str) { _init(); assign(str.data(), str.size()); } //-------------------------------------------------------------------------- UString::UString(const utf32string& str) { _init(); assign(str); } //-------------------------------------------------------------------------- UString::~UString() { _cleanBuffer(); } //-------------------------------------------------------------------------- UString::size_type UString::size() const { return mData.size(); } //-------------------------------------------------------------------------- UString::size_type UString::length() const { return size(); } //-------------------------------------------------------------------------- UString::size_type UString::length_Characters() const { const_iterator i = begin(); const_iterator ie = end(); size_type c = 0; while (i != ie) { i.moveNext(); ++c; } return c; } //-------------------------------------------------------------------------- UString::size_type UString::max_size() const { return mData.max_size(); } //-------------------------------------------------------------------------- void UString::reserve(size_type size) { mData.reserve(size); } //-------------------------------------------------------------------------- void UString::resize(size_type num, const code_point& val /*= 0 */) { mData.resize(num, val); } //-------------------------------------------------------------------------- void UString::swap(UString& from) { mData.swap(from.mData); } //-------------------------------------------------------------------------- bool UString::empty() const { return mData.empty(); } //-------------------------------------------------------------------------- const UString::code_point* UString::c_str() const { return mData.c_str(); } //-------------------------------------------------------------------------- const UString::code_point* UString::data() const { return c_str(); } //-------------------------------------------------------------------------- UString::size_type UString::capacity() const { return mData.capacity(); } //-------------------------------------------------------------------------- void UString::clear() { mData.clear(); } //-------------------------------------------------------------------------- UString UString::substr(size_type index, size_type num /*= npos */) const { // this could avoid the extra copy if we used a private specialty constructor dstring data = mData.substr(index, num); UString tmp; tmp.mData.swap(data); return tmp; } //-------------------------------------------------------------------------- void UString::push_back(unicode_char val) { code_point cp[2]; size_t c = _utf32_to_utf16(val, cp); if (c > 0) push_back(cp[0]); if (c > 1) push_back(cp[1]); } //-------------------------------------------------------------------------- #if MYGUI_IS_NATIVE_WCHAR_T void UString::push_back(wchar_t val) { // we do this because the Unicode method still preserves UTF-16 code points mData.push_back(static_cast<code_point>(val)); } #endif //-------------------------------------------------------------------------- void UString::push_back(code_point val) { mData.push_back(val); } void UString::push_back(char val) { mData.push_back(static_cast<code_point>(val)); } bool UString::inString(unicode_char ch) const { const_iterator i; const_iterator ie = end(); for (i = begin(); i != ie; i.moveNext()) { if (i.getCharacter() == ch) return true; } return false; } const std::string& UString::asUTF8() const { _load_buffer_UTF8(); return *m_buffer.mStrBuffer; } const char* UString::asUTF8_c_str() const { _load_buffer_UTF8(); return m_buffer.mStrBuffer->c_str(); } const UString::utf32string& UString::asUTF32() const { _load_buffer_UTF32(); return *m_buffer.mUTF32StrBuffer; } const UString::unicode_char* UString::asUTF32_c_str() const { _load_buffer_UTF32(); return m_buffer.mUTF32StrBuffer->c_str(); } const std::wstring& UString::asWStr() const { _load_buffer_WStr(); return *m_buffer.mWStrBuffer; } const wchar_t* UString::asWStr_c_str() const { _load_buffer_WStr(); return m_buffer.mWStrBuffer->c_str(); } UString::code_point& UString::at(size_type loc) { return mData.at(loc); } const UString::code_point& UString::at(size_type loc) const { return mData.at(loc); } UString::unicode_char UString::getChar(size_type loc) const { const code_point* ptr = c_str(); unicode_char uc; size_t l = _utf16_char_length(ptr[loc]); code_point cp[2] = {/* blame the code beautifier */ 0, 0}; cp[0] = ptr[loc]; if (l == 2 && (loc + 1) < mData.length()) { cp[1] = ptr[loc + 1]; } _utf16_to_utf32(cp, uc); return uc; } int UString::setChar(size_type loc, unicode_char ch) { code_point cp[2] = {/* blame the code beautifier */ 0, 0}; size_t l = _utf32_to_utf16(ch, cp); unicode_char existingChar = getChar(loc); size_t existingSize = _utf16_char_length(existingChar); size_t newSize = _utf16_char_length(ch); if (newSize > existingSize) { at(loc) = cp[0]; insert(loc + 1, 1, cp[1]); return 1; } if (newSize < existingSize) { erase(loc, 1); at(loc) = cp[0]; return -1; } // newSize == existingSize at(loc) = cp[0]; if (l == 2) at(loc + 1) = cp[1]; return 0; } UString::iterator UString::begin() { iterator i; i.mIter = mData.begin(); i.mString = this; return i; } UString::const_iterator UString::begin() const { const_iterator i; i.mIter = const_cast<UString*>(this)->mData.begin(); i.mString = const_cast<UString*>(this); return i; } UString::iterator UString::end() { iterator i; i.mIter = mData.end(); i.mString = this; return i; } UString::const_iterator UString::end() const { const_iterator i; i.mIter = const_cast<UString*>(this)->mData.end(); i.mString = const_cast<UString*>(this); return i; } UString::reverse_iterator UString::rbegin() { reverse_iterator i; i.mIter = mData.end(); i.mString = this; return i; } UString::const_reverse_iterator UString::rbegin() const { const_reverse_iterator i; i.mIter = const_cast<UString*>(this)->mData.end(); i.mString = const_cast<UString*>(this); return i; } UString::reverse_iterator UString::rend() { reverse_iterator i; i.mIter = mData.begin(); i.mString = this; return i; } UString::const_reverse_iterator UString::rend() const { const_reverse_iterator i; i.mIter = const_cast<UString*>(this)->mData.begin(); i.mString = const_cast<UString*>(this); return i; } UString& UString::assign(iterator start, iterator end) { mData.assign(start.mIter, end.mIter); return *this; } UString& UString::assign(const UString& str) { mData.assign(str.mData); return *this; } UString& UString::assign(const code_point* str) { mData.assign(str); return *this; } UString& UString::assign(const code_point* str, size_type num) { mData.assign(str, num); return *this; } UString& UString::assign(const UString& str, size_type index, size_type len) { mData.assign(str.mData, index, len); return *this; } UString& UString::assign(size_type num, const code_point& ch) { mData.assign(num, ch); return *this; } UString& UString::assign(const std::wstring& wstr) { mData.clear(); mData.reserve(wstr.length()); // best guess bulk allocate #ifdef WCHAR_UTF16 // if we're already working in UTF-16, this is easy code_point tmp; std::wstring::const_iterator i, ie = wstr.end(); for (i = wstr.begin(); i != ie; i++) { tmp = static_cast<code_point>(*i); mData.push_back(tmp); } #else // otherwise we do it the safe way (which is still 100% safe to pass UTF-16 through, just slower) code_point cp[3] = {0, 0, 0}; unicode_char tmp; std::wstring::const_iterator i; std::wstring::const_iterator ie = wstr.end(); for (i = wstr.begin(); i != ie; i++) { tmp = static_cast<unicode_char>(*i); size_t l = _utf32_to_utf16(tmp, cp); if (l > 0) mData.push_back(cp[0]); if (l > 1) mData.push_back(cp[1]); } #endif return *this; } #if MYGUI_IS_NATIVE_WCHAR_T UString& UString::assign(const wchar_t* w_str) { std::wstring tmp; tmp.assign(w_str); return assign(tmp); } UString& UString::assign(const wchar_t* w_str, size_type num) { std::wstring tmp; tmp.assign(w_str, num); return assign(tmp); } #endif UString& UString::assign(const utf32string& str) { for (const auto& character : str) { push_back(character); } return *this; } UString& UString::assign(const char* c_str, size_type num) { size_type len = _verifyUTF8(c_str, num); clear(); // empty our contents, if there are any reserve(len); // best guess bulk capacity growth // This is a 3 step process, converting each byte in the UTF-8 stream to UTF-32, // then converting it to UTF-16, then finally appending the data buffer unicode_char uc; // temporary Unicode character buffer unsigned char utf8buf[7]; // temporary UTF-8 buffer utf8buf[6] = 0; size_t utf8len; // UTF-8 length code_point utf16buff[3]; // temporary UTF-16 buffer utf16buff[2] = 0; size_t utf16len; // UTF-16 length for (size_type i = 0; i < num; ++i) { utf8len = std::min(_utf8_char_length(static_cast<unsigned char>(c_str[i])), num - i); // estimate bytes to load for (size_t j = 0; j < utf8len; j++) { // load the needed UTF-8 bytes utf8buf[j] = (static_cast<unsigned char>( c_str [i + j])); // we don't increment 'i' here just in case the estimate is wrong (shouldn't happen, but we're being careful) } utf8buf[utf8len] = 0; // nul terminate so we throw an exception before running off the end of the buffer utf8len = _utf8_to_utf32(utf8buf, uc); // do the UTF-8 -> UTF-32 conversion i += utf8len - 1; // we subtract 1 for the increment of the 'for' loop utf16len = _utf32_to_utf16(uc, utf16buff); // UTF-32 -> UTF-16 conversion append(utf16buff, utf16len); // append the characters to the string } return *this; } UString& UString::append(const UString& str) { mData.append(str.mData); return *this; } UString& UString::append(const code_point* str) { mData.append(str); return *this; } UString& UString::append(const UString& str, size_type index, size_type len) { mData.append(str.mData, index, len); return *this; } UString& UString::append(const code_point* str, size_type num) { mData.append(str, num); return *this; } UString& UString::append(size_type num, code_point ch) { mData.append(num, ch); return *this; } UString& UString::append(iterator start, iterator end) { mData.append(start.mIter, end.mIter); return *this; } #if MYGUI_IS_NATIVE_WCHAR_T UString& UString::append(const wchar_t* w_str, size_type num) { std::wstring tmp(w_str, num); return append(tmp); } UString& UString::append(size_type num, wchar_t ch) { return append(num, static_cast<unicode_char>(ch)); } #endif UString& UString::append(const char* c_str, size_type num) { UString tmp(c_str, num); append(tmp); return *this; } UString& UString::append(size_type num, char ch) { append(num, static_cast<code_point>(ch)); return *this; } UString& UString::append(size_type num, unicode_char ch) { code_point cp[2] = {0, 0}; if (_utf32_to_utf16(ch, cp) == 2) { for (size_type i = 0; i < num; i++) { append(1, cp[0]); append(1, cp[1]); } } else { for (size_type i = 0; i < num; i++) { append(1, cp[0]); } } return *this; } UString::iterator UString::insert(iterator i, const code_point& ch) { iterator ret; ret.mIter = mData.insert(i.mIter, ch); ret.mString = this; return ret; } UString& UString::insert(size_type index, const UString& str) { mData.insert(index, str.mData); return *this; } UString& UString::insert(size_type index1, const UString& str, size_type index2, size_type num) { mData.insert(index1, str.mData, index2, num); return *this; } void UString::insert(iterator i, iterator start, iterator end) { mData.insert(i.mIter, start.mIter, end.mIter); } UString& UString::insert(size_type index, const code_point* str, size_type num) { mData.insert(index, str, num); return *this; } #if MYGUI_IS_NATIVE_WCHAR_T UString& UString::insert(size_type index, const wchar_t* w_str, size_type num) { UString tmp(w_str, num); insert(index, tmp); return *this; } #endif UString& UString::insert(size_type index, const char* c_str, size_type num) { UString tmp(c_str, num); insert(index, tmp); return *this; } UString& UString::insert(size_type index, size_type num, code_point ch) { mData.insert(index, num, ch); return *this; } #if MYGUI_IS_NATIVE_WCHAR_T UString& UString::insert(size_type index, size_type num, wchar_t ch) { insert(index, num, static_cast<unicode_char>(ch)); return *this; } #endif UString& UString::insert(size_type index, size_type num, char ch) { insert(index, num, static_cast<code_point>(ch)); return *this; } UString& UString::insert(size_type index, size_type num, unicode_char ch) { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); if (l == 1) { return insert(index, num, cp[0]); } for (size_type c = 0; c < num; c++) { // insert in reverse order to preserve ordering after insert insert(index, 1, cp[1]); insert(index, 1, cp[0]); } return *this; } void UString::insert(iterator i, size_type num, const code_point& ch) { mData.insert(i.mIter, num, ch); } #if MYGUI_IS_NATIVE_WCHAR_T void UString::insert(iterator i, size_type num, const wchar_t& ch) { insert(i, num, static_cast<unicode_char>(ch)); } #endif void UString::insert(iterator i, size_type num, const char& ch) { insert(i, num, static_cast<code_point>(ch)); } void UString::insert(iterator i, size_type num, const unicode_char& ch) { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); if (l == 1) { insert(i, num, cp[0]); } else { for (size_type c = 0; c < num; c++) { // insert in reverse order to preserve ordering after insert insert(i, 1, cp[1]); insert(i, 1, cp[0]); } } } UString::iterator UString::erase(iterator loc) { iterator ret; ret.mIter = mData.erase(loc.mIter); ret.mString = this; return ret; } UString::iterator UString::erase(iterator start, iterator end) { iterator ret; ret.mIter = mData.erase(start.mIter, end.mIter); ret.mString = this; return ret; } UString& UString::erase(size_type index /*= 0*/, size_type num /*= npos */) { if (num == npos) mData.erase(index); else mData.erase(index, num); return *this; } UString& UString::replace(size_type index1, size_type num1, const UString& str) { mData.replace(index1, num1, str.mData, 0, npos); return *this; } UString& UString::replace(size_type index1, size_type num1, const UString& str, size_type num2) { mData.replace(index1, num1, str.mData, 0, num2); return *this; } UString& UString::replace(size_type index1, size_type num1, const UString& str, size_type index2, size_type num2) { mData.replace(index1, num1, str.mData, index2, num2); return *this; } UString& UString::replace(iterator start, iterator end, const UString& str, size_type num /*= npos */) { _const_fwd_iterator st(start); //Work around for gcc, allow it to find correct overload size_type index1 = begin() - st; size_type num1 = end - st; return replace(index1, num1, str, 0, num); } UString& UString::replace(size_type index, size_type num1, size_type num2, code_point ch) { mData.replace(index, num1, num2, ch); return *this; } UString& UString::replace(iterator start, iterator end, size_type num, code_point ch) { _const_fwd_iterator st(start); //Work around for gcc, allow it to find correct overload size_type index1 = begin() - st; size_type num1 = end - st; return replace(index1, num1, num, ch); } int UString::compare(const UString& str) const { return mData.compare(str.mData); } int UString::compare(const code_point* str) const { return mData.compare(str); } int UString::compare(size_type index, size_type length, const UString& str) const { return mData.compare(index, length, str.mData); } int UString::compare(size_type index, size_type length, const UString& str, size_type index2, size_type length2) const { return mData.compare(index, length, str.mData, index2, length2); } int UString::compare(size_type index, size_type length, const code_point* str, size_type length2) const { return mData.compare(index, length, str, length2); } #if MYGUI_IS_NATIVE_WCHAR_T int UString::compare(size_type index, size_type length, const wchar_t* w_str, size_type length2) const { UString tmp(w_str, length2); return compare(index, length, tmp); } #endif int UString::compare(size_type index, size_type length, const char* c_str, size_type length2) const { UString tmp(c_str, length2); return compare(index, length, tmp); } UString::size_type UString::find(const UString& str, size_type index /*= 0 */) const { return mData.find(str.c_str(), index); } UString::size_type UString::find(const code_point* cp_str, size_type index, size_type length) const { UString tmp(cp_str); return mData.find(tmp.c_str(), index, length); } UString::size_type UString::find(const char* c_str, size_type index, size_type length) const { UString tmp(c_str); return mData.find(tmp.c_str(), index, length); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::find(const wchar_t* w_str, size_type index, size_type length) const { UString tmp(w_str); return mData.find(tmp.c_str(), index, length); } #endif UString::size_type UString::find(char ch, size_type index /*= 0 */) const { return find(static_cast<code_point>(ch), index); } UString::size_type UString::find(code_point ch, size_type index /*= 0 */) const { return mData.find(ch, index); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::find(wchar_t ch, size_type index /*= 0 */) const { return find(static_cast<unicode_char>(ch), index); } #endif UString::size_type UString::find(unicode_char ch, size_type index /*= 0 */) const { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); return find(UString(cp, l), index); } UString::size_type UString::rfind(const UString& str, size_type index /*= 0 */) const { return mData.rfind(str.c_str(), index); } UString::size_type UString::rfind(const code_point* cp_str, size_type index, size_type num) const { UString tmp(cp_str); return mData.rfind(tmp.c_str(), index, num); } UString::size_type UString::rfind(const char* c_str, size_type index, size_type num) const { UString tmp(c_str); return mData.rfind(tmp.c_str(), index, num); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::rfind(const wchar_t* w_str, size_type index, size_type num) const { UString tmp(w_str); return mData.rfind(tmp.c_str(), index, num); } #endif UString::size_type UString::rfind(char ch, size_type index /*= 0 */) const { return rfind(static_cast<code_point>(ch), index); } UString::size_type UString::rfind(code_point ch, size_type index) const { return mData.rfind(ch, index); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::rfind(wchar_t ch, size_type index /*= 0 */) const { return rfind(static_cast<unicode_char>(ch), index); } #endif UString::size_type UString::rfind(unicode_char ch, size_type index /*= 0 */) const { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); return rfind(UString(cp, l), index); } UString::size_type UString::find_first_of(const UString& str, size_type index /*= 0*/, size_type num /*= npos */) const { size_type i = 0; const size_type len = length(); while (i < num && (index + i) < len) { unicode_char ch = getChar(index + i); if (str.inString(ch)) return index + i; i += _utf16_char_length(ch); // increment by the Unicode character length } return npos; } UString::size_type UString::find_first_of(code_point ch, size_type index /*= 0 */) const { UString tmp; tmp.assign(1, ch); return find_first_of(tmp, index); } UString::size_type UString::find_first_of(char ch, size_type index /*= 0 */) const { return find_first_of(static_cast<code_point>(ch), index); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::find_first_of(wchar_t ch, size_type index /*= 0 */) const { return find_first_of(static_cast<unicode_char>(ch), index); } #endif UString::size_type UString::find_first_of(unicode_char ch, size_type index /*= 0 */) const { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); return find_first_of(UString(cp, l), index); } UString::size_type UString::find_first_not_of( const UString& str, size_type index /*= 0*/, size_type num /*= npos */) const { size_type i = 0; const size_type len = length(); while (i < num && (index + i) < len) { unicode_char ch = getChar(index + i); if (!str.inString(ch)) return index + i; i += _utf16_char_length(ch); // increment by the Unicode character length } return npos; } UString::size_type UString::find_first_not_of(code_point ch, size_type index /*= 0 */) const { UString tmp; tmp.assign(1, ch); return find_first_not_of(tmp, index); } UString::size_type UString::find_first_not_of(char ch, size_type index /*= 0 */) const { return find_first_not_of(static_cast<code_point>(ch), index); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::find_first_not_of(wchar_t ch, size_type index /*= 0 */) const { return find_first_not_of(static_cast<unicode_char>(ch), index); } #endif UString::size_type UString::find_first_not_of(unicode_char ch, size_type index /*= 0 */) const { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); return find_first_not_of(UString(cp, l), index); } UString::size_type UString::find_last_of(const UString& str, size_type index /*= npos*/, size_type num /*= npos */) const { size_type i = 0; const size_type len = length(); if (index > len) index = len - 1; while (i < num && (index - i) != npos) { size_type j = index - i; // careful to step full Unicode characters if (j != 0 && _utf16_surrogate_follow(at(j)) && _utf16_surrogate_lead(at(j - 1))) { j = index - ++i; } // and back to the usual dull test unicode_char ch = getChar(j); if (str.inString(ch)) return j; i++; } return npos; } UString::size_type UString::find_last_of(code_point ch, size_type index /*= npos */) const { UString tmp; tmp.assign(1, ch); return find_last_of(tmp, index); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::find_last_of(wchar_t ch, size_type index /*= npos */) const { return find_last_of(static_cast<unicode_char>(ch), index); } #endif UString::size_type UString::find_last_of(unicode_char ch, size_type index /*= npos */) const { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); return find_last_of(UString(cp, l), index); } UString::size_type UString::find_last_not_of( const UString& str, size_type index /*= npos*/, size_type num /*= npos */) const { size_type i = 0; const size_type len = length(); if (index > len) index = len - 1; while (i < num && (index - i) != npos) { size_type j = index - i; // careful to step full Unicode characters if (j != 0 && _utf16_surrogate_follow(at(j)) && _utf16_surrogate_lead(at(j - 1))) { j = index - ++i; } // and back to the usual dull test unicode_char ch = getChar(j); if (!str.inString(ch)) return j; i++; } return npos; } UString::size_type UString::find_last_not_of(code_point ch, size_type index /*= npos */) const { UString tmp; tmp.assign(1, ch); return find_last_not_of(tmp, index); } UString::size_type UString::find_last_not_of(char ch, size_type index /*= npos */) const { return find_last_not_of(static_cast<code_point>(ch), index); } #if MYGUI_IS_NATIVE_WCHAR_T UString::size_type UString::find_last_not_of(wchar_t ch, size_type index /*= npos */) const { return find_last_not_of(static_cast<unicode_char>(ch), index); } #endif UString::size_type UString::find_last_not_of(unicode_char ch, size_type index /*= npos */) const { code_point cp[3] = {0, 0, 0}; size_t l = _utf32_to_utf16(ch, cp); return find_last_not_of(UString(cp, l), index); } bool UString::operator<(const UString& right) const { return compare(right) < 0; } bool UString::operator<=(const UString& right) const { return compare(right) <= 0; } UString& UString::operator=(const UString& s) { return assign(s); } UString& UString::operator=(code_point ch) { clear(); return append(1, ch); } UString& UString::operator=(char ch) { clear(); return append(1, ch); } #if MYGUI_IS_NATIVE_WCHAR_T UString& UString::operator=(wchar_t ch) { clear(); return append(1, ch); } #endif UString& UString::operator=(unicode_char ch) { clear(); return append(1, ch); } bool UString::operator>(const UString& right) const { return compare(right) > 0; } bool UString::operator>=(const UString& right) const { return compare(right) >= 0; } bool UString::operator==(const UString& right) const { return compare(right) == 0; } bool UString::operator!=(const UString& right) const { return !operator==(right); } UString::code_point& UString::operator[](size_type index) { return at(index); } const UString::code_point& UString::operator[](size_type index) const { return at(index); } UString::operator std::string() const { return asUTF8(); } //! implicit cast to std::wstring UString::operator std::wstring() const { return asWStr(); } bool UString::_utf16_independent_char(code_point cp) { // tests if the cp is within the surrogate pair range // everything else is a standalone code point, ot it matches a surrogate pair signature return 0xD800 > cp || cp > 0xDFFF; } bool UString::_utf16_surrogate_lead(code_point cp) { // tests if the cp is within the 2nd word of a surrogate pair // it is a 1st word, or it isn't return 0xD800 <= cp && cp <= 0xDBFF; } bool UString::_utf16_surrogate_follow(code_point cp) { // tests if the cp is within the 2nd word of a surrogate pair // it is a 2nd word, everything else isn't return 0xDC00 <= cp && cp <= 0xDFFF; } size_t UString::_utf16_char_length(code_point cp) { if (0xD800 <= cp && cp <= 0xDBFF) // test if cp is the beginning of a surrogate pair return 2; // if it is, then we are 2 words long return 1; // otherwise we are only 1 word long } size_t UString::_utf16_char_length(unicode_char uc) { if (uc > 0xFFFF) // test if uc is greater than the single word maximum return 2; // if so, we need a surrogate pair return 1; // otherwise we can stuff it into a single word } size_t UString::_utf16_to_utf32(const code_point in_cp[2], unicode_char& out_uc) { const code_point& cp1 = in_cp[0]; const code_point& cp2 = in_cp[1]; bool wordPair = false; // does it look like a surrogate pair? if (0xD800 <= cp1 && cp1 <= 0xDBFF) { // looks like one, but does the other half match the algorithm as well? if (0xDC00 <= cp2 && cp2 <= 0xDFFF) wordPair = true; // yep! } if (!wordPair) { // if we aren't a 100% authentic surrogate pair, then just copy the value out_uc = cp1; return 1; } unsigned short cU = cp1; unsigned short cL = cp2; // copy upper and lower words of surrogate pair to writable buffers cU -= 0xD800; // remove the encoding markers cL -= 0xDC00; out_uc = (cU & 0x03FF) << 10; // grab the 10 upper bits and set them in their proper location out_uc |= (cL & 0x03FF); // combine in the lower 10 bits out_uc += 0x10000; // add back in the value offset return 2; // this whole operation takes to words, so that's what we'll return } size_t UString::_utf32_to_utf16(const unicode_char& in_uc, code_point out_cp[2]) { if (in_uc <= 0xFFFF) { // we blindly preserve sentinel values because our decoder understands them out_cp[0] = static_cast<code_point>(in_uc); return 1; } unicode_char uc = in_uc; // copy to writable buffer unsigned short tmp; // single code point buffer uc -= 0x10000; // subtract value offset //process upper word tmp = static_cast<unsigned short>((uc >> 10) & 0x03FF); // grab the upper 10 bits tmp += 0xD800; // add encoding offset out_cp[0] = tmp; // write // process lower word tmp = static_cast<unsigned short>(uc & 0x03FF); // grab the lower 10 bits tmp += 0xDC00; // add encoding offset out_cp[1] = tmp; // write return 2; // return used word count (2 for surrogate pairs) } bool UString::_utf8_start_char(unsigned char cp) { return (cp & ~_cont_mask) != _cont; } size_t UString::_utf8_char_length(unsigned char cp) { if (!(cp & 0x80)) return 1; if ((cp & ~_lead1_mask) == _lead1) return 2; if ((cp & ~_lead2_mask) == _lead2) return 3; if ((cp & ~_lead3_mask) == _lead3) return 4; if ((cp & ~_lead4_mask) == _lead4) return 5; if ((cp & ~_lead5_mask) == _lead5) return 6; return 1; //throw invalid_data( "invalid UTF-8 sequence header value" ); } size_t UString::_utf8_char_length(unicode_char uc) { /* 7 bit: U-00000000 - U-0000007F: 0xxxxxxx 11 bit: U-00000080 - U-000007FF: 110xxxxx 10xxxxxx 16 bit: U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx 21 bit: U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 26 bit: U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 31 bit: U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */ if (!(uc & ~0x0000007F)) return 1; if (!(uc & ~0x000007FF)) return 2; if (!(uc & ~0x0000FFFF)) return 3; if (!(uc & ~0x001FFFFF)) return 4; if (!(uc & ~0x03FFFFFF)) return 5; if (!(uc & ~0x7FFFFFFF)) return 6; return 1; //throw invalid_data( "invalid UTF-32 value" ); } size_t UString::_utf8_to_utf32(const unsigned char in_cp[6], unicode_char& out_uc) { size_t len = _utf8_char_length(in_cp[0]); if (len == 1) { // if we are only 1 byte long, then just grab it and exit out_uc = in_cp[0]; return 1; } unicode_char c = 0; // temporary buffer size_t i = 0; switch (len) { // load header byte case 6: c = in_cp[i] & _lead5_mask; break; case 5: c = in_cp[i] & _lead4_mask; break; case 4: c = in_cp[i] & _lead3_mask; break; case 3: c = in_cp[i] & _lead2_mask; break; case 2: c = in_cp[i] & _lead1_mask; break; default: break; } // load each continuation byte for (++i; i < len; i++) { if ((in_cp[i] & ~_cont_mask) != _cont) { //throw invalid_data( "bad UTF-8 continuation byte" ); out_uc = in_cp[0]; return 1; } c <<= 6; c |= (in_cp[i] & _cont_mask); } out_uc = c; // write the final value and return the used byte length return len; } size_t UString::_utf32_to_utf8(const unicode_char& in_uc, unsigned char out_cp[6]) { size_t len = _utf8_char_length(in_uc); // predict byte length of sequence unicode_char c = in_uc; // copy to temp buffer //stuff all of the lower bits for (size_t i = len - 1; i > 0; i--) { out_cp[i] = static_cast<unsigned char>(((c)&_cont_mask) | _cont); c >>= 6; } //now write the header byte switch (len) { case 6: out_cp[0] = static_cast<unsigned char>(((c)&_lead5_mask) | _lead5); break; case 5: out_cp[0] = static_cast<unsigned char>(((c)&_lead4_mask) | _lead4); break; case 4: out_cp[0] = static_cast<unsigned char>(((c)&_lead3_mask) | _lead3); break; case 3: out_cp[0] = static_cast<unsigned char>(((c)&_lead2_mask) | _lead2); break; case 2: out_cp[0] = static_cast<unsigned char>(((c)&_lead1_mask) | _lead1); break; case 1: default: out_cp[0] = static_cast<unsigned char>((c)&0x7F); break; } // return the byte length of the sequence return len; } UString::size_type UString::_verifyUTF8(const unsigned char* c_str) { std::string_view tmp(reinterpret_cast<const char*>(c_str)); return _verifyUTF8(tmp); } UString::size_type UString::_verifyUTF8(const char* c_str, size_type num) { size_type length = 0; for (size_type i = 0; i < num; ++i) { // characters pass until we find an extended sequence if (c_str[i] & 0x80) { if (i + 1 >= num) // invalid extended sequence return num; unsigned char c = c_str[i]; size_t contBytes = 0; // get continuation byte count and test for overlong sequences if ((c & ~_lead1_mask) == _lead1) { // 1 additional byte if (c == _lead1) { //throw invalid_data( "overlong UTF-8 sequence" ); return num; } contBytes = 1; } else if ((c & ~_lead2_mask) == _lead2) { // 2 additional bytes contBytes = 2; if (c == _lead2) { // possible overlong UTF-8 sequence c = c_str[i + 1]; // look ahead to next byte in sequence if ((c & _lead2) == _cont) { //throw invalid_data( "overlong UTF-8 sequence" ); return num; } } } else if ((c & ~_lead3_mask) == _lead3) { // 3 additional bytes contBytes = 3; if (c == _lead3) { // possible overlong UTF-8 sequence c = c_str[i + 1]; // look ahead to next byte in sequence if ((c & _lead3) == _cont) { //throw invalid_data( "overlong UTF-8 sequence" ); return num; } } } else if ((c & ~_lead4_mask) == _lead4) { // 4 additional bytes contBytes = 4; if (c == _lead4) { // possible overlong UTF-8 sequence c = c_str[i + 1]; // look ahead to next byte in sequence if ((c & _lead4) == _cont) { //throw invalid_data( "overlong UTF-8 sequence" ); return num; } } } else if ((c & ~_lead5_mask) == _lead5) { // 5 additional bytes contBytes = 5; if (c == _lead5) { // possible overlong UTF-8 sequence c = c_str[i + 1]; // look ahead to next byte in sequence if ((c & _lead5) == _cont) { //throw invalid_data( "overlong UTF-8 sequence" ); return num; } } } if (i + contBytes >= num) // invalid extended sequence return num; // check remaining continuation bytes for while (contBytes--) { c = c_str[++i]; // get next byte in sequence if ((c & ~_cont_mask) != _cont) { //throw invalid_data( "bad UTF-8 continuation byte" ); return num; } } } length++; } return length; } void UString::_init() { m_buffer.mVoidBuffer = nullptr; m_bufferType = bt_none; m_bufferSize = 0; } void UString::_cleanBuffer() const { if (m_buffer.mVoidBuffer != nullptr) { switch (m_bufferType) { case bt_string: delete m_buffer.mStrBuffer; break; case bt_wstring: delete m_buffer.mWStrBuffer; break; case bt_utf32string: delete m_buffer.mUTF32StrBuffer; break; case bt_none: // under the worse of circumstances, this is all we can do, and hope it works out //delete m_buffer.mVoidBuffer; // delete void* is undefined, don't do that static_assert("This should never happen - mVoidBuffer should never contain something if we " "don't know the type"); break; } m_buffer.mVoidBuffer = nullptr; m_bufferSize = 0; m_bufferType = bt_none; } } void UString::_getBufferStr() const { if (m_bufferType != bt_string) { _cleanBuffer(); m_buffer.mStrBuffer = new std::string(); m_bufferType = bt_string; } m_buffer.mStrBuffer->clear(); } void UString::_getBufferWStr() const { if (m_bufferType != bt_wstring) { _cleanBuffer(); m_buffer.mWStrBuffer = new std::wstring(); m_bufferType = bt_wstring; } m_buffer.mWStrBuffer->clear(); } void UString::_getBufferUTF32Str() const { if (m_bufferType != bt_utf32string) { _cleanBuffer(); m_buffer.mUTF32StrBuffer = new utf32string(); m_bufferType = bt_utf32string; } m_buffer.mUTF32StrBuffer->clear(); } void UString::_load_buffer_UTF8() const { _getBufferStr(); std::string& buffer = (*m_buffer.mStrBuffer); buffer.reserve(length()); unsigned char utf8buf[6]; char* charbuf = (char*)utf8buf; unicode_char c; size_t len; const_iterator i; const_iterator ie = end(); for (i = begin(); i != ie; i.moveNext()) { c = i.getCharacter(); len = _utf32_to_utf8(c, utf8buf); size_t j = 0; while (j < len) buffer.push_back(charbuf[j++]); } } void UString::_load_buffer_WStr() const { _getBufferWStr(); std::wstring& buffer = (*m_buffer.mWStrBuffer); buffer.reserve(length()); // may over reserve, but should be close enough #ifdef WCHAR_UTF16 // wchar_t matches UTF-16 const_iterator i, ie = end(); for (i = begin(); i != ie; ++i) { buffer.push_back((wchar_t)(*i)); } #else // wchar_t fits UTF-32 unicode_char c; const_iterator i; const_iterator ie = end(); for (i = begin(); i != ie; i.moveNext()) { c = i.getCharacter(); buffer.push_back((wchar_t)c); } #endif } void UString::_load_buffer_UTF32() const { _getBufferUTF32Str(); utf32string& buffer = (*m_buffer.mUTF32StrBuffer); buffer.reserve(length()); // may over reserve, but should be close enough unicode_char c; const_iterator i; const_iterator ie = end(); for (i = begin(); i != ie; i.moveNext()) { c = i.getCharacter(); buffer.push_back(c); } } } // namespace MyGUI
true
7c5d08a7102cdcb527e43f0271bfdde9ffaa11bb
C++
CSUF-CPSC121-2021S01/siligame-05-Alexlychee
/player.cc
UTF-8
792
2.71875
3
[]
no_license
#include "player.h" void Player::Draw(graphics::Image &my_player) { graphics::Image NINJA; NINJA.Load("player.bmp"); for (int i = 0; i < NINJA.GetHeight(); i++) { for (int j = 0; j < NINJA.GetWidth(); j++) { my_player.SetColor(GetX() + j, GetY() + i, NINJA.GetColor(j, i)); } } } void Player::Move(const graphics::Image &move) {} void PlayerProjectile::Draw(graphics::Image &p_projectile) { graphics::Image STAR; STAR.Load("p_projectile.bmp"); for (int i = 0; i < STAR.GetHeight(); i++) { for (int j = 0; j < STAR.GetWidth(); j++) { p_projectile.SetColor(GetX() + j, GetY() + i, STAR.GetColor(j, i)); } } } void PlayerProjectile::Move(const graphics::Image &move) { SetY(GetY() - 8); if (IsOutOfBounds(move)) { SetIsActive(false); } }
true
04cf485a8e0ddb394a4d9a4bf009696cb545a97b
C++
974steph/WLED
/wled00/wled09_button.ino
UTF-8
1,320
2.65625
3
[ "MIT" ]
permissive
/* * Physical IO */ void handleButton() { if (buttonEnabled) { if (digitalRead(buttonPin) == LOW && !buttonPressedBefore) { buttonPressedBefore = true; if (bri == 0) { bri = bri_last; } else { bri_last = bri; bri = 0; } colorUpdated(2); } else if (digitalRead(buttonPin) == HIGH && buttonPressedBefore) { delay(15); if (digitalRead(buttonPin) == HIGH) { buttonPressedBefore = false; } } } //output if (auxActive || auxActiveBefore) { if (!auxActiveBefore) { auxActiveBefore = true; switch (auxTriggeredState) { case 0: pinMode(auxPin, INPUT); break; case 1: pinMode(auxPin, OUTPUT); digitalWrite(auxPin, HIGH); break; case 2: pinMode(auxPin, OUTPUT); digitalWrite(auxPin, LOW); break; } auxStartTime = millis(); } if ((millis() - auxStartTime > auxTime*1000 && auxTime != 255) || !auxActive) { auxActive = false; auxActiveBefore = false; switch (auxDefaultState) { case 0: pinMode(auxPin, INPUT); break; case 1: pinMode(auxPin, OUTPUT); digitalWrite(auxPin, HIGH); break; case 2: pinMode(auxPin, OUTPUT); digitalWrite(auxPin, LOW); break; } } } }
true
6f5169905c4825720168a4ba44d4e56b5a6467df
C++
Arelaxe/practicasED
/Práctica_3/cola_max/src/Cola_max_pila.cpp
UTF-8
2,022
3.40625
3
[]
no_license
#include "Cola_max_pila.h" //////////////////////////////////////// // MÉTODOS PÚBLICOS //////////////////////////////////////// template <class T> Cola_max<T> :: Cola_max(){ } template <class T> void Cola_max<T> :: poner (T elemento){ Pareja<T> a_insertar; a_insertar.dato = elemento; a_insertar.max = elemento; if (!vacia()){ if (elemento > maximo()){ actualizar_maximo (elemento); } else if (elemento > entrada.top().max) actualizar_maximo_intervalo (elemento); } entrada.push (a_insertar); } template <class T> void Cola_max<T> :: quitar (){ volcar_pila(entrada, salida); salida.pop(); } template <class T> const T Cola_max<T> :: maximo (){ volcar_pila(entrada, salida); T m = salida.top().max; volcar_pila(salida, entrada); return m; } template <class T> int Cola_max<T> :: num_elementos(){ volcar_pila(entrada, salida); int tam = salida.size(); volcar_pila(salida, entrada); return (tam); } template <class T> const T Cola_max<T> :: frente (){ volcar_pila(entrada, salida); T f = salida.top().dato; volcar_pila (salida, entrada); return (f); } template <class T> bool Cola_max<T> :: vacia (){ return (salida.empty() && entrada.empty()); } //////////////////////////////////////// // MÉTODOS PRIVADOS //////////////////////////////////////// template <class T> void Cola_max<T> :: actualizar_maximo (T nuevo_maximo){ while (!entrada.empty()){ salida.push(entrada.top()); salida.top().max = nuevo_maximo; entrada.pop(); } volcar_pila (salida, entrada); } template <class T> void Cola_max<T> :: actualizar_maximo_intervalo (T nuevo_maximo){ while (!entrada.empty() && nuevo_maximo > entrada.top().max){ salida.push(entrada.top()); salida.top().max = nuevo_maximo; entrada.pop(); } volcar_pila (entrada, salida); volcar_pila (salida, entrada); } template <class T> void Cola_max<T> :: volcar_pila (stack<Pareja<T>> & a_volcar, stack<Pareja<T>> & volcada){ while (!a_volcar.empty()){ volcada.push(a_volcar.top()); a_volcar.pop(); } }
true
1fef3c4cbb0040e457984cef2305e369e7f713e7
C++
brokenlanceorg/owlsong
/code/cc/Genetic/Chromosome.cpp
UTF-8
7,583
2.71875
3
[]
no_license
//*********************************************************************************************** // File : Chromosome.cpp // Purpose : // : // Author : Brandon Benham // Date : 9/16/01 //*********************************************************************************************** #include"Chromosome.hpp" //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : Default Constructor // Purpose : Performs the basic construction actions. //*********************************************************************************************** ChromosomE::ChromosomE() { Setup(); } // end ChromosomE default constructor //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : Destructor // Purpose : Performs the destruction actions. //*********************************************************************************************** ChromosomE::~ChromosomE() { if( _myCrosser != 0 ) { delete (CrossoverStrategY*)_myCrosser; _myCrosser = 0; } // end if not null if( _myGenome != 0 ) { delete _myGenome; _myGenome = 0; } // end if not null if( _myMutator != 0 ) { delete (MutationStrategY*)_myMutator; _myMutator = 0; } // end if not null } // end ChromosomE destructor //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : Setup // Purpose : Performs the basic setup actions. //*********************************************************************************************** void ChromosomE::Setup() { _myCrosser = 0; _myGenome = 0; _myMutator = 0; _LowEndpoint = 0.3; _HighEndpoint = 0.7; } // end Setup //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : SetCrossoverStrategy // Purpose : //*********************************************************************************************** void ChromosomE::SetCrossoverStrategy( void* theStrat ) { if( _myCrosser != 0 ) { delete ((CrossoverStrategY*)_myCrosser); } // end if not null _myCrosser = theStrat; // Type: CrossoverStrategY* } // end SetCrossoverStrategy //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : Crossover // Purpose : //*********************************************************************************************** ChromosomE* ChromosomE::Crossover( ChromosomE* theMate ) { ChromosomE* theChild = this->Clone(); ((CrossoverStrategY*)_myCrosser)->Crossover( this, theMate, theChild ); theChild->SetMutationStrategy( this->CloneMutationStrategy() ); theChild->SetCrossoverStrategy( this->CloneCrossoverStrategy() ); return theChild; } // end Crossover //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : Mutate // Purpose : //*********************************************************************************************** void ChromosomE::Mutate() { ((MutationStrategY*)_myMutator)->Mutate( this ); } // end Mutate //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : GetGenes // Purpose : This method returns the genes located at positions iStart to iEnd // : inclusive (zero-based). //*********************************************************************************************** VectoR* ChromosomE::GetGenes( int iStart, int iEnd ) { VectoR* theGenes = new VectoR( iEnd - iStart + 1 ); int iCounter = 0; for( int i=iStart; i<iEnd+1; i++ ) { theGenes->pVariables[ iCounter++ ] = _myGenome->pVariables[ i ]; } // end for loop return theGenes; } // end GetGenes //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : AddGenes // Purpose : Adds the specified genes to the genome. //*********************************************************************************************** void ChromosomE::AddGenes( VectoR* theGenes ) { if( _myGenome == 0 ) { _myGenome = new VectoR( theGenes ); delete theGenes; return; } // end if first add VectoR* tempVector = new VectoR( _myGenome->cnRows + theGenes->cnRows ); int iCounter = 0; for( int i=0; i<_myGenome->cnRows; i++ ) { tempVector->pVariables[ iCounter++ ] = _myGenome->pVariables[ i ]; } // end for loop for( int i=0; i<theGenes->cnRows; i++ ) { tempVector->pVariables[ iCounter++ ] = theGenes->pVariables[ i ]; } // end for loop delete _myGenome; delete theGenes; _myGenome = tempVector; } // end AddGenes //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : SetMutationStrategy // Purpose : //*********************************************************************************************** void ChromosomE::SetMutationStrategy( void* theStrat ) { if( _myMutator != 0 ) { delete ((CrossoverStrategY*)_myMutator); } // end if not null _myMutator = theStrat; // Type: MutationStrategY* } // end SetMutationStrategy //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : SetGenome // Purpose : //*********************************************************************************************** void ChromosomE::SetGenome( VectoR* theGenome ) { if( _myGenome != 0 ) { delete _myGenome; } // end if not null _myGenome = theGenome; } // end setGenome //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : CloneMutationStrategy // Purpose : //*********************************************************************************************** void* ChromosomE::CloneMutationStrategy() { return ((MutationStrategY*)_myMutator)->Clone(); } // end CloneMutationStrategy //*********************************************************************************************** // Class : ChromosomE //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method : CloneCrossoverStrategy // Purpose : //*********************************************************************************************** void* ChromosomE::CloneCrossoverStrategy() { return ((CrossoverStrategY*)_myCrosser)->Clone(); } // end CloneCrossoverStrategy
true
24bd98d2efa934c8e937893e6800de44073918bf
C++
StarWix/ClickHouse
/libs/libcommon/src/DateLUT.cpp
UTF-8
972
2.796875
3
[ "Apache-2.0" ]
permissive
#include <common/DateLUT.h> #include <Poco/Exception.h> #pragma GCC diagnostic push #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wold-style-cast" #endif #include <unicode/timezone.h> #include <unicode/unistr.h> #pragma GCC diagnostic pop DateLUT::DateLUT() { /// Initialize the pointer to the default DateLUTImpl. std::unique_ptr<icu::TimeZone> tz(icu::TimeZone::createDefault()); if (tz == nullptr) throw Poco::Exception("Failed to determine the host time zone."); icu::UnicodeString u_out; tz->getID(u_out); std::string default_time_zone; u_out.toUTF8String(default_time_zone); default_impl.store(&getImplementation(default_time_zone), std::memory_order_release); } const DateLUTImpl & DateLUT::getImplementation(const std::string & time_zone) const { std::lock_guard<std::mutex> lock(mutex); auto it = impls.emplace(time_zone, nullptr).first; if (!it->second) it->second = std::make_unique<DateLUTImpl>(time_zone); return *it->second; }
true
9df0e6e19fc76eb477532c8c48123357dff58c09
C++
yuangu-google/arcs
/src/wasm/cpp/tests/entity-class-test.cc
UTF-8
15,714
2.65625
3
[ "BSD-3-Clause", "WTFPL", "Apache-2.0" ]
permissive
#include <vector> #include <set> #include <unordered_set> #include "src/wasm/cpp/tests/test-base.h" using arcs::internal::Accessor; template<typename T> static size_t hash(const T& d) { return std::hash<T>()(d); } static arcs::Ref<arcs::Foo> make_ref(const std::string& id, const std::string& key) { return Accessor::make_ref<arcs::Foo>(id, key); } static auto converter() { return [](const arcs::Data& d) { return arcs::entity_to_str(d); }; } class EntityClassApiTest : public TestBase { public: void init() override { RUN(test_field_methods); RUN(test_id_equality); RUN(test_number_field_equality); RUN(test_text_field_equality); RUN(test_url_field_equality); RUN(test_boolean_field_equality); RUN(test_reference_field_equality); RUN(test_entity_equality); RUN(test_clone_entity); RUN(test_entity_to_str); RUN(test_stl_vector); RUN(test_stl_set); RUN(test_stl_unordered_set); RUN(test_empty_schema); } void test_field_methods() { arcs::Data d; IS_FALSE(d.has_num()); EQUAL(d.num(), 0); d.set_num(7.3); IS_TRUE(d.has_num()); EQUAL(d.num(), 7.3); d.clear_num(); IS_FALSE(d.has_num()); d.set_num(0); IS_TRUE(d.has_num()); EQUAL(d.num(), 0); IS_FALSE(d.has_txt()); EQUAL(d.txt(), ""); d.set_txt("abc"); IS_TRUE(d.has_txt()); EQUAL(d.txt(), "abc"); d.clear_txt(); IS_FALSE(d.has_txt()); d.set_txt(""); IS_TRUE(d.has_txt()); EQUAL(d.txt(), ""); IS_FALSE(d.has_lnk()); EQUAL(d.lnk(), ""); d.set_lnk("url"); IS_TRUE(d.has_lnk()); EQUAL(d.lnk(), "url"); d.clear_lnk(); IS_FALSE(d.has_lnk()); d.set_lnk(""); IS_TRUE(d.has_lnk()); EQUAL(d.lnk(), ""); IS_FALSE(d.has_flg()); IS_FALSE(d.flg()); d.set_flg(true); IS_TRUE(d.has_flg()); IS_TRUE(d.flg()); d.clear_flg(); IS_FALSE(d.has_flg()); d.set_flg(false); IS_TRUE(d.has_flg()); IS_FALSE(d.flg()); arcs::Ref<arcs::Foo> empty; arcs::Ref<arcs::Foo> populated = make_ref("id", "key"); IS_FALSE(d.has_ref()); EQUAL(d.ref(), empty); d.set_ref(populated); IS_TRUE(d.has_ref()); EQUAL(d.ref(), populated); d.clear_ref(); IS_FALSE(d.has_ref()); d.set_ref(empty); IS_TRUE(d.has_ref()); EQUAL(d.ref(), empty); } void test_id_equality() { arcs::Data d1, d2; EQUAL(Accessor::get_id(d1), ""); // unset vs value Accessor::set_id(&d1, "id_a"); EQUAL(Accessor::get_id(d1), "id_a"); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); // value vs value Accessor::set_id(&d2, "id_b"); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); Accessor::set_id(&d2, "id_a"); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); } void test_number_field_equality() { arcs::Data d1, d2; // unset vs default value d2.set_num(0); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // unset vs other value d2.set_num(5); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // default vs default d1.set_num(0); d2.set_num(0); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); // value vs value d1.set_num(3); d2.set_num(5); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); d1.set_num(5); d2.set_num(5); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); d1.set_num(7); d2.set_num(5); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); } void test_text_field_equality() { arcs::Data d1, d2; // unset vs default value d2.set_txt(""); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // unset vs other value d2.set_txt("a"); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // default vs default d1.set_txt(""); d2.set_txt(""); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); // value vs value d1.set_txt("aaa"); d2.set_txt("bbb"); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); d1.set_txt("bbb"); d2.set_txt("bbb"); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); d1.set_txt("ccc"); d2.set_txt("bbb"); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); } void test_url_field_equality() { arcs::Data d1, d2; // unset vs default value d2.set_lnk(""); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // unset vs other value d2.set_lnk("a"); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // default vs default d1.set_lnk(""); d2.set_lnk(""); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); // value vs value d1.set_lnk("aaa"); d2.set_lnk("bbb"); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); d1.set_lnk("bbb"); d2.set_lnk("bbb"); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); d1.set_lnk("ccc"); d2.set_lnk("bbb"); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); } void test_boolean_field_equality() { arcs::Data d1, d2; // unset vs default value d2.set_flg(false); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // unset vs other value d2.set_flg(true); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // default vs default d1.set_flg(false); d2.set_flg(false); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); // value vs value d1.set_flg(false); d2.set_flg(true); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); d1.set_flg(true); d2.set_flg(true); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); } void test_reference_field_equality() { arcs::Data d1, d2; arcs::Ref<arcs::Foo> empty; // unset vs default value d2.set_ref({}); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // unset vs other value d2.set_ref(make_ref("id1", "key1")); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); // default vs default d1.set_ref(empty); d2.set_ref(empty); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); // value vs value d1.set_ref(make_ref("id5", "key5")); d2.set_ref(make_ref("id7", "key7")); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); d1.set_ref(make_ref("id7", "key7")); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); d2.set_ref(make_ref("id3", "key3")); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); } void test_entity_equality() { arcs::Data d1, d2; // Empty entities are equal EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); IS_TRUE(arcs::fields_equal(d1, d2)); EQUAL(hash(d1), hash(d2)); // Entities with the same fields are equal for (arcs::Data* d : std::vector{&d1, &d2}) { d->set_num(3); d->set_txt("abc"); d->set_lnk(""); d->set_flg(false); } EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); IS_TRUE(arcs::fields_equal(d1, d2)); EQUAL(hash(d1), hash(d2)); // Entities with the same fields but different ids are op!= but fields_equal() Accessor::set_id(&d1, "id_a"); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); IS_TRUE(arcs::fields_equal(d1, d2)); NOT_EQUAL(hash(d1), hash(d2)); Accessor::set_id(&d2, "id_b"); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); IS_TRUE(arcs::fields_equal(d1, d2)); NOT_EQUAL(hash(d1), hash(d2)); // Entities with the same fields and ids are op== and fields_equal() Accessor::set_id(&d2, "id_a"); EQUAL(d1, d2); NOT_LESS(d1, d2); NOT_LESS(d2, d1); IS_TRUE(arcs::fields_equal(d1, d2)); EQUAL(hash(d1), hash(d2)); // d1.txt > d2.txt implies d1 > d2 d1.set_txt("xyz"); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); IS_FALSE(arcs::fields_equal(d1, d2)); NOT_EQUAL(hash(d1), hash(d2)); d1.set_txt("abc"); // d1.flg < d2.flg implies d1 < d2 d2.set_flg(true); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); IS_FALSE(arcs::fields_equal(d1, d2)); NOT_EQUAL(hash(d1), hash(d2)); // d1.lnk && !d2.lnk implies d1 > d2 (takes precedence over flg from above) d2.clear_lnk(); NOT_EQUAL(d1, d2); NOT_LESS(d1, d2); LESS(d2, d1); IS_FALSE(arcs::fields_equal(d1, d2)); NOT_EQUAL(hash(d1), hash(d2)); // !d1.num && d2.num implies d1 < d2 (takes precedence over lnk and flg from above) d1.clear_num(); NOT_EQUAL(d1, d2); LESS(d1, d2); NOT_LESS(d2, d1); IS_FALSE(arcs::fields_equal(d1, d2)); NOT_EQUAL(hash(d1), hash(d2)); } void test_clone_entity() { arcs::Data src; arcs::Data d1 = arcs::clone_entity(src); EQUAL(d1, src); IS_TRUE(arcs::fields_equal(d1, src)); EQUAL(hash(d1), hash(src)); src.set_num(8); src.set_txt("def"); src.set_flg(false); arcs::Data d2 = arcs::clone_entity(src); EQUAL(d2, src); IS_TRUE(arcs::fields_equal(d2, src)); EQUAL(hash(d2), hash(src)); // Cloned references should still refer to the same underlying entity. EQUAL(&(d2.ref().entity()), &(src.ref().entity())); // Cloning doesn't include the internal id. Accessor::set_id(&src, "id"); arcs::Data d3 = arcs::clone_entity(src); EQUAL(Accessor::get_id(d3), ""); NOT_EQUAL(d3, src); IS_TRUE(arcs::fields_equal(d3, src)); NOT_EQUAL(hash(d3), hash(src)); } void test_entity_to_str() { arcs::Data d; EQUAL(arcs::entity_to_str(d), "{}"); d.set_num(6); d.set_txt("boo"); d.set_flg(false); EQUAL(arcs::entity_to_str(d), "{}, num: 6, txt: boo, flg: false"); EQUAL(arcs::entity_to_str(d, "|"), "{}|num: 6|txt: boo|flg: false"); Accessor::set_id(&d, "id"); d.clear_flg(); d.set_ref(make_ref("i12", "k34")); EQUAL(arcs::entity_to_str(d), "{id}, num: 6, txt: boo, ref: REF<i12|k34>"); } void test_stl_vector() { arcs::Data d1, d2, d3; d1.set_num(12); d2.set_num(12); Accessor::set_id(&d3, "id"); std::vector<arcs::Data> v; v.push_back(std::move(d1)); v.push_back(std::move(d2)); v.push_back(std::move(d3)); std::vector<std::string> expected = { "{}, num: 12", "{}, num: 12", "{id}" }; CHECK_ORDERED(v, converter(), expected); } void test_stl_set() { arcs::Data d1; d1.set_num(45); d1.set_txt("woop"); // duplicate arcs::Data d2; d2.set_num(45); d2.set_txt("woop"); // duplicate fields but with an id arcs::Data d3; Accessor::set_id(&d3, "id"); d3.set_num(45); d3.set_txt("woop"); // same id, different fields arcs::Data d4; Accessor::set_id(&d4, "id"); d4.set_flg(false); // duplicate arcs::Data d5 = arcs::clone_entity(d4); Accessor::set_id(&d5, "id"); std::set<arcs::Data> s; s.insert(std::move(d1)); s.insert(std::move(d2)); s.insert(std::move(d3)); s.insert(std::move(d4)); s.insert(std::move(d5)); std::vector<std::string> expected = { "{id}, flg: false", "{id}, num: 45, txt: woop", "{}, num: 45, txt: woop" }; CHECK_UNORDERED(s, converter(), expected); } void test_stl_unordered_set() { arcs::Data d1; d1.set_num(45); d1.set_txt("woop"); // duplicate arcs::Data d2; d2.set_num(45); d2.set_txt("woop"); // duplicate fields but with an id arcs::Data d3; Accessor::set_id(&d3, "id"); d3.set_num(45); d3.set_txt("woop"); // same id, different fields arcs::Data d4; Accessor::set_id(&d4, "id"); d4.set_flg(false); // duplicate arcs::Data d5 = arcs::clone_entity(d4); Accessor::set_id(&d5, "id"); std::unordered_set<arcs::Data> s; s.insert(std::move(d1)); s.insert(std::move(d2)); s.insert(std::move(d3)); s.insert(std::move(d4)); s.insert(std::move(d5)); std::vector<std::string> expected = { "{id}, flg: false", "{id}, num: 45, txt: woop", "{}, num: 45, txt: woop" }; CHECK_UNORDERED(s, converter(), expected); } void test_empty_schema() { arcs::Empty e1, e2; EQUAL(Accessor::get_id(e1), ""); EQUAL(e1, e2); NOT_LESS(e1, e2); NOT_LESS(e2, e1); IS_TRUE(arcs::fields_equal(e1, e2)); EQUAL(hash(e1), hash(e2)); EQUAL(arcs::entity_to_str(e1), "{}"); Accessor::set_id(&e1, "id"); EQUAL(Accessor::get_id(e1), "id"); NOT_EQUAL(e1, e2); NOT_LESS(e1, e2); LESS(e2, e1); IS_TRUE(arcs::fields_equal(e1, e2)); NOT_EQUAL(hash(e1), hash(e2)); EQUAL(arcs::entity_to_str(e1), "{id}"); Accessor::set_id(&e2, "id"); EQUAL(e1, e2); NOT_LESS(e1, e2); NOT_LESS(e2, e1); IS_TRUE(arcs::fields_equal(e1, e2)); EQUAL(hash(e1), hash(e2)); arcs::Empty e3 = arcs::clone_entity(e1); EQUAL(arcs::entity_to_str(e3), "{}"); auto converter = [](const arcs::Empty& e) { return arcs::entity_to_str(e); }; std::vector<std::string> expected = {"{id}", "{}"}; std::set<arcs::Empty> s1; s1.insert(std::move(e1)); s1.insert(std::move(e3)); CHECK_UNORDERED(s1, converter, expected); std::unordered_set<arcs::Empty> s2; arcs::Empty e4; s2.insert(std::move(e2)); s2.insert(std::move(e4)); CHECK_UNORDERED(s2, converter, expected); } }; DEFINE_PARTICLE(EntityClassApiTest) class SpecialSchemaFieldsTest : public TestBase { public: void init() override { RUN(test_language_keyword_field); RUN(test_internal_id_field); RUN(test_general_usage); } // Test that language keywords can be field names. void test_language_keyword_field() { arcs::SpecialFields s; IS_FALSE(s.has_for()); EQUAL(s._for(), ""); s.set_for("abc"); IS_TRUE(s.has_for()); EQUAL(s._for(), "abc"); s.clear_for(); IS_FALSE(s.has_for()); s.set_for(""); IS_TRUE(s.has_for()); EQUAL(s._for(), ""); } // Test that a field called 'internal_id' doesn't conflict with the Arcs internal id. void test_internal_id_field() { arcs::SpecialFields s; Accessor::set_id(&s, "real"); IS_FALSE(s.has_internal_id()); EQUAL(s.internal_id(), 0); s.set_internal_id(76); IS_TRUE(s.has_internal_id()); EQUAL(s.internal_id(), 76); s.clear_internal_id(); IS_FALSE(s.has_internal_id()); s.set_internal_id(0); IS_TRUE(s.has_internal_id()); EQUAL(s.internal_id(), 0); EQUAL(Accessor::get_id(s), "real"); } void test_general_usage() { arcs::SpecialFields s1; Accessor::set_id(&s1, "id"); s1.set_for("abc"); s1.set_internal_id(15); NOT_EQUAL(hash(s1), 0); EQUAL(arcs::entity_to_str(s1), "{id}, for: abc, internal_id: 15"); // same fields, different ids arcs::SpecialFields s2 = arcs::clone_entity(s1); NOT_EQUAL(s1, s2); NOT_LESS(s1, s2); LESS(s2, s1); IS_TRUE(arcs::fields_equal(s1, s2)); NOT_EQUAL(hash(s1), hash(s2)); // same fields and ids Accessor::set_id(&s2, "id"); EQUAL(s1, s2); NOT_LESS(s1, s2); NOT_LESS(s2, s1); IS_TRUE(arcs::fields_equal(s1, s2)); EQUAL(hash(s1), hash(s2)); // different fields s1.clear_for(); NOT_EQUAL(s1, s2); LESS(s1, s2); NOT_LESS(s2, s1); IS_FALSE(arcs::fields_equal(s1, s2)); NOT_EQUAL(hash(s1), hash(s2)); s1.set_for("abc"); s2.set_internal_id(12); NOT_EQUAL(s1, s2); NOT_LESS(s1, s2); LESS(s2, s1); IS_FALSE(arcs::fields_equal(s1, s2)); NOT_EQUAL(hash(s1), hash(s2)); } }; DEFINE_PARTICLE(SpecialSchemaFieldsTest)
true
f976c73a04676c0b2d04abce75878e5a8391595b
C++
Dugy/lightweight_containers
/circular_buffer.cpp
UTF-8
1,857
3.109375
3
[ "MIT" ]
permissive
#include "circular_buffer.hpp" #include <cstring> CircularBufferImpl::CircularBufferImpl(uint8_t* data, short int capacity, short int elementSize) : _data(data), _capacity(capacity), _elementSize(elementSize) { } void CircularBufferImpl::pushBack(const void* data) { if (_lastInserted >= 0) _lastInserted = (_lastInserted + 1) % _capacity; else { _lastInserted = _firstInserted; } memcpy(_data + _lastInserted * _elementSize, data, size_t(_elementSize)); } void* CircularBufferImpl::front() const { return (_data + _firstInserted * _elementSize); } void CircularBufferImpl::popFront() { bool emptied = (_lastInserted == _firstInserted); _firstInserted = (_firstInserted + 1) % _capacity; if (emptied) _lastInserted = -1; } bool CircularBufferImpl::find(uint8_t* sequence, int from, int till, uint8_t* copyLocation, bool erase) { if (_lastInserted == -1) return false; for (int i = _firstInserted; i <= _lastInserted; i = (i + 1) % _capacity) { bool matches = true; int offset = i * _elementSize + from; for (int j = 0; j < till - from; j++) if (sequence[j] != _data[offset + j]) { matches = false; break; } if (matches) { if (copyLocation) { for (int j = 0; j < _elementSize; j++) copyLocation[j] = _data[i * _elementSize + j]; } if (erase) { if (_firstInserted != _lastInserted) { for (int j = 0; j < _elementSize; j++) copyLocation[i * _elementSize + j] = _data[_firstInserted * _elementSize + j]; } popFront(); } return true; } } return false; } bool CircularBufferImpl::full() const { return ((_lastInserted + 1) % _capacity != _firstInserted); } int CircularBufferImpl::size() const { if (_lastInserted == -1) return 0; return (_lastInserted + _capacity - _firstInserted) % _capacity + 1; } bool CircularBufferImpl::empty() const { return _lastInserted == -1; }
true
9e9a6baf8f2ebce273288dd4cd947cc7dbf7acae
C++
mauroFH/OptiDAR_DEV
/Dev/Modulo-Opti/src/sort.cpp
UTF-8
3,760
3.0625
3
[]
no_license
/** \file sort.cpp * Sorting utilities. * Version 1.0.0 * -------------------------------------------------------------------------- * Licensed Materials - Property of *--------------------------------------------------------------------------- */ #include "../../Modulo-Main/DARH.h" /**---------------------------------------------------------------------------- // Sort values (one-dmensional) // nval: number of values // val[i]: i-th value // ind[i]: index of the i-th ordered value // sense: -1 increasing; +1 decreasing //----------------------------------------------------------------------------- */ int SortValues(int nval, int *val, int *ind, int sense) { int i; Sorter Data; Data.NLevel = 1; Data.NItem = nval; Data.Init(); for (i=0; i<nval; i++) { Data.Item[i].Pos = i; Data.Item[i].Val[0] = val[i]; } Data.Sort(sense); for (i=0; i<nval; i++) { ind[i] = Data.Item[i].Pos; } return 0; } /**---------------------------------------------------------------------------- // Sorter: Constructor //----------------------------------------------------------------------------- */ Sorter::Sorter(void) { NLevel = 0; NItem = 0;; Item = NULL; } /**---------------------------------------------------------------------------- // Sorter: Destructor //----------------------------------------------------------------------------- */ Sorter::~Sorter(void) { NLevel = 0; NItem = 0; if (Item != NULL) delete [] Item; } /**---------------------------------------------------------------------------- // Sorter: Initialize //----------------------------------------------------------------------------- */ int Sorter::Init(void) { Item = new QSData [NItem]; return 0; } /**---------------------------------------------------------------------------- // Sort item (sense: -1 increasing; +1 decreasing) //----------------------------------------------------------------------------- */ int Sorter::Sort(int sense) { QSort(Item,0,NItem-1,NLevel,sense); return 0; } /**---------------------------------------------------------------------------- // Quick sort for Double Varibles // (sense: -1 increasing; +1 decreasing) //----------------------------------------------------------------------------- */ void Sorter::QSort(QSData *a, int first, int last, int QSNVal, int sense) { int mid; if (last>=first+1) { mid=Split(a,first,last,QSNVal,sense); QSort(a,first,mid-1,QSNVal,sense); QSort(a,mid+1,last,QSNVal,sense); } } /**---------------------------------------------------------------------------- // Quick sort for Double Varibles // Fuction for perfoming the splitting //----------------------------------------------------------------------------- */ int Sorter::Split(QSData *a, int first, int last, int QSNVal, int sense) { int left,right; QSData temp; left=first+1; right=last; for (;;) { while ((left<=last)&&(QSCmp(&a[left],&a[first],QSNVal,sense)<0)) left++; while ((QSCmp(&a[right],&a[first],QSNVal,sense)>0)) right--; if (left<right) { temp=a[left]; a[left]=a[right]; a[right]=temp; left++; right--; } else { temp=a[first]; a[first]=a[right]; a[right]=temp; return right; } } } /**---------------------------------------------------------------------------- // Quick sort for Double Varibles // Fuction for comparing two items //----------------------------------------------------------------------------- */ int Sorter::QSCmp(QSData *pi, QSData *pj, int QSNVal, int sense) { int i; for (i=0;i<QSNVal;i++) { if (pi->Val[i]>pj->Val[i]) return -sense; if (pi->Val[i]<pj->Val[i]) return sense; } return 0; }
true
12190d234e82133a7b67c763cd060384daffec0b
C++
Char1sk/AlgorithmContestBook
/Book/Unit7/Extra7.5/BoolArraySubset.cpp
UTF-8
595
3.125
3
[]
no_license
#include <iostream> const int maxN = 3; void printSubset(int arr[maxN], bool judge[maxN], int index) { if (index == maxN) { for (int i = 0; i < index; ++i) { if (judge[i]) { printf("%d ", arr[i]); } } printf("\n"); } else { judge[index] = false; printSubset(arr, judge, index+1); judge[index] = true; printSubset(arr, judge, index+1); } } int main() { int arr[maxN] = {1, 4, 5}; bool judge[maxN]; printSubset(arr, judge, 0); return 0; }
true
366b0276445cb33566802a3e8d78b39306761d02
C++
keivanzavari/polygon
/test/line_test.cc
UTF-8
4,590
3.03125
3
[]
no_license
#include "line.h" #include <gtest/gtest.h> namespace geopoly { TEST(Line, ConstructTest1) { Line line({4, -2}, {3, 4}); ASSERT_DOUBLE_EQ(line.a, -6); ASSERT_DOUBLE_EQ(line.b, -1); ASSERT_DOUBLE_EQ(line.c, 22); } TEST(Line, ConstructTest2) { Line line({4, 5}, {0, 5}); ASSERT_DOUBLE_EQ(line.a, 0); ASSERT_DOUBLE_EQ(line.b, -4); ASSERT_DOUBLE_EQ(line.c, 20); line.normalize(); ASSERT_DOUBLE_EQ(line.a, 0); ASSERT_DOUBLE_EQ(line.b, -4 / sqrt(416)); ASSERT_DOUBLE_EQ(line.c, 20 / sqrt(416)); } TEST(Line, ConstructTest3) { Line line({2.5, 0}, {2.5, 4}); ASSERT_DOUBLE_EQ(line.a, -4); ASSERT_DOUBLE_EQ(line.b, 0); ASSERT_DOUBLE_EQ(line.c, 10); line.normalize(); ASSERT_DOUBLE_EQ(line.a, -4 / sqrt(116)); ASSERT_DOUBLE_EQ(line.b, 0); ASSERT_DOUBLE_EQ(line.c, 10 / sqrt(116)); } TEST(Line, SideTest1) { Vector2d<double> point1{1, 3}; Vector2d<double> point2{2, 7}; Line line1(point1, point2); ASSERT_TRUE(line1.areAtSameSide(Vector2d<double>{1, 4}, Vector2d<double>{1.5, 7})); ASSERT_TRUE(line1.isPointOnLine(point1)); ASSERT_TRUE(line1.isPointOnLine(point2)); Vector2d<double> point3{2, 3}; Vector2d<double> point4{1, 6}; Line line2(point3, point4); ASSERT_FALSE(line2.areAtSameSide(Vector2d<double>{1, 4}, Vector2d<double>{1.5, 7})); ASSERT_TRUE(line2.isPointOnLine(point3)); ASSERT_TRUE(line2.isPointOnLine(point4)); } TEST(Line, SideTest2) { Vector2d<double> point1{0, 0}; Vector2d<double> point2{5, 0}; Line line1(point1, point2); Vector2d<double> point3{-4, 3}; Vector2d<double> point4{-4, -6}; Line line2(point3, point4); ASSERT_FALSE(line1.areAtSameSide(point3, point4)); ASSERT_TRUE(line2.areAtSameSide(point1, point2)); } TEST(LineSegment, ConstructTest) { Vector2d<double> point1{5.0, 0.0}; Vector2d<double> point2{0.0, 0.0}; LineSegment lineSegment(point1, point2); ASSERT_FALSE(lineSegment.intersectsWithHorizontalLine(1.0)); ASSERT_FALSE(lineSegment.intersectsWithHorizontalLine(-1.0)); ASSERT_TRUE(lineSegment.intersectsWithHorizontalLine(0.0)); } TEST(LineSegment, IsInRange1) { Vector2d<double> point1{5.0, 0.0}; Vector2d<double> point2{0.0, 0.0}; LineSegment lineSegment(point1, point2); ASSERT_FALSE(lineSegment.isInRange({1.0, 1.0})); } TEST(LineSegment, IsInRange2) { Vector2d<double> point1{0.0, 0.0}; Vector2d<double> point2{1.0, 1.0}; LineSegment lineSegment(point1, point2); ASSERT_TRUE(lineSegment.isInRange(point1)); ASSERT_TRUE(lineSegment.isInRange(point2)); ASSERT_TRUE(lineSegment.isInRange({0.5, 0.5})); ASSERT_FALSE(lineSegment.isInRange({-0.5, 0.5})); ASSERT_FALSE(lineSegment.isInRange({0.5, -0.5})); } TEST(LineSegment, IntersectionTest1) { Vector2d<double> point1{5.0, 0.0}; Vector2d<double> point2{0.0, 0.0}; LineSegment lineSegment1(point1, point2); Vector2d<double> point3{5.0, 20.0}; Vector2d<double> point4{0.0, 20.0}; LineSegment lineSegment2(point1, point2); auto intersection = computeIntersection(lineSegment1, lineSegment2); ASSERT_FALSE(intersection.has_value()); } TEST(LineSegment, IntersectionTest2) { Vector2d<double> point1{5.0, 0.0}; Vector2d<double> point2{0.0, 0.0}; LineSegment lineSegment1(point1, point2); Vector2d<double> point3{-2.0, 2.0}; Vector2d<double> point4{-2.0, -3.0}; LineSegment lineSegment2(point3, point4); // The two lines intersect, but the line segments do not. auto intersection = computeIntersection(lineSegment1, lineSegment2); ASSERT_FALSE(intersection.has_value()); auto line1 = toLine(lineSegment1); auto line2 = toLine(lineSegment2); intersection = computeIntersection(line1, line2); ASSERT_TRUE(intersection.has_value()); } TEST(Line, IntersectionTest1) { Vector2d<double> point1{1, 1}; Vector2d<double> point2{2, 2}; Line line1(point1, point2); Vector2d<double> point3{0, 0}; Vector2d<double> point4{0, 1}; Line line2(point3, point4); auto intersection = computeIntersection(line1, line2); ASSERT_TRUE(intersection.has_value()); ASSERT_DOUBLE_EQ(intersection.value().x(), 0.0); ASSERT_DOUBLE_EQ(intersection.value().y(), 0.0); } TEST(Line, IntersectionTest2) { Vector2d<double> point1{1, 3}; Vector2d<double> point2{2, 7}; Line line1(point1, point2); Vector2d<double> point3{2, 3}; Vector2d<double> point4{1, 6}; Line line2(point3, point4); auto intersection = computeIntersection(line1, line2); ASSERT_TRUE(intersection.has_value()); ASSERT_DOUBLE_EQ(intersection.value().x(), 10.0 / 7.0); ASSERT_DOUBLE_EQ(intersection.value().y(), 33.0 / 7.0); } } // namespace geopoly
true
c2d65649ac9f4bd27331c94d52386459092ba35b
C++
3x1l3/gladiators-rpg-game
/Gladiators/Weapon.cc
UTF-8
1,972
3.140625
3
[]
no_license
/********************************************************* /// \file /// \brief Implimentation file for the Weapon Class /// /// The implimentation for the functions defined in Weapon.h /// /// A class that defines a weapon. /// Currently, weapons differentiate by attackvalue only. /// Inside the parent, Item, their other attributes are set. /// /// \author Adam Shepley /// \date November 24th, 2010 *******************************************************/ #include "Weapon.h" Weapon::Weapon() { Item::SetName("Default Weapon"); Item::SetDescription("This is a Weapon"); Item::SetPrice(100); Equipable::SetEquipStatus(false); attackValue = 10; defenseValue = 10; } Weapon::Weapon(const std::string name, const std::string description, const int price, const int attackVal, const int defenseVal) { Item::SetName(name); Item::SetDescription(description); Item::SetPrice(price); Equipable::SetEquipStatus(false); attackValue = attackVal; defenseValue = defenseVal; } Weapon::~Weapon() { } void Weapon::ChangeAttackValue(const int & newValue) { attackValue = newValue; } void Weapon::ChangeDefenseValue(const int & newValue) { defenseValue = newValue; } int& Weapon::GetAttackValue() { return attackValue; } int& Weapon::GetDefenseValue() { return defenseValue; } bool Weapon::operator==(Weapon* otherWeapon) { return ( this->GetAttackValue() == otherWeapon->GetAttackValue() && this->GetName() == otherWeapon->GetName() && this->GetDescription() == otherWeapon->GetDescription() && this->GetPrice() == otherWeapon->GetPrice() ); } Weapon Weapon::operator=(Weapon origWeapon) { Weapon wpn; wpn.SetName(origWeapon.GetName()); wpn.SetPrice(origWeapon.GetPrice()); wpn.SetDescription(origWeapon.GetDescription()); wpn.attackValue = wpn.attackValue; return wpn; }
true
ab8800160baeaef6d22afffb41575d7b053761d4
C++
ohwada/MAC_cpp_Samples
/SDL/example_image/RenderThread.h
UTF-8
1,362
2.65625
3
[]
no_license
/** * SDL Sample * 2020-03-01 K.OHWADA */ // original : https://www.hiroom2.com/2015/05/14/sdl2%E3%81%AEbmp%E7%94%BB%E5%83%8F%E3%81%A8png%E7%94%BB%E5%83%8F%E3%81%AE%E6%8F%8F%E7%94%BB%E5%87%A6%E7%90%86/#sec-2 #ifndef __MYSDL_RENDER_THREAD_H #define __MYSDL_RENDER_THREAD_H #include <SDL.h> #include "Renderer.h" namespace mysdl { extern int runRenderThread(void *); class RenderThread { private: SDL_Window *mWindow; Renderer *mRenderer; SDL_semaphore *mSemaphore; SDL_Thread *mThread; bool mStop; public: RenderThread(SDL_Window *window) : mWindow(window), mStop(false) { mSemaphore = SDL_CreateSemaphore(0); mThread = SDL_CreateThread(runRenderThread, "RenderThread", (void *) this); SDL_SemWait(mSemaphore); } ~RenderThread() { if (!mStop) stop(); SDL_DestroySemaphore(mSemaphore); } void initialize() { mRenderer = new Renderer(mWindow); SDL_SemPost(mSemaphore); } void finalize() { delete mRenderer; } void run() { while (!mStop) { mRenderer->recv(); mRenderer->draw(); SDL_Delay(10); } } void stop() { int ret; mStop = true; SDL_WaitThread(mThread, &ret); mThread = nullptr; } Renderer *getRenderer() { return mRenderer; } }; }; #endif /** __MYSDL_RENDER_THREAD_H */
true
db581253d6fae25312a3e6df434804430e35ea03
C++
MohamedDarkaoui/Computer-Graphics
/ZBuffering_Lines/ZBuffering_lines.cpp
UTF-8
6,050
2.703125
3
[]
no_license
#include "ZBuffering_lines.h" #include <limits> using namespace std; #include "../easy_image/easy_image.h" #include <fstream> #include <stdexcept> #include <string> #include <list> #include <tuple> #include <cmath> #include <cctype> #include "../parser/l_parser.h" #include "../Surface.h" #include <limits> #include <cassert> void draw_Zbuff_line(img::EasyImage &image, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, const img::Color& color, double z0, double z1, ZBuffer& buffer) { assert(x0 < image.get_width() && y0 < image.get_height()); assert(x1 < image.get_width() && y1 < image.get_height()); if (x0 == x1) { //special case for x0 == x1 int k = std::max(y0, y1); int l = std::min(y0, y1); for ( int i = k - l; i >= 0; i--) { unsigned int a = std::max(y0, y1) - std::min(y0, y1); double _z = ((double)i / a)/z1 + (1 - (double)i/a)/z0; unsigned int j = i + std::min(y0, y1); if (buffer[x0][j] > _z){ buffer[x0][j] = _z; image(x0, j) = color; } } } else if (y0 == y1) { //special case for y0 == y1 int k = std::max(x0, x1); int l = std::min(x0, x1); for (int i = k - l; i >= 0 ; i--) { unsigned int a = std::max(x0, x1) - std::min(x0, x1); double _z = ((double)i / a)/z1 + (1 - (double)i/a)/z0; unsigned int j = i + std::min(x0, x1); if (buffer[j][y0] > _z) { buffer[j][y0] = _z; image(j, y0) = color; } } } else { if (x0 > x1) { //flip points if x1>x0: we want x0 to have the lowest value std::swap(x0, x1); std::swap(y0, y1); std::swap(z0, z1); } double m = ((double) y1 - (double) y0) / ((double) x1 - (double) x0); if (-1.0 <= m && m <= 1.0) { for (int i = (int)(x1 - x0) ; i >= 0; i--) { unsigned int a = x1 - x0; double _z = ((double)i / a)/z1 + (1 - (double)i/a)/z0; if (buffer[x0+i][(unsigned int) round(y0 + m * i)] > _z) { buffer[x0+i][(unsigned int) round(y0 + m * i)] = _z; image(x0 + i, (unsigned int) round(y0 + m * i)) = color; } } } else if (m > 1.0) { for (int i = (int)(y1 - y0); i >= 0; i--) { unsigned int a = y1 - y0; double _z = ((double)i / a)/z1 + (1 - (double)i/a)/z0; if (buffer[(unsigned int) round(x0 + (i / m))][y0 + i] > _z) { buffer[(unsigned int) round(x0 + (i / m))][y0 + i] = _z; image((unsigned int) round(x0 + (i / m)), y0 + i) = color; } } } else if (m < -1.0) { for (int i = (int)(y0 - y1); i >= 0; i--) { unsigned int a = y0 - y1; double _z = ((double)i / a)/z1 + (1 - (double)i/a)/z0; if (buffer[(unsigned int) round(x0 - (i / m))][y0 - i] > _z) { buffer[(unsigned int) round(x0 - (i / m))][y0 - i] = _z; image((unsigned int) round(x0 - (i / m)), y0 - i) = color; } } } } } //draw lines with real coordinates img::EasyImage draw_Zbuf_Lines(Lines2D &lines, const int size, tuple<double,double,double> &background_color){ double x_min, x_max, y_min, y_max, image_x, image_y, x_range, y_range; //find X_min, X_max, Y_min, Y_max x_min = lines[0].p1.x; x_max = lines[0].p1.x; y_min = lines[0].p1.y; y_max = lines[0].p1.y; for (Line2D line : lines){ if (line.p1.x < x_min){x_min = line.p1.x;} if (line.p2.x < x_min){x_min = line.p2.x;} if (line.p1.x > x_max){x_max = line.p1.x;} if (line.p2.x > x_max){x_max = line.p2.x;} if (line.p1.y < y_min){y_min = line.p1.y;} if (line.p2.y < y_min){y_min = line.p2.y;} if (line.p1.y > y_max){y_max = line.p1.y;} if (line.p2.y > y_max){y_max = line.p2.y;} } //find the range x_range = x_max - x_min, y_range = y_max - y_min; //calculate the size of the image image_x = (size * x_range)/max(x_range,y_range); image_y = (size * y_range)/(max(x_range,y_range)); //scale double d = (0.95 * image_x)/x_range; for (Line2D &line: lines){ line.p1.x *= d; line.p1.y *= d; line.p2.x *= d; line.p2.y *= d; } //move the lines double DC_x = d * (x_min + x_max)/2, DC_y = d * (y_min + y_max)/2, dx = (image_x/2) - DC_x, dy = (image_y/2) - DC_y; for (Line2D &line: lines){ line.p1.x += dx; line.p1.y += dy; line.p2.x += dx; line.p2.y += dy; } img::EasyImage image((int)image_x,(int)image_y); //paint the background for (int i = 0; i < (int)image_x; i++){ for (int j = 0; j < (int)image_y; j++){ image(i,j).red = get<0>(background_color); image(i,j).green = get<1>(background_color); image(i,j).blue = get<2>(background_color); } } ZBuffer zBuffer = ZBuffer((int)image_x,(int)image_y); //draw the lines for (Line2D line: lines) { img::Color color; color.blue = line.Color.blue; color.red = line.Color.red; color.green = line.Color.green; draw_Zbuff_line(image, (unsigned int) line.p1.x, (unsigned int) line.p1.y, (unsigned int) line.p2.x, (unsigned int) line.p2.y, color, line.z1, line.z2, zBuffer); } return image; }
true
f70538bfd564d6a0594641fe22c09c8b20612549
C++
Huioqy/JianZhi_Offer
/15.反转链表.cpp
UTF-8
1,767
3.859375
4
[]
no_license
/*反转链表*/ /* 输入一个链表,反转链表后,输出新链表的表头。 */ /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ /* 递归的方法其实是非常巧的,它利用递归走到链表的末端, 然后再更新每一个node的next 值 ,实现链表的反转。 而newhead 的值没有发生改变,为该链表的最后一个结点, 所以,反转后,我们可以得到新链表的head。 */ class Solution { public: ListNode* ReverseList(ListNode* pHead) { //第二种方法是:递归方法 if(pHead==NULL||pHead->next==NULL) return pHead; //先反转后面的链表,走到链表的末端结点 ListNode* pReverseNode=ReverseList(pHead->next); //再将当前节点设置为后面节点的后续节点 pHead->next->next=pHead; pHead->next=NULL; return pReverseNode; //第一种方法是:非递归方法:三个指针在链表上同时滑动 /* if(pHead==NULL) return NULL;//注意程序鲁棒性 ListNode* pNode=pHead;//当前指针 ListNode* pPrev=NULL;//当前指针的前一个结点 ListNode* pReverseHead=NULL;//新链表的头指针 while(pNode!=NULL){//当前结点不为空时才执行 ListNode* pNext=pNode->next;//链断开之前一定要保存断开位置后边的结点 if(pNext==NULL)//当pNext为空时,说明当前结点为尾节点 pReverseHead=pNode; pNode->next=pPrev;//指针反转 pPrev=pNode; pNode=pNext; } return pReverseHead; */ } };
true
f4619bade04ddea7cf4627a8ccaa87044d9e7541
C++
TianhangSun/MapleJuice
/scheduler.cpp
UTF-8
2,594
3.28125
3
[]
no_license
#include <queue> #include <map> #include <string> #include <mutex> #include <set> using namespace std; // a scheduler class class scheduler{ private: // multiple queues for incoming maple, juice jobs mutex mtx; queue<map<string,string>> maple_queue; queue<map<string,string>> juice_queue; map<string,int> worker_info; public: // add a single worker void add_worker(string name){ mtx.lock(); if(worker_info.find(name) == worker_info.end()){ worker_info[name] = 0; } mtx.unlock(); } // delete a worker int delete_worker(string name){ mtx.lock(); worker_info.erase(name); mtx.unlock(); return 0; } // receive a single ack void ack_received(string name){ mtx.lock(); worker_info[name] += 1; mtx.unlock(); } // return the number of ack int ack_sum(){ mtx.lock(); int cnt = 0; for(auto i: worker_info){ cnt += i.second; } mtx.unlock(); return cnt; } // clear all worker in the system void clear_worker(){ mtx.lock(); worker_info.clear(); mtx.unlock(); } // function to add a maple job void add_maple_job(string exe, string tmp_prefix, string DFS_filename, int num, int upload){ map<string,string> job; job["type"] = "maple"; job["exe"] = exe; job["tmp_prefix"] = tmp_prefix; job["DFS_filename"] = DFS_filename; job["num"] = to_string(num); job["upload"] = to_string(upload); mtx.lock(); maple_queue.push(job); mtx.unlock(); } // function to add a juice job void add_juice_job(string exe, string tmp_prefix, string dest_filename, int num, int del){ map<string,string> job; job["type"] = "juice"; job["exe"] = exe; job["tmp_prefix"] = tmp_prefix; job["dest_filename"] = dest_filename; job["num"] = to_string(num); job["del"] = to_string(del); mtx.lock(); juice_queue.push(job); mtx.unlock(); } // function to get the job to run map<string,string> get_job(){ mtx.lock(); if(maple_queue.size() != 0){ map<string,string> job = maple_queue.front(); mtx.unlock(); return job; } else if(juice_queue.size() != 0){ map<string,string> job = juice_queue.front(); mtx.unlock(); return job; } else{ mtx.unlock(); map<string,string> job; return job; } } // function to delete a job in queue (when finished) void delete_job(string type){ mtx.lock(); if(type == "maple"){ maple_queue.pop(); } else if(type == "juice"){ juice_queue.pop(); } mtx.unlock(); } };
true
7eb12734040326dbd2c3a9b5a4ce237719f6533e
C++
tanht-lavamyth/Algorithm
/Competitive Programming Exercises/Codeforces/George and Accommodation.cpp
UTF-8
459
2.625
3
[]
no_license
/* * @Author: tanht * @Date: 2020-09-20 08:36:39 * @Last Modified by: tanht * @Last Modified time: 2020-09-20 08:37:26 * @Email: tanht.lavamyth@gmail.com */ #include <iostream> using namespace std; const int AMAX = 100; int p[AMAX], q[AMAX]; int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { cin >> p[i] >> q[i]; } int availableRooms = 0; for (int i = 0; i < n; ++i) { if (q[i] - p[i] >= 2) { ++availableRooms; } } cout << availableRooms; }
true
ba4d2404aeb7a9c559d660d61b1b1a2de2fd0a88
C++
g-akash/spoj_codes
/range_hamster.cpp
UTF-8
853
2.890625
3
[]
no_license
#include<iostream> #include<vector> #include<math.h> #include<iomanip> using namespace std; #define PI 3.14159265 int main() { int t; cin>>t; for(int i=0;i<t;i++) { double u,k1,k2; cin>>u>>k1>>k2; //cout<<k1<<" "<<k2<<endl; if(k1==0) { cout<<fixed<<setprecision(3)<<1.571<<" "<<(k2*u*u)/(2.0*10.0)<<endl; } else if(k2==0) { cout<<fixed<<setprecision(3)<<0.785<<" "<<(k1*u*u)/10.0<<endl; } else { //cout<<"hello"<<endl; double var = (atan2((4.0*k1),-1.0*k2))/2.0; //cout<<var<<endl; //double s2t = ((4.0*k1)/k2)/sqrt(1.0+(((4.0*k1)/k2)*((4.0*k1)/k2))); //double sst = (0.5)*((1.0)-(1.0/sqrt(1.0+(var*var)))); double s2t = sin(2*var); double sst = sin(var)*sin(var); cout<<fixed<<setprecision(3)<<(atan2((4.0*k1),-1.0*k2))/2.0<<" "<<((k1*u*u*s2t)/(10.0))+(k2*u*u*sst)/(2.0*10.0)<<endl; } } }
true
1602db1ea1a6abfb61c4eca1b52d2178cf2234e5
C++
xxsds/sdsl-lite
/include/sdsl/suffix_tree_algorithm.hpp
UTF-8
9,846
2.625
3
[ "BSD-3-Clause" ]
permissive
// Copyright (c) 2016, the SDSL Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. /*!\file suffix_tree_algorithm.hpp * \brief suffix_tree_algorithm.hpp contains algorithms on CSTs * \author Simon Gog */ #ifndef INCLUDED_SDSL_SUFFIX_TREE_ALGORITHM #define INCLUDED_SDSL_SUFFIX_TREE_ALGORITHM #include <math.h> #include <set> #include <stddef.h> #include <type_traits> #include <utility> #include <sdsl/config.hpp> #include <sdsl/int_vector.hpp> #include <sdsl/sdsl_concepts.hpp> // clang-format off // Cyclic includes start #include <sdsl/suffix_array_algorithm.hpp> // Cyclic includes end // clang-format on namespace sdsl { //! Forward search for a character c on the path on depth \f$d\f$ to node \f$v\f$. /*! * \param cst The CST object * \param v The node at the endpoint of the current edge. * \param d The current depth of the path starting with 0. * \param c The character c which should be matched with pathlabel_{root()..v}[d] * \param char_pos T[char_pos-d+1..char_pos] matches with the already matched pattern P[0..d-1] or * d=0 => char_pos=0. * \return The number of the matching substrings in T. * * \par Time complexity * \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$ */ template <class t_cst> typename t_cst::size_type forward_search( t_cst const & cst, typename t_cst::node_type & v, const typename t_cst::size_type d, const typename t_cst::char_type c, typename t_cst::size_type & char_pos, SDSL_UNUSED typename std::enable_if<std::is_same<cst_tag, typename t_cst::index_category>::value, cst_tag>::type x = cst_tag()) { auto cc = cst.csa.char2comp[c]; // check if c occurs in the text of the csa if (cc == 0 and cc != c) // " " " " " " " " " " return 0; typename t_cst::size_type depth_node = cst.depth(v); if (d < depth_node) { // in an edge, no branching char_pos = cst.csa.psi[char_pos]; if (char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc + 1]) return 0; return cst.size(v); } else if (d == depth_node) { // at a node, branching v = cst.child(v, c, char_pos); if (v == cst.root()) return 0; else return cst.size(v); } else { return 0; } } //! Forward search for a pattern pat on the path on depth \f$d\f$ to node \f$v\f$. /*! * \param cst The compressed suffix tree. * \param v The node at the endpoint of the current edge. * \param d The current depth of the path. 0 = first character on each edge of the root node. * \param pat The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$. * \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() * and d=0 => char_pos=0. * * \par Time complexity * \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$ */ template <class t_cst, class t_pat_iter> typename t_cst::size_type forward_search( t_cst const & cst, typename t_cst::node_type & v, typename t_cst::size_type d, t_pat_iter begin, t_pat_iter end, typename t_cst::size_type & char_pos, SDSL_UNUSED typename std::enable_if<std::is_same<cst_tag, typename t_cst::index_category>::value, cst_tag>::type x = cst_tag()) { if (begin == end) return cst.size(v); typename t_cst::size_type size = 0; t_pat_iter it = begin; while (it != end and (size = forward_search(cst, v, d, *it, char_pos))) { ++d; ++it; } return size; } //! Counts the number of occurrences of a pattern in a CST. /*! * \tparam t_cst CST type. * \tparam t_pat_iter Pattern iterator type. * * \param cst The CST object. * \param begin Iterator to the begin of the pattern (inclusive). * \param end Iterator to the end of the pattern (exclusive). * \return The number of occurrences of the pattern in the CSA. * * \par Time complexity * \f$ \Order{ t_{backward\_search} } \f$ */ template <class t_cst, class t_pat_iter> typename t_cst::size_type count(t_cst const & cst, t_pat_iter begin, t_pat_iter end, cst_tag) { return count(cst.csa, begin, end); } //! Calculates all occurrences of a pattern pat in a CST. /*! * \tparam t_cst CST type. * \tparam t_pat_iter Pattern iterator type. * \tparam t_rac Resizeable random access container. * * \param cst The CST object. * \param begin Iterator to the begin of the pattern (inclusive). * \param end Iterator to the end of the pattern (exclusive). * \return A vector containing the occurrences of the pattern in the CST. * * \par Time complexity * \f$ \Order{ t_{backward\_search} + z \cdot t_{SA} } \f$, where \f$z\f$ is the number of * occurrences of pattern in the CST. */ template <class t_cst, class t_pat_iter, class t_rac = int_vector<64>> t_rac locate(t_cst const & cst, t_pat_iter begin, t_pat_iter end, SDSL_UNUSED typename std::enable_if<std::is_same<cst_tag, typename t_cst::index_category>::value, cst_tag>::type x = cst_tag()) { return locate(cst.csa, begin, end); } //! Calculate the concatenation of edge labels from the root to the node v of a CST. /*! * \tparam t_cst CST type. * \tparam t_text_iter Random access iterator type. * * \param cst The CST object. * \param v The node where the concatenation of the edge label ends. * \param text Random access iterator pointing to the start of an container, which can hold at least (end-begin+1) * character. \returns The length of the extracted edge label. \pre text has to be initialized with enough memory (\f$ * cst.depth(v)+1\f$ bytes) to hold the extracted text. */ template <class t_cst, class t_text_iter> typename t_cst::size_type extract( t_cst const & cst, const typename t_cst::node_type & v, t_text_iter text, SDSL_UNUSED typename std::enable_if<std::is_same<cst_tag, typename t_cst::index_category>::value, cst_tag>::type x = cst_tag()) { if (v == cst.root()) { text[0] = 0; return 0; } // first get the suffix array entry of the leftmost leaf in the subtree rooted at v typename t_cst::size_type begin = cst.csa[cst.lb(v)]; // then call the extract method on the compressed suffix array extract(cst.csa, begin, begin + cst.depth(v) - 1, text); } //! Calculate the concatenation of edge labels from the root to the node v of of c CST. /*! * \tparam t_rac Random access container which should hold the result. * \tparam t_cst CSA type. * * \param cst The CST object. * \return A t_rac object holding the extracted edge label. * \return The string of the concatenated edge labels from the root to the node v. */ template <class t_cst> typename t_cst::csa_type::string_type extract( t_cst const & cst, const typename t_cst::node_type & v, SDSL_UNUSED typename std::enable_if<std::is_same<cst_tag, typename t_cst::index_category>::value, cst_tag>::type x = cst_tag()) { typedef typename t_cst::csa_type::string_type t_rac; if (v == cst.root()) { return t_rac{}; } // first get the suffix array entry of the leftmost leaf in the subtree rooted at v typename t_cst::size_type begin = cst.csa[cst.lb(v)]; // then call the extract method on the compressed suffix array return extract(cst.csa, begin, begin + cst.depth(v) - 1); } //! Calculate the zeroth order entropy of the text that follows a certain substring s /*! * \param v A suffix tree node v. The label of the path from the root to v is s. * \param cst The suffix tree of v. * \return The zeroth order entropy of the concatenation of all characters that follow * s in the original text. */ template <class t_cst> double H0(const typename t_cst::node_type & v, t_cst const & cst) { if (cst.is_leaf(v)) { return 0; } else { double h0 = 0; auto n = cst.size(v); for (auto const & child : cst.children(v)) { double p = ((double)cst.size(child)) / n; h0 -= p * log2(p); } return h0; } } //! Calculate the k-th order entropy of a text /*! * \param cst The suffix tree. * \param k Parameter k for which H_k should be calculated. * \return H_k and the number of contexts. */ template <class t_cst> std::pair<double, size_t> Hk(t_cst const & cst, typename t_cst::size_type k) { double hk = 0; size_t context = 0; std::set<typename t_cst::size_type> leafs_with_d_smaller_k; for (typename t_cst::size_type d = 1; d < k; ++d) { leafs_with_d_smaller_k.insert(cst.csa.isa[cst.csa.size() - d]); } for (typename t_cst::const_iterator it = cst.begin(), end = cst.end(); it != end; ++it) { if (it.visit() == 1) { if (!cst.is_leaf(*it)) { typename t_cst::size_type d = cst.depth(*it); if (d >= k) { if (d == k) { hk += cst.size(*it) * H0(*it, cst); } ++context; it.skip_subtree(); } } else { // if d of leaf is >= k, add context if (leafs_with_d_smaller_k.find(cst.lb(*it)) == leafs_with_d_smaller_k.end()) { ++context; } } } } hk /= cst.size(); return {hk, context}; } } // namespace sdsl #endif
true
edc91b42305f42f4ab5dcfb7966c901fa0d0f04f
C++
itsyash009/Interview_DS_Algo
/Arrays/Two Pointer/Container With Most Water.cpp
UTF-8
2,184
3.609375
4
[]
no_license
/* Company Tags : Bloomberg, Facebook, Google, Amazon, Adobe Leetcode Link : https://leetcode.com/problems/container-with-most-water/ */ //Why does my solution given below works ? /* Idea / Proof (Gathered from Discussion Section of Leetcode from some intelligent programmers) : The widest container (using first and last line) is a good candidate, because of its width. Its water level is the height of the smaller one of first and last line. All other containers are less wide and thus would need a higher water level in order to hold more water. The smaller one of first and last line doesn't support a higher water level and can thus be safely removed from further consideration. */ //Approach-1 (Two pointer Greedy (O(N)) class Solution { public: int maxArea(vector<int>& height) { int n = height.size(); int i = 0, j = n-1; int water = 0; while(i<j) { //start from the smallest one and calculate water int h = min(height[i], height[j]); int w = j-i; int area = h*w; water = max(water, area); if(height[i] < height[j]) i++; else j--; } return water; } }; //Approach-2 (Two pointer Greedy (O(N)) (It's similar to Approach-1) //Just that we are eliminating heights at one go class Solution { public: int maxArea(vector<int>& height) { int n = height.size(); int i = 0, j = n-1; int water = 0; while(i<j) { //start from the smallest one and calculate water int h = min(height[i], height[j]); int w = j-i; int area = h*w; water = max(water, area); //Then move towards large one because we can have better answer if(height[i] < while(i < j && height[i] <= h) i++; //Same, move towards large one because we can have better answer while(i < j && height[j] <= h) j--; } return water; } };
true
d543d614dd5d5d4f6e7f1ed393edbaf592e73514
C++
AliAkberAakash/_CONTESTS_
/DCC practice contest 18/D.cpp
UTF-8
717
2.515625
3
[]
no_license
#include<cstdio> #include<iostream> #define X 1000001 using namespace std; typedef long long int LLD; bool flag[X]; LLD NOD(LLD num) { LLD c=0; for(LLD i=1; i<=num; i++) if(num%i==0) c++; return c; } void theSeries() { LLD n,m; m=1; flag [1]=1; for(LLD i=1; i<=X; i++) { n=m+NOD(m); flag[n]=1; m=n; } } int main() { theSeries(); LLD a,b; int t; scanf("%d", &t); for(int i=1; i<=t; i++) { int c=0; scanf("%lld %lld", &a, &b); for(int j=a; j<=b; j++) if(flag[j]) c++; printf("Case %d: %d\n",i,c); } return 0; }
true
b3a25823b9118c8cfff7be2ce660b3ae9dd42ade
C++
carameldrizzle/intro_mechatronics_final
/motorTest/motorTest.ino
UTF-8
2,358
2.625
3
[]
no_license
//#include <Keypad.h> //#include <NewPing.h> const byte ROWS = 4; const byte COLS = 3; char hexaKeys[ROWS][COLS] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte rowPins[ROWS] = {9, 8, 7, 6}; byte colPins[COLS] = {5, 4, 3}; //Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); int enable1 = 11; int enable2 = 10; int A = 1; int B = 2; int leftPin = A0; int echoPin = 13; int trigPin = 12; const int MAX_DISTANCE = 350; //NewPing sonar(trigPin, echoPin, MAX_DISTANCE); float duration, distance; void setup() { Serial.begin(9600); pinMode(A, OUTPUT); pinMode(B, OUTPUT); pinMode(echoPin, INPUT); pinMode(trigPin, OUTPUT); digitalWrite(A, LOW); digitalWrite(B, LOW); } void loop() { delay(4000); digitalWrite(A, LOW); digitalWrite(B, HIGH); Serial.print("hey"); // rbt_forward(); // delay(3000); // Serial.print("middle"); // rbt_stop(); // delay(3000); // Serial.print("end"); // char customKey1 = customKeypad.getKey(); // Testing US // digitalWrite(trigPin, LOW); // delayMicroseconds(2); // digitalWrite(trigPin, HIGH); // delayMicroseconds(5); // digitalWrite(trigPin, LOW); // duration = pulseIn(echoPin, HIGH); // Serial.println("duration"); // Serial.println(duration); // distance = microsecondsToInches(duration); // Serial.println("distance"); // Serial.println(distance); // delay(1000); // if (distance > 5) { // rbt_stop(); // rbt_left(); // Serial.println("turn left"); // } // if (customKey1 == '9') { // digitalWrite(A, LOW); // digitalWrite(B, HIGH); // // int lSensor = analogRead(A0); // // if (lSensor < 200) { // analogWrite (enable1, 255); // left // analogWrite (enable2, 240); // } // else { // delay(50); // // duration = sonar.ping(); // distance = (duration / 2) * .0343; // // if (distance < 10) { // analogWrite (enable1, 0); // analogWrite (enable2, 240); // } // } // } } double microsecondsToInches(double microseconds) { return microseconds / 74 / 2; } void rbt_stop() { digitalWrite(A, LOW); digitalWrite(B, LOW); } void rbt_forward() { digitalWrite(A, LOW); digitalWrite(B, HIGH); } void rbt_left(int left, int right) { analogWrite(enable1, left); // left analogWrite(enable2, right); }
true
01e059aa47e83404917b87f1bf444765ea2e1115
C++
SherstiukAndrii/Prata
/Chapter 5/Exercise 2/Source.cpp
UTF-8
358
3.28125
3
[]
no_license
#include <iostream> #include <array> const int ArSize = 101; int main () { std::array<long double, ArSize> factorials; factorials [1] = factorials [0] = 1LL; for (int i {2}; i < ArSize; ++i) factorials [i] = i * factorials [i - 1]; for (int i {}; i < ArSize; ++i) std::cout << i << " ! = " << factorials [i] << std::endl; }
true
2a0235f5149ed5be20c8659ebfe3fff97ff85847
C++
shamozhishu/VayoEngine
/main/2d/inc/Vayo2dColor.h
WINDOWS-1252
2,386
2.875
3
[]
no_license
/*************************************************************************\ * 1.0 * Copyright (c) 2018-2019 authored by Ӻ * ɫ \*************************************************************************/ #ifndef __VAYO2D_COLOR_H__ #define __VAYO2D_COLOR_H__ #include "Vayo2dSupport.h" NS_VAYO2D_BEGIN inline void colorClamp(float& x) { if (x < 0.0f) x = 0.0f; if (x > 1.0f) x = 1.0f; } class Color { public: float _r, _g, _b, _a; Color(const float r, const float g, const float b, const float a = 1.0f) { _r = r; _g = g; _b = b; _a = a; } Color(const unsigned int col) { setHWColor(col); } Color() { _r = _g = _b = _a = 0; } Color operator-(const Color& c) const { return Color(_r - c._r, _g - c._g, _b - c._b, _a - c._a); } Color operator+(const Color& c) const { return Color(_r + c._r, _g + c._g, _b + c._b, _a + c._a); } Color operator*(const Color& c) const { return Color(_r * c._r, _g * c._g, _b * c._b, _a * c._a); } Color& operator-=(const Color& c) { _r -= c._r; _g -= c._g; _b -= c._b; _a -= c._a; return *this; } Color& operator+=(const Color& c) { _r += c._r; _g += c._g; _b += c._b; _a += c._a; return *this; } bool operator==(const Color& c) const { return (_r == c._r && _g == c._g && _b == c._b && _a == c._a); } bool operator!=(const Color& c) const { return (_r != c._r || _g != c._g || _b != c._b || _a != c._a); } Color operator/(const float scalar) const { return Color(_r / scalar, _g / scalar, _b / scalar, _a / scalar); } Color operator*(const float scalar) const { return Color(_r * scalar, _g * scalar, _b * scalar, _a * scalar); } Color& operator*=(const float scalar) { _r *= scalar; _g *= scalar; _b *= scalar; _a *= scalar; return *this; } void clamp() { colorClamp(_r); colorClamp(_g); colorClamp(_b); colorClamp(_a); } void setHWColor(const unsigned int col) { _a = (col >> 24) / 255.0f; _r = ((col >> 16) & 0xFF) / 255.0f; _g = ((col >> 8) & 0xFF) / 255.0f; _b = (col & 0xFF) / 255.0f; } unsigned int getHWColor() const { return (unsigned(_a * 255.0f) << 24) + (unsigned(_r * 255.0f) << 16) + (unsigned(_g * 255.0f) << 8) + unsigned(_b * 255.0f); } }; inline Color operator*(const float sc, const Color& c) { return c * sc; } NS_VAYO2D_END #endif // __VAYO2D_COLOR_H__
true
83b7a5c713cd2eb04f46fe1c5cb64e6f34434d42
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/7/1236.c
UTF-8
694
2.609375
3
[]
no_license
int main() { char str[1000], sub[500], rep[500]; int n, m, cut, i = 0, flag = 0; cin >> str >> sub >> rep; n = strlen(str); m = strlen(sub); cut = strlen(rep); while(str[i] != '\0') { if(str[i] == sub[0]) { int j = 0; int k = i; while(sub[j] != '\0') { if(sub[j] == str[k]) { j++; k++; } else break; } if(j == m) { for(int t = n-1; t >= i + m; t--) { str[t + cut - m] = str[t]; } str[n + cut - m ] = '\0'; for(int t = i; t < i + cut ;t++) { str[t] = rep[t-i]; } flag = 1; } if(flag == 1) break; } i++; } cout<<str; return 0; }
true
6959fb720678f3bd55d2436efd0a7287a5827246
C++
bayareaviking/CIS25
/cisFraction.h
UTF-8
1,241
3.09375
3
[]
no_license
/*** FILE #1: Header file or Fraction Class * Program Name cisFraction.h * Written By: Marcus Larsson * Date Written: 11/09/2011 */ #ifndef CISFRACTION_H #define CISFRACTION_H #include <iostream> using namespace std; class Fraction { public: // Constructors Fraction(); Fraction(const Fraction & arg); Fraction(int arg1, int arg2); //Destructor ~Fraction(); // Accessors int getNum(); int getDenom(); // Mutators void setNum(int arg); void setDenom(int arg); // Declared friend functions friend Fraction operator+(const Fraction & arg1, const Fraction & arg2); friend Fraction operator-(const Fraction & arg1, const Fraction & arg2); friend Fraction operator*(const Fraction & arg1, const Fraction & arg2); friend Fraction operator/(const Fraction & arg1, const Fraction & arg2); // Finding the GCD with Euclid's algorithm and reducing the fraction void reduce(int arg1, int arg2); private: int iNum; int iDenom; }; // Stand-alone functions Fraction operator+(const Fraction & arg1, const Fraction & arg2); Fraction operator-(const Fraction & arg1, const Fraction & arg2); Fraction operator*(const Fraction & arg1, const Fraction & arg2); Fraction operator/(const Fraction & arg1, const Fraction & arg2); #endif
true
04e5906e5bb3ed159a883fc607c94a3782cf2a36
C++
githubcai/leetcode
/29.cpp
UTF-8
378
2.734375
3
[]
no_license
class Solution { public: int divide(int dividend, int divisor) { if(divisor == 0) return INT_MAX; if(dividend == 0) return 0; long long res = exp(log(fabs(dividend)) - log(fabs(divisor))); if(divisor < 0) res = -res; if(dividend < 0) res = -res; if(res > INT_MAX || res < INT_MIN) return INT_MAX; return res; } };
true
60031193c0d7a4373389d8415bb686d44de2db4e
C++
kieraw/cse471-project1
/Synthie/AmpFilter.cpp
UTF-8
805
2.75
3
[]
no_license
/** * \file AmpFilter.cpp * * \author Kiera Wheatley * * \brief changes amplitude of source wave */ #include "stdafx.h" #include "AmpFilter.h" #include "Envelope.h" CAmpFilter::CAmpFilter() { } CAmpFilter::~CAmpFilter() { } void CAmpFilter::Start() { m_time = 0; // set the duration, sample rate of the envelope m_envelope->SetDuration(m_duration); m_envelope->SetSampleRate(GetSampleRate()); // start envelope generation m_envelope->Start(); } bool CAmpFilter::Generate() { // get the amplitude factor, based on envelope level auto amplitude_factor = m_envelope->GetEnvelopeLevel(); // set the frames m_frame[0] = m_source->Frame(0) * amplitude_factor; m_frame[1] = m_source->Frame(1) * amplitude_factor; // update the time m_time += GetSamplePeriod(); return m_duration > m_time; }
true
74d3a5bf9288fa04bac2d4a1f8293910a337577e
C++
yrpang/oop-Homework
/User.hpp
UTF-8
2,984
2.84375
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <ctime> #include <boost/serialization/base_object.hpp> #include <boost/serialization/vector.hpp> #ifndef USER_H #define USER_H #include "Hotel.hpp" class User { protected: int No; std::string userName; std::string passwd; std::string name; std::string phoneNum; time_t lastLogin; static int maxNo; friend class boost::serialization::access; template <class Archive> void serialize(Archive &ar, const unsigned int version) { ar &No; ar &userName; ar &passwd; ar &name; ar &phoneNum; ar &lastLogin; ar &maxNo; } public: User() {} User(std::string userName, std::string passwd, std::string name, std::string phoneNum); std::string getUserName(); int getNo(); bool login(std::string passwd); }; class Admin : public User { private: Hotel *h; friend class boost::serialization::access; template <class Archive> void serialize(Archive &ar, const unsigned int version) { ar &boost::serialization::base_object<User>(*this); ar &h; } public: Admin() {} Admin(std::string userName, std::string passwd, std::string name, std::string phoneNum, Hotel &h); void showstatus(); void setPrice(int roomNo, float newprice); void setUserDiscount(); void setDaysDiscount(); void addRoom(); void delRoom(); }; class Waiter : public User { private: Hotel *h; friend class boost::serialization::access; template <class Archive> void serialize(Archive &ar, const unsigned int version) { ar &boost::serialization::base_object<User>(*this); ar &h; } public: Waiter() {} Waiter(std::string userName, std::string passwd, std::string name, std::string phoneNum, Hotel &h); void showstatus(); void checkIn(); void changeRoom(); void checkOut(); }; class Customer : public User { private: int starLevel; int status; // 0: just resigin 1: schedual 2: in 3: finished time_t startTime; time_t endTime; time_t schedualTime; std::vector<std::string> comments; int roomNo; Hotel *h; friend class boost::serialization::access; template <class Archive> void serialize(Archive &ar, const unsigned int version) { ar &boost::serialization::base_object<User>(*this); ar &h; ar &starLevel; ar &status; ar &startTime; ar &endTime; ar &schedualTime; ar &comments; ar &roomNo; } public: Customer() {} Customer(std::string userName, std::string passwd, std::string name, std::string phoneNum, Hotel &h); void checkIn(int roomNo); int getRoomNo(); void changeRoomNo(int roomNo); int checkOut(); bool ifIn(); bool ifBook(); int getStar(); void book(); void cancel(); void comment(); }; #endif
true
07e627a024ff4ea89fe09ec9a3704a228ada70ff
C++
telugubhavya/DS
/singlelink.cpp
UTF-8
2,968
3.90625
4
[]
no_license
#include<stdio.h> #include<iostream> #include<stdlib.h> using namespace std; class s11 { struct list { int data; struct list*next; }*head; public : typedef struct list node; s11(); void create(); void insert(); void display(); int count(); int deletepos(); void insertatbeg(); void insertatmid(); void insertatend(); void search(); }; s11::s11() { head = NULL; } int main() { int ch,k,c; s11 obj; do{ cout << "\n\t main menu\n"; cout <<"\t\t 1.create\n\t\t 2.display\n\t\t 3.insert \n\t\t 4.deletepost\n"; cout << "5.count\n\t\t 6.search\n\t\t 7.exit\n"; cout <<"\n\t enter ur choice"; cin >> ch; switch(ch) { case 1 :obj.create(); break; case 2 : obj.display(); break; case 3: obj.insert(); break; case 4 : k=obj.deletepos(); cout<< "\n deleted element from the list :" << k; break; case 5 : c = obj.count(); cout << "no of elements to count : " << c; break; case 6 : obj.search(); break; case 7: exit(0); } }while(ch >0 && ch <8); } void s11:: create() { node *temp,*p; temp = new node; cout << "enter the elements"; cin >> temp->data; if (head == NULL) { temp->next = head; head = temp; } else{ p = head; while(p->next!= NULL) p = p->next; temp->next = NULL; p -> next = temp; } } void s11:: display() { int d; node *q; q = head; cout <<"\n elements in the list"; while(q!=NULL) { cout << "->" << q->data; q = q->next; } } int s11::count() { node *p; int c=0; p=head; while(p!=NULL) { p = p->next; c++; } return (c); } void s11::search() { int f = 0,k,v; node *p; p = head; cout << "enter the element to find"; cin >> k; while(p!= NULL) { if(p->data == k) { f= 1; cout << "element found"; } p = p->next; } if ( f==0) {cout << "element not found"; } } void s11::insert() { int ch; do { cout <<"\n1.insertat beg\t2.insertatmid\t3.insertatend\t4.display\t5.exit"; cout << "enter ur choice"; cin >> ch; switch(ch) { case 1: insertatbeg(); break; case 2: insertatmid(); break; case 3:insertatend(); break; case 4:display(); default : break; } } while(ch > 0 && ch<5); } void s11::insertatbeg() { node *temp; temp = new node; cout << "enter thr inserted element"; cin >> temp->data; temp->next = head; head = temp; } void s11::insertatmid() { node *temp,*p; int key; temp = new node; cout <<"enter element"; cin >> temp -> data; cout << "enter key"; cin >> key; p = head; while(p!=NULL) { if(p->data == key) { temp ->next = p->next; p->next = temp; } p = p->next; } } void s11::insertatend() { node *temp,*p; temp = new node; cout <<"enter element"; cin >> temp->data; if(head == NULL) { temp->next = head; head = temp; } else { p = head; while(p ->next!=NULL) p = p->next; temp ->next = NULL; p->next= temp; } } int s11 :: deletepos() { node *p; int pos,i,k; cout << "enter elementfor deletion"; cin >> pos; if(head!= NULL) { if( pos == 1) { k = head->data; head = head->next; return (k); } else { i=2; p = head; while((p!=NULL)&&(i<pos)) { p = p->next; i++; } if(p!=NULL) { k= p->next->data; p->next = p->next->next; return (k); } } } else cout <<"\n list is empty"; }
true
e99a712580b9bd804f39589bab3853d39ed9a3ef
C++
AnupamaRajkumar/AutomaticImageAnalysis_SoSe2020
/Assignment1/src/main.cpp
UTF-8
1,904
2.828125
3
[]
no_license
#include <iostream> #include <vector> #include "given.hpp" #include "yours.hpp" using namespace std; using namespace cv; // TODO(student): // Loads a test image and saves and shows the results of image processing // Read the docs for OpenCV! // https://docs.opencv.org/4.2.0/ int main(int argc, char** argv) { // TODO: declare some matrices for the images // https://docs.opencv.org/4.2.0/d3/d63/classcv_1_1Mat.html cout << "In main!!" << endl; //windows to display images const char* win_1 = "Original Image"; const char* win_2 = "Smoothened Image"; namedWindow(win_1); // TODO: load image // https://docs.opencv.org/4.2.0/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56 cout << "Load image" << endl; Mat inputImage = imread(argv[1]); std::string fname = "./data/test.jpg"; // check if image is loaded successfully if (!inputImage.data){ std::cerr << "ERROR: Cannot read file " << fname << std::endl; exit(-1); } // TODO: show input image // https://docs.opencv.org/master/d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563 cout << "Image loaded" << endl; cout << inputImage.dims<< endl; //display loaded image given::showImage(inputImage, win_1, 0); imwrite("original_input_image.png", inputImage); // TODO: call the function that handles the actual image processing // It's the function in yours.cpp called processImage Mat processedImage = yours::processImage(inputImage); // TODO: save result // https://docs.opencv.org/master/d4/da8/group__imgcodecs.html#gabbc7ef1aa2edfaa87772f1202d67e0ce imwrite("smooth_binary_image.png", processedImage); // TODO: show result and wait for key // https://docs.opencv.org/master/d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7 namedWindow(win_2); given::showImage(processedImage, win_2, 0); waitKey(0); return 0; }
true
ff85ebd3bacee90108055be416614dddd3ba9417
C++
SayaUrobuchi/uvachan
/TIOJ/1054.cpp
UTF-8
348
2.828125
3
[]
no_license
#include <stdio.h> #include <string.h> char str[7][20] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; char s[100]; int main() { int n, i; while(scanf("%s%d", s, &n) == 2) { for(i=0; ; i++) { if(!strcmp(str[i], s)) { break; } } i += n; i %= 7; printf("%s\n", str[i]); } return 0; }
true
9f4b2d77500fa3932ff4d4f10d991788a81f8d33
C++
anthonywgao/Jug_Problem
/Jug.h
UTF-8
1,098
3.203125
3
[]
no_license
#ifndef __JUG_H__ #define __JUG_H__ #include <iostream> #include <string> #include <vector> #include <limits> using namespace std; struct Vertex { Vertex(){ dist = numeric_limits<int>::max(); prev = 0; act = ""; } int dist; Vertex* prev; string act; }; class Jug { public: Jug(int, int, int, int, int, int, int, int, int); ~Jug(); //solve is used to check input and find the solution if one exists //returns -1 if invalid inputs. solution set to empty string. //returns 0 if inputs are valid but a solution does not exist. solution set to empty string. //returns 1 if solution is found and stores solution steps in solution string. int solve(string& solution); private: //anything else you need //returns true if a is min int min(int a, int b) { if (a > b) { return b; } return a; } int Ca; int Cb; int N; int cfA; int cfB; int ceA; int ceB; int cpAB; int cpBA; bool invalid; vector<vector<Vertex*> >graph; void buildGraph(int, int, int, Vertex*, string); void print(string&, Vertex*); }; #endif
true
167c3d38ae6fef3fb06e8347c2f3db4fef837019
C++
tventura97/AccMgmt-Console-App
/stockAccount.cpp
UTF-8
12,671
3.375
3
[]
no_license
//#include "stdafx.h" #include <iostream> #include <fstream> #include "Account.h" #include "stockAccount.h" #include <string> #include <cstdlib> #include "time.h" #include <stdio.h> #include <codecvt> #include <vector> #include <locale> #include <math.h> #include <ctime> #include <iomanip> using namespace std; vector <PortfolioItem> Items; // creates vector to store portfolio items int randomnumbercounter = 0; char LINE[256]; // Constructor. Creates Stock Transactions file. Writes Headers. stockAccount::stockAccount(double A) : Account(A) { string line = "\nAction\t\tSymbol\t\tShares\t\tPrice\t\tTime\n"; ofstream myfile; myfile.open("Transactions.txt", ios_base::app); myfile << line; myfile.close(); } //Destructor stockAccount::~stockAccount() { cout << "Termin"; } // Opens a random text file and searches the file for a stock symbol (token) string stockAccount::findstock(string token) { string line; srand(randomnumbercounter); ifstream StockFile; int randno = rand()%4 + 1; randomnumbercounter++; StockFile.open("stock"+to_string(randno)+".txt"); // open random file while(getline(StockFile, line)) { if (line.find(token) != string::npos) // search for token in file { found = 1; // if found, set found flag to 1 return line; // return line to caller } else { found = 0; // if line not found, set found flag to 0 } } if (found == 0) { return "not found"; // if line not found, return 'not found' } } // Displays stock information requested by user void stockAccount::displayPrice() { string token; cout << "Enter stock symbol for checking price: "; cin.getline(LINE,256); // gets stock symbol from user cout << LINE << endl; token = LINE; string stock; stock = findstock(token); // calls findstock(), passes stock symbol if (found == 1) // if found print line and time { cout << endl << stock + "\t\t\t\t\t\t\t\t\t\t" + gettime() << endl; found = 0; // reset flag } else if (found == 0) // if not found, print error { cout << "Stock not found" << endl; } } // Buys stock requested by user void stockAccount::buyStock() { string stock; int shares; float price; float currentprice; string currenttime = gettime(); cout << "Please enter the stock, number of shares, and price." << endl; cin.getline(LINE,256); cout << LINE << endl; stock = getInput(LINE, 0); shares = stoi(getInput(LINE, 1)); price = stof(getInput(LINE, 2)); if (findstock(stock) == "not found") // Checks if stock exists { cout << "Cannot process transaction. Stock not found." << endl; goto buyfinish; } currentprice = getprice(findstock(stock)); // if offer price < market price, transaction fails if (currentprice > price) { cout << "Cannot process transaction" << endl; cout << "Offer of " << price << " is less than market price of " << currentprice << endl; goto buyfinish; } if (shares*currentprice > cashBalance) { cout << "Cannot process transaction. Insufficient funds." << endl; // if insufficient funds, transaction fails goto buyfinish; } cout << "Buying " << shares << " shares of " << stock << " for $" << currentprice << " each." << endl; cashBalance -= shares*currentprice; // reduce cashBalance by total cost of purchase writeTransaction("Buy", stock, shares,currenttime); // calls writeTransaction() to write transaction to file updatePortfolio(stock, getcompany(findstock(stock)), shares); // calls updatePortfolio() to update portfolio (vector<PortfolioItem> Items) buyfinish: { 1+1; } } // sells stocks. Practically the same as the buyStock() function void stockAccount::sellStock() { string stock; int shares; float price; string currenttime = gettime(); float currentprice = getprice(findstock(stock)); int foundsymbol = 0; cout << "Please enter the stock, number of shares, and selling price" << endl; cin.getline(LINE,256); cout << LINE << endl; stock = getInput(LINE, 0); shares = stoi(getInput(LINE, 1)); price = stof(getInput(LINE, 2)); for (int i = 0; i < Items.size(); i++) { if (getsymbol(stock)==Items[i].Symbol) // Checks if user owns stock they want to sell { foundsymbol = 1; } } if (foundsymbol != 1) { cout << "Cannot process transaction. Stock not owned." << endl; goto sellfinish; } if (price > currentprice) { cout << "Cannot process transaction." << endl; cout << "Selling price of " << price << " is greater than market price of " << currentprice << endl; } if (price <= currentprice) { cout << "Selling " << shares << " shares of " << getsymbol(stock) << " for $" << currentprice << " each." << endl; cashBalance += shares*currentprice; writeTransaction("Sell", stock, shares,currenttime); updatePortfolio(stock, getcompany(findstock(stock)), -shares); } sellfinish: { 1+1; } } // parses inputline string stockAccount::getInput(string line, int a) { string delim = " "; vector <string> tokens; tokens.clear(); for (int i = 0; i<3; i++) { if (i == 2) { line = line.substr(line.rfind(delim)+1,string::npos); tokens.push_back(line); } tokens.push_back(line.substr(0,line.find(delim))); line = line.substr(line.find(delim)+1, string::npos); } return tokens[a]; } //Parses a line from the text files and returns the stock's symbol string stockAccount::getsymbol(string line) { string delim = "\t"; vector <string> tokens; tokens.clear(); for (int i = 0; i<3; i++) { if (i == 2) { line = line.substr(line.rfind(delim)+1,string::npos); tokens.push_back(line); } tokens.push_back(line.substr(0,line.find(delim))); line = line.substr(line.find(delim)+1, string::npos); } return tokens[0]; } //parses a line from the text file and returns the stock's company name string stockAccount::getcompany(string line) { string delim = "\t"; vector <string> tokens; tokens.clear(); for (int i = 0; i<3; i++) { if (i == 2) { line = line.substr(line.rfind(delim)+1,string::npos); tokens.push_back(line); } tokens.push_back(line.substr(0,line.find(delim))); line = line.substr(line.find(delim)+1, string::npos); } return tokens[1]; } // parses line from stock file and returns stock's price float stockAccount::getprice(string line) { string delim = "\t"; vector <string> tokens; tokens.clear(); for (int i = 0; i<3; i++) { if (i == 2) { line = line.substr(line.rfind(delim)+1,string::npos); tokens.push_back(line); } tokens.push_back(line.substr(0,line.find(delim))); line = line.substr(line.find(delim)+1, string::npos); } return stof(tokens[2]); } //writes transactions to file void stockAccount::writeTransaction(string action, string stock, int shares, string currenttime) { string line = findstock(stock); float price = getprice(line); string company = getcompany(line); string symbol = getsymbol(line); ofstream myfile; myfile.open("Transactions.txt", ios_base::app); string Line = action+"\t\t"+symbol+"\t\t"; myfile << Line; myfile << fixed << setprecision(2) << shares; Line = "\t\t"; myfile << Line; myfile << fixed << setprecision(2) << price; Line = "\t\t"+currenttime+"\n"; myfile << Line; myfile.close(); } //prints Transactions.txt file to the console void stockAccount::displayTransactions() { ifstream Transactionfile; Transactionfile.open("Transactions.txt"); string line; while (getline(Transactionfile,line)) { cout << line << endl; } } // updates portfolio vector void stockAccount::updatePortfolio(string symbol, string company, int number) { bool present; PortfolioItem newItem; newItem.CompanyName = company; newItem.Symbol = symbol; newItem.NumShares = number; for (int i = 0; i< Items.size(); i++) { if (Items[i].Symbol == symbol) { present = true; if (Items[i].NumShares + number >= 0) { if (Items[i].NumShares + number == 0) { Items[i].NumShares += number; cout << "Stock " << Items[i].Symbol << " no longer owned. All shares sold." << endl; Items.erase(Items.begin()+i); } Items[i].NumShares += number; } else if (Items[i].NumShares + number < 0) { cout << "Cannot process transaction. Insufficient Shares." << endl; } } } if (present != true) { Items.push_back(newItem); } sortStocks(); } // prints portfolio vector void stockAccount::displayCurrentPortfolio() { printf("\nCash balance = $%.2f\n\n", cashBalance); cout << "Symbol\t\tCompany\t\t\t\t\tNumber\t\tPrice\t\tTotal" << endl; double total = 0; string tab; for (int i = 0; i < Items.size(); i++) { if (Items[i].CompanyName.length() > 23) //Fixes formatting { tab = "\t\t"; } else if (Items[i].CompanyName.length() <= 23) { tab = "\t\t\t"; } cout << Items[i].Symbol+"\t\t"+Items[i].CompanyName+tab+to_string(Items[i].NumShares)+"\t\t$" << getprice(findstock(Items[i].Symbol))<< "\t\t$"; cout << fixed << setprecision(2) << getprice(findstock(Items[i].Symbol))*Items[i].NumShares << endl; total +=getprice(findstock(Items[i].Symbol))*Items[i].NumShares; } printf("\nTotal portfolio value is: %.2f\n\n", total+cashBalance); } //gets current system time. returns as a string. string stockAccount::gettime() { time_t now = time(0); tm * gmtm = gmtime(&now); string currenttime = to_string(gmtm->tm_hour) + ":" + to_string(gmtm->tm_min) + ":" + to_string(gmtm->tm_sec); return currenttime; } //sorts portfolio by symbol alphabetically. Uses insertion sort. void stockAccount::sortStocks() { PortfolioItem SMALLEST; SMALLEST.Symbol = "ZZZZ"; PortfolioItem TEMP; int place = 0; // track current location in vector int smallestindex; int charcounter = 0; int flag = 0; for (int i = 0; i < Items.size(); i ++) { SMALLEST.Symbol = "ZZZZ"; for (int j = place; j < Items.size(); j++) { charcounter = 0; // reset character counter while(charcounter < 4) { if (int(Items[j].Symbol[charcounter]) == int(SMALLEST.Symbol[charcounter])) { charcounter++; // If characters are the same, compare next character } else if (int(Items[j].Symbol[charcounter]) < int(SMALLEST.Symbol[charcounter])) { SMALLEST = Items[j]; // Smallest member is reassigned smallestindex = j; // Store location of smallest member flag = 1; break; } else if (int(Items[j].Symbol[charcounter]) > int(SMALLEST.Symbol[charcounter])) { break; } } } if (flag == 1) { TEMP = Items[place]; // Swap Items[place] = SMALLEST; Items[smallestindex] = TEMP; flag = 0; // reset flag } place ++; } }
true
b1121ceffc97b1f2d6bf19e1c674d2bde76705ab
C++
Simon-chevolleau/cppLearning
/zesteDeSavoir/containerFunction/cutStringCorrection.cpp
UTF-8
1,012
3.625
4
[]
no_license
#include <algorithm> #include <iostream> #include <string> #include <vector> int main() { std::string texte { "Voici une phrase que je vais couper." }; char const delimiteur { ' ' }; std::vector<std::string> parties {}; auto debut = std::begin(texte); auto fin = std::end(texte); auto iterateur = std::find(debut, fin, delimiteur); while (iterateur != fin) { // Grâce à std::distance, nous obtenons la taille du mot. std::string mot { debut, debut + std::distance(debut, iterateur) }; parties.push_back(mot); // +1 pour sauter le délimiteur. debut = iterateur + 1; // Et on recommence. iterateur = std::find(debut, fin, delimiteur); } // Ne pas oublier le dernier mot. std::string mot { debut, debut + std::distance(debut, iterateur) }; parties.push_back(mot); // On affiche pour vérifier. for (std::string mot : parties) { std::cout << mot << std::endl; } return 0; }
true
744cc92c84d9db0f95eb85de09bedd94f785088e
C++
andyprowl/ape
/Ape/World/Scene/src/PerspectiveProjection.cpp
UTF-8
1,959
2.71875
3
[]
no_license
#include <Ape/World/Scene/PerspectiveProjection.hpp> #include <Ape/World/Scene/Camera.hpp> #include <glm/gtc/matrix_transform.hpp> namespace ape { PerspectiveProjection::PerspectiveProjection(Frustum const & frustum, Camera & parent) : frustum{frustum} , transformation{makeProjection()} , parent{&parent} { } auto PerspectiveProjection::getTransformation() const -> glm::mat4 const & { return transformation; } auto PerspectiveProjection::getFrustum() const -> Frustum const & { return frustum; } auto PerspectiveProjection::setFrustum(Frustum const & newFrustum) -> void { frustum = newFrustum; recalculateProjectionAndNotifyParent(); } auto PerspectiveProjection::getFieldOfView() const -> float { return frustum.fieldOfView; } auto PerspectiveProjection::setFieldOfView(float const newFieldOfView) -> void { if (frustum.fieldOfView == newFieldOfView) { return; } frustum.fieldOfView = newFieldOfView; recalculateProjectionAndNotifyParent(); } auto PerspectiveProjection::getAspectRatio() const -> float { return frustum.aspectRatio; } auto PerspectiveProjection::setAspectRatio(float const newAspectRatio) -> void { if (frustum.aspectRatio == newAspectRatio) { return; } frustum.aspectRatio = newAspectRatio; recalculateProjectionAndNotifyParent(); } auto PerspectiveProjection::getParent() const -> Camera & { return *parent; } auto PerspectiveProjection::makeProjection() const -> glm::mat4 { return glm::perspective(frustum.fieldOfView, frustum.aspectRatio, frustum.near, frustum.far); } auto PerspectiveProjection::recalculateProjectionAndNotifyParent() -> void { transformation = makeProjection(); parent->updateTransformationAfterProjectionChanged(transformation); } auto PerspectiveProjection::setParent(Camera & camera) -> void { parent = &camera; } } // namespace ape
true
24acaf8a0f63e761729f7e1b80bfa25583ce4e2a
C++
vaishakp9/BillingSystem
/Billing/Comp/resource_file.cpp
UTF-8
2,786
2.71875
3
[]
no_license
#include<iostream.h> struct object_detail { char name[100]; int rate; int qty; int amt; }; /* 0. Burgers 1. Add-Ons 2. Beverages 3. Desserts */ void res() { object_detail item[4][8]; strcpy(item[0][0].name,"McSpicy Paneer"); item[0][0].rate=50; item[0][0].qty=0; item[0][0].amt=0; strcpy(item[0][1].name,"McVeggie"); item[0][1].rate=50; item[0][1].qty=0; item[0][1].amt=0; strcpy(item[0][2].name,"McAloo Tikki"); item[0][2].rate=25; item[0][2].qty=0; item[0][2].amt=0; strcpy(item[0][3].name,"McSpicy Chicken"); item[0][3].rate=65; item[0][3].qty=0; item[0][3].amt=0; strcpy(item[0][4].name,"McChicken"); item[0][4].rate=55; item[0][4].qty=0; item[0][4].amt=0; strcpy(item[0][5].name,"Chicken McGrill"); item[0][5].rate=30; item[0][5].qty=0; item[0][5].amt=0; strcpy(item[0][6].name,"Chicken Maharaja-Mac"); item[0][6].rate=80; item[0][6].qty=0; item[0][6].amt=0; strcpy(item[1][0].name,"BigSpicy Paneer Wrap"); item[1][0].rate=0; item[1][0].qty=0; item[1][0].amt=0; strcpy(item[1][1].name,"Veg Pizza McPuff"); item[1][1].rate=0; item[1][1].qty=0; item[1][1].amt=0; strcpy(item[1][2].name,"French Fries"); item[1][2].rate=0; item[1][2].qty=0; item[1][2].amt=0; strcpy(item[1][3].name,"BigSpicy Chicken Wrap"); item[1][3].rate=0; item[1][3].qty=0; item[1][3].amt=0; strcpy(item[1][4].name,"Chicken McNuggets"); item[1][4].rate=0; item[1][4].qty=0; item[1][4].amt=0; strcpy(item[2][0].name,"Cafe Mocha"); item[2][0].rate=40; item[2][0].qty=0; item[2][0].amt=0; strcpy(item[2][1].name,"Cold Coffee"); item[2][1].rate=30; item[2][1].qty=0; item[2][1].amt=0; strcpy(item[2][2].name,"Hot Chocolate"); item[2][2].rate=40; item[2][2].qty=0; item[2][2].amt=0; strcpy(item[2][3].name,"Cappuccino"); item[2][3].rate=35; item[2][3].qty=0; item[2][3].amt=0; strcpy(item[2][4].name,"Soft Drinks"); item[2][4].rate=25; item[2][4].qty=0; item[2][4].amt=0; strcpy(item[2][5].name,"Plain Tea"); item[2][5].rate=25; item[2][5].qty=0; item[2][5].amt=0; strcpy(item[2][6].name,"Iced tea"); item[2][6].rate=35; item[2][6].qty=0; item[2][6].amt=0; strcpy(item[3][0].name,"McSwirl"); item[3][0].rate=0; item[3][0].qty=0; item[3][0].amt=0; strcpy(item[3][1].name,"McFlurry"); item[3][1].rate=0; item[3][1].qty=0; item[3][1].amt=0; strcpy(item[3][2].name,"soft serve chocolate"); item[3][2].rate=0; item[3][2].qty=0; item[3][2].amt=0; strcpy(item[3][3].name,"left serve strawberry"); item[3][3].rate=0; item[3][3].qty=0; item[3][3].amt=0; strcpy(item[3][4].name,"McShake(chocolate)"); item[3][4].rate=0; item[3][4].qty=0; item[3][4].amt=0; strcpy(item[3][5].name,"McShake(strawberry)"); item[3][5].rate=0; item[3][5].qty=0; item[3][5].amt=0; }
true
dab49ffebb8cfdb98829bd2406a07fdcf861acf4
C++
errata-c/pathfinder_cpp
/gpu/Enums.hpp
UTF-8
4,298
2.515625
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once #include <cinttypes> #include <iosfwd> #include <string_view> namespace pf { enum class TextureFormat { R8, R16F, RGBA8, RGBA16F, RGBA32F, }; std::size_t channels(TextureFormat format) noexcept; std::size_t bytesPerPixel(TextureFormat format) noexcept; enum class ProgramKind { Raster, Compute }; enum class VertexAttrType { F32, I8, I16, I32, U8, U16, }; enum class BufferTarget { Vertex, Index, Storage, }; enum class BufferUploadMode { Static, Dynamic, }; enum class ShaderKind { Vertex, Fragment, Compute, }; enum class Primitive { Triangles, Lines, }; enum class BlendFactor { Zero, One, SrcAlpha, OneMinusSrcAlpha, DestAlpha, OneMinusDestAlpha, DestColor, }; enum class BlendOp { Add, Subtract, ReverseSubtract, Min, Max, }; enum class DepthFunc { Less, Always, }; enum class StencilFunc { Always, Equal, }; enum class VertexAttrClass { Float, FloatNorm, Int, }; enum class ImageAccess { Read, Write, ReadWrite, }; enum class TextureSamplingFlags : uint8_t { None = 0, RepeatU = 1, RepeatV = 1 << 1, NearestMin = 1 << 2, NearestMag = 1 << 3, All = 0xF, }; enum class FeatureLevel { D3D9, D3D11, }; std::string_view to_string_view(pf::TextureFormat val); std::string_view to_string_view(pf::VertexAttrType val); std::string_view to_string_view(pf::BufferUploadMode val); std::string_view to_string_view(pf::ShaderKind val); std::string_view to_string_view(pf::Primitive val); std::string_view to_string_view(pf::BlendFactor val); std::string_view to_string_view(pf::BlendOp val); std::string_view to_string_view(pf::DepthFunc val); std::string_view to_string_view(pf::StencilFunc val); std::string_view to_string_view(pf::VertexAttrClass val); std::string_view to_string_view(pf::ImageAccess val); std::string_view to_string_view(pf::FeatureLevel val); std::string_view to_string_view(pf::ProgramKind val); std::string to_string(pf::TextureFormat val); std::string to_string(pf::VertexAttrType val); std::string to_string(pf::BufferUploadMode val); std::string to_string(pf::ShaderKind val); std::string to_string(pf::Primitive val); std::string to_string(pf::BlendFactor val); std::string to_string(pf::BlendOp val); std::string to_string(pf::DepthFunc val); std::string to_string(pf::StencilFunc val); std::string to_string(pf::VertexAttrClass val); std::string to_string(pf::ImageAccess val); std::string to_string(pf::FeatureLevel val); std::string to_string(pf::ProgramKind val); bool contains(pf::TextureSamplingFlags lh, pf::TextureSamplingFlags rh) noexcept; }; pf::TextureSamplingFlags operator|(pf::TextureSamplingFlags lh, pf::TextureSamplingFlags rh) noexcept; pf::TextureSamplingFlags operator&(pf::TextureSamplingFlags lh, pf::TextureSamplingFlags rh) noexcept; pf::TextureSamplingFlags operator^(pf::TextureSamplingFlags lh, pf::TextureSamplingFlags rh) noexcept; pf::TextureSamplingFlags operator~(pf::TextureSamplingFlags lh) noexcept; pf::TextureSamplingFlags& operator|=(pf::TextureSamplingFlags& lh, pf::TextureSamplingFlags rh) noexcept; pf::TextureSamplingFlags& operator&=(pf::TextureSamplingFlags& lh, pf::TextureSamplingFlags rh) noexcept; pf::TextureSamplingFlags& operator^=(pf::TextureSamplingFlags& lh, pf::TextureSamplingFlags rh) noexcept; std::ostream& operator<<(std::ostream& os, pf::TextureFormat val); std::ostream& operator<<(std::ostream& os, pf::VertexAttrType val); std::ostream& operator<<(std::ostream& os, pf::BufferUploadMode val); std::ostream& operator<<(std::ostream& os, pf::ShaderKind val); std::ostream& operator<<(std::ostream& os, pf::Primitive val); std::ostream& operator<<(std::ostream& os, pf::BlendFactor val); std::ostream& operator<<(std::ostream& os, pf::BlendOp val); std::ostream& operator<<(std::ostream& os, pf::DepthFunc val); std::ostream& operator<<(std::ostream& os, pf::StencilFunc val); std::ostream& operator<<(std::ostream& os, pf::VertexAttrClass val); std::ostream& operator<<(std::ostream& os, pf::ImageAccess val); std::ostream& operator<<(std::ostream& os, pf::FeatureLevel val); std::ostream& operator<<(std::ostream& os, pf::TextureSamplingFlags val); std::ostream& operator<<(std::ostream& os, pf::ProgramKind val);
true
381607ba51c55aa915a3866fb28c5995754882fb
C++
yakataN/arihon_practice
/ch02_1/11_next_permutation.cpp
UTF-8
701
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> lpair; const ll MOD = 1e9 + 7; const ll INF = 1e18; #define REP(i,m,n) for(ll i = (m); i < (n); i++) #define rep(i,n) REP(i, 0, n) #define rrep(i,n) REP(i,1,n+1) // void print(const std::vector<int>& v) // { // std::for_each(v.begin(), v.end(), [](int x) { // std::cout << x << " "; // }); // std::cout << std::endl; // } int main () { // 昇順にソート済みの入力 std::vector<int> v = {1, 2, 3, 4}; do { // print(v); for (auto itr = v.begin();itr!=v.end();itr++) { cout << *itr << " "; } cout << endl; } while (std::next_permutation(v.begin(), v.end())); }
true
0a55b8edb366d3cd34b8c25782c738eb4b009b41
C++
blickens/flie
/Header/Formula.h
ISO-8859-3
6,386
2.5625
3
[ "MIT" ]
permissive
/* MIT License Copyright (c) [2019] [Joshua Blickensdrfer] 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. */ #pragma once #include <vector> #include <z3++.h> #include <time.h> #include "Header/Grammar.h" #include "Header/Dag.h" #include "Header/Sample_Tracer.h" #include <memory> /* Structure to represent the DAG. */ struct Node { int formula; Node *left; Node *right; }; /* Class which can handle solver and optimizer */ class Solve_And_Optimize { public: bool using_Optimize = false; Solve_And_Optimize(){} virtual void add(z3::expr expr) {} virtual void add(z3::expr expr, int weight) {} }; class Sat_Solver:public Solve_And_Optimize{ public: z3::solver& solver; Sat_Solver(z3::solver& solver):solver(solver){}; void add(z3::expr expr){ solver.add(expr); } }; class Max_Sat_Solver:public Solve_And_Optimize{ public: z3::optimize& optimize; Max_Sat_Solver(z3::optimize& optimize):optimize(optimize) {using_Optimize = true;} void add(z3::expr expr){ optimize.add(expr); } void add(z3::expr expr, int weight) { optimize.add(expr, weight); } }; class Formula { public: //Methods:--------------------------------------------------------------- Formula(); /* Find a LTL formula fullfilling all requirements. */ std::string find_LTL(); /* Set the grammar if a grammar is used. */ void set_Grammar(std::vector<std::string>& grammar); /* Adds all formulas for the first iteration of the algorithm. */ void initialize(); /* Sets the iteration in which an optimizer is used instead of a solver. optimized_Run: the iteration in which an optimizer should be used */ void set_Optimized_Run(int optimized_Run) {this->optimized_Run = optimized_Run;}; /* Sets the setting of all data structures to use an incremental solver and constructs this solver. */ void set_Using_Incremental(); void set_Vebose(int verbose) { this->verbose = verbose;}; ~Formula(); protected: //Attributes:------------------------------------------------------------ /* The higher verbose is the more outputs are made. */ int verbose = 0; /* The current iteration. */ int iteration = 0; /* Is true when a grammar is used. */ bool using_Grammar = false; /* The iteration in which an optimizer instead of a solver is used. (1,...) */ int optimized_Run = 0; /* The number of variables used in each letter. */ int number_Of_Variables; /* Is true if an incremental solver is used */ bool using_Incremental = false; /* The context where all expressions are added. */ z3::context context; /* Pointer to the solver used in the incremental case. Only is defined if an incremental approach is used */ z3::solver* solver; /* Contains all formulas and variables for the positive sample. */ std::unique_ptr<Sample_Tracer> positive_Sample; /* Contains all formulas and variables for the negative sample. */ std::unique_ptr<Sample_Tracer> negative_Sample; /* Contains all formulas and variables for the DAG. */ std::unique_ptr<Dag> dag; /* Contains all formulas and variables for the grammar. */ std::unique_ptr<Grammar> context_Free_Grammar; /* Used in order to take the time */ clock_t start; /* Used in order to take the time */ clock_t finish; /* Used in order to take the time */ double z3_Time; /* Used in order to take the time */ double own_Execution_Time; /* Is true if and only if a SLTL file should be examined */ bool using_SLTL = false; /* Is true if and only if a LTL file should be examined */ bool using_LTL = false; //Methods:--------------------------------------------------------------- /* Add all the new variables for the next iteration. */ void add_Variables(); /* Prepares all variables and formulas for the next iteration. */ void prepare_New_Iteration(); /* Builds the tree from the satisfying assignment. model: the satisfying assignment root: index of the current node node_Vector: array containing pointers to all the constructed nodes touched: vector saying wether a node was already constructed */ virtual Node* build_Tree(z3::model &model, int root, Node** node_Vector, std::vector<bool>& touched); /* Solves the current iteration. */ std::pair<bool, std::string> solve_Iteration(); /* Solves the current iteration with an incremental solver. */ std::pair<bool, std::string> solve_Iteration_Incrementally(); /* Solves the current iteration with an optimizer. */ std::pair<bool, std::string> solve_Iteration_Optimize(); /* Constructs a string representing the formula of the tree. root: root of the tree */ virtual std::string print_Tree(Node *root); /* Adds all formulas to the Solver/Optimizer and checks the satisfiablility */ void add_Formulas(Solve_And_Optimize& solver_Optimizer); /* Creates the tree and Formula when everything is satisfiable */ void make_Result(z3::model& model, std::pair<bool, std::string>& result); /* sets the using_LTL variable to be true */ void set_LTL() { using_LTL = true; }; /* sets the using_SLTL variable to be true */ void set_STL() { using_SLTL = true; }; };
true
183e948569f7e3550a24232ee943f79b37bf34fe
C++
MeiRenxing/ShotStick
/ShotStick/ShotStick.cpp
UTF-8
4,003
2.90625
3
[]
no_license
#include "ShotStick.h" #include "Game.h" #include "TextureManager.h" ShotStick::ShotStick() :m_fingerId(-1)//当前无手指绑定 { m_relativePoint.x = 0; m_relativePoint.y = 0; } ShotStick::~ShotStick() { } bool ShotStick::init(const std::string& rockerID, const std::string& backgroundID) { m_rockerID = rockerID; m_backgroundID = backgroundID; //获取摇杆rect SDL_Rect rect1 = TheTextureManager::Instance()->getTextureRectFromId(rockerID); SDL_Rect rect2 = TheTextureManager::Instance()->getTextureRectFromId(backgroundID); //圆半径 m_outCircle.radius = rect1.w/2; m_inCircle.radius = rect2.w/2; return true; } void ShotStick::draw(SDL_Renderer * ren) { // 画出虚拟摇杆画出外圆 int screenW = TheGame::getInstance()->getGameWidth(); int screenH = TheGame::getInstance()->getGameHeight(); // 圆心 m_inCircle.x = m_outCircle.x = m_outCircle.radius; m_inCircle.y = m_outCircle.y = screenH - m_outCircle.radius; TheTextureManager::Instance()->draw(m_rockerID ,m_outCircle.x - m_outCircle .radius,m_outCircle.y - m_outCircle.radius); // 画出内圆 TheTextureManager::Instance()->draw(m_backgroundID ,m_inCircle.x + m_relativePoint.x - m_inCircle.radius ,m_inCircle.y + m_relativePoint.y - m_inCircle.radius); } void ShotStick::update() { } Vector2D ShotStick::getVelocity() { double x = m_relativePoint.x; double y = m_relativePoint.y; double r = std::sqrt(x * x + y * y); if (r == 0) return Vector2D(0, 0); /* sin = y/r; cos = x/r; */ r = m_outCircle.radius; return Vector2D(x / r, y / r); } void ShotStick::handleEvents(SDL_Event* event) { switch (event->type) { case SDL_MOUSEBUTTONDOWN: { if (event->button.button != SDL_BUTTON_LEFT) break; Sint32 x = event->motion.x, y = event->motion.y; auto distance = std::sqrt(std::pow(x - m_outCircle.x, 2) + std::pow(y - m_outCircle.y, 2)); //超出距离 if (distance > m_outCircle.radius) { m_fingerId = -1; break; } else m_fingerId = 0; } case SDL_MOUSEMOTION: { if (m_fingerId == -1) break; Sint32 x = event->motion.x, y = event->motion.y; //保证不会超过摇杆背景圆 double x_average = x - m_outCircle.x; double y_average = y - m_outCircle.y; double d = std::sqrt(std::pow(x_average, 2) + std::pow(y_average, 2)); double m = d > m_outCircle.radius ? m_outCircle.radius : d; m_relativePoint.x = m * (x_average / d); m_relativePoint.y = m * (y_average / d); }break; case SDL_MOUSEBUTTONUP: { if (event->button.button != SDL_BUTTON_LEFT) break; m_fingerId = -1; m_relativePoint.x = 0.0; m_relativePoint.y = 0.0; }break; case SDL_FINGERDOWN: { SDL_Finger finger; finger.x = event->tfinger.x * TheGame::getInstance()->getGameWidth(); finger.y = event->tfinger.y * TheGame::getInstance()->getGameHeight(); // 绑定有效id if (m_fingerId == -1 && std::sqrt(std::pow(finger.x - m_outCircle.x, 2) + std::pow(finger.y - m_outCircle.y, 2)) <= m_outCircle.radius) m_fingerId = event->tfinger.fingerId; } case SDL_FINGERMOTION: { SDL_FingerID id = event->tfinger.fingerId; // 如果不相等,退出 if (m_fingerId != id) break; SDL_Finger finger; finger.id = id; finger.x = event->tfinger.x * TheGame::getInstance()->getGameWidth(); finger.y = event->tfinger.y * TheGame::getInstance()->getGameHeight(); double x_average = finger.x - m_outCircle.x; double y_average = finger.y - m_outCircle.y; double d = std::sqrt(std::pow(x_average, 2) + std::pow(y_average, 2)); double m = d > m_outCircle.radius ? m_outCircle.radius : d; m_relativePoint.x = m * (x_average / d); m_relativePoint.y = m * (y_average / d); }break; case SDL_FINGERUP: { SDL_FingerID id = event->tfinger.fingerId; // 如果为有效id if (id == m_fingerId) { m_relativePoint.x = 0; m_relativePoint.y = 0; m_fingerId = -1; } }break; }// end switch } void ShotStick::clean() { }
true
7ff76a7756f0549f7391af5046d84904664284d5
C++
orangezeit/leetcode
/CPP/0601-0700/0684-Redundant-Connection.cpp
UTF-8
991
2.90625
3
[ "BSD-3-Clause" ]
permissive
template<typename T> struct DynamicUnion { unordered_map<T, T> parents; unordered_map<T, int> ranks; constexpr T find(const T& x) { if (x != parents[x]) parents[x] = find(parents[x]); return parents[x]; } constexpr void unite(const T& x, const T& y) { const T px(find(x)), py(find(y)); if (px == py) return; ranks[px] >= ranks[py] ? parents[py] = px : parents[px] = py; if (ranks[px] == ranks[py]) ranks[px]++; } }; class Solution { public: vector<int> findRedundantConnection(vector<vector<int>>& edges) { DynamicUnion<int> uf; for (const vector<int>& e: edges) { if (uf.parents[e[0]] && uf.parents[e[1]] && uf.find(e[0]) == uf.find(e[1])) return {e[0], e[1]}; if (!uf.parents[e[0]]) uf.parents[e[0]] = e[0]; if (!uf.parents[e[1]]) uf.parents[e[1]] = e[1]; uf.unite(e[0], e[1]); } return {}; } };
true
2ee7d9066126e5cf47ac1b8fc3d2896841cbd91a
C++
labanau/HackerRank_30_DaysOfCode
/Day 8_ Dictionaries and Maps.cpp
UTF-8
728
3.0625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <map> #include <string> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int i, n; cin>>n; string name, number, key; map<string, string> phone_dir; for(i=0; i<n; i++) { cin>>name>>number; phone_dir.insert(pair <string, string> (name, number)); } while(cin>>key) { if (auto res = phone_dir.find(key); res != phone_dir.end()) { std::cout << key << "=" << res->second << std::endl; } else { std::cout << "Not found" << std::endl; } } return 0; }
true
6f5390045dbebb5c3e9c1348b2af6359dd470183
C++
SadMathLovergo/LeetCodeSolution
/130Solve/130Solve.cpp
GB18030
2,068
3.609375
4
[]
no_license
#include <vector> #include <iostream> using namespace std; /************************************ ˼· ֻб߽ϵ'O'Լ߽ϵ'O''O'ᱻ'X'Χ ˣҳвڱ߽ϣҲ߽ϵ'O''O' floodfill㷨Ա߽ϵ'O'бҵ߽ϵ'O''O'ʣµ'O'ΪƵ'O' ************************************/ class Solution { private: int RowSize;// int ColumnSize;// vector<vector<bool>> isSurrounded;//滷ϢƵ'O'ΪtrueΪfalse vector<vector<int>> direction{ vector<int>{-1,0},vector<int>{0,1}, vector<int>{1,0}, vector<int>{0,-1} }; //жǷϷ bool inArea(int i, int j) { return i >= 0 && i < RowSize && j >= 0 && j < ColumnSize; } //ҵ뵱ǰ'O'ڵ'O'isSurroundedϢ void floodfill(int iIndex, int jIndex) { //ΪǷΪ'X'ΪѾ'O' if (!inArea(iIndex, jIndex) || !isSurrounded[iIndex][jIndex]) return; isSurrounded[iIndex][jIndex] = false; for (int i = 0; i < 4; i++) floodfill(iIndex + direction[i][0], jIndex + direction[i][1]); } public: void solve(vector<vector<char>>& board) { if (board.empty()) return; RowSize = board.size(); ColumnSize = board[0].size(); isSurrounded = vector<vector<bool>>(RowSize, vector<bool>(ColumnSize, false)); //һ'O'Ϊtrue'X'Ϊfalse for (int i = 0; i < RowSize; i++) { for (int j = 0; j < ColumnSize; j++) { if (board[i][j] == 'O') isSurrounded[i][j] = true; } } //±߽ for (int i = 0; i < ColumnSize; i++) { floodfill(0, i); floodfill(RowSize - 1, i); } //ұ߽ for (int i = 0; i < RowSize; i++) { floodfill(i, 0); floodfill(i, ColumnSize - 1); } // for (int i = 0; i < RowSize; i++) for (int j = 0; j < ColumnSize; j++) if (isSurrounded[i][j]) board[i][j] = 'X'; } };
true
8722f81b3b8e238f1b244f4f5a4f1b4977bd12d1
C++
Ungerfall/VS-Solutions
/OOP_labrab2/OOP_labrab2/CEllipse.cpp
WINDOWS-1251
1,640
3.5
4
[]
no_license
#include "CEllipse.h" using namespace std; const double pi = 3.14; CEllipse::CEllipse() :a(CPoint(0, 3)), b(CPoint(0, 0)), c(CPoint(3, 0)) {} // CEllipse::CEllipse(CPoint& a, CPoint& b, CPoint& c) :a(a), b(b), c(c) {} std::string CEllipse::Name() { return ""; } void CEllipse::About() { cout << "\n: " << "\t" << this->Name() << endl; cout << " :" << endl; cout << "a:\t\t" << this->GetEdgeA() << endl; cout << "b:\t\t" << this->GetEdgeB() << endl; cout << ":" << "\t" << this->Square(); } double CEllipse::Square() { double sqr; sqr = pi * this->GetEdgeA() * this->GetEdgeB(); return abs(sqr); } // void CEllipse::SetEdge(CPoint& a, CPoint& b) { this->a = a; this->b = b; } // void CEllipse::SetA(CPoint& a) { this->a = a; } // B void CEllipse::SetB(CPoint& b) { this->b = b; } // CPoint& CEllipse::GetPointA() { return this->a; } // B CPoint& CEllipse::GetPointB() { return this->b; } // C CPoint& CEllipse::GetPointC() { return this->c; } // double CEllipse::GetEdgeA() { return abs((this->a.GetX() - this->b.GetX()) - (this->a.GetY() - this->b.GetY())); } // B double CEllipse::GetEdgeB() { return abs((this->b.GetX() - this->c.GetX()) - (this->b.GetY() - this->c.GetY())); }
true
ce1fa472313de6c2959f504596de1a6f967963e2
C++
YanOlerinskiy/Complex
/complex.h
UTF-8
1,315
2.9375
3
[]
no_license
#ifndef COMPLEX_H #define COMPLEX_H #include <iostream> #include <vector> #include <cmath> using namespace std; const double EPS = 0.0000001; class Complex { public: Complex(); Complex(double real, double imag = 0.0); double c_real() const { return real; } double c_imag() const { return imag; } vector<Complex> roots(int n); friend Complex operator+ (const Complex &a, const Complex &b); friend Complex operator- (const Complex &a, const Complex &b); friend Complex operator* (const Complex &a, const Complex &b); friend Complex operator/ (const Complex &a, const Complex &b); friend ostream& operator<< (ostream &os, const Complex &a); friend istream& operator>> (istream &is, const Complex &a); friend Complex pow(const Complex &z, int n); friend vector<Complex> roots(Complex &a, double n); Complex& operator+= (const Complex &other); Complex& operator-= (const Complex &other); Complex& operator*= (const Complex &other); Complex& operator/= (const Complex &other); bool operator== (const Complex &other) const; bool operator!= (const Complex &other) const; Complex conjugate() const; protected: double real; double imag; }; Complex polar(double r, double phi); double fabs(const Complex &c); #endif // COMPLEX_H
true
84e9afc48f48c7bbd10c89bc5b393ef82f9573fe
C++
jontoto/autoplanter
/src/moisture_sensor.cpp
UTF-8
696
2.734375
3
[]
no_license
#include <chrono> #include <memory> #include <thread> #include "adc_mcp3008.hpp" #include "digital_pin.hpp" #include "moisture_sensor.hpp" MoistureSensor::MoistureSensor(int power_pin, int analog_channel) : m_analog_channel{analog_channel} { m_power = std::make_shared<DigitalPin>(power_pin); m_reader = std::make_shared<ADCMcp3008>(SPI_CHANNEL_ID, SPI_FREQUENCY_HZ); } int MoistureSensor::get_reading() { m_power->turn_on(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); uint32_t sensor_value = m_reader->read_channel(m_analog_channel); // Turn off the power pin so the sensor doesn't corrode m_power->turn_off(); return (int) sensor_value; }
true
5d6545d5a1fee60228661af63f8976a02763fdf8
C++
kashifjumani115/HacktoberFest21
/Factorial.cpp
UTF-8
205
2.703125
3
[]
no_license
#include<iostream> using namespace std; int main() { int f=1,n,i; cout<<"Enter the value of n:"; cin>>n; for(i=1;i<=n;i++) { f=f*i; } cout<<"Factorial of n is: "<<f<<endl; }
true
35366124aad7f17b9f8c8b77b5cf138da884092a
C++
mohsin0176/C-Plus-Plus-Notes
/Basic Programme/armstrong-2-interval.cpp
UTF-8
377
2.890625
3
[]
no_license
#include<iostream> using namespace std; int main() { int num1,num2,i,num,digit,sum; cin>>num1>>num2; for(i=num1;i<=num2;i++) { sum=0; num=i; for(;num>0;num=num/10) { digit=num%10; sum=sum+digit*digit*digit; } if(sum==i) { cout<<i<<endl; } } return 0; }
true
b02f6ac8cd74f398ea234944782e969f57fc645e
C++
yuanrongxi/leveldb
/mutexlock.h
WINDOWS-1252
449
2.734375
3
[]
no_license
#ifndef __LEVEL_DB_MUTEXLOCK_H_ #define __LEVEL_DB_MUTEXLOCK_H_ namespace leveldb{ class SCOPED_LOCKABLE MutexLock { public: explicit MutexLock(port::Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) { this->mu_->Lock(); } ~MutexLock() UNLOCK_FUNCTION() { this->mu_->Unlock(); } private: //ؿ͸ֵ MutexLock(const MutexLock&); void operator=(const MutexLock&); port::Mutex *const mu_; }; } #endif
true
19418fbfd234920b6da512592ab2da93341845c8
C++
maryana-la/cpp_modules
/cpp05/ex03/PresidentialPardonForm.cpp
UTF-8
878
2.890625
3
[]
no_license
#include "PresidentialPardonForm.hpp" PresidentialPardonForm::PresidentialPardonForm() {} PresidentialPardonForm::PresidentialPardonForm(const std::string tar) : Form("PresidentialPardon", 25, 5), _target(tar) {} PresidentialPardonForm::PresidentialPardonForm(const PresidentialPardonForm &other) : Form(other), _target(other._target) {} PresidentialPardonForm::~PresidentialPardonForm() {} std::string PresidentialPardonForm::getTarget () const { return (this->_target); } PresidentialPardonForm & PresidentialPardonForm::operator=(const PresidentialPardonForm &other) { if (this == &other) return (*this); Form::operator=(other); return (*this); } void PresidentialPardonForm::execute(Bureaucrat const & executor) const { Form::checkExecRights(executor); std::cout << this->getTarget() << " has been pardoned by Zafod Beeblebrox!" << std::endl; }
true
e12a7d0479e5bf899b3f852c3a8ea62d2c3be97c
C++
kristiantorres/acoustic_isotropic_operators
/acoustic_iso_lib/seis_utils/seis_utils_float/src/interpBSpline2d.cpp
UTF-8
34,806
2.6875
3
[]
no_license
#include <string> #include <iostream> #include "interpBSpline2d.h" #include <omp.h> #include <vector> // Contructor interpBSpline2d::interpBSpline2d(int zOrder, int xOrder, std::shared_ptr<float1DReg> zControlPoints, std::shared_ptr<float1DReg> xControlPoints, axis zDataAxis, axis xDataAxis, int nzParamVector, int nxParamVector, int scaling, float zTolerance, float xTolerance, int fat){ // B-spline parameters _zOrder = zOrder; // Order of interpolation in the z-direction _xOrder = xOrder; // Order of interpolation in the x-direction _scaling = scaling; // if = 1, compute and apply scaling to balance operator amplitudes // Model _zControlPoints = zControlPoints; _xControlPoints = xControlPoints; _nzModel = _zControlPoints->getHyper()->getAxis(1).n; // Number of control points in the z-direction _nxModel = _xControlPoints->getHyper()->getAxis(1).n; // Number of control points in the x-direction _nModel = _nzModel*_nxModel; // Total model size // Initialize the scale vector to 1.0 _scaleVector=std::make_shared<float2DReg>(_nzModel, _nxModel); #pragma omp parallel for for (int ixModel=0; ixModel<_nxModel; ixModel++){ for (int izModel=0; izModel<_nzModel; izModel++){ (*_scaleVector->_mat)[ixModel][izModel]=1.0; } } // Data _fat = fat; _zDataAxis = zDataAxis; // z-coordinates of data points assumed to be uniformly distributed _xDataAxis = xDataAxis; // x-coordinates of data points assumed to be uniformly distributed _nzData = _zDataAxis.n; _nxData = _xDataAxis.n; _nData = _zDataAxis.n*_xDataAxis.n; _zData = std::make_shared<float1DReg>(_nzData); _xData = std::make_shared<float1DReg>(_nxData); // Compute z- and x-positions of data points on each axis for (int izData=0; izData<_nzData; izData++){ (*_zData->_mat)[izData]=_zDataAxis.o+_zDataAxis.d*izData; } for (int ixData=0; ixData<_nxData; ixData++){ (*_xData->_mat)[ixData]=_xDataAxis.o+_xDataAxis.d*ixData; } // Set the tolerance [km] _zTolerance=zTolerance*_zDataAxis.d; _xTolerance=xTolerance*_xDataAxis.d; // Number of points to evaluate in the parameter vectors _nzParamVector = nzParamVector; _nxParamVector = nxParamVector; // Build the knot vectors buildKnotVectors2d(); // Compute parameter vectors _zParamVector = computeParamVectorZ(); _xParamVector = computeParamVectorX(); // Compute scale for amplitude balancing if(_scaling == 1) { _scaleVector = computeScaleVector(); } } // Model mesh std::shared_ptr<float1DReg> interpBSpline2d::getZMeshModel(){ _zMeshModelVector = std::make_shared<float1DReg>(_nModel); #pragma omp parallel for collapse(2) for (int ix=0; ix<_nxModel; ix++){ for (int iz=0; iz<_nzModel; iz++){ int i=ix*_nzModel+iz; (*_zMeshModelVector->_mat)[i]=(*_zControlPoints->_mat)[iz]; } } return _zMeshModelVector; } std::shared_ptr<float1DReg> interpBSpline2d::getXMeshModel(){ _xMeshModelVector = std::make_shared<float1DReg>(_nModel); #pragma omp parallel for collapse(2) for (int ix=0; ix<_nxModel; ix++){ for (int iz=0; iz<_nzModel; iz++){ int i=ix*_nzModel+iz; (*_xMeshModelVector->_mat)[i]=(*_xControlPoints->_mat)[ix]; } } return _xMeshModelVector; } // Data mesh std::shared_ptr<float1DReg> interpBSpline2d::getZMeshData(){ _zMeshDataVector = std::make_shared<float1DReg>(_nData); // Build mesh vectors (1D array) for the fine grid for (int ix=0; ix<_nxData; ix++){ for (int iz=0; iz<_nzData; iz++){ int i=ix*_nzData+iz; (*_zMeshDataVector->_mat)[i]=(*_zData->_mat)[iz]; } } return _zMeshDataVector; } std::shared_ptr<float1DReg> interpBSpline2d::getXMeshData(){ _xMeshDataVector = std::make_shared<float1DReg>(_nData); // Build mesh vectors (1D array) for the fine grid for (int ix=0; ix<_nxData; ix++){ for (int iz=0; iz<_nzData; iz++){ int i=ix*_nzData+iz; (*_xMeshDataVector->_mat)[i]=(*_xData->_mat)[ix]; } } return _xMeshDataVector; } // Knot vectors for both directions void interpBSpline2d::buildKnotVectors2d() { // Knots for the z-axis _nkz=_nzModel+_zOrder+1; // Number of knots _nkzSimple=_nkz-2*_zOrder; // Number of simple knots _okz = 0.0; // Position of FIRST knot _fkz = 1.0; // Position of LAST knot _dkz=(_fkz-_okz)/(_nkzSimple-1); // Knot sampling _dkz3=_dkz*_dkz*_dkz; _dkz2=_dkz*_dkz; _kzAxis = axis(_nkz, _okz, _dkz); // Knot axis _zKnots = std::make_shared<float1DReg>(_kzAxis); // Knots for the x-axis _nkx=_nxModel+_xOrder+1; // Number of knots _nkxSimple=_nkx-2*_xOrder; // Number of simple knots _okx = 0.0; // Position of FIRST knot _fkx = 1.0; // Position of LAST knot _dkx=(_fkx-_okx)/(_nkxSimple-1); // Knot sampling _dkx3=_dkx*_dkx*_dkx; _dkx2=_dkx*_dkx; _kxAxis = axis(_nkx, _okx, _dkx); // Knot axis _xKnots = std::make_shared<float1DReg>(_kxAxis); // Compute starting knots with multiplicity > 1 (if order>0) for (int ikz=0; ikz<_zOrder+1; ikz++){ (*_zKnots->_mat)[ikz] = _okz; } // Compute knots with multiplicity 1 for (int ikz=_zOrder+1; ikz<_nkz-_zOrder; ikz++){ (*_zKnots->_mat)[ikz] = _okz+(ikz-_zOrder)*_dkz; } // Compute end knots with multiplicity > 1 (if order>0) for (int ikz=_nkz-_zOrder; ikz<_nkz; ikz++){ (*_zKnots->_mat)[ikz] = _fkz; } // Compute starting knots with multiplicity > 1 (if order>0) for (int ikx=0; ikx<_xOrder+1; ikx++){ (*_xKnots->_mat)[ikx] = _okx; } // Compute knots with multiplicity 1 for (int ikx=_xOrder+1; ikx<_nkx-_xOrder; ikx++){ (*_xKnots->_mat)[ikx] = _okx+(ikx-_xOrder)*_dkx; } // Compute end knots with multiplicity > 1 (if order>0) for (int ikx=_nkx-_xOrder; ikx<_nkx; ikx++){ (*_xKnots->_mat)[ikx] = _fkx; } } // Compute parameter vector containing optimal parameters std::shared_ptr<float1DReg> interpBSpline2d::computeParamVectorZ(){ // Generate u (z-direction) int nu = _nzParamVector; float ou = _okz; float fu = _fkz; float du = (fu-ou)/(nu-1); nu=nu-1; std::shared_ptr<float1DReg> u(new float1DReg(nu)); axis uAxis = axis(nu, ou, du); std::shared_ptr<float1DReg> paramVector(new float1DReg(_nzData)); // Initialize param vector with -1 #pragma omp parallel for for (int iData=0; iData<_nzData; iData++){ (*paramVector->_mat)[iData]=-1.0; } // Loop over data space #pragma omp parallel for for (int izData=_fat; izData<_nzData-_fat; izData++){ float error=100000; for (int iu=0; iu<nu; iu++){ float uValue=ou+iu*du; float zInterp = 0; for (int izModel=0; izModel<_nzModel; izModel++){ float sz=uValue-(*_zKnots->_mat)[izModel]; float sz3=sz*sz*sz; float sz2=sz*sz; float zWeight=0.0; if ( sz>=0.0 && sz<4.0*_dkz ){ if (izModel==0){ if (sz>=0 && sz<_dkz){ zWeight=-sz*sz*sz/(_dkz*_dkz*_dkz)+3.0*sz*sz/(_dkz*_dkz)-3.0*sz/_dkz+1.0; } } else if (izModel==1){ if (sz>=0 && sz<_dkz){ zWeight=7.0*sz*sz*sz/(4.0*_dkz*_dkz*_dkz)-9.0*sz*sz/(2.0*_dkz*_dkz)+3.0*sz/_dkz; } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight=-sz*sz*sz/(4.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz)-3.0*sz/_dkz+2.0; } } else if (izModel==2){ if (sz>=0 && sz<_dkz){ zWeight=-11.0*sz*sz*sz/(12.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz); } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight=7.0*sz*sz*sz/(12.0*_dkz*_dkz*_dkz)-3*sz*sz/(_dkz*_dkz)+9.0*sz/(2.0*_dkz)-3.0/2.0; } else if (sz>=(2.0*_dkz) && sz<(3.0*_dkz)){ zWeight=-sz*sz*sz/(6.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz)-9.0*sz/(2.0*_dkz)+9.0/2.0; } } else if (izModel>=3 && izModel<_nzModel-3){ if (sz>=0.0 && sz<_dkz){ zWeight=sz3/(6.0*_dkz3); } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight = -sz3/(2.0*_dkz3) + 2.0*sz2/_dkz2 - 2.0*sz/_dkz + 2.0/3.0; } else if (sz>=(2.0*_dkz) && sz<(3.0*_dkz)){ zWeight = 1/(2.0*_dkz3)*sz3 - 4.0/_dkz2*sz2 + 10.0*sz/_dkz -22.0/3.0; } else if (sz>=(3.0*_dkz) && sz<(4.0*_dkz)){ zWeight = -sz3/(6.0*_dkz3) + 2.0*sz2/_dkz2 - 8.0*sz/_dkz + 32.0/3.0; } } else if (izModel==_nzModel-3){ if (sz>=0.0 && sz<_dkz){ zWeight=sz*sz*sz/(6.0*_dkz*_dkz*_dkz); } else if(sz>=_dkz && sz<(2.0*_dkz)) { zWeight=-sz*sz*sz/(3.0*_dkz*_dkz*_dkz)+sz*sz/(_dkz*_dkz)-sz/(2*_dkz)+(3.0/2.0-sz/(2.0*_dkz))*(sz-_dkz)*(sz-_dkz)/(2.0*_dkz*_dkz); } else if(sz>=(2.0*_dkz) && sz<=(3.0*_dkz)) { zWeight=sz/(3.0*_dkz)*(sz*sz/(2.0*_dkz*_dkz)-3*sz/_dkz+9.0/2.0); zWeight+=(3.0/2.0-sz/(2.0*_dkz))*(-3*(sz-_dkz)*(sz-_dkz)/(2.0*_dkz*_dkz)+4*(sz-_dkz)/_dkz-2.0); } } else if (izModel==_nzModel-2){ if (sz>=0.0 && sz<_dkz){ zWeight=sz*sz*sz/(4.0*_dkz*_dkz*_dkz); } else if(sz>=_dkz && sz<=(2.0*_dkz)) { zWeight=sz/(2.0*_dkz)*(-3.0*sz*sz/(2.0*_dkz*_dkz)+4.0*sz/_dkz-2.0); zWeight+=(2.0-sz/_dkz)*(sz-_dkz)*(sz-_dkz)/(_dkz*_dkz); } } else if (izModel==_nzModel-1){ if (sz>=0.0 && sz<=_dkz){ zWeight=sz*sz*sz/(_dkz*_dkz*_dkz); } } } // Add contribution of model point zInterp+=zWeight*(*_zControlPoints->_mat)[izModel]; } // Finished computing interpolated position for this u-value // Update the optimal u-value if interpolated point is clsoer to data point if (std::abs(zInterp-(*_zData->_mat)[izData]) < error) { error=std::abs(zInterp-(*_zData->_mat)[izData]); (*paramVector->_mat)[izData]=uValue; } } // Finished computing interpolated values for all u's if (std::abs(error)>_zTolerance){ std::cout << "**** ERROR: Could not find a parameter for data point in the z-direction #" << izData << " " << (*_zData->_mat)[izData] << " [km]. Try increasing the number of samples! ****" << std::endl; std::cout << "Error = " << error << std::endl; std::cout << "Tolerance = " << _zTolerance << " [km]" << std::endl; throw std::runtime_error(""); } } return paramVector; } std::shared_ptr<float1DReg> interpBSpline2d::computeParamVectorX(){ // Generate u (z-direction) int nv = _nxParamVector; float ov = _okx; float fv = _fkx; float dv = (fv-ov)/(nv-1); nv=nv-1; std::shared_ptr<float1DReg> v(new float1DReg(nv)); axis vAxis = axis(nv, ov, dv); std::shared_ptr<float1DReg> paramVector(new float1DReg(_nxData)); // Initialize param vector with -1 #pragma omp parallel for for (int iData=0; iData<_nxData; iData++){ (*paramVector->_mat)[iData]=-1.0; } // Loop over data space #pragma omp parallel for for (int ixData=_fat; ixData<_nxData-_fat; ixData++){ float error=100000; for (int iv=0; iv<nv; iv++){ float vValue=ov+iv*dv; float xInterp = 0; for (int ixModel=0; ixModel<_nxModel; ixModel++){ float sx=vValue-(*_xKnots->_mat)[ixModel]; float sx3=sx*sx*sx; float sx2=sx*sx; float xWeight=0.0; if ( sx>=0.0 && sx<4.0*_dkx ){ if (ixModel==0){ if (sx>=0 && sx<_dkx){ xWeight=-sx*sx*sx/(_dkx*_dkx*_dkx)+3.0*sx*sx/(_dkx*_dkx)-3.0*sx/_dkx+1.0; } } else if (ixModel==1){ if (sx>=0 && sx<_dkx){ xWeight=7.0*sx*sx*sx/(4.0*_dkx*_dkx*_dkx)-9.0*sx*sx/(2.0*_dkx*_dkx)+3.0*sx/_dkx; } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight=-sx*sx*sx/(4.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx)-3.0*sx/_dkx+2.0; } } else if (ixModel==2){ if (sx>=0 && sx<_dkx){ xWeight=-11.0*sx*sx*sx/(12.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx); } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight=7.0*sx*sx*sx/(12.0*_dkx*_dkx*_dkx)-3*sx*sx/(_dkx*_dkx)+9.0*sx/(2.0*_dkx)-3.0/2.0; } else if (sx>=(2.0*_dkx) && sx<(3.0*_dkx)){ xWeight=-sx*sx*sx/(6.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx)-9.0*sx/(2.0*_dkx)+9.0/2.0; } } else if (ixModel>=3 && ixModel<_nxModel-3){ if (sx>=0.0 && sx<_dkx){ xWeight=sx3/(6.0*_dkx3); } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight = -sx3/(2.0*_dkx3) + 2.0*sx2/(_dkx2) - 2.0*sx/_dkx + 2.0/3.0; } else if (sx>=(2.0*_dkx) && sx<(3.0*_dkx)){ xWeight = 1/(2.0*_dkx3)*sx3 - 4.0/_dkx2*sx2 + 10.0*sx/_dkx -22.0/3.0; } else if (sx>=(3.0*_dkx) && sx<(4.0*_dkx)){ xWeight = -sx3/(6.0*_dkx3) + 2.0*sx2/_dkx2 - 8.0*sx/_dkx + 32.0/3.0; } } else if (ixModel==_nxModel-3){ if (sx>=0.0 && sx<_dkx){ xWeight=sx*sx*sx/(6.0*_dkx*_dkx*_dkx); } else if(sx>=_dkx && sx<(2.0*_dkx)) { xWeight=-sx*sx*sx/(3.0*_dkx*_dkx*_dkx)+sx*sx/(_dkx*_dkx)-sx/(2*_dkx)+(3.0/2.0-sx/(2.0*_dkx))*(sx-_dkx)*(sx-_dkx)/(2.0*_dkx*_dkx); } else if(sx>=(2.0*_dkx) && sx<=(3.0*_dkx)) { xWeight=sx/(3.0*_dkx)*(sx*sx/(2.0*_dkx*_dkx)-3*sx/_dkx+9.0/2.0); xWeight+=(3.0/2.0-sx/(2.0*_dkx))*(-3*(sx-_dkx)*(sx-_dkx)/(2.0*_dkx*_dkx)+4*(sx-_dkx)/_dkx-2.0); } } else if (ixModel==_nxModel-2){ if (sx>=0.0 && sx<_dkx){ xWeight=sx*sx*sx/(4.0*_dkx*_dkx*_dkx); } else if(sx>=_dkx && sx<=(2.0*_dkx)) { xWeight=sx/(2.0*_dkx)*(-3.0*sx*sx/(2.0*_dkx*_dkx)+4.0*sx/_dkx-2.0); xWeight+=(2.0-sx/_dkx)*(sx-_dkx)*(sx-_dkx)/(_dkx*_dkx); } } else if (ixModel==_nxModel-1){ if (sx>=0.0 && sx<=_dkx){ xWeight=sx*sx*sx/(_dkx*_dkx*_dkx); } } // Add contribution of model point xInterp+=xWeight*(*_xControlPoints->_mat)[ixModel]; } } // Finished computing interpolated position for this u-value // Update the optimal u-value if interpolated point is clsoer to data point if (std::abs(xInterp-(*_xData->_mat)[ixData]) < error) { error=std::abs(xInterp-(*_xData->_mat)[ixData]); (*paramVector->_mat)[ixData]=vValue; } } // Finished computing interpolated values for all u's if (std::abs(error)>_xTolerance){ std::cout << "**** ERROR: Could not find a parameter for data point in the x-direction #" << ixData << " " << (*_xData->_mat)[ixData]<< " [km]. Try increasing the number of samples! ****" << std::endl; std::cout << "Error = " << error << std::endl; std::cout << "Tolerance = " << _xTolerance << " [km]" << std::endl; throw std::runtime_error(""); } } return paramVector; } // Scaling vector std::shared_ptr<float2DReg> interpBSpline2d::computeScaleVector(){ // Variables declaration float uValue, vValue, zWeight, xWeight; std::shared_ptr<float2DReg> scaleVector, scaleVectorData; scaleVector = std::make_shared<float2DReg>(_nzModel, _nxModel); scaleVectorData = std::make_shared<float2DReg>(_nzData, _nxData); scaleVectorData->scale(0.0); scaleVector->set(1.0); // Apply one forward forward(false, scaleVector, scaleVectorData); // Apply one adjoint adjoint(false, scaleVector, scaleVectorData); // Compute scaling #pragma omp parallel for collapse(2) for (int ixModel=0; ixModel<_nxModel; ixModel++){ for (int izModel=0; izModel<_nzModel; izModel++){ (*scaleVector->_mat)[ixModel][izModel]=1.0/sqrt((*scaleVector->_mat)[ixModel][izModel]); } } return scaleVector; } // Forward void interpBSpline2d::forward(const bool add, const std::shared_ptr<float2DReg> model, std::shared_ptr<float2DReg> data) const { // Forward: Coarse grid to fine grid // Model can be on an irregular grid if (!add) data->scale(0.0); // Loop over data (fine sampling grid) #pragma omp parallel for collapse(2) for (int ixData=_fat; ixData<_nxData-_fat; ixData++){ for (int izData=_fat; izData<_nzData-_fat; izData++){ float uValue = (*_zParamVector->_mat)[izData]; float vValue = (*_xParamVector->_mat)[ixData]; for (int ixModel=0; ixModel<_nxModel; ixModel++){ float sx=vValue-(*_xKnots->_mat)[ixModel]; float sx3=sx*sx*sx; float sx2=sx*sx; float xWeight=0.0; if( sx>=0.0 && sx<4.0*_dkx ){ if (ixModel==0){ if (sx>=0 && sx<_dkx){ xWeight=-sx*sx*sx/(_dkx*_dkx*_dkx)+3.0*sx*sx/(_dkx*_dkx)-3.0*sx/_dkx+1.0; } } else if (ixModel==1){ if (sx>=0 && sx<_dkx){ xWeight=7.0*sx*sx*sx/(4.0*_dkx*_dkx*_dkx)-9.0*sx*sx/(2.0*_dkx*_dkx)+3.0*sx/_dkx; } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight=-sx*sx*sx/(4.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx)-3.0*sx/_dkx+2.0; } } else if (ixModel==2){ if (sx>=0 && sx<_dkx){ xWeight=-11.0*sx*sx*sx/(12.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx); } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight=7.0*sx*sx*sx/(12.0*_dkx*_dkx*_dkx)-3*sx*sx/(_dkx*_dkx)+9.0*sx/(2.0*_dkx)-3.0/2.0; } else if (sx>=(2.0*_dkx) && sx<(3.0*_dkx)){ xWeight=-sx*sx*sx/(6.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx)-9.0*sx/(2.0*_dkx)+9.0/2.0; } } else if (ixModel>=3 && ixModel<_nxModel-3){ if (sx>=0.0 && sx<_dkx){ xWeight=sx3/(6.0*_dkx3); } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight = -sx3/(2.0*_dkx3) + 2.0*sx2/(_dkx2) - 2.0*sx/_dkx + 2.0/3.0; } else if (sx>=(2.0*_dkx) && sx<(3.0*_dkx)){ xWeight = 1/(2.0*_dkx3)*sx3 - 4.0/_dkx2*sx2 + 10.0*sx/_dkx -22.0/3.0; } else if (sx>=(3.0*_dkx) && sx<(4.0*_dkx)){ xWeight = -sx3/(6.0*_dkx3) + 2.0*sx2/_dkx2 - 8.0*sx/_dkx + 32.0/3.0; } } else if (ixModel==_nxModel-3){ if (sx>=0.0 && sx<_dkx){ xWeight=sx*sx*sx/(6.0*_dkx*_dkx*_dkx); } else if(sx>=_dkx && sx<(2.0*_dkx)) { xWeight=-sx*sx*sx/(3.0*_dkx*_dkx*_dkx)+sx*sx/(_dkx*_dkx)-sx/(2*_dkx)+(3.0/2.0-sx/(2.0*_dkx))*(sx-_dkx)*(sx-_dkx)/(2.0*_dkx*_dkx); } else if(sx>=(2.0*_dkx) && sx<=(3.0*_dkx)) { xWeight=sx/(3.0*_dkx)*(sx*sx/(2.0*_dkx*_dkx)-3*sx/_dkx+9.0/2.0); xWeight+=(3.0/2.0-sx/(2.0*_dkx))*(-3*(sx-_dkx)*(sx-_dkx)/(2.0*_dkx*_dkx)+4*(sx-_dkx)/_dkx-2.0); } } else if (ixModel==_nxModel-2){ if (sx>=0.0 && sx<_dkx){ xWeight=sx*sx*sx/(4.0*_dkx*_dkx*_dkx); } else if(sx>=_dkx && sx<=(2.0*_dkx)) { xWeight=sx/(2.0*_dkx)*(-3.0*sx*sx/(2.0*_dkx*_dkx)+4.0*sx/_dkx-2.0); xWeight+=(2.0-sx/_dkx)*(sx-_dkx)*(sx-_dkx)/(_dkx*_dkx); } } else if (ixModel==_nxModel-1){ if (sx>=0.0 && sx<=_dkx){ xWeight=sx*sx*sx/(_dkx*_dkx*_dkx); } } for (int izModel=0; izModel<_nzModel; izModel++){ float sz=uValue-(*_zKnots->_mat)[izModel]; float sz3=sz*sz*sz; float sz2=sz*sz; float zWeight=0.0; if( sz>=0.0 && sz<4.0*_dkz ){ if (izModel==0){ if (sz>=0 && sz<_dkz){ zWeight=-sz*sz*sz/(_dkz*_dkz*_dkz)+3.0*sz*sz/(_dkz*_dkz)-3.0*sz/_dkz+1.0; } } else if (izModel==1){ if (sz>=0 && sz<_dkz){ zWeight=7.0*sz*sz*sz/(4.0*_dkz*_dkz*_dkz)-9.0*sz*sz/(2.0*_dkz*_dkz)+3.0*sz/_dkz; } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight=-sz*sz*sz/(4.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz)-3.0*sz/_dkz+2.0; } } else if (izModel==2){ if (sz>=0 && sz<_dkz){ zWeight=-11.0*sz*sz*sz/(12.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz); } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight=7.0*sz*sz*sz/(12.0*_dkz*_dkz*_dkz)-3*sz*sz/(_dkz*_dkz)+9.0*sz/(2.0*_dkz)-3.0/2.0; } else if (sz>=(2.0*_dkz) && sz<(3.0*_dkz)){ zWeight=-sz*sz*sz/(6.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz)-9.0*sz/(2.0*_dkz)+9.0/2.0; } } else if (izModel>=3 && izModel<_nzModel-3){ if (sz>=0.0 && sz<_dkz){ // zWeight=sz*sz*sz/(6.0*_dkz*_dkz*_dkz); zWeight=sz3/(6.0*_dkz3); } else if (sz>=_dkz && sz<(2.0*_dkz)){ // zWeight = -sz*sz*sz/(2.0*_dkz*_dkz*_dkz) + 2.0*sz*sz/(_dkz*_dkz) - 2.0*sz/_dkz + 2.0/3.0; zWeight = -sz3/(2.0*_dkz3) + 2.0*sz2/_dkz2 - 2.0*sz/_dkz + 2.0/3.0; } else if (sz>=(2.0*_dkz) && sz<(3.0*_dkz)){ // zWeight = 1/(2.0*_dkz*_dkz*_dkz)*sz*sz*sz - 4.0/(_dkz*_dkz)*sz*sz + 10.0*sz/_dkz -22.0/3.0; zWeight = 1/(2.0*_dkz3)*sz3 - 4.0/_dkz2*sz2 + 10.0*sz/_dkz -22.0/3.0; } else if (sz>=(3.0*_dkz) && sz<(4.0*_dkz)){ // zWeight = -sz*sz*sz/(6.0*_dkz*_dkz*_dkz) + 2.0*sz*sz/(_dkz*_dkz) - 8.0*sz/_dkz + 32.0/3.0; zWeight = -sz3/(6.0*_dkz3) + 2.0*sz2/_dkz2 - 8.0*sz/_dkz + 32.0/3.0; } } else if (izModel==_nzModel-3){ if (sz>=0.0 && sz<_dkz){ zWeight=sz*sz*sz/(6.0*_dkz*_dkz*_dkz); } else if(sz>=_dkz && sz<(2.0*_dkz)) { zWeight=-sz*sz*sz/(3.0*_dkz*_dkz*_dkz)+sz*sz/(_dkz*_dkz)-sz/(2*_dkz)+(3.0/2.0-sz/(2.0*_dkz))*(sz-_dkz)*(sz-_dkz)/(2.0*_dkz*_dkz); } else if(sz>=(2.0*_dkz) && sz<=(3.0*_dkz)) { zWeight=sz/(3.0*_dkz)*(sz*sz/(2.0*_dkz*_dkz)-3*sz/_dkz+9.0/2.0); zWeight+=(3.0/2.0-sz/(2.0*_dkz))*(-3*(sz-_dkz)*(sz-_dkz)/(2.0*_dkz*_dkz)+4*(sz-_dkz)/_dkz-2.0); } } else if (izModel==_nzModel-2){ if (sz>=0.0 && sz<_dkz){ zWeight=sz*sz*sz/(4.0*_dkz*_dkz*_dkz); } else if(sz>=_dkz && sz<=(2.0*_dkz)) { zWeight=sz/(2.0*_dkz)*(-3.0*sz*sz/(2.0*_dkz*_dkz)+4.0*sz/_dkz-2.0); zWeight+=(2.0-sz/_dkz)*(sz-_dkz)*(sz-_dkz)/(_dkz*_dkz); } } else if (izModel==_nzModel-1){ if (sz>=0.0 && sz<=_dkz){ zWeight=sz*sz*sz/(_dkz*_dkz*_dkz); } } // Add contribution to interpolated value (data) (*data->_mat)[ixData][izData] += xWeight*zWeight*(*_scaleVector->_mat)[ixModel][izModel]*(*model->_mat)[ixModel][izModel]; } } } } } } } // Adjoint void interpBSpline2d::adjoint(const bool add, std::shared_ptr<float2DReg> model, const std::shared_ptr<float2DReg> data) const { // Adjoint: Fine grid to coarse grid // Model can be on an irregular grid if (!add) model->scale(0.0); #pragma omp parallel for collapse(2) for (int ixModel=0; ixModel<_nxModel; ixModel++){ for (int izModel=0; izModel<_nzModel; izModel++){ for (int ixData=_fat; ixData<_nxData-_fat; ixData++){ float vValue = (*_xParamVector->_mat)[ixData]; float sx=vValue-(*_xKnots->_mat)[ixModel]; float sx3=sx*sx*sx; float sx2=sx*sx; float xWeight=0.0; if( sx>=0.0 && sx<4.0*_dkx ){ if (ixModel==0){ if (sx>=0 && sx<_dkx){ xWeight=-sx*sx*sx/(_dkx*_dkx*_dkx)+3.0*sx*sx/(_dkx*_dkx)-3.0*sx/_dkx+1.0; } } else if (ixModel==1){ if (sx>=0 && sx<_dkx){ xWeight=7.0*sx*sx*sx/(4.0*_dkx*_dkx*_dkx)-9.0*sx*sx/(2.0*_dkx*_dkx)+3.0*sx/_dkx; } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight=-sx*sx*sx/(4.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx)-3.0*sx/_dkx+2.0; } } else if (ixModel==2){ if (sx>=0 && sx<_dkx){ xWeight=-11.0*sx*sx*sx/(12.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx); } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight=7.0*sx*sx*sx/(12.0*_dkx*_dkx*_dkx)-3*sx*sx/(_dkx*_dkx)+9.0*sx/(2.0*_dkx)-3.0/2.0; } else if (sx>=(2.0*_dkx) && sx<(3.0*_dkx)){ xWeight=-sx*sx*sx/(6.0*_dkx*_dkx*_dkx)+3.0*sx*sx/(2.0*_dkx*_dkx)-9.0*sx/(2.0*_dkx)+9.0/2.0; } } else if (ixModel>=3 && ixModel<_nxModel-3){ if (sx>=0.0 && sx<_dkx){ xWeight=sx3/(6.0*_dkx3); } else if (sx>=_dkx && sx<(2.0*_dkx)){ xWeight = -sx3/(2.0*_dkx3) + 2.0*sx2/(_dkx2) - 2.0*sx/_dkx + 2.0/3.0; } else if (sx>=(2.0*_dkx) && sx<(3.0*_dkx)){ xWeight = 1/(2.0*_dkx3)*sx3 - 4.0/_dkx2*sx2 + 10.0*sx/_dkx -22.0/3.0; } else if (sx>=(3.0*_dkx) && sx<(4.0*_dkx)){ xWeight = -sx3/(6.0*_dkx3) + 2.0*sx2/_dkx2 - 8.0*sx/_dkx + 32.0/3.0; } } else if (ixModel==_nxModel-3){ if (sx>=0.0 && sx<_dkx){ xWeight=sx*sx*sx/(6.0*_dkx*_dkx*_dkx); } else if(sx>=_dkx && sx<(2.0*_dkx)) { xWeight=-sx*sx*sx/(3.0*_dkx*_dkx*_dkx)+sx*sx/(_dkx*_dkx)-sx/(2*_dkx)+(3.0/2.0-sx/(2.0*_dkx))*(sx-_dkx)*(sx-_dkx)/(2.0*_dkx*_dkx); } else if(sx>=(2.0*_dkx) && sx<=(3.0*_dkx)) { xWeight=sx/(3.0*_dkx)*(sx*sx/(2.0*_dkx*_dkx)-3*sx/_dkx+9.0/2.0); xWeight+=(3.0/2.0-sx/(2.0*_dkx))*(-3*(sx-_dkx)*(sx-_dkx)/(2.0*_dkx*_dkx)+4*(sx-_dkx)/_dkx-2.0); } } else if (ixModel==_nxModel-2){ if (sx>=0.0 && sx<_dkx){ xWeight=sx*sx*sx/(4.0*_dkx*_dkx*_dkx); } else if(sx>=_dkx && sx<=(2.0*_dkx)) { xWeight=sx/(2.0*_dkx)*(-3.0*sx*sx/(2.0*_dkx*_dkx)+4.0*sx/_dkx-2.0); xWeight+=(2.0-sx/_dkx)*(sx-_dkx)*(sx-_dkx)/(_dkx*_dkx); } } else if (ixModel==_nxModel-1){ if (sx>=0.0 && sx<=_dkx){ xWeight=sx*sx*sx/(_dkx*_dkx*_dkx); } } for (int izData=_fat; izData<_nzData-_fat; izData++){ float uValue = (*_zParamVector->_mat)[izData]; float sz=uValue-(*_zKnots->_mat)[izModel]; float sz3=sz*sz*sz; float sz2=sz*sz; float zWeight=0.0; if( sz>=0.0 && sz<4.0*_dkz ){ if (izModel==0){ if (sz>=0 && sz<_dkz){ zWeight=-sz*sz*sz/(_dkz*_dkz*_dkz)+3.0*sz*sz/(_dkz*_dkz)-3.0*sz/_dkz+1.0; } } else if (izModel==1){ if (sz>=0 && sz<_dkz){ zWeight=7.0*sz*sz*sz/(4.0*_dkz*_dkz*_dkz)-9.0*sz*sz/(2.0*_dkz*_dkz)+3.0*sz/_dkz; } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight=-sz*sz*sz/(4.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz)-3.0*sz/_dkz+2.0; } } else if (izModel==2){ if (sz>=0 && sz<_dkz){ zWeight=-11.0*sz*sz*sz/(12.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz); } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight=7.0*sz*sz*sz/(12.0*_dkz*_dkz*_dkz)-3*sz*sz/(_dkz*_dkz)+9.0*sz/(2.0*_dkz)-3.0/2.0; } else if (sz>=(2.0*_dkz) && sz<(3.0*_dkz)){ zWeight=-sz*sz*sz/(6.0*_dkz*_dkz*_dkz)+3.0*sz*sz/(2.0*_dkz*_dkz)-9.0*sz/(2.0*_dkz)+9.0/2.0; } } else if (izModel>=3 && izModel<_nzModel-3){ if (sz>=0.0 && sz<_dkz){ zWeight=sz3/(6.0*_dkz3); } else if (sz>=_dkz && sz<(2.0*_dkz)){ zWeight = -sz3/(2.0*_dkz3) + 2.0*sz2/_dkz2 - 2.0*sz/_dkz + 2.0/3.0; } else if (sz>=(2.0*_dkz) && sz<(3.0*_dkz)){ zWeight = 1/(2.0*_dkz3)*sz3 - 4.0/_dkz2*sz2 + 10.0*sz/_dkz -22.0/3.0; } else if (sz>=(3.0*_dkz) && sz<(4.0*_dkz)){ zWeight = -sz3/(6.0*_dkz3) + 2.0*sz2/_dkz2 - 8.0*sz/_dkz + 32.0/3.0; } } else if (izModel==_nzModel-3){ if (sz>=0.0 && sz<_dkz){ zWeight=sz*sz*sz/(6.0*_dkz*_dkz*_dkz); } else if(sz>=_dkz && sz<(2.0*_dkz)) { zWeight=-sz*sz*sz/(3.0*_dkz*_dkz*_dkz)+sz*sz/(_dkz*_dkz)-sz/(2*_dkz)+(3.0/2.0-sz/(2.0*_dkz))*(sz-_dkz)*(sz-_dkz)/(2.0*_dkz*_dkz); } else if(sz>=(2.0*_dkz) && sz<=(3.0*_dkz)) { zWeight=sz/(3.0*_dkz)*(sz*sz/(2.0*_dkz*_dkz)-3*sz/_dkz+9.0/2.0); zWeight+=(3.0/2.0-sz/(2.0*_dkz))*(-3*(sz-_dkz)*(sz-_dkz)/(2.0*_dkz*_dkz)+4*(sz-_dkz)/_dkz-2.0); } } else if (izModel==_nzModel-2){ if (sz>=0.0 && sz<_dkz){ zWeight=sz*sz*sz/(4.0*_dkz*_dkz*_dkz); } else if(sz>=_dkz && sz<=(2.0*_dkz)) { zWeight=sz/(2.0*_dkz)*(-3.0*sz*sz/(2.0*_dkz*_dkz)+4.0*sz/_dkz-2.0); zWeight+=(2.0-sz/_dkz)*(sz-_dkz)*(sz-_dkz)/(_dkz*_dkz); } } else if (izModel==_nzModel-1){ if (sz>=0.0 && sz<=_dkz){ zWeight=sz*sz*sz/(_dkz*_dkz*_dkz); } } (*model->_mat)[ixModel][izModel] += xWeight*zWeight*(*_scaleVector->_mat)[ixModel][izModel]*(*data->_mat)[ixData][izData]; } } } } } } }
true
91ad6e698ab14016d0b55ee72d85861d41701429
C++
awp4211/LearningOpenCV
/5Morphology/5Morphology/morpho2.cpp
UTF-8
935
2.546875
3
[]
no_license
#include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "morphoFeature.h" /* int main() { cv::Mat image = cv::imread("car.jpg"); cv::namedWindow("Image"); cv::imshow("Image", image); MorphoFeatures morpho; morpho.setThreshold(40); // Get the edges cv::Mat edges; edges = morpho.getEdges(image); cv::namedWindow("Edge Image"); cv::imshow("Edge Image", edges); // Get the corners morpho.setThreshold(-1); cv::Mat corners; corners = morpho.getCorners(image); cv::morphologyEx(corners, corners, cv::MORPH_TOPHAT, cv::Mat()); cv::threshold(corners, corners, 40, 255, cv::THRESH_BINARY_INV); cv::namedWindow("Corner Image"); cv::imshow("Corner Image", corners); // Display the corner on the image morpho.drawOnImage(corners, image); cv::namedWindow("Corners on Image"); cv::imshow("Corners on Image", image); cv::waitKey(); return 0; } */
true
b3ccd0c138d2d3eb81d78bfeca2e45b71c93260f
C++
Gael21ruiz/practica_03_Tarea
/Ejercicio_09 switch.cpp
UTF-8
718
3.1875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> int main(){ char val; printf("Introduzca un caracter: "); scanf("%s",&val); switch(val){ case '0': printf("El caracter es numero"); break; case '1': printf("El caracter es numero"); break; case '2': printf("El caracter es numero"); break; case '3': printf("El caracter es numero"); break; case '4': printf("El caracter es numero"); break; case '5': printf("El caracter es numero"); break; case '6': printf("El caracter es numero"); break; case '7': printf("El caracter es numero"); break; case '8': printf("El caracter es numero"); break; case '9': printf("El caracter es numero"); break; default: printf("El caracter es letra"); } }
true
0fb54a38b3c4bea805a5fc04450cf6356e81ddc1
C++
Pranta-Saha/codeforces-solved
/714B.cpp
UTF-8
476
2.59375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n,i,tmp; set<int >st; set<int >::iterator it,it2,it3; cin>>n; while(n--) { cin>>tmp; st.insert(tmp); } it=st.begin(); if(st.size()<=2) {cout<<"YES"; return 0;} else if(st.size()==3) { it2=it; it2++; it3=it2; it3++; if(*it2-*it==*it3-*it2) {cout<<"YES"; return 0;} } cout<<"NO"; return 0; }
true
cc9792fc18627ba3555bba0e64fc0a339ea8082e
C++
jenniferexong/bunny-game
/src/engine/Camera.cpp
UTF-8
454
2.984375
3
[]
no_license
#include "Camera.h" /* Moves camera under water, then inverts the pitch */ void Camera::positionForReflection(float water_height) { float distance = position_.y - water_height; position_.y -= 2 * distance; rotation_.y *= -1; } /* Moves camera back to original position above water */ void Camera::positionForRefraction(float water_height) { float distance = water_height - position_.y; position_.y += 2 * distance; rotation_.y *= -1; // invert }
true
4be61a3c4ebb2aa3fd8974303b91e1715b19f7bf
C++
sagor2364/Cpp-Course
/URI/1021.cpp
UTF-8
273
3.078125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int A, B, C, D; cin>> A>> B>> C>> D; if(B>C && D>A && C+D > A+B && C > 0 && D > 0 && A % 2 == 0){ cout << "Valores aceitos"; }else{ cout << "Valores nao aceitos"; } return 0; }
true
cf0a4bd4ac9ace790aa0bbc581fc629de3be346e
C++
zoveale/CSE461
/Filesys.cpp
UTF-8
6,264
3.3125
3
[]
no_license
/** * Name: Joseph Lord * Program: Filesys.cpp * Class: CSE 461 Adv Operating Systems * Date: 2019-11-18 * Purpose: Implementation of the Filesys class **/ #include <string> #include <vector> #include <sstream> #include <iostream> #include <stdio.h> #include "Sdisk.h" #include "Filesys.h" using namespace std; Filesys::Filesys(string diskname, int numberofblocks, int blocksize): Sdisk(diskname, numberofblocks, blocksize) { rootsize = getblocksize() / 13; fatsize = ((getnumberofblocks() * 4) / getblocksize()) + 1; string buffer = ""; getblock(1, buffer); //gets the first block of the disk, which is the root directory if(buffer[1] == '#') { //no filesystem, create and store //create root for(int i = 0; i < rootsize; i++) { filename.push_back("xxxxxxxx"); //8 x's stand for an open file spot firstblock.push_back(0); } //create FAT fat.push_back(2 + fatsize); //initial data block fat.push_back(-1); //unusable blocks for(int i = 0; i < fatsize; i++) { fat.push_back(-1); } for(int i = (2 + fatsize); i < getnumberofblocks(); i++) { fat.push_back(i + 1); //adds the next contiguous block } fat[fat.size() - 1] = 0; //the last block in the fat goes back to the beginning of the fat fssynch(); //to write back to the disk, use fssynch } else { //filesystem exists, read it in //root directory is in buffer istringstream instream; instream.str(buffer); //reads in the buffer for(int i = 0; i < rootsize; i++) { string f = ""; int b = 0; instream >> f >> b; filename.push_back(f); firstblock.push_back(b); } //read in fat istringstream instream2; buffer.clear(); for(int i = 0; i < fatsize; i++) { //get all the fat blocks string b = ""; getblock(2 + i, b); buffer += b; } instream2.str(buffer); for(int i = 0; i < getnumberofblocks(); i++) { //read all the fat blocks int f = 0; instream2 >> f; fat.push_back(f); } } } int Filesys::fsclose() { fssynch(); //closes the filesystem after writing?? } int Filesys::fssynch() { //write root to disk ostringstream outstream2; for(int i = 0; i < rootsize; i++) { outstream2 << filename[i] << " " << firstblock[i] << " "; } //dont need to use block(), root directory only takes up one block string buffer2 = outstream2.str(); putblock(1, buffer2); //write fat to disk string buffer; ostringstream outstream; for(int i = 0; i < getblocksize(); i++) { outstream<< fat[i] <<" "; } buffer = outstream.str(); vector<string> blocks = block(buffer, getblocksize()); for(int i = 0; i < blocks.size(); i++) { putblock(2 + i, blocks[i]); //2 is the first block of the FAT } } int Filesys::newfile(string file) { for(int i = 0; i < rootsize; i++) { if(filename[i] == "xxxxxxxx") { //there is an available slot filename[i] = file; //change "xxxxxxx" to the name of the file firstblock[i] = 0; //change 0 to the first available block fssynch(); //write to disk return 1; } } return -1; //there is not available slot, or the file already exists } int Filesys::rmfile(string file) { for(int i = 0; i < rootsize; i++) { if(filename[i] == file) { //checks if file exists if(firstblock[i] == 0) { //checks if file is empty filename[i] = "xxxxxxxx"; fssynch(); //write to disk return 1; } } } return -1; //file does not exist or file is not empty } int Filesys::getfirstblock(string file) { for(int i = 0; i < rootsize; i++) { if(filename[i] == file) { //checks if file exists return firstblock[i]; } } return -1; //file does not exist } int Filesys::addblock(string file, string buffer) { int first = getfirstblock(file); if (first == -1) { //printf("%s does not exist!\n", file); cout << file << " does not exist!\n"; return -1; //file does not exist } int allocate = fat[0]; if (allocate == 0) { printf("No more space on the disk!\n"); return -1; //no more free data blocks } fat[0] = fat[fat[0]]; //Set fat[0] to next available block fat[allocate] = 0; if (first == 0) { //If file exists, but is empty for (int i = 0; i < rootsize; i++) { if(filename[i] == file) { firstblock[i] = allocate; } } } else { //If file exists and already uses some blocks int iblock = first; while (fat[iblock] != 0) { iblock = fat[iblock]; } fat[iblock] = allocate; } fssynch(); putblock(allocate, buffer); return allocate; } int Filesys::delblock(string file, int blocknumber) { if(!checkblock(file, blocknumber)) { return -1; //blocknumber is not part of the file } int deallocate = blocknumber; if(deallocate == getfirstblock(file)) { //blocknumber is first block in file for(int i = 0; i < filename.size(); i++) { if(file == filename[i]) { firstblock[i] = fat[deallocate]; break; } } } else { int iblock = getfirstblock(file); while(fat[iblock] != deallocate) { iblock = fat[iblock]; } //fat[iblock] == deallocate fat[iblock] = fat[deallocate]; } fat[deallocate] = fat[0]; fat[0] = deallocate; fssynch(); } int Filesys::readblock(string file, int blocknumber, string& buffer) { if(checkblock(file, blocknumber)) { getblock(blocknumber, buffer); return 1; } else { return -1; //block is not in that file } } int Filesys::writeblock(string file, int blocknumber, string buffer) { if(checkblock(file, blocknumber)) { putblock(blocknumber, buffer); return 1; } else { return -1; //block is not in that file } } int Filesys::nextblock(string file, int blocknumber) { if(checkblock(file, blocknumber)) { return fat[blocknumber]; } else { return -1; //block is not in that file } } bool Filesys::checkblock(string file, int blocknumber) { int iblock = getfirstblock(file); while(iblock >= 0) { if(iblock == blocknumber) { return true; //block is in file } iblock = fat[iblock]; //next block in file } return false; //block is not in file } vector<string> Filesys::ls() { vector<string> flist; for(int i = 0; i < filename.size(); i++) { if(filename[i] != "xxxxxxxx") { flist.push_back(filename[i]); } } return flist; }
true
92fbed06270d9a8b764c74271fee69bcea8799c8
C++
CodingInterview2018Gazua/coding_interview
/coding_interview/b/hanoi.cpp
UTF-8
823
3.140625
3
[]
no_license
// // main.cpp // hanoi_tower // // Created by 김인태 on 2018. 8. 18.. // Copyright © 2018년 김인태. All rights reserved. // #include <iostream> #include <stack> using namespace std; void hanoi(int n, stack<int> &src, stack<int> &dest, stack<int> &aux) { if (n == 1) { dest.push(src.top()); src.pop(); return; } hanoi(n-1, src, aux, dest); dest.push(src.top()); src.pop(); hanoi(n-1, aux, dest, src); } void test() { stack<int> src; stack<int> aux; stack<int> dest; int n = 10; for(int i=n; i>0; --i) { src.push(i); } hanoi(10, src, dest, aux); while(!dest.empty()) { cout << dest.top() << endl; dest.pop(); } } int main(int argc, const char * argv[]) { test(); return 0; }
true
677e878513a119bcadd09ddabcbf3cb4a6ed695a
C++
cnbluesky/esp
/src/Mqtt.cpp
UTF-8
6,310
2.671875
3
[]
no_license
#include "Config.h" #include "Debug.h" #include "Mqtt.h" #include "Wifi.h" #include <PubSubClient.h> bool Mqtt::mqttConnect() { if (WiFi.status() != WL_CONNECTED) { Debug.AddLog(LOG_LEVEL_INFO, PSTR("wifi disconnected")); return false; } if (config.mqtt.port == 0) { return false; } if (mqttClient.connected()) { return true; } Debug.AddLog(LOG_LEVEL_INFO, PSTR("Connecting to %s:%d Broker . . "), config.mqtt.server, config.mqtt.port); mqttClient.setServer(config.mqtt.server, config.mqtt.port); if (mqttClient.connect(UID, config.mqtt.user, config.mqtt.pass, getTeleTopic(F("availability")).c_str(), 0, false, "offline")) { Debug.AddLog(LOG_LEVEL_INFO, PSTR("(Re)Connected.")); if (_connectedCallback != NULL) { _connectedCallback(); } } else { Debug.AddLog(LOG_LEVEL_INFO, PSTR("failed, rc=%d"), mqttClient.state()); } return mqttClient.connected(); } String Mqtt::msToHumanString(uint32_t const msecs) { uint32_t totalseconds = msecs / 1000; if (totalseconds == 0) return F("Now"); // Note: millis() can only count up to 45 days, so uint8_t is safe. uint8_t days = totalseconds / (60 * 60 * 24); uint8_t hours = (totalseconds / (60 * 60)) % 24; uint8_t minutes = (totalseconds / 60) % 60; uint8_t seconds = totalseconds % 60; String result = ""; if (days) result += String(days) + " day"; if (days > 1) result += 's'; if (hours) result += ' ' + String(hours) + " hour"; if (hours > 1) result += 's'; if (minutes) result += ' ' + String(minutes) + " minute"; if (minutes > 1) result += 's'; if (seconds) result += ' ' + String(seconds) + " second"; if (seconds > 1) result += 's'; result.trim(); return result; } String Mqtt::timeSince(uint32_t const start) { if (start == 0) return F("Never"); uint32_t diff = 0; uint32_t now = millis(); if (start < now) diff = now - start; else diff = UINT32_MAX - start + now; return msToHumanString(diff) + " ago"; } void Mqtt::doReport() { char message[250]; sprintf(message, "{\"UID\":\"%s\",\"SSID\":\"%s\",\"RSSI\":\"%s\",\"Version\":\"%s\",\"ip\":\"%s\",\"mac\":\"%s\",\"freeMem\":%d,\"uptime\":%d}", UID, WiFi.SSID().c_str(), String(WiFi.RSSI()).c_str(), VERSION, WiFi.localIP().toString().c_str(), WiFi.macAddress().c_str(), ESP.getFreeHeap(), millis() / 1000); Debug.AddLog(LOG_LEVEL_INFO, PSTR("%s"), message); publish(getTeleTopic(F("HEARTBEAT")), message); publish(getTeleTopic(F("availability")), "online", false); } void Mqtt::perSecondDo() { if (perSecond % 60 != 0) { return; } if (mqttClient.connected()) { doReport(); } } void Mqtt::loop() { uint32_t now = millis(); if (!mqttClient.connected()) { if (WiFi.status() != WL_CONNECTED) { return; } if (wasConnected) { lastDisconnectedTime = now; wasConnected = false; mqttDisconnectCounter++; } if (now - lastReconnectAttempt > kMqttReconnectTime || lastReconnectAttempt == 0) { lastReconnectAttempt = now; Debug.AddLog(LOG_LEVEL_INFO, PSTR("client mqtt not connected, trying to connect")); if (mqttConnect()) { lastReconnectAttempt = 0; wasConnected = true; if (mqttIsFirst) { Debug.AddLog(LOG_LEVEL_INFO, PSTR("MQTT just booted")); mqttIsFirst = false; } else { Debug.AddLog(LOG_LEVEL_INFO, PSTR("MQTT just (re)connected to MQTT. Lost connection about %s"), timeSince(lastConnectedTime).c_str()); } lastConnectedTime = now; Debug.AddLog(LOG_LEVEL_INFO, PSTR("successful client mqtt connection")); doReport(); } } } else { lastConnectedTime = now; mqttClient.loop(); } } void Mqtt::setTopic() { topicCmnd = getTopic(0, ""); topicStat = getTopic(1, ""); topicTele = getTopic(2, ""); } String Mqtt::getCmndTopic(String topic) { return topicCmnd + topic; } String Mqtt::getStatTopic(String topic) { return topicStat + topic; } String Mqtt::getTeleTopic(String topic) { return topicTele + topic; } void Mqtt::mqttSetLoopCallback(MQTT_CALLBACK_SIGNATURE) { mqttClient.setCallback(callback); } void Mqtt::mqttSetConnectedCallback(void (*func)(void)) { _connectedCallback = func; } PubSubClient &Mqtt::setClient(Client &client) { setTopic(); return mqttClient.setClient(client); } boolean Mqtt::publish(String topic, const char *payload) { return mqttClient.publish(topic.c_str(), payload); } boolean Mqtt::publish(String topic, const char *payload, boolean retained) { return mqttClient.publish(topic.c_str(), payload, retained); } boolean Mqtt::publish(const char *topic, const char *payload) { return mqttClient.publish(topic, payload); } boolean Mqtt::publish(const char *topic, const char *payload, boolean retained) { return mqttClient.publish(topic, payload, retained); } boolean Mqtt::publish(const char *topic, const uint8_t *payload, unsigned int plength) { return mqttClient.publish(topic, payload, plength); } boolean Mqtt::publish(const char *topic, const uint8_t *payload, unsigned int plength, boolean retained) { return mqttClient.publish(topic, payload, plength, retained); } boolean Mqtt::publish_P(const char *topic, const char *payload, boolean retained) { return mqttClient.publish_P(topic, payload, retained); } boolean Mqtt::publish_P(const char *topic, const uint8_t *payload, unsigned int plength, boolean retained) { return mqttClient.publish_P(topic, payload, plength, retained); } boolean Mqtt::subscribe(String topic) { return mqttClient.subscribe(topic.c_str()); } boolean Mqtt::subscribe(String topic, uint8_t qos) { return mqttClient.subscribe(topic.c_str(), qos); } boolean Mqtt::unsubscribe(String topic) { return mqttClient.unsubscribe(topic.c_str()); } String Mqtt::getTopic(uint8_t prefix, String subtopic) { // 0: Cmnd 1:Stat 2:Tele String fulltopic = String(config.mqtt.topic); if ((0 == prefix) && (-1 == fulltopic.indexOf(F("%prefix%")))) { fulltopic += F("/%prefix%"); // Need prefix for commands to handle mqtt topic loops } fulltopic.replace(F("%prefix%"), (prefix == 0 ? F("cmnd") : ((prefix == 1 ? F("stat") : F("tele"))))); fulltopic.replace(F("%hostname%"), UID); fulltopic.replace(F("%module%"), module->moduleName()); fulltopic.replace(F("#"), ""); fulltopic.replace(F("//"), "/"); if (!fulltopic.endsWith(F("/"))) fulltopic += F("/"); return fulltopic + subtopic; } Mqtt *mqtt;
true
8f5f544c5d9f2f33c534e770ede64e820cfe64d9
C++
MARCGRAUUdG/EDA_S9
/Candidats.h
UTF-8
700
2.671875
3
[]
no_license
// // Created by Marc Grau on 09/12/2018. // #ifndef EDA_S9_CANDIDATS_H #define EDA_S9_CANDIDATS_H #include <vector> class Candidats { public: Candidats(int vertex, int total_vertex); // Pre: n>0 // Post: S’ha inicialitzat el candidat amb la posicio anterior i el nombre de salts bool esFi() const; // Pre: -- // Post: Retorna cert si ja no queden candidats int cActual() const; // Pre:-- (Error: no hi ha candidat) // Post: Actualitza el candidat actual, el guarda i el retorna void seguent(); // Pre: -- (Error: no hi ha candidat) // Post: Passa al següent candidat private: int _iCan; int _max; }; #endif //EDA_S9_CANDIDATS_H
true
ba27a0c891a60129367e194f90a00f546952498c
C++
JoergWarthemann/ringbuffer
/RingBuffer/include/RingBuffer.h
UTF-8
19,728
3.640625
4
[ "BSL-1.0" ]
permissive
#pragma once #include <algorithm> #include <assert.h> #include <atomic> #include <functional> #include <memory> #include <type_traits> namespace Buffer { /** Does not cast into move iterator. Simply return the passed iterator. Iterator ... The type of iterator. std::is_lvalue_reference<Type&&>::value returns true. \param iterator ... The iterator. \param std::true_type ... Is always std::true_type. \return auto ... Iterator. */ template <typename Iterator> Iterator make_forward_iterator(Iterator iterator, std::true_type) { return iterator; } /** Casts iterator into a move iterator. Iterator ... The type of iterator. std::is_lvalue_reference<Type&&>::value returns false. \param iterator ... The iterator. \param std::false_type ... Is always std::false_type. \return auto ... The moveable version of iterator. */ template <typename Iterator> auto make_forward_iterator(Iterator iterator, std::false_type) { return std::make_move_iterator(iterator); } /** Uses SFINAE to cast an iterator into a move iterator when the forwarded type is moveable. Type ... The type that is to be iterated. Iterator ... The type of iterator. std::is_lvalue_reference<Type&&>{} is true or false type. \param iterator ... The iterator. \return auto ... Iterator or iterator casted to be moveable. */ template <typename Type, typename Iterator> auto make_forward_iterator(Iterator iterator) { return make_forward_iterator<Iterator>(iterator, std::is_lvalue_reference<Type&&>{}); } /** Iterates through an array and calls a function on the element together with an incremental index. Iterator ... The type of iterator. Function ... The type of function that is to be called on iterated elements. \param first ... A start iterator. \param last ... An end iterator. \param initial ... An initial value that gets incremented inside. \param func ... The function object that is to be called on the element. \return Function ... The function object. */ template <typename Iterator, typename Function> Function enumerate(Iterator first, Iterator last, typename std::iterator_traits<Iterator>::difference_type initial, Function func) { for (; first != last; ++first, ++initial) func(initial, std::forward<typename std::iterator_traits<Iterator>::value_type>(*first)); return func; } /** This defines a ring buffer. When reaching the buffer end while inserting new elements it will overwrite the oldest elements. Uses aligned storage for performance gain. Element ... The type of elements that are getting stored. */ template<typename Element> class RingBuffer { // Create a type which optimally aligns Element for internal use. typedef typename std::aligned_storage<sizeof(Element), alignof(Element)>::type ElementStorageType; std::function<void(ElementStorageType*)> customizedStorageDeleter_ = [this](ElementStorageType* storageToGetDeleted) { const std::size_t tmpCapacity = capacity_.load(std::memory_order_relaxed); const std::size_t tmpCurrentSize = currentSize_.load(std::memory_order_relaxed); // First of all we need to call each Elements dtor. Then we are allowed to delete the array. for (std::size_t position = 0; position < std::min(tmpCurrentSize, tmpCapacity); ++position) reinterpret_cast<const Element*>(&storageToGetDeleted[position])->~Element(); delete[] storageToGetDeleted; }; // Use different cache lines in order to avoid false sharing. alignas(64) std::atomic<std::size_t> readPosition_; alignas(64) std::atomic<std::size_t> writePosition_; alignas(64) std::atomic<std::size_t> currentSize_; alignas(64) std::atomic<std::size_t> capacity_; std::unique_ptr<ElementStorageType, decltype(customizedStorageDeleter_)> buffer_; /** Destructs a range of elements. \param from ... The index of the first element. \param to ... The indexof the last element. */ void destruct(const std::size_t from, const std::size_t to) { enumerate( make_forward_iterator<ElementStorageType>(&buffer_.get()[from]), make_forward_iterator<ElementStorageType>(&buffer_.get()[to]), 0, [](std::size_t index, ElementStorageType&& element) { reinterpret_cast<Element*>(&element)->~Element(); }); } /////////////////////////////////////////////////////////////////////////////////////////////// // Insert. /////////////////////////////////////////////////////////////////////////////////////////////// /** Inserts a sample. \param sample ... Universal reference of an object of type Element. */ template <typename T> void insertImpl(T&& sample) { const std::size_t tmpCapacity = capacity_.load(std::memory_order_relaxed); std::size_t tmpCurrentSize = currentSize_.load(std::memory_order_relaxed); std::size_t tmpWritePosition = writePosition_.load(std::memory_order_relaxed); // This read-acquire synchronizes with a write-release in extract implementations. const std::size_t tmpReadPosition = readPosition_.load(std::memory_order_acquire); if (tmpCurrentSize == tmpCapacity) // Call the destructor of the element that gets overwritten. reinterpret_cast<Element*>(&buffer_.get()[tmpWritePosition])->~Element(); else // Update the size of the stored array. ++tmpCurrentSize; // Assign memory at buffer_[writePosition_] to a pointer of Element. // Since we use placement new no memory needs to be allocated. // Sample gets moved (when possible). Element* element = new(&buffer_.get()[tmpWritePosition]) Element(std::forward<T>(sample)); // Update the position. tmpWritePosition = (tmpWritePosition + 1) % tmpCapacity; // These write-release synchronize with read-acquire in extract implementations. currentSize_.store(tmpCurrentSize, std::memory_order_release); writePosition_.store(tmpWritePosition, std::memory_order_release); } /** Moves or copies number elements from source to buffer_. \param source ... Universal reference to an array of Element objects. \param sourceStart ... Start position of the move/copy operation in source. \param number ... The number of elements that is to be moved/copied from source to buffer_. \param destinationStart ... Start position of the move/copy operation in buffer_. */ template <typename T> void insertBlockElements(T&& source, const std::size_t sourceStart, const std::size_t destinationStart, const std::size_t number, const std::size_t capacity, std::size_t& currentSize) { if (currentSize == capacity) // Call the destructor of all elements that get overwritten. destruct(destinationStart, destinationStart + number); std::uninitialized_copy( make_forward_iterator<T>(&source[sourceStart]), // Create an iterator for the last element. Since uninitialized_copy copies like [first, ..., last) // we add 1 to point after the array. make_forward_iterator<T>(&source[sourceStart + number - 1]) + 1, reinterpret_cast<Element*>(&buffer_.get()[destinationStart])); // Update the size of the stored array. if (currentSize < capacity) currentSize = std::min(capacity, currentSize + number); } /** Inserts a block of length samples. \param block ... Universal reference to an array of Element objects. \param length ... The length of the array of Element objects. */ template <typename T> void insertBlockImpl(T&& block, std::size_t blockLength) { const std::size_t tmpCapacity = capacity_.load(std::memory_order_relaxed); std::size_t tmpCurrentSize = currentSize_.load(std::memory_order_relaxed); std::size_t tmpWritePosition = writePosition_.load(std::memory_order_relaxed); // This read-acquire synchronizes with a write-release in extract implementations. const std::size_t tmpReadPosition = readPosition_.load(std::memory_order_acquire); std::size_t adjustedBlockLength = blockLength; // Do we need to crop the block to fit into the buffer? if (blockLength > tmpCapacity) adjustedBlockLength = tmpCapacity; // Limit the length to the buffer's length. // Do we need to divide the block at the physical end of the buffer? if ((tmpWritePosition + adjustedBlockLength) > tmpCapacity) { // Forwards samples to the end of the buffer. insertBlockElements( std::forward<T>(block), blockLength - adjustedBlockLength, tmpWritePosition, tmpCapacity - tmpWritePosition, tmpCapacity, tmpCurrentSize); // Forwards samples to the begin of the buffer. insertBlockElements( std::forward<T>(block), tmpCapacity - tmpWritePosition, 0, adjustedBlockLength - tmpCapacity + tmpWritePosition, tmpCapacity, tmpCurrentSize); // Update current position. tmpWritePosition = adjustedBlockLength - tmpCapacity + tmpWritePosition; } else { // Forwards the entire block to the first free location. insertBlockElements( std::forward<T>(block), blockLength - adjustedBlockLength, tmpWritePosition, adjustedBlockLength, tmpCapacity, tmpCurrentSize); // Update current position. tmpWritePosition = tmpWritePosition + adjustedBlockLength; } // Reset the position of the first free element if buffer is full. if (tmpWritePosition > tmpCapacity - 1) tmpWritePosition = 0; // These write-release synchronize with read-acquire in extract implementations. currentSize_.store(tmpCurrentSize, std::memory_order_release); writePosition_.store(tmpWritePosition, std::memory_order_release); } /////////////////////////////////////////////////////////////////////////////////////////////// // Extract. /////////////////////////////////////////////////////////////////////////////////////////////// /** Copies the block of the samples first ... last. SourceType ... The type of the source array. DestinationType ... The type of the destination array. \param source ... Universal reference to the buffer array. \param destination ... Pointer to the destination array that is to be filled with source elements. \param first ... Index of the first element that is to be copied. \param last ... Index of the last element that is to be copied. \param std::true_type ... Is always std::true_type. */ template <typename SourceType, typename DestinationType> void extractBlockElementsImpl(SourceType&& source, DestinationType* destination, std::size_t first, std::size_t last, std::true_type) { enumerate( make_forward_iterator<SourceType>(&source.get()[first]), make_forward_iterator<SourceType>(&source.get()[last]), 0, [&destination](std::size_t index, ElementStorageType&& element) { destination[index] = *reinterpret_cast<DestinationType*>(&element); }); } /** Moves the block of the samples first ... last. SourceType ... The type of the source array. DestinationType ... The type of the destination array. \param source ... Universal reference to the buffer array. \param destination ... Pointer to the destination array that is to be filled with source elements. \param first ... Index of the first element that is to be moved. \param last ... Index of the last element that is to be moved. \param std::false_type ... Is always std::false_type. */ template <typename SourceType, typename DestinationType> void extractBlockElementsImpl(SourceType&& source, DestinationType* destination, std::size_t first, std::size_t last, std::false_type) { enumerate( make_forward_iterator<SourceType>(&source.get()[first]), make_forward_iterator<SourceType>(&source.get()[last]), 0, [&destination](std::size_t index, ElementStorageType&& element) { destination[index] = std::forward<DestinationType>(*reinterpret_cast<DestinationType*>(&element)); }); } /** Extracts the block of numberOfElements samples. Uses SFINAE (based on the forwarded type of the source array) to get the right method for moving/copying. SourceType ... The type of the source array. DestinationType ... The type of the destination array. \param source ... Universal reference to the buffer array. \param destination ... Pointer to the destination array that is to be filled with source elements. \param numberOfElements ... The number of elements that are to be moved/copied from source to destinatin. */ template <typename SourceType, typename DestinationType> std::size_t extractBlockElements(SourceType&& source, DestinationType* destination, std::size_t numberOfElements) { assert(destination != nullptr); // These read-acquire synchronize with a write-release in insert implementations. const std::size_t tmpCurrentSize = currentSize_.load(std::memory_order_acquire); const std::size_t tmpWritePosition = writePosition_.load(std::memory_order_acquire); // We cannot give back more than we have. if (numberOfElements > tmpCurrentSize) numberOfElements = tmpCurrentSize; if (numberOfElements > 0) { std::size_t start = (tmpWritePosition + (tmpCurrentSize - numberOfElements)) % tmpCurrentSize; std::size_t size = ((tmpCurrentSize - start) < numberOfElements) ? (tmpCurrentSize - start) : numberOfElements; extractBlockElementsImpl( std::forward<SourceType>(source), destination, start, start + size, std::is_lvalue_reference<SourceType&&>{}); int numberOfRemaining = static_cast<int>(numberOfElements - size); std::size_t startOfRemaining = (start + size) % tmpCurrentSize; if (numberOfRemaining > 0) extractBlockElementsImpl( std::forward<SourceType>(source), destination + size, startOfRemaining, startOfRemaining + numberOfRemaining, std::is_lvalue_reference<SourceType&&>{}); } // This write-release synchronizes with a read-acquire in insert implementations. readPosition_.store(tmpWritePosition, std::memory_order_release); return numberOfElements; } /** Copies the sample feeded sampleBackwards samples ago. \param samplesBackward ... The reverse sample index. \return The sample feeded sampleBackward samples ago. */ Element extractImpl(const std::size_t samplesBackward) { const std::size_t tmpCapacity = capacity_.load(std::memory_order_relaxed); // These read-acquire synchronize with a write-release in insert implementations. const std::size_t tmpCurrentSize = currentSize_.load(std::memory_order_acquire); const std::size_t tmpWritePosition = writePosition_.load(std::memory_order_acquire); if (tmpCurrentSize == 0) return Element(); auto element = *reinterpret_cast<Element*>(&buffer_.get()[(tmpWritePosition - 1 - samplesBackward % tmpCapacity + tmpCapacity) % tmpCapacity]); // This write-release synchronizes with a read-acquire in insert implementations. readPosition_.store(tmpWritePosition, std::memory_order_release); return element; } public: RingBuffer(const RingBuffer<Element>&) = delete; RingBuffer& operator=(const RingBuffer<Element>&) = delete; RingBuffer(RingBuffer<Element>&&) = delete; RingBuffer& operator=(RingBuffer<Element>&&) = delete; RingBuffer(void) // make_unique has no overload allowing to specify a custom deleter. Hence we need to live with the naked new. : buffer_(new ElementStorageType[0], customizedStorageDeleter_), capacity_(0), readPosition_(0), writePosition_(0), currentSize_(0) {} explicit RingBuffer(const std::size_t capacity) // make_unique has no overload allowing to specify a custom deleter. Hence we need to live with the naked new. : buffer_(new ElementStorageType[capacity], customizedStorageDeleter_), capacity_(capacity), readPosition_(0), writePosition_(0), currentSize_(0) {} ~RingBuffer(void) { reset(); } /** Destructs all buffer elements and resets the buffer size. */ void reset(void) { const std::size_t tmpCapacity = capacity_.load(std::memory_order_relaxed); const std::size_t tmpWritePosition = writePosition_.load(std::memory_order_relaxed); const std::size_t tmpCurrentSize = currentSize_.load(std::memory_order_relaxed); if (tmpCurrentSize == 0) return; std::size_t oldestElement = (tmpWritePosition - tmpCurrentSize + tmpCapacity) % tmpCapacity; std::size_t supposedNewestElement = oldestElement + tmpCurrentSize; std::size_t factualNewestElement = std::min(supposedNewestElement, static_cast<std::size_t>(tmpCapacity)); destruct(oldestElement, factualNewestElement); factualNewestElement = supposedNewestElement - tmpCapacity; if (factualNewestElement > 0) destruct(0, factualNewestElement); writePosition_.store(0, std::memory_order_release); readPosition_.store(0, std::memory_order_release); currentSize_.store(0, std::memory_order_release); } /** Destructs all buffer elements and reinitializes the buffer with a new capacity. */ void reset(std::size_t newCapacity) { reset(); capacity_.store(newCapacity, std::memory_order_relaxed); buffer_.reset(new ElementStorageType[newCapacity]); } /** Inserts a sample. Declaring and using T brings us an universal reference and we can profit from type deduction. So lvalue and rvalue references can be passed to this member (pefectly forwarded). \param sample ... Universal reference of an object of type Element. */ template <typename T> void insert(T&& sample) { insertImpl(std::forward<T>(sample)); } /** Inserts a block of length samples. \param block ... Universal reference to an array of Element objects. \param length ... The length of the array of Element objects. */ template <typename T> void insert(T&& block, std::size_t blockLength) { insertBlockImpl(std::forward<T>(block), blockLength); } /** Copies the sample feeded sampleBackwards samples ago. e.g. get(0) Returns the last feeded sample. get(capacity_ - 1) Returns the oldest sample. get(capacity_ * n) returns the last feeded sample. get(capacity_ * n + 1) returns the sample feeded in prior to the last one. \param samplesBackward ... The reverse sample index. \return The sample feeded sampleBackward samples ago. */ Element copy(const std::size_t samplesBackward) { return extractImpl(samplesBackward); } /** Copies the last numberOfElements samples from buffer_ into destination. Attention: destination needs to have enough space for numberOfElements samples. \param destination ... Pointer to an array of Element. \param numberOfElements ... The number of elements that are to be copied into destination. \return The number of samples being copied. */ std::size_t copy(Element* destination, std::size_t numberOfElements) { return extractBlockElements(buffer_, destination, numberOfElements); } /** \return The number of elements that the buffer could contain without overwriting older ones. */ std::size_t capacity(void) const { return capacity_.load(std::memory_order_relaxed); } /** \return The number of elements in the buffer. */ std::size_t currentSize(void) const { return currentSize_.load(std::memory_order_relaxed); } }; }
true
e74b804aee6b2440231646a3f200b267250fe641
C++
utexas-bwi/scavenger_hunt
/bwi_scavenger/src/path_planning.cpp
UTF-8
5,952
2.90625
3
[]
no_license
#include <algorithm> #include <limits> #include <iostream> #include <math.h> #include <random> #include "bwi_scavenger/path_planning.h" #include "bwi_scavenger/world_mapping.h" LocationEvaluator::LocationEvaluator(World w) { if (w == SIM) world_waypoints = &WORLD_WAYPOINTS_SIM; else if (w == IRL) world_waypoints = &WORLD_WAYPOINTS_IRL; } void LocationEvaluator::add_location(EnvironmentLocation loc) { locations.push_back(loc); object_db[loc] = std::vector<std::string>(); } void LocationEvaluator::add_object(EnvironmentLocation loc, std::string label) { object_db[loc].push_back(label); } EnvironmentLocation LocationEvaluator::get_closest_location(coordinates_t c, bool start) { float closest_dist = std::numeric_limits<float>::infinity(); std::size_t closest_ind = 0; for (std::size_t i = 0; i < locations.size(); i++) { coordinates_t coords = (*world_waypoints)[locations[i]]; float dx = coords.x - c.x; float dy = coords.y - c.y; float dist = sqrt(dx * dx + dy * dy); if (dist < closest_dist) { closest_dist = dist; closest_ind = i; } } if (start) loc_index = closest_ind; return locations[closest_ind]; } /******************************************************************************* * COMPLETE BASELINE ALGORITHM * Simply goes to the next location in the path. Does not consider proximity * nor probabilities. ******************************************************************************/ CompleteLocationEvaluator::CompleteLocationEvaluator(World w) : LocationEvaluator(w) {} EnvironmentLocation CompleteLocationEvaluator::get_location( const std::vector<std::string>& remaining_objects, coordinates_t coords_current) { EnvironmentLocation loc = locations[loc_index % locations.size()]; loc_index++; return loc; } /******************************************************************************* * OCCUPANCY GRID BASELINE ALGORITHM * Goes to the location with the highest probabilty of finding the rest of * the objects. * Objects are considered to be of the same value, thus the location with the * most objects would be chosen ******************************************************************************/ OccupancyGridLocationEvaluator::OccupancyGridLocationEvaluator(World w) : fallback_eval(w), LocationEvaluator(w) {} void OccupancyGridLocationEvaluator::add_location(EnvironmentLocation loc) { LocationEvaluator::add_location(loc); fallback_eval.add_location(loc); } void OccupancyGridLocationEvaluator::add_object(EnvironmentLocation loc, std::string label) { object_db[loc].push_back(label); fallback_eval.add_object(loc, label); visited[loc] = false; } void OccupancyGridLocationEvaluator::start_fallback(coordinates_t coords_current) { if (!fallback_started) { fallback_eval.get_closest_location(coords_current, true); fallback_started = true; } } EnvironmentLocation OccupancyGridLocationEvaluator::get_location( const std::vector<std::string>& remaining_objects, coordinates_t coords_current) { if (remaining_objects.size() == 0) start_fallback(coords_current); if (fallback_started) return fallback_eval.get_location(remaining_objects, coords_current); std::map<EnvironmentLocation, unsigned int> occurrences; for (const EnvironmentLocation& loc : locations) occurrences[loc] = 0; for (const EnvironmentLocation& loc : locations) { const std::vector<std::string>& loc_objects = object_db[loc]; for (const std::string& obj : remaining_objects) if (std::find(loc_objects.begin(), loc_objects.end(), obj) != loc_objects.end()) occurrences[loc]++; } EnvironmentLocation best_loc; unsigned int best_loc_score = 0; for (const EnvironmentLocation& loc : locations) { unsigned int score = occurrences[loc]; if (score > best_loc_score && !visited[loc]) { best_loc = loc; best_loc_score = score; } } if (best_loc_score == 0) { start_fallback(coords_current); EnvironmentLocation l = fallback_eval.get_location(remaining_objects, coords_current); return l; } visited[best_loc] = true; return best_loc; } /******************************************************************************* * PROXIMITY BASELINE ALGORITHM * Goes to the next closest location that still contains an object that has not * been found. ******************************************************************************/ EnvironmentLocation ProximityBasedLocationEvaluator::get_location( const std::vector<std::string>& remaining_objects, coordinates_t coords_current) { if (remaining_objects.size() == 0) start_fallback(coords_current); if (fallback_started) return fallback_eval.get_location(remaining_objects, coords_current); EnvironmentLocation current_location = locations[loc_index]; // determine the closest location that still contains an unfound object float closest_dist = std::numeric_limits<float>::infinity(); std::size_t closest_ind = 0; for (std::size_t i = 0; i < locations.size(); i++) { // check that this location has an object that has not yet been found bool look_here = false; const std::vector<std::string>& loc_objects = object_db[current_location]; for (const std::string& obj : remaining_objects) if (std::find(loc_objects.begin(), loc_objects.end(), obj) != loc_objects.end()){ look_here = true; break; } if(!look_here) continue; // determine the distance to the current location coordinates_t coords = (*world_waypoints)[current_location]; float dx = coords.x - coords_current.x; float dy = coords.y - coords_current.y; float dist = sqrt(dx * dx + dy * dy); if (dist < closest_dist) { closest_dist = dist; closest_ind = i; } } loc_index = closest_ind; return locations[closest_ind]; }
true
9a080cb6f26e2667ca713dce5c5bbc2d9b02b261
C++
adhuliya/ws-misc
/cpp/namespace-lookup.cc
UTF-8
472
3.078125
3
[]
no_license
#include <iostream> using namespace std; int max = 12; namespace { int max = 10; void print() { std::cout << max; // current namespace' max std::cout << ::max; // global namespace' max } } namespace { void printt() { std::cout << max; // current namespace' max std::cout << ::max; // global namespace' max } } int main(int argc, char **argv) { printt(); // links to the unnamed namespace return 0; }
true
a5d2064959338451de7e85c14bf23ec3601fe280
C++
Pliskeviski/GameEngine
/Classes/Texture.h
UTF-8
757
2.578125
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include <string> #include <assert.h> #include <GL\glew.h> #include <SOIL2\SOIL2.h> enum TextureType { TYPE_CUBEMAP, TYPE_DIFFUSE, TYPE_METALLIC, TYPE_ROUGHNESS, TYPE_NORMAL, TYPE_AO }; struct m_Texture { GLuint id; TextureType type; }; class Texture { public: Texture(std::string path, TextureType type); Texture(std::vector<std::string> faces, TextureType type); inline GLuint getID() { return texture.id; } inline TextureType getType() { return texture.type; } inline void Delete() { glDeleteTextures(1, &texture.id); } private: GLuint loadTexture(std::string path); GLuint loadCubeMap(std::vector<std::string> faces); m_Texture texture; };
true
08c6971475e44e173ef54b22def8bbda320bf16a
C++
arkadiusz-er/PersonalBudget
/DataOfBalance.h
UTF-8
449
2.53125
3
[]
no_license
#ifndef DATAOFBALANCE_H #define DATAOFBALANCE_H #include <iostream> using namespace std; class DataOfBalance { protected: int userId; string date; string item; double amount; public: void setUserId(int newUserId); void setDate (string newDate); void setItem (string newItem); void setAmount (double newAmount); int getUserId(); string getDate(); string getItem(); double getAmount(); }; #endif
true
b0ae5b109a1a2779ea78efd9f0bea8b5ad9226c0
C++
yuanyuewandou/DesignPatternsCppDemo
/src/responsibilitychain.cpp
UTF-8
3,431
3.640625
4
[]
no_license
/* 小鱼号的代码日志 * 设计模式 * 职责链模式 * 使用多个对象都有机会处理请求 * 从而避免请求的发送和接受之间的耦合关系 * 将这个对象连成一条链,并沿着这条链传递该请求 * 知道有一个对象处理它为止 * 实例: * 学校采购金额审批流程 * < 3000 系主任审批 * 3000 - 5000 学院主任审批 * 5000 - 30000 副校长审批 * 30000 - 30000000 校长审批 * > 30000000 都没办法审批 */ #include<iostream> #include<string> using namespace std; ///请求类 class PurchaseRequeset { public: PurchaseRequeset(int price) { m_price = price; } int getPrice() { return m_price; } private: int m_price; //审批金额 }; ///请求的处理者 class Approver { public: Approver(string name) { m_name = name; } void setNextApprover(Approver* nextApprover) { m_nextApprover = nextApprover; } ///处理请求 virtual void processRequest(PurchaseRequeset req) { cout << "can not process Requese" << endl; } protected: Approver* m_nextApprover; ///下一个处理者 string m_name; }; ///系主任 级别的处理者 class DepartmentApprover : public Approver { public: DepartmentApprover(string name) : Approver(name) { } void processRequest(PurchaseRequeset req) { int price = req.getPrice(); if(price < 3000) { cout << "name:" << m_name << " process request $:" << price << endl; } else { cout << "name:" << m_name << " can not process request" << endl; m_nextApprover->processRequest(req); } } }; ///学院主任 级别的处理者 class CollegeApprover : public Approver { public: CollegeApprover(string name) : Approver(name) { } void processRequest(PurchaseRequeset req) { int price = req.getPrice(); if(price > 3000 && price < 5000) { cout << "name:" << m_name << " process request $:" << price << endl; } else { cout << "name:" << m_name << " can not process request" << endl; m_nextApprover->processRequest(req); } } }; ///副校长 级别的处理者 class ViceSchoolMasterApprover : public Approver { public: ViceSchoolMasterApprover(string name) : Approver(name) { } void processRequest(PurchaseRequeset req) { int price = req.getPrice(); if(price > 5000 && price < 30000) { cout << "name:" << m_name << " process request $:" << price << endl; } else { cout << "name:" << m_name << " can not process request" << endl; m_nextApprover->processRequest(req); } } }; ///校长 级别的处理者 class SchoolMasterApprover : public Approver { public: SchoolMasterApprover(string name) : Approver(name) { } void processRequest(PurchaseRequeset req) { int price = req.getPrice(); if(price > 30000 && price < 30000000) { cout << "name:" << m_name << " process request $:" << price << endl; } else { cout << "name:" << m_name << " can not process request" << endl; m_nextApprover->processRequest(req); } } };
true
c0176f081310d104122bc3d2665970e471c4cb89
C++
WrongSandwich/programProjects
/projects2/Lab05/Trout-2839780-Lab-05/MapReader.h
UTF-8
1,147
3.15625
3
[]
no_license
/******************************************************************************* *@author Evan Trout *@file MapReader.h *@date 10/04/2018 *@brief Header file for the MapReader class. Reads input from input file and * creates a 2D char array and associated integers. Also contains getters * for all private members. *******************************************************************************/ #ifndef MAP_READER_H #define MAP_READER_H class MapReader { private: char** map; int numRows; int numCols; int startRow; int startCol; int waterAmnt; public: /** * @param fileName: a fileName with data and a map to be used * @post Reads data into private members and creates a 2D char map * @return the constructed MapReader */ MapReader(std::string fileName); /** * @return char** map */ char** getMap(); /** * @return int numRows */ int getRows(); /** * @return int numCols */ int getCols(); /** * @return int startRow */ int getStartRow(); /** * @return int startCol */ int getStartCol(); /** * @return int waterAmnt */ int getWater(); }; #endif
true
951572ddd6016f6192d19ec775e1746c536072aa
C++
mgb/nullspace
/src/render/TextureMap.cpp
UTF-8
2,018
3.0625
3
[ "MIT" ]
permissive
#include "TextureMap.h" #include <cassert> #include <cstring> #include "../Memory.h" namespace null { u32 Hash(const char* str) { u32 hash = 5381; char c; while ((c = *str++)) { hash = hash * 33 ^ c; } return hash; } TextureMap::TextureMap(MemoryArena& arena) : arena(arena), free(nullptr) { for (size_t i = 0; i < kTextureMapBuckets; ++i) { elements[i] = nullptr; } for (size_t i = 0; i < 32; ++i) { Element* element = memory_arena_push_type(&arena, Element); element->next = free; free = element; } } void TextureMap::Insert(const char* name, u32 id, u32 width, u32 height) { u32 bucket = Hash(name) & (kTextureMapBuckets - 1); Element* element = elements[bucket]; while (element) { if (strcmp(element->name, name) == 0) { break; } element = element->next; } if (element == nullptr) { element = Allocate(); assert(strlen(name) < NULLSPACE_ARRAY_SIZE(element->name)); strcpy(element->name, name); element->next = elements[bucket]; elements[bucket] = element; } element->value.id = id; element->value.width = width; element->value.height = height; } TextureData* TextureMap::Find(const char* name) { u32 bucket = Hash(name) & (kTextureMapBuckets - 1); Element* element = elements[bucket]; while (element) { if (strcmp(element->name, name) == 0) { return &element->value; } element = element->next; } return nullptr; } TextureMap::Element* TextureMap::Allocate() { Element* result = nullptr; if (free) { result = free; free = free->next; } else { result = memory_arena_push_type(&arena, Element); } result->next = nullptr; return result; } void TextureMap::Clear() { for (size_t i = 0; i < kTextureMapBuckets; ++i) { Element* element = elements[i]; while (element) { Element* next = element->next; element->next = free; free = element; element = next; } elements[i] = nullptr; } } } // namespace null
true
9324bd249cf64e73bfb29bc86e673430426ae1f1
C++
marwan-abdellah/ServerClient
/client.cpp
UTF-8
2,958
2.875
3
[]
no_license
#include <stdio.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdio.h> #include <iostream> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdlib.h> #include <stdio.h> #include "Shared.h" #define ARRAY_SIZE 8 int main(int argc , char** argv) { int sCount = 1; if (argc < 2) { std::cout << "Enter a clinet number " << std::endl; return 0; } // Identify the client float clinetValue = atof(argv[1]); std::cout << "Clinet : " << clinetValue << std::endl; // The application socket that connects the client with the server int appSocket; // Server address struct sockaddr_in serverAddress; // Messages char serverReply[2000]; // Create the clinet socket appSocket = socket(AF_INET , SOCK_STREAM , 0); if (appSocket == -1) std::cout << "Could not create the client-side socket"; else std::cout << "Client socket has been successfully created"; // Fill in the address of the server // TODO: Change the hardcoded port number and the local host serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons( 8888 ); // Connect to remote server int errorCode = connect(appSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)); if (errorCode < 0) { std::cout << "Connection failed. Error, application terminates" << std::endl; return 1; } else std::cout << "Client is connected to the server" << std::endl; Packet packet; int replyMessage = 0; // Keep communicating with server until you drop the client while(1) { sleep(replyMessage); for (int i = 0; i < ARRAY_SIZE; i++) { packet.imageData[i] = i + clinetValue; } packet.clinetNumber = clinetValue; /// Get the image /// /// Send the image wait for the receiver to send back move on and the angle // Send the message errorCode = send(appSocket, &packet, sizeof(Packet), 0); if(errorCode < 0) { std::cout << "Sending the message failed" << std::endl; return 1; } // Receive a reply from the server errorCode = recv(appSocket , &replyMessage , sizeof(int), 0); if(errorCode < 0) { std::cout << "Receving the message from the server failed, Exiting" << std::endl; break; } else { std::cout << "Server reply : " << replyMessage << std::endl; sCount++; } } // If the loop terminates, then close the socket close(appSocket); return 0; }
true
b4e805b32f24e6103dd48bd3c3dcc2cfe4796b42
C++
shugo256/AtCoder
/others/CPSCO2019_S4_C_Make_a_Team.cpp
UTF-8
522
2.65625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; long c2(long n) { if (n < 2) return 0; else return n*(n-1) / 2; } int main() { long n; long d; cin >> n >> d; long r[n]; for (auto i=0; i<n; i++) cin >> r[i]; sort(r, r+n); long j=0, sum=0; for (auto i=0; i<n; i++) { while (j < n && r[i] + d >= r[j]) j++; sum += c2(j - i - 1); // cerr << i << ' ' << j << ' ' << r[i] << ' ' << c2(j-i-1) << '\n'; } cout << sum << '\n'; return 0; }
true
e23060a82fac45e1ae399b0abeadc82940bf2628
C++
ChialeKuan/algorithm
/dp/bool_backpack.cc
UTF-8
2,144
3.234375
3
[]
no_license
#include <iostream> #define N 100 #define M 1000 using namespace std; // index <= N + 1 // volume <= M + 1 int dp[N + 1][M + 1]; int dp_[M + 1]; int weight[N + 1]; int value[N + 1]; int total_w, total_n; void dim_2() { int tmp; for (int i = 0; i != total_w + 1; ++i) { dp[0][i] = 0; } for (int i = 1; i != total_n + 1; ++i) { for (int j = 0; j != total_w + 1; ++j) { dp[i][j] = dp[i - 1][j]; if (j >= weight[i]) { // 如果可以装下 // 这里可以看出 dp 实际上可以用一位数组来实现 dp[i][j] = dp[i - 1][j]; // 注意这里是 i - 1, 不是 i tmp = dp[i - 1][j - weight[i]] + value[i]; if (tmp > dp[i][j]) { dp[i][j] = tmp; // cout << tmp << "!" << endl; } } } } cout << dp[total_n][total_w] << endl; } void dim_1() { for (int i = 0; i != total_w + 1; ++i) { dp_[i] = 0; } for (int i = 1; i != total_n + 1; ++i) { for (int j = total_w; j >= weight[i]; --j) { // 反向更新,事实上只能从上一级里面多取一个 if (dp_[j - weight[i]] + value[i] > dp_[j]) dp_[j] = dp_[j - weight[i]] + value[i]; } } cout << dp_[total_w] << endl; } void dim_1_not_bool() { for (int i = 0; i != total_w + 1; ++i) { dp_[i] = 0; } for (int i = 1; i != total_n + 1; ++i) { for (int j = weight[i]; j <= total_w + 1; ++j) { // 正向更新,可以取很多歌 if (dp_[j - weight[i]] + value[i] > dp_[j]) dp_[j] = dp_[j - weight[i]] + value[i]; } } cout << dp_[total_w] << endl; } int main(int argc, const char* argv[]) { while (cin >> total_w >> total_n) { for (int i = 1; i != total_n + 1; ++i) { cin >> weight[i] >> value[i]; } cout << "1D:\t"; dim_1(); cout << "2D:\t"; dim_2(); cout << "MANY:\t"; dim_1_not_bool(); } return 0; }
true
b84b0e8b1f0c2b26fa0688ce442af77ae38c4123
C++
mgalang229/Hackerrank-Possible-Path
/sol.cpp
UTF-8
409
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; long long __gcd(long long a, long long b) { if (b == 0) { return a; } return __gcd(b, a % b); } int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { long long a, b, x, y; cin >> a >> b >> x >> y; if (__gcd(a, b) == __gcd(x, y)) { cout << "YES"; } else { cout << "NO"; } cout << '\n'; } return 0; }
true
c839da77405377f062a0a09d293e0d7e7aa6a386
C++
Gilsmeister/ChessInHex
/ChessInHex/move.h
UTF-8
100
2.609375
3
[]
no_license
class Move { public: int pos; // position in board array; int m; // move Move(int p, int M); };
true
e4591862eff39dc4e2e9d87d82d520dcb1f94055
C++
CS246-CS247-Quadris/tangsaidi-tetris
/levelFour.cc
UTF-8
1,001
2.890625
3
[ "MIT" ]
permissive
#include "levelFour.h" #include <cstdlib> #include <utility> using namespace std; LevelFour::LevelFour(Board* board): LevelThree(board){ srand(Level::seed); } // Check if we have removable rows bool LevelFour::hasRemovable() { for (auto &r: *(getBoard())) { if (r.isRemovable()) { return true; } } return false; } // get the next block on this level, failed command also trigger heavy move std::unique_ptr<Block> LevelFour::getNext() { std::unique_ptr<Block> ret = LevelThree::getNext(); counter++; if (hasRemovable()) { counter = 0; } if (counter != 0 && counter % 5 == 0) { int dropRow = 14; int const mid = 5; if (!getBoard()->at(dropRow).isOccupied(mid)) { for (int i = 14; i>-1; --i) { if (getBoard()->at(i).isOccupied(mid)) { break; } else { dropRow--; } } dropRow++; board->createSettler(std::make_pair(mid, dropRow)); } } return ret; } LevelFour::~LevelFour() {}
true
beecac9ca94fd3be1549b55533b36a2001d8b407
C++
aluo/LoanBrick
/LAB 3 Loan Calculator GUI/CalculatorBU.h
UTF-8
827
2.890625
3
[]
no_license
/* LAB 3: Loan Calculator GUI * Amy Luo * CSC 330 - Object Oriented Programming * 2013-10-07 */ #ifndef CALCULATORBU_H #define CALCULATORBU_H #include <math.h> #include <string> #using <Microsoft.VisualBasic.dll> using namespace std; class LoanCalc{ private: // VARIABLES // // C - Loan Amount // R - Interest Rate % // P - Monthly Payment // N - Number of Months double C, R, P, N; public: LoanCalc(){C = 0; R = 0; N = 0; P = 0;}; //initializing main variables double findMonthlyPay(double,double,double); // Finds Monthly Pay (P) double findInterestRate(double,double,double); // Finds Interest Rate (R) double findNumMonths(double,double,double); // Finds Number of Months (N) double findLoanAmt(double,double,double); // Finds Loan Amount (C) }; #endif
true
d6232992ce4adaa6c1f2c3b3bb57b67a5a2a48d8
C++
Lykos/Olaf
/protocols/event/setdepthevent.h
UTF-8
455
2.625
3
[]
no_license
#ifndef SETDEPTHEVENT_H #define SETDEPTHEVENT_H #include "protocols/event/engineevent.h" #include <chrono> namespace olaf { /** * @brief The SetDepthEvent class represents an event that the maximum * depth for the engine has changed. */ class SetDepthEvent : public EngineEvent { public: SetDepthEvent(int depth); void execute(EngineState* engine_state); private: const int m_depth; }; } // namespace olaf #endif // SETDEPTHEVENT_H
true
24ad5ac4eddc99f20edab360f706d47a935faa77
C++
Cyber-SiKu/nowcoder
/35/35-2.cpp
UTF-8
1,122
3.546875
4
[]
no_license
#include <iostream> #include <string> using namespace std; class Solution { private: int max_length; public: Solution(string str1, string str2); ~Solution(); friend ostream& operator<<(ostream& os, const Solution& s); }; Solution::Solution(string str1, string str2) { if (str1.length() < str2.length()) { // 保证str1最长 string tmp = str1; str1 = str2; str2 = tmp; } max_length = 0; for (int i = str2.length(); i > 0; i--) { // 假设最长字串长度为 i for (int j = 0, e = str2.length(); j + i <= e; i++) { string sub = string(str2.begin() + j, str2.begin() + j + i); if (str1.find(sub) != str1.npos) { this->max_length = i; return; } } } } Solution::~Solution() { } ostream& operator<<(ostream& os, const Solution& s) { os << s.max_length; return os; } int main(int argc, char* argv[]) { string str1; string str2; getline(cin, str1); getline(cin, str2); Solution s(str1, str2); cout << s << endl; return 0; }
true
3ec082e96ce63e81c8c89ca2bfbc57a4bfdb5612
C++
patrickpclee/codfs
/branch/0.2/src/osd/codingmodule.hh
UTF-8
2,616
2.8125
3
[]
no_license
/** * codingmodule.hh */ #ifndef __CODINGMODULE_HH__ #define __CODINGMODULE_HH__ #include <map> #include <vector> #include <stdint.h> #include "../coding/coding.hh" #include "../common/segmentdata.hh" #include "../common/objectdata.hh" #include "../common/enums.hh" struct CodingSetting { CodingScheme codingScheme; string setting; }; class CodingModule { public: CodingModule(); /** * Encode an object to a list of segments * @param objectData ObjectData structure * @param setting for the coding scheme * @return A list of SegmentData structure */ vector<struct SegmentData> encodeObjectToSegment(CodingScheme codingScheme, struct ObjectData objectData, string setting); /** * Encode an object to a list of segments * @param objectId Object ID * @param buf Pointer to buffer holding object data * @param length length of the object * @return A list of SegmentData structure */ vector<struct SegmentData> encodeObjectToSegment(CodingScheme codingScheme, uint64_t objectId, char* buf, uint64_t length, string setting); /** * Decode a list of segments into an object * @param objectId Destination object ID * @param segmentData a list of SegmentData structure * @param requiredSegments IDs of segments that are required to do decode * @return an ObjectData structure */ struct ObjectData decodeSegmentToObject(CodingScheme codingScheme, uint64_t objectId, vector<struct SegmentData> segmentData, vector<uint32_t> requiredSegments, string setting); /** * Get the list of segments required to do decode * @param codingScheme Coding Scheme * @param setting Coding Setting * @param secondaryOsdStatus a bool array containing the status of the OSD * @return list of segment ID */ vector<uint32_t> getRequiredSegmentIds(CodingScheme codingScheme, string setting, vector<bool> secondaryOsdStatus); /** * Get the number of segments that the scheme uses * @param codingScheme Coding Scheme * @param setting Coding Setting * @return number of segments */ uint32_t getNumberOfSegments(CodingScheme codingScheme, string setting); /** * Get the Coding object according to the codingScheme specified * @param codingScheme Type of coding scheme * @return The Coding object */ Coding* getCoding(CodingScheme codingScheme); /** * Retrieve a segment from the storage module * @param objectId ID of the object that the segment is belonged to * @param segmentId ID of the segment to retrieve * @return a SegmentData structure */ private: // Coding* _coding; map<CodingScheme, Coding*> _codingWorker; }; #endif
true
605c4749d91190f7fd09af81865ed89bc9bfd54c
C++
marinofranusic/CodeEval
/Hard/GridWalk/GridWalk.cpp
UTF-8
3,728
3.515625
4
[]
no_license
/* GRID WALK SPONSORING COMPANY: AVANOO CHALLENGE DESCRIPTION: There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself? INPUT SAMPLE: There is no input for this program. OUTPUT SAMPLE: Print the number of points the monkey can access. It should be printed as an integer — for example, if the number of points is 10, print "10", not "10.0" or "10.00", etc. */ #include <fstream> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; struct point_t { int x; int y; }; struct find_point { point_t p; find_point(point_t p): p(p) {} bool operator () ( const point_t& pt) const { if(p.x==pt.x && p.y==pt.y) return true; else return false; } }; int abs(int num) { if(num<0) return num*(-1); else return num; } int SumOfDigits(point_t *p) { int sum=0; int num = abs(p->x); while ( num > 0 ) { sum += num % 10; num /= 10; } num = abs(p->y); while ( num > 0 ) { sum += num % 10; num /= 10; } return sum; } bool CanWalk(point_t *p) { if(SumOfDigits(p)<=19) return true; else return false; } bool IsInPastPoints(point_t *p, vector<point_t> *v) { bool retVal=false; if(find_if((*v).begin(),(*v).end(),find_point(*p))!=(*v).end()) {retVal=true;} else {retVal=false;} return retVal; } int main(int arg, char* args[]) { point_t p; p.x=0; p.y=0; vector<point_t> PastPoints; vector<point_t> ToProcess; PastPoints.push_back(p); ToProcess.push_back(p); //Count duplicates from quarter solution while(ToProcess.size()>0) { point_t tempPoint; tempPoint=ToProcess.back(); ToProcess.pop_back(); tempPoint.x--; if(CanWalk(&tempPoint)==true && IsInPastPoints(&tempPoint,&PastPoints)==false) { PastPoints.push_back(tempPoint); ToProcess.push_back(tempPoint); } tempPoint.x++; } int duplicates=PastPoints.size(); PastPoints.clear(); ToProcess.clear(); p.x=0; p.y=0; PastPoints.push_back(p); ToProcess.push_back(p); //Count quarter solution while(ToProcess.size()>0) { point_t tempPoint; tempPoint=ToProcess.back(); ToProcess.pop_back(); tempPoint.x--; if(CanWalk(&tempPoint)==true && IsInPastPoints(&tempPoint,&PastPoints)==false) { PastPoints.push_back(tempPoint); ToProcess.push_back(tempPoint); } tempPoint.x++; //up tempPoint.y--; if(CanWalk(&tempPoint)==true && IsInPastPoints(&tempPoint,&PastPoints)==false) { PastPoints.push_back(tempPoint); ToProcess.push_back(tempPoint); } tempPoint.y++; } int quarter=PastPoints.size(); cout<<(quarter-duplicates)*4+1<<endl; return 0; }
true
e95762c0543916d0a12d101165e5094460e4569f
C++
hayate891/carpg
/source/game/Gui2.h
WINDOWS-1250
8,901
2.671875
3
[ "MIT" ]
permissive
#pragma once #include "VertexDeclaration.h" //----------------------------------------------------------------------------- // Opis znaku czcionki struct Glyph { BOX2D uv; int width; bool ok; }; //----------------------------------------------------------------------------- // Przechowuje string lub cstring struct StringOrCstring { union { string* str; cstring cstr; }; bool is_str; StringOrCstring(cstring cstr) : cstr(cstr), is_str(false) { } StringOrCstring(string& _str) : str(&_str), is_str(true) { } StringOrCstring(const string& _str) : cstr(_str.c_str()), is_str(false) { } StringOrCstring(LocalString& _str) : str(_str.get_ptr()), is_str(true) { } inline size_t length() const { return is_str ? str->length() : strlen(cstr); } inline cstring c_str() { return is_str ? str->c_str() : cstr; } inline void AddTo(string& s) const { if(is_str) s += *str; else s += cstr; } }; //----------------------------------------------------------------------------- // Czcionka struct Font { TEX tex, texOutline; int height; float outline_shift; Glyph glyph[256]; // zwraca szeroko znaku inline int GetCharWidth(char c) const { const Glyph& g = glyph[byte(c)]; if(g.ok) return g.width; else return 0; } // oblicza szeroko linijki tekstu int LineWidth(cstring str) const; // oblicza wysoko i szeroko bloku tekstu INT2 CalculateSize(StringOrCstring str, int limit_width=INT_MAX) const; // dzieli tekst na linijki bool SplitLine(size_t& OutBegin, size_t& OutEnd, int& OutWidth, size_t& InOutIndex, cstring Text, size_t TextEnd, DWORD Flags, int Width) const; }; //----------------------------------------------------------------------------- // Wasne flagi do rysowania tekstu // aktualnie obsugiwane DT_LEFT, DT_CENTER, DT_RIGHT, DT_TOP, DT_VCENTER, DT_BOTTOM, DT_SINGLELINE, DT_OUTLINE #define DT_OUTLINE (1<<31) //----------------------------------------------------------------------------- // Zdarzenie gui enum GuiEvent { GuiEvent_GainFocus, GuiEvent_LostFocus, GuiEvent_Moved, GuiEvent_Resize, GuiEvent_Show, GuiEvent_WindowResize, GuiEvent_Close, GuiEvent_Custom }; //----------------------------------------------------------------------------- class Control; class Container; class Dialog; //----------------------------------------------------------------------------- struct Hitbox { RECT rect; int index, index2; }; //----------------------------------------------------------------------------- enum class HitboxOpen { No, Yes, Group }; //----------------------------------------------------------------------------- struct HitboxContext { vector<Hitbox>* hitbox; int counter, group_index, group_index2; HitboxOpen open; RECT region; }; //----------------------------------------------------------------------------- enum CursorMode { CURSOR_NORMAL, CURSOR_HAND, CURSOR_TEXT }; //----------------------------------------------------------------------------- enum GUI_DialogType { DIALOG_OK, DIALOG_YESNO, DIALOG_CUSTOM }; //----------------------------------------------------------------------------- typedef fastdelegate::FastDelegate1<int> DialogEvent; typedef fastdelegate::FastDelegate2<int, int> DialogEvent2; //----------------------------------------------------------------------------- enum DialogOrder { ORDER_NORMAL, ORDER_TOP, ORDER_TOPMOST }; //----------------------------------------------------------------------------- struct DialogInfo { DialogInfo() : custom_names(nullptr), have_tick(false), ticked(false) { } string name, text; GUI_DialogType type; Control* parent; DialogEvent event; DialogOrder order; bool pause, have_tick, ticked; cstring* custom_names, tick_text; }; //----------------------------------------------------------------------------- class OnCharHandler { public: virtual void OnChar(char c) {} }; //----------------------------------------------------------------------------- struct TextLine { size_t begin, end; int width; TextLine(size_t begin, size_t end, int width) : begin(begin), end(end), width(width) { } }; //----------------------------------------------------------------------------- // GUI class IGUI { public: IGUI(); ~IGUI(); void Init(IDirect3DDevice9* device, ID3DXSprite* sprite); void SetShader(ID3DXEffect* e); void Draw(const INT2& wnd_size); Font* CreateFont(cstring name, int size, int weight, int tex_size, int outline=0); /* zaawansowane renderowanie tekstu (w porwnaniu do ID3DXFont) zwraca false jeeli by clipping od dou (nie kontuuj tekstu w flow) Znak $ oznacza jak specjaln czynno: $$ - wstaw $ $c? - ustaw kolor (r-czerwony, g-zielony, y-ty, b-czarny, w-biay, -przywrc domylny) $h+ - informacja o hitboxie $h- - koniec hitboxa /$b - przerwa w tekcie /$n - nie przerywaj tekstu a do nastpnego takiego symbolu (np $njaki tekst$n - ten tekst nigdy nie zostanie rozdzielony pomidzy dwie linijki) */ bool DrawText(Font* font, StringOrCstring text, DWORD flags, DWORD color, const RECT& rect, const RECT* clipping=nullptr, vector<Hitbox>* hitboxes=nullptr, int* hitbox_counter=nullptr, const vector<TextLine>* lines=nullptr); void Add(Control* ctrl); void DrawItem(TEX t, const INT2& item_pos, const INT2& item_size, DWORD color, int corner=16, int size=64); void Update(float dt); void DrawSprite(TEX t, const INT2& pos, DWORD color=WHITE, const RECT* clipping=nullptr); void OnReset(); void OnReload(); void OnClean(); void OnChar(char c); Dialog* ShowDialog(const DialogInfo& info); void ShowDialog(Dialog* dialog); bool CloseDialog(Dialog* d); void CloseDialogInternal(Dialog* d); bool HaveTopDialog(cstring name) const; bool HaveDialog() const; void DrawSpriteFull(TEX t, DWORD color); inline void AddOnCharHandler(OnCharHandler* h) { on_char.push_back(h); } inline void RemoveOnCharHandler(OnCharHandler* h) { RemoveElement(on_char, h); } void SimpleDialog(cstring text, Control* parent, cstring name="simple"); void DrawSpriteRect(TEX t, const RECT& rect, DWORD color=WHITE); bool HaveDialog(cstring name); inline IDirect3DDevice9* GetDevice() { return device; } bool AnythingVisible() const; void OnResize(const INT2& wnd_size); void DrawSpriteRectPart(TEX t, const RECT& rect, const RECT& part, DWORD color=WHITE); void DrawSpriteTransform(TEX t, const MATRIX& mat, DWORD color=WHITE); void DrawLine(const VEC2* lines, uint count, DWORD color=BLACK, bool strip=true); void LineBegin(); void LineEnd(); bool NeedCursor(); void DrawText3D(Font* font, StringOrCstring text, DWORD flags, DWORD color, const VEC3& pos, float hpp=-1.f); bool To2dPoint(const VEC3& pos, INT2& pt); //void DrawSpritePart(TEX t, const INT2& pos, const RECT& part, DWORD color=WHITE); //void DrawSprite(TEX t, const RECT& rect, const RECT* part, const RECT* clipping, DWORD color); //void DrawSpriteTransform(TEX t, MATRIX& mat, const RECT* part, DWORD color); static bool Intersect(vector<Hitbox>& hitboxes, const INT2& pt, int* index, int* index2=nullptr); void DrawSpriteTransformPart(TEX t, const MATRIX& mat, const RECT& part, DWORD color=WHITE); void CloseDialogs(); bool HavePauseDialog() const; Dialog* GetDialog(cstring name); void DrawSprite2(TEX t, const MATRIX* mat, const RECT* part, const RECT* clipping, DWORD color); MATRIX mIdentity, mViewProj; INT2 cursor_pos, wnd_size; Font* default_font, *fBig, *fSmall; TEX tCursor[3], tMinihp[2]; CursorMode cursor_mode; cstring txOk, txYes, txNo, txCancel; static TEX tBox, tBox2, tPix, tDown; Control* focused_ctrl; float mouse_wheel; vector<Dialog*> created_dialogs; private: void CreateVertexBuffer(); void DrawLine(Font* font, cstring text, size_t LineBegin, size_t LineEnd, const VEC4& def_color, VEC4& color, int x, int y, const RECT* clipping, HitboxContext* hc); void DrawLineOutline(Font* font, cstring text, size_t LineBegin, size_t LineEnd, const VEC4& def_color, VEC4& color, int x, int y, const RECT* clipping, HitboxContext* hc); int Clip(int x, int y, int w, int h, const RECT* clipping); void Lock(bool outline=false); void Flush(bool lock=false); void SkipLine(cstring text, size_t LineBegin, size_t LineEnd, HitboxContext* hc); bool CreateFontInternal(Font* font, ID3DXFont* dx_font, int tex_size, int outline, int max_outline); IDirect3DDevice9* device; ID3DXSprite* sprite; TEX tFontTarget; TEX tSet, tCurrent, tCurrent2; int max_tex_size; vector<Font*> fonts; ID3DXEffect* eGui; D3DXHANDLE techGui, techGui2; D3DXHANDLE hGuiSize, hGuiTex; Container* layer, *dialog_layer; VParticle* v, *v2; uint in_buffer, in_buffer2; VEC4 color_table[6]; VB vb, vb2; HitboxContext tmpHitboxContext; vector<OnCharHandler*> on_char; bool vb2_locked; float outline_alpha; }; //----------------------------------------------------------------------------- extern IGUI GUI;
true
8b8eb890e7e91fff7440bc9056d1d7c99b293cba
C++
GutoHere/Maratona-ICPC
/Project_Euler/0001.cpp
UTF-8
735
2.8125
3
[]
no_license
// ============================================================================ // // Filename: 0001.cpp // // Description: Project Euler 1 - Multiples of 3 and 5 // projecteuler.net/problem=1 // // Version: 1.0 // Created: 08/15/2012 08:02:51 PM // Revision: none // Compiler: g++ // // Author: Julio B. Silva (351202), julio(at)juliobs.com // Company: UFSCar // // ============================================================================ #include <iostream> using namespace std; int main() { int soma = 0; for (int n = 3; n < 1000; n++) { if (n % 3 == 0 || n % 5 == 0) soma += n; } cout << soma << endl; return 0; }
true
86b7ff2ee93cecb7205544b6baa07b4119d2a98c
C++
Rooster13/Star-Guardian-Ahri-Glittering-Tails-Lights
/SG_Ahri_Tails.ino
UTF-8
3,481
2.71875
3
[]
no_license
#include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif #define SINGLE_PIN 15 #define FULL_PIN 1 #define selectorPin 2 // Parameter 1 = number of pixels in strip // Parameter 2 = Arduino pin number (most are valid) // Parameter 3 = pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) // NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) Adafruit_NeoPixel strip = Adafruit_NeoPixel(53, FULL_PIN, NEO_GRB + NEO_KHZ800); // IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across // pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input // and minimize distance between Arduino and first pixel. Avoid connecting // on a live circuit...if you must, connect GND first. int sparkle1 = 0; int sparkle2 = 0; void setup() { // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket #if defined (__AVR_ATtiny85__) if (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif // End of trinket special code // pinMode(selectorPin, INPUT_PULLUP); // pinMode(14, OUTPUT); // digitalWrite(14, HIGH); strip.begin(); strip.show(); // Initialize all pixels to 'off' } void loop() { // Here I'm assigning the two sparkle locations a random number between zero and the number of pixels minus 1. // This is the same numbering system that the pixel array uses, so you will always have two LEDs lit up in white. sparkle1 = random(strip.numPixels() - 1); sparkle2 = random(strip.numPixels() - 1); // This is the loop that actually fills the pixel array with the information for what color to light each LED. // The first quarter of the strip should be pink, so the first if statement is checking that we are in the first // quarter of the strand. It assigns all of those LEDs the same color. // The 0.67 multiplier is a gain factor to bring the brightness down by a third to conserve battery. In testing, // this turned out to be a great compromise between brigthness and power-saving. Also, running the string at 100% // had a tendency to over-current the battery we were using upon start-up. The battery's smarts were tricked into // thinking that the huge onrush of current at start-up was a short between power and ground, and the battery // would shut down immediatly. // The else section is generating the soft gradient from the pink to an off-white color. Again, I've implemented // a multiplier of 0.67 for each RGB value for power saving and to prevent battery shutdown. // The last if section catches the random numbers generated for sparkle1 and sparkle2 and sets those LEDs to white // to create the glittering effect. for(int i=0; i< strip.numPixels(); i++) { if(i < strip.numPixels() / 4) strip.setPixelColor(i, 255*.67, 0*.67, 75*.67); else strip.setPixelColor(i, 255*.67, .67*((i - strip.numPixels() / 4) * 100 / (0.75 * strip.numPixels())), 75*.67); if(i == sparkle1 || i == sparkle2) strip.setPixelColor(i, 255, 255, 255); } strip.show(); delay(50); // This delay is just to make sure the sparkle flashes are lit up long enough to be seen. }
true
818f00ae9c67e433bf167e6871901816338bcbb3
C++
flytigerw/Computer
/DataStructure/Dictionary/skiplist.h
UTF-8
6,244
3.34375
3
[]
no_license
#pragma once #include "dictioary.h" #include "myExceptions.h" #include <sstream> #include <math.h> //在跳表中存储键值对 //节点以K来排序 template<class K,class V> struct SkipNode{ typedef std::pair<const K,V> KV; KV m_kv; //跳表节点的next具有层级属性 SkipNode** next; //数组 SkipNode(const KV& kv,int size):m_kv(kv){ next = new SkipNode*[size]; } ~SkipNode(){ delete []next; } }; template<class K,class V> class SkipList : public dictionary<K,V>{ public: typedef std::pair<const K,V> KV; typedef SkipNode<K,V> Node; protected: //头尾Node Node* head,*tail; //当前达到的最大层级 int cur_max_level =0; //跳表允许的最大层级 int max_level; //跳表运行的最大key K largest_key; //存储的键值对个数 int m_size =0; //插入与删除时,若节点位于第i层,则该节点0~i层的前驱指针都需要改变. //也可以插入和删除中将其定义为临时变量 ---> 但需要不停地申请和释放 ---> 故将其作为成员变量 Node** pres; //数组 //在规则的跳表中,上层与下层的节点个数比: p = 0.5 //当然,用户也可自行决定 int m_probablity; //私有辅助函数 protected: //通过随机数产生器来决定新节点的level int level() const; //遍历搜集前驱节点 Node* search(const K&) const; public: SkipList(K, int max_pairs = 10000, float prob = 0.5); ~SkipList(); //对外接口 public: bool empty() const override{return m_size == 0;} int size()const override{return m_size;} KV* find(const K& ) const override; void insert(const KV&) override; void erase(const K&) override; void output(std::ostream& out) const; }; template<class K,class V> SkipList<K,V>::SkipList(K key,int max_pairs,float p):largest_key(key),m_probablity(p){ //最大节点数为n,max_level = ceil(log(1/p)(n))- 1 max_level = (int)(ceil(logf((float)max_pairs)) / logf(1/p))-1; KV largest_kv; largest_kv.first = largest_key; //层级和size之间关系: size = level+1 head = new Node(largest_kv,max_level+1); tail = new Node(largest_kv,0); //初始时,head的每一层的next都指向tail for(int i=0;i<=max_level;i++) head->next[i] = tail; pres = new Node*[max_level+1]; } template<class K,class V> SkipList<K,V>::~SkipList(){ //类似单向链表的删除 Node* node; while(head != tail){ //先保存下一个节点,再删除当前节点 node = head->next[0]; delete node; head = node; } delete tail; delete []pres; } //找到该节点,并收集该节点在历来层级上的前驱 template<class K,class V> typename SkipList<K,V>::Node* SkipList<K,V>::search(const K& key) const{ //从最大层开始向下找 Node* node = head; for(int i=cur_max_level;i>=0;i--){ //node->next[i]:二分点 //若二分点的key较小,则向起点向右挪动 while(node->next[i].m_kv.first < key) node = node->next[i]; //若二分点的key较大,则起点不变,只降低层级即可 //记录前驱 pres[i] = node; } return node->next[0]; } template<class K,class V> typename SkipList<K,V>::KV* SkipList<K,V>::find(const K& key) const{ if(key >= largest_key) return nullptr; //类似search,但不需要保存前驱 Node* node = head; for(int i=cur_max_level;i>=0;i--) while(node->next[i].m_kv.first < key) node = node->next[i]; //若二分点的key较大,则起点不变,只降低层级即可 //若找到了就返回 if(node->next[0]->m_kv.fisr == key) return &node->next[0]->m_kv; return nullptr; } template<class K,class V> int SkipList<K,V>::level() const{ //生成随机数范围 0~RAND_MAX //若<= p*RADN_MAX,就++level int lev = 0; while(rand() <= m_probablity*RAND_MAX) ++lev; //不能超过最大层级 return (lev<=max_level) ? lev : max_level; } template<class K,class V> void SkipList<K,V>::insert(const KV& kv) { if(kv.first >= largest_key){ std::ostringstream s; s << "Key = " << kv.first << " Must be <" << largest_key; throw illegalParameterValue(s.str()); } //先查找其是否存在,以及前驱节点 Node* node = search(kv.first); if(node->m_kv.first == kv.first){ //存在,就只更新V node->m_kv.second = kv.second; return; } //没找到,就新建节点 int new_level = level(); //下调 if(new_level > cur_max_level){ new_level = ++cur_max_level; pres[new_level] = head; //可要,可不要 } //创建新节点 Node* new_node = new Node(kv,new_node+1); //改变下层链表的前驱节点指针 for(int i=0;i<=new_level;i++){ //插入到中间 new_node->next[i] = pres->next[i]; pres->next[i] = new_node; } ++m_size; return; } template<class K,class V> void SkipList<K,V>::erase(const K& key) { if(key >= largest_key){ std::ostringstream s; s << "Key = " << key << " Must be <" << largest_key; throw illegalParameterValue(s.str()); } //先查找该节点 Node* node = search(key); //考察是否找到 if(node->m_kv.first != key) return; //自底向上的删除 //SkipNode没有指明自己的level有多高 for(int i=0;i<=cur_max_level && pres[i]->next == node;i++){ //和普通链表的操作是一样的 pres->next[i] = node->next[i]; } //删除节点可能导致最高层已经没有节点,head指向tail //此时需要降级 while(cur_max_level > 0 && head[cur_max_level] == tail) --cur_max_level; delete node; --m_size; } template<class K, class V> void SkipList<K,V>::output(ostream& out) const{ // Insert the dictionary pairs into the stream out. // follow level 0 chain for (Node* currentNode = head->next[0]; currentNode != tail; currentNode = currentNode->next[0]) out << currentNode->element.first << " " << currentNode->element.second << " "; } // overload << template <class K, class E> ostream& operator<<(ostream& out, const SkipList<K,E>& x){ x.output(out); return out; }
true
b0c48fd72faf19753c06cffa4ccf563c97abe7a5
C++
sandywang/oobicpl
/src/mniBaseVolume.h
UTF-8
4,795
2.6875
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
#ifndef __MNIBASEVOLUME__ #define __MNIBASEVOLUME__ extern "C" { #include "bicpl.h" #include "volume_io.h" } #include <iostream> using namespace std; // static value used as default for volume loading static STRING ZXYdimOrder[] = {(char *) MIzspace, (char *) MIxspace, (char *) MIyspace}; static STRING ZYXdimOrder[] = {(char *) MIzspace, (char *) MIyspace, (char *) MIxspace}; static STRING XYZdimOrder[] = {(char *) MIxspace, (char *) MIyspace, (char *) MIzspace}; static STRING XZYdimOrder[] = {(char *) MIxspace, (char *) MIzspace, (char *) MIyspace}; static STRING YXZdimOrder[] = {(char *) MIyspace, (char *) MIxspace, (char *) MIzspace}; static STRING YZXdimOrder[] = {(char *) MIyspace, (char *) MIzspace, (char *) MIxspace}; //! An abstract baseclass for a minc volume /*! This is an abstract class, meaning that no members of this type can ever be created. One of the derived classes, mniVolume or mniLabelVolume has to be used instead. \todo Incorporate the voxel to world transformation info */ class mniBaseVolume { protected: //! Holds the volume_io volume Volume volume; //! Holds the sizes - has to be instantiated before use int *sizes; //! Holds the number of dimensions int nDimensions; //! Holds the dimension order STRING* dimNames; //! Holds the original filename - not yet used STRING filename; //! Holds the minc data type nc_type dataType; //! Holds the minimum voxel value Real voxelMin; //! Holds the maximum voxel value Real voxelMax; //! Whether the data type is signed or not BOOLEAN signedFlag; public: //! Load exception class class loadException { }; //! Write exception class class writeException { }; //! Set the filename void setFilename(STRING file) { filename = file; }; //! Return pointer to volume_io volume Volume getVolume() { return this->volume; }; //! Get pointer to volume sizes int* getSizes() { return this->sizes; }; //! Get one size from sizes array int getSize(int index) { return this->sizes[index]; }; //! Get dimensions names STRING *getDimNames() { return this->dimNames; }; //! Return volume min Real getVoxelMin() { return this->voxelMin; }; //! Retrun volume max Real getVoxelMax() { return this->voxelMax; }; //! Set the volume real range void setRealRange(Real lower, Real upper) { set_volume_real_range( this->volume, lower, upper); } //! Return signed flag BOOLEAN getSignedFlag() { return this->signedFlag; }; //! Return data type nc_type getDataType() { return this->dataType; }; // voxel to world coordinate stuff: //!converts a voxel to world space /*! Returns a voxel to from voxel space to world space \param voxel[] An array holding the voxel to be converted \return An array holding the world coordinates in X Y Z order \note You have to free the memory of the returned array yourself */ Real* convertVoxelToWorld(Real voxel[]); //! Convert a world coordinate into a voxel /*! \return An array holding the voxel coordinates */ Real* convertWorldToVoxel(Real xWorld, Real yWorld, Real zWorld); //! Gets interpolated value at indices /*! \bug Use with caution - the returned Real argument ought to be an array, since in some situations the underlying volume_io function is supposed to return more than one value. But I don't quite (yet) understand when and how this is supposed to happen. */ Real getInterpolatedVoxel(Real indices[], int degreesContinuity=2, BOOLEAN interpolatingDimensions[]=NULL, int useLinearAtEdge=TRUE, Real outsideValue=0, Real **firstDerivative=NULL, Real ***secondDerivative=NULL) { Real tmpReturnValue; evaluate_volume(this->volume, indices, interpolatingDimensions, degreesContinuity, useLinearAtEdge, outsideValue, &tmpReturnValue, firstDerivative, secondDerivative); return tmpReturnValue; }; //! Overloaded version of getInterpolatedVoxel Real getInterpolatedVoxel(Real v1, Real v2, Real v3, int degreesContinuity=2, BOOLEAN interpolatingDimensions[]=NULL, int useLinearAtEdge=TRUE, Real outsideValue=0, Real **firstDerivative=NULL, Real ***secondDerivative=NULL) { Real tmpReturnValue; Real indices[3] = {v1, v2, v3}; evaluate_volume(this->volume, indices, interpolatingDimensions, degreesContinuity, useLinearAtEdge, outsideValue, &tmpReturnValue, firstDerivative, secondDerivative); return tmpReturnValue; }; //! Output the volume virtual void output(STRING file, int cropValue = 0) = 0; }; #endif
true
8a1a06fbc86c1ffd6195fd4fe0f3c9cdfaf639bd
C++
venkatesh7199/LongAssignment
/BinaryTree.cpp
UTF-8
4,311
3.140625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define ll long long #define REP(i,a,b) for(ll i=a;i<b;i++) #define MP make_pair #define PB push_back #define N 100001 #define HOLE 1000000007 ll power(ll x,ll y) { ll res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x)%HOLE; // n must be even now y = y >> 1; // y = y/2 x = (x * x)%HOLE; // Change x to x^2 } return res; } struct Node { ll keys; Node* leftChild; Node* rightChild; Node* Parent; }; struct Node* CreateNode (){ struct Node * newNode =(struct Node*)malloc(sizeof(struct Node)); return newNode; } void SwapNodes (struct Node* root, struct Node* temp){ struct Node* temp2; temp2 = temp->rightChild; temp->rightChild = root->rightChild; if(temp->rightChild != NULL ) temp->rightChild->Parent = temp; root->rightChild = temp2; if(temp2 != NULL ) temp2->Parent = root; temp2 = temp->leftChild; temp->leftChild = root->leftChild; if(temp->leftChild != NULL )temp->leftChild->Parent = temp; root->leftChild = temp2; if(temp2 != NULL )temp2->Parent = root; temp2 = temp->Parent; temp->Parent = root->Parent; if(temp->Parent != NULL ){ if(temp->Parent->rightChild == root){ temp->Parent->rightChild = temp; } else { temp->Parent->leftChild = temp; } } root->Parent = temp2; if(temp2 != NULL ){ if(temp2->rightChild == temp){ temp2->rightChild = root; } else { temp2->leftChild = root; } } return; } struct Node* InsertNode (struct Node* root, ll x, bool LRFlag){ struct Node* temp = CreateNode(); temp->keys=x; if(LRFlag){ if(root != NULL )temp->rightChild = root->rightChild; temp->Parent = root; if(root != NULL && root->rightChild !=NULL )root->rightChild->Parent = temp; if(root != NULL )root->rightChild = temp; temp->leftChild = NULL; if(root == NULL ) temp->rightChild = NULL; } else { if(root != NULL )temp->leftChild = root->leftChild; temp->Parent = root; if(root != NULL && root->leftChild !=NULL )root->leftChild->Parent = temp; if(root != NULL )root->leftChild = temp; temp->rightChild = NULL; if(root == NULL ) temp->leftChild = NULL; } return temp; } struct Node* DeleteNode (struct Node* root ){ if (root->rightChild == NULL){ if(root->leftChild != NULL )root->leftChild->Parent = root->Parent; if(root->Parent != NULL ){ if (root->Parent->rightChild == root){ root->Parent->rightChild = root->leftChild; } else{ root->Parent->leftChild = root->leftChild; } } free(root); return root->leftChild; } else if (root-> leftChild == NULL){ if(root->rightChild != NULL )root->rightChild->Parent = root->Parent; if(root->Parent != NULL ){ if (root->Parent->rightChild == root){ root->Parent->rightChild = root->rightChild; } else{ root->Parent->leftChild = root->rightChild; } } free(root); return root->rightChild; } else { struct Node* temp = root->rightChild; struct Node* temp2; while (temp->leftChild!=NULL){ temp=temp->leftChild; } SwapNodes(root,temp); DeleteNode (root); return temp; } } void InorderTraversal (struct Node* root){ if(root == NULL)return; if( root->leftChild != NULL ) InorderTraversal (root->leftChild); cout<< (root->keys) <<endl; if( root->rightChild != NULL ) InorderTraversal (root->rightChild); return; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); struct Node* root = NULL; root= InsertNode(root,15,true); InsertNode(root,25,false); InsertNode(root,35,true); InsertNode(root,45,true); InorderTraversal(root); return 0; }
true
ae6a9be1ea67f3f39d8581dcd79cc00209d24e18
C++
natezzz/leeeet
/c++/guess-number-higher-or-lower/guess-number-higher-or-lower.cpp
UTF-8
566
3.796875
4
[]
no_license
// Forward declaration of guess API. // @param num, your guess // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); class Solution { public: int guessNumber(int n) { int low = 1; int high = n; while (true) { int m = low + (high - low)/2; int res = guess(m); if (res == 1) { low = m + 1; } else if (res == -1) { high = m - 1; } else { return m ; } } } };
true
9259c1f471102e0db954912a4a7019c195a7e8bb
C++
stavalfi/stavalfi_cpp_ex2
/include/ConfigurationReader.h
UTF-8
1,270
2.671875
3
[]
no_license
#ifndef STAVALFI_CPP_EX2_CONFIGURATION_READER_H #define STAVALFI_CPP_EX2_CONFIGURATION_READER_H #include "Player.h" #include <string.h> class ConfigurationReader { const std::string fileGameConfigurationLocation; const std::string fileSoldierDirectionsLocation; protected: const std::string &getFileGameConfigurationLocation() const; const std::string &getFileSoldierDirectionsLocation() const; public: struct MapSize { const signed int mapWidth, mapHigh; MapSize(int mapWidth, int mapLength); const int getMapWidth() const; const int getMapHigh() const; }; ConfigurationReader(const std::string &fileGameConfigurationLocation, const std::string &fileSoldierDirectionsLocation); virtual MapSize getMapSize() const = 0; virtual std::list<std::shared_ptr<Player>> getPlayers(const std::shared_ptr<const MapReader> &map) const = 0; virtual std::list<std::shared_ptr<Armor>> getArmorsInMap() const = 0; virtual std::list<std::shared_ptr<Weapon>> getWeaponsInMap() const = 0; virtual std::list<std::shared_ptr<const SolidItem>> getSolidItemsInMap() const = 0; virtual ~ConfigurationReader() = 0; }; #endif //STAVALFI_CPP_EX2_CONFIGURATION_READER_H
true
f7a9ff7b429357e8c161a6e3fd6fb0512ad0ed26
C++
yuancheng314/PAT
/Advanced/1008.cpp
UTF-8
301
2.5625
3
[]
no_license
#include<iostream> using namespace std; const int stop=5,up=6,down=4; int main() { int N,sum=0,from=0,to; cin>>N; sum+=N*stop; for(int i=0;i<N;i++) { scanf("%d",&to); sum+= to-from>0 ? (to-from)*up : (to-from)*down*-1; from=to; } cout<<sum; return 0; }
true
fd9dcffb0edac6f956bcc709bfdcbdb22247bdd2
C++
shunpeizhang/Graph-Store
/Graph Store/Graph Store/Hash/Hash Function/HashFunctionStringSpecialization.h
UTF-8
770
2.859375
3
[]
no_license
/* This class specialization implements the FNV hash algorithm: http://www.isthe.com/chongo/tech/comp/fnv/#top */ #ifndef __HASH_FUNCTION_STRING_SPECIALIZATION_HEADER_INCLUDED__ #define __HASH_FUNCTION_STRING_SPECIALIZATION_HEADER_INCLUDED__ #include "HashFunction.h" #include "../../String/String.h" template <> class HashFunction<String> { static const unsigned FNV_OFFSET_BASIS = 2166136261; static const unsigned FNV_PRIME = 16777619; public: unsigned operator()(const String& key) const { const char* string = key.cString(); unsigned hashValue = FNV_OFFSET_BASIS; while (*string) { hashValue *= FNV_PRIME; hashValue ^= *string; ++string; } return hashValue; } }; #endif //__HASH_FUNCTION_STRING_SPECIALIZATION_HEADER_INCLUDED__
true
97f6641f20c336c29c82e0db08d6af5e0af252f6
C++
CodeeChallenge/GetIntoRocket
/s.cpp
UTF-8
385
3.09375
3
[]
no_license
//divide the array into 2 equal half such that absolute diff is minimum. #include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { float f[5] = {1.0,1.2,1.3,1.4,1.5}; float* f1 = &f[0]; float* f2 = f1 + 3; cout<<f2 - f1; /*vector<int> v1; int n,item; cin>>n; while(n--){ cin>>item; v1.push_back(item); } cout<<findEqualHalf(v1) */return 0; }
true
671c0dc93a5b4dc90120d45d66e93ab353b0b377
C++
nathansmith11170/Delver
/MazeGenerate.cpp
UTF-8
3,454
2.953125
3
[]
no_license
/* Author: Nathan Smith Here is code taken from the Mazes with SFML project. A recurisve backtracker that relies upon the MatrixGraph type, and a maze-generate function that simply calls teh backtracker repeatedly until the maze is complete. */ #include "MatrixGraph.h" #include "prototypes.h" #include <stack> #include <algorithm> #include <ctime> #include <cstdlib> static int recursiveBacktracker(MatrixGraph grid, MatrixGraph *maze, \ std::stack<int> *stack, std::unordered_set<int> *visitedSet, \ int currentVertex) { int i, j, isVisited = 0, randomIndex, nextVertex; std::vector<int> unvisitedNeighbors; std::vector<int> neighbors; int isvisited; //From the neighbors of the current node, determine which are unvisited neighbors = grid.get_neighbors(currentVertex); for (i = 0; i < neighbors.size(); i++) { if (!(*visitedSet).count(neighbors.at(i))) { unvisitedNeighbors.push_back(neighbors.at(i)); } } if (!unvisitedNeighbors.empty()) { //Get a random neighbor std::random_shuffle(unvisitedNeighbors.begin(), unvisitedNeighbors.end()); nextVertex = unvisitedNeighbors.back(); //Push current node onto the stack (*stack).push(currentVertex); //Add the appropriate edge to the maze (*maze).add_edge(currentVertex, nextVertex); (*visitedSet).insert(nextVertex); } else if (!(*stack).empty()) { //If there were no unvisited neighbors, go to the next vertex in the frontier nextVertex = (*stack).top(); (*stack).pop(); } return nextVertex; } MatrixGraph mazeGenerate(int NODES) { srand(time(NULL)); //Define two graphs MatrixGraph maze, grid; //The size of the maze int i, row, column; //Data for maze generation std::stack<int> frontier; std::unordered_set<int> visited; int currentVertex = 0; //Add the vertices to the graph for (i = 0; i < NODES * NODES; i++) { maze.add_vertice(i); grid.add_vertice(i); } //Populate the grid with the proper edges row = 0; column = 0; for (i = 0; i < NODES * NODES; i++) { if (i + 1 <= (row + 1) * NODES - 1) { grid.add_edge(i, i + 1); } if (i - 1 >= row * NODES) { grid.add_edge(i, i - 1); } if (i + NODES <= NODES * NODES - 1) { grid.add_edge(i, i + NODES); } if (i - NODES >= 0) { grid.add_edge(i, i - NODES); } column++; if (column >= NODES) { column = 0; row++; } } //Generate a maze frontier.push(currentVertex); while (!frontier.empty()) { currentVertex = recursiveBacktracker(grid, &maze, &frontier, &visited, currentVertex); } //Clear the unused grid grid.clear(); return maze; } std::vector<SDL_Rect> generateRects( MatrixGraph maze, int SCREEN_WIDTH, int SCREEN_HEIGHT, int STROKE ) { //Set up vertices int row = 0, column = 0, i, j; long columns = (long)sqrtl(maze.size()); std::vector<SDL_Rect> rects; for (i = 0; i < maze.size(); i++) { SDL_Rect temp = { STROKE + column * ((SCREEN_WIDTH - 240) / columns), STROKE + row * (SCREEN_HEIGHT / columns), (SCREEN_WIDTH - 240) / columns - 2 * STROKE, SCREEN_HEIGHT / columns - 2 * STROKE }; rects.push_back(temp); column++; if (column >= sqrt(maze.size())) { column = 0; row++; } } //Set up edges for (i = 0; i < maze.size(); i++) { std::vector<int> temp = maze.get_neighbors(i); for (j = 0; j < temp.size(); j++) { if (temp.at(j) == i + 1) { rects.at(i).w += 2 * STROKE; } else if (temp.at(j) == i + columns) { rects.at(i).h += 2 * STROKE; } } } return rects; }
true
2856b4275081de68368900f30cce1db5b1360d5d
C++
K20shores/OSProject
/kernel/arch/i386/utils.cpp
UTF-8
823
2.75
3
[]
no_license
#include <kernel/utils.h> /* http://www.osdever.net/bkerndev/Docs/creatingmain.htm */ /* We will use this later on for reading from the I/O ports to get data * from devices such as the keyboard. We are using what is called * 'inline assembly' in these routines to actually do the work */ unsigned char inportb (unsigned short _port) { unsigned char rv; __asm__ __volatile__ ("inb %1, %0" : "=a" (rv) : "dN" (_port)); return rv; } /* We will use this to write to I/O ports to send bytes to devices. This * will be used in the next tutorial for changing the textmode cursor * position. Again, we use some inline assembly for the stuff that simply * cannot be done in C */ void outportb (unsigned short _port, unsigned char _data) { __asm__ __volatile__ ("outb %1, %0" : : "dN" (_port), "a" (_data)); }
true