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
c476b40c7a4cbe78a52b8b9d76ae932821fa67c0
C++
robotsupc/balance
/arduino/src/MPU6050.cpp
UTF-8
1,199
2.71875
3
[]
no_license
#include <MPU6050.h> #include <Wire.h> MPU6050::MPU6050() { } void MPU6050::begin(int sda, int scl) { this->sda = sda; this->scl = scl; this->addr = 0x68; Wire.begin(sda, scl); // sda, scl Wire.beginTransmission(this->addr); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); } void MPU6050::loop() { Wire.beginTransmission(this->addr); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(this->addr,14,true); // request a total of 14 registers acc[0]=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) acc[1]=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) acc[2]=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) int temperature =Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L) gyro[0]=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) gyro[1]=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) gyro[2]=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) }
true
21f5efcc9c33dedb03f1a426377beac4541dc416
C++
401040579/cpts122-Data-Structures
/RanTaoPA6_122/RanTaoPA6_122/RanTaoPA6_122/BSTNode.h
UTF-8
6,264
3.28125
3
[]
no_license
/******************************************************************************************* * Programmer: Ran Tao * Class: CptS 122, Spring 2016 * Programming Assignment: PA 6 * Created: March 19, 2016 * Last Revised: March 23, 2016 * Description: a Binary Search Tree (BST) data structure is a nonlinear data structure. A BST is traversed by starting at the root pointer. The root node is the first node inserted into the tree. Nodes are inserted into the tree such that all items to the left of the root node are less than, and all items to the right of the root are greater than its item. Also, this property holds true for any particular node in the tree. *******************************************************************************************/ #ifndef BSTNode_H #define BSTNode_H #include <iostream> #include <string> // allows for us to use string operations #include <fstream> using std::cin; using std::cout; using std::endl; using std::string; using std::ofstream; using std::ifstream; using std::fstream; using std::ios; template <class C, class S> class Node { public: Node(); Node(C newText = NULL, S newMorse = ""); ~Node(); // we will implement a copy constructor and destructor later... //int getData() const; // can't call non const functions C getText() const; S getMorse() const; Node<C, S> *& getLeft(); Node<C, S> *& getRight(); // setData ("literal string"); //void setData(const int newData); // setData (string newData); void setText(const C newText); void setMorse(const S newMorse); void setLeft(Node<C, S> * const newLeft); void setRight(Node<C, S> * const newRight); private: //int mData; C mText; S mMorse; Node<C, S> *mpLeft; Node<C, S> *mpRight; }; /************************************************************* * Function: Node() * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: Constructor * Return: NONE *************************************************************/ template<class C, class S> Node<C, S>::Node() { } /************************************************************* * Function: Node(C newText, S newMorse) * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: copy Constructor * Return: NONE *************************************************************/ template <class C, class S> Node<C, S>::Node(C newText, S newMorse) { mText = newText; mMorse = newMorse; // will be on heap mpLeft = nullptr; mpRight = nullptr; } /************************************************************* * Function: ~Node() * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: Destructor * Return: NONE *************************************************************/ template <class C, class S> Node<C, S>::~Node() { //cout << "Inside Node's destructor!" << endl; //cout << "Deleting node with data: " << mText << endl; } //int Node::getData() const // can't call non const functions //{ // return mData; //} /************************************************************* * Function: getText() * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: get text * Return: template class C *************************************************************/ template <class C, class S> C Node<C, S>::getText() const { return mText; } /************************************************************* * Function: getMorse() * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: get morse code * Return: template class S *************************************************************/ template <class C, class S> S Node<C, S>::getMorse() const { return mMorse; } /************************************************************* * Function: getLeft() * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: get left pointer * Return: Node<C, S> *& *************************************************************/ template <class C, class S> Node<C, S> *& Node<C, S>::getLeft() { return mpLeft; } /************************************************************* * Function: getRight() * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: get right pointer * Return: Node<C, S> *& *************************************************************/ template <class C, class S> Node<C, S> *& Node<C, S>::getRight() { return mpRight; } // setData ("literal string"); //void Node::setData(const int newData) // setData (string newData); //{ // mData = newData; //} /************************************************************* * Function: setText(const C newText) * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: set text * Return: NONE *************************************************************/ template <class C, class S> void Node<C, S>::setText(const C newText) { mText = newText; } /************************************************************* * Function: setMorse(const S newMorse) * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: set morse * Return: NONE *************************************************************/ template <class C, class S> void Node<C, S>::setMorse(const S newMorse) { mMorse = newMorse; } /************************************************************* * Function: setLeft(Node<C, S> * const newLeft) * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: set left pointer * Return: NONE *************************************************************/ template <class C, class S> void Node<C, S>::setLeft(Node<C, S> * const newLeft) { mpLeft = newLeft; } /************************************************************* * Function: setRight(Node<C, S> * const newRight) * Date Created: March 19, 2016 * Date Last Modified: March 23, 2016 * Description: set right pointer * Return: NONE *************************************************************/ template <class C, class S> void Node<C, S>::setRight(Node<C, S> * const newRight) { mpRight = newRight; } #endif // !BSTNode_H
true
f919c681c59839d74c1d17c4a3fdaf54ee8ebb2a
C++
Do-ho/Linear-Algebra
/HW06/HW06/KDH_function.h
UHC
3,851
3.171875
3
[]
no_license
#pragma once #include <iostream> #include <cstdio> #include <cmath> #include <array> using namespace std; void print_matrix(array<array<float, 4>, 4> matrix, int row, int col); void rref07(array<array<float, 4>, 4>* matrix, int row, int col); void rref16(array<array<float, 4>, 4>* matrix, int row, int col); void swap(array<array<float, 4>, 4>* matrix, int i, int j); void add(array<array<float, 4>, 4>* matrix, int i, int j, float m); void multiple(array<array<float, 4>, 4>* matrix, int i, float j); void subtract(array<array<float, 4>, 6>* matrix, int i, int j, float m); void matrix_add(const array<array<int, 2>, 2> a, const array<array<int, 2>, 2> b); void print_matrix(array<array<float, 5>, 9> matrix, int row, int col); void matrix_add(const array<array<int, 2>, 2> a, const array<array<int, 2>, 2> b) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("%d ", a[i][j] + b[i][j]); } printf("\n"); } } void print_matrix(array<array<float, 4>, 6> matrix, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << matrix[i][j] << " "; } cout << endl; } } void print_matrix(array<array<float, 5>, 9> matrix, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << matrix[i][j] << " "; } cout << endl; } } void swap(array<array<float, 4>, 6>* matrix, int i, int j) { for (int w = 0; w < 4; w++) { float temp; temp = (*matrix)[i][w]; (*matrix)[i][w] = (*matrix)[j][w]; (*matrix)[j][w] = temp; } } void swap(array<array<float, 5>, 9>* matrix, int i, int j) { for (int w = 0; w < 5; w++) { float temp; temp = (*matrix)[i][w]; (*matrix)[i][w] = (*matrix)[j][w]; (*matrix)[j][w] = temp; } } void add(array<array<float, 4>, 6>* matrix, int i, int j, float m) { for (int w = 0; w < 4; w++) { (*matrix)[i][w] += (*matrix)[j][w] * m; } } void add(array<array<float, 5>, 9>* matrix, int i, int j, float m) { for (int w = 0; w < 5; w++) { (*matrix)[i][w] += (*matrix)[j][w] * m; } } void subtract(array<array<float, 4>, 6>* matrix, int i, int j, float m) { for (int w = 0; w < 4; w++) { (*matrix)[i][w] -= (*matrix)[j][w] * m; } } void subtract(array<array<float, 5>, 9>* matrix, int i, int j, float m) { for (int w = 0; w < 5; w++) { (*matrix)[i][w] -= (*matrix)[j][w] * m; } } void multiple(array<array<float, 4>, 6>* matrix, int i, float j) { for (int w = 0; w < 4; w++) { (*matrix)[i][w] *= j; } } void multiple(array<array<float, 5>, 9>* matrix, int i, float j) { for (int w = 0; w < 5; w++) { (*matrix)[i][w] *= j; } } void rref07(array<array<float, 4>, 6>* matrix, int row, int col) { add(matrix, 2, 0, 1.0f); subtract(matrix, 4, 0, 1.0f); subtract(matrix, 4, 1, 1.0f); multiple(matrix, 1, 0.5f); add(matrix, 0, 1, 1.0f); add(matrix, 2, 1, 1.0f); multiple(matrix, 2, 0.4f); subtract(matrix, 0, 2, 1.5f); subtract(matrix, 1, 2, 0.5f); add(matrix, 4, 2, 2.0f); swap(matrix, 3, 4); add(matrix, 2, 3, -3.0f); (*matrix)[2][3] = 0; // multiple(matrix, 3, 5.0f / 3.0f); (*matrix)[3][3] = 1; // subtract(matrix, 0, 3, 0.8f); (*matrix)[0][3] = 0; // add(matrix, 1, 3, 0.4f); (*matrix)[1][3] = 0; // } void rref16(array<array<float, 5>, 9>* matrix, int row, int col) { add(matrix, 1, 0, 1.0f); add(matrix, 4, 0, -2.0f); add(matrix, 7, 0, -2.0f); add(matrix, 8, 0, -6.0f); add(matrix, 8, 1, 1.0f); multiple(matrix, 1, 1.0f / 3.0f); add(matrix, 0, 1, -2.0f); add(matrix, 4, 1, 1.0f); swap(matrix, 2, 7); add(matrix, 0, 2, 1.0f); add(matrix, 1, 2, -1.0f); add(matrix, 8, 2, -2.0f); swap(matrix, 3, 4); add(matrix, 0, 3, -1.0f); add(matrix, 1, 3, 2.0f); add(matrix, 2, 3, -2.0f); add(matrix, 8, 3, 2.0f); }
true
468274cf49fc365bf4dabfe46af376c538937523
C++
amankumartiwari/Leetcode-Challenges
/jewels and stones.cpp
UTF-8
314
2.59375
3
[]
no_license
class Solution { public: int numJewelsInStones(string J, string S) { map<char,int>mp; for(char c:S){ mp[c]++; } int ans=0; for(char c:J){ if(mp.count(c)==1){ ans+=mp[c]; } } return ans; } };
true
9dabbebddbea28c5dde467efba19fb4627d4a5c0
C++
pencilCool/design-partten-c-
/template1.cpp
UTF-8
1,214
3.140625
3
[]
no_license
// // main.cpp // template1 // // Created by Tang yuhua on 16/6/17. // Copyright © 2016年 Tang yuhua. All rights reserved. // #include <iostream> #include <string> using namespace std; class TestPaper{ public: void question1(){ cout<<"1+1"<<answer1()<<endl; } void question2(){ cout<<"1*1"<<answer2()<<endl; } virtual string answer1(){ return ""; } virtual string answer2(){ return ""; } virtual ~TestPaper(){ cout<<" testpaper delete"<<endl; } }; class TestPaperA:public TestPaper{ public: string answer1(){ return "2"; } string answer2(){ return "1"; } }; class TestPaperB:public TestPaper{ public: string answer1(){ return "3"; } string answer2(){ return "4"; } }; int main(int argc, const char * argv[]) { cout<<"A test paper"<<endl; TestPaper *s1 = new TestPaperA(); s1->question1(); s1->question2(); delete s1; cout<<endl; cout<<"B test paper"<<endl; TestPaper *s2 = new TestPaperB(); s2->question1(); s2->question2(); delete s2; return 0; }
true
5aa75478b95340debdf273e60abaf56e51d04561
C++
BravoXavi/Swashbuckler
/Swashbuckler/creature.cpp
UTF-8
305
2.703125
3
[ "MIT" ]
permissive
#include <iostream> #include "creature.h" Creature::Creature(const char* creatureName, const char* creatureDescription, Room* loc) : Entity(creatureName, creatureDescription) { name = creatureName; description = creatureDescription; entityType = creature; location = loc; } Creature::~Creature() {}
true
a07910fe1330fdcd50d7641b5a793318d9d944cf
C++
oscarpfernandez/SubtitleBroadcast
/Str2Creator/src/projectsetupconfig.cpp
UTF-8
10,702
2.71875
3
[]
no_license
#include "projectsetupconfig.h" #include "mainwindow.h" /****************************************************************************** * Description: the purpose of this class is to create a project setup confi- * ration GUI, the allows the user to setup primary project conditions: * - base path, supported languages, project name, description, etc. ******************************************************************************/ ProjectSetUpConfig::ProjectSetUpConfig(QWidget *parent) : QDialog(parent) { setWindowTitle("Project Configuration"); setModal(true); setMinimumSize(400,250); setMaximumSize(600,500); progressLabel = new QLabel(); progressLabel->setAlignment(Qt::AlignCenter); progressDialog = new QProgressDialog(this); progressDialog->setLabel(progressLabel); progressDialog->setModal(true); progressDialog->setAutoReset(false); progressDialog->setAutoClose(false); progressDialog->setCancelButton(0); progressDialog->setFixedSize(350,100); createGuiElements(); setWindowOpacity(0.85); } /****************************************************************************** * Creates projects GUI layout elements. ******************************************************************************/ void ProjectSetUpConfig::createGuiElements() { mainProjectConfigVLayout = new QVBoxLayout; projectPathConfigLineHLayout = new QHBoxLayout; languagesConfigVLayout = new QVBoxLayout; //Project Name projectName = new QLabel(tr("Project Name:")); projectNameLine = new QLineEdit(this); projectNameHBoxLayout = new QHBoxLayout; projectNameHBoxLayout->addWidget(projectName); projectNameHBoxLayout->addWidget(projectNameLine); //Project Description Text projectDescriptionVBoxLayout = new QVBoxLayout; projectBasicPropertiesVLayout = new QVBoxLayout; projectDescription = new QLabel("Description:"); projectDescriptionText = new QTextEdit; projectDescriptionText->setMinimumHeight(50); projectDescriptionVBoxLayout->addWidget(projectDescription); projectDescriptionVBoxLayout->addWidget(projectDescriptionText); projectBasicPropertiesVLayout->addLayout(projectNameHBoxLayout); projectBasicPropertiesVLayout->addSpacing(10); projectBasicPropertiesVLayout->addLayout(projectDescriptionVBoxLayout); projectBasicPropertiesGroupBox = new QGroupBox(tr("Basic Properties")); projectBasicPropertiesGroupBox->setLayout(projectBasicPropertiesVLayout); //Project's Path Configuration projectPathGroupBox = new QGroupBox(tr("Path Configuration")); projectPathLabel = new QLabel(tr("Path:")); projectPathLine = new QLineEdit; projectPathLine->setReadOnly(true); projectPathButton = new QPushButton(tr("Choose")); projectPathConfigLineHLayout->addWidget(projectPathLabel); projectPathConfigLineHLayout->addWidget(projectPathLine); projectPathConfigLineHLayout->addWidget(projectPathButton); projectPathGroupBox->setLayout(projectPathConfigLineHLayout); //Languages configuration languagesGroupBox = new QGroupBox(tr("Supported Languages")); languagesLayout = new QGridLayout(); languagesLayout->addWidget( rightButton = new QPushButton( ">>" ), 1, 1 ); languagesLayout->addWidget( leftButton = new QPushButton( "<<" ), 0, 1 ); languagesLayout->addWidget( leftLanguageList = new QListWidget, 0, 0, 3, 1 ); languagesLayout->addWidget( rightLanguageList = new QListWidget, 0, 2, 3, 1 ); languagesGroupBox->setLayout(languagesLayout); buttonsHLayout = new QHBoxLayout; okButton = new QPushButton(tr("Ok"),this); okButton->setMaximumWidth(okButton->sizeHint().width()); cancelButton = new QPushButton(tr("Cancel"),this); cancelButton->setMaximumWidth(cancelButton->sizeHint().width()); cancelButton->setFocus(); buttonsHLayout->addWidget(cancelButton); buttonsHLayout->addWidget(okButton); buttonsHLayout->setAlignment(Qt::AlignRight); connect( okButton, SIGNAL(clicked()), this, SLOT(okActionSaveConfigurations())); connect( cancelButton, SIGNAL(clicked()), this, SLOT(close())); connect( leftButton, SIGNAL(clicked()), this, SLOT(moveLanguageLeft()) ); connect( rightButton, SIGNAL(clicked()), this, SLOT(moveLanguageRight()) ); connect( projectPathButton, SIGNAL(clicked()),this, SLOT(setUpProjectBaseDir())); languageItems << SPANISH << ITALIAN << ENGLISH << CATALAN; leftLanguageList->addItems(languageItems); leftLanguageList->sortItems(Qt::AscendingOrder); mainProjectConfigVLayout->addWidget(projectBasicPropertiesGroupBox); mainProjectConfigVLayout->addSpacing(10); mainProjectConfigVLayout->addWidget(projectPathGroupBox); mainProjectConfigVLayout->addSpacing(10); mainProjectConfigVLayout->addWidget(languagesGroupBox); mainProjectConfigVLayout->addLayout(buttonsHLayout); setLayout(mainProjectConfigVLayout); } /****************************************************************************** * <Slot>: deselects the language from the project by moving it to the left * list. ******************************************************************************/ void ProjectSetUpConfig::moveLanguageLeft(){ if( rightLanguageList->selectedItems().count() == 0 ){ return; } QListWidgetItem *item = rightLanguageList->takeItem( rightLanguageList->currentRow() ); leftLanguageList->addItem( item ); leftLanguageList->sortItems(Qt::AscendingOrder); supportedLangs.sort(); supportedLangs.removeAt(rightLanguageList->currentRow()); } /****************************************************************************** * <Slot>: selects the language to the project by moving it to the right * list. ******************************************************************************/ void ProjectSetUpConfig::moveLanguageRight(){ if( leftLanguageList->selectedItems().count() == 0 ){ return; } QListWidgetItem *item = leftLanguageList->takeItem( leftLanguageList->currentRow() ); rightLanguageList->addItem( item ); rightLanguageList->sortItems(Qt::AscendingOrder); supportedLangs << item->text(); } void ProjectSetUpConfig::changeSupportedLanguages(){ //TODO reload the actual supported languages projectPathGroupBox->setDisabled(true); } /****************************************************************************** * <Slot>: triggers the setup of the project, if all conditions are satisfied: * - valid project path * - non empty project title * - at least one language is selected ******************************************************************************/ void ProjectSetUpConfig::okActionSaveConfigurations(){ bool isDirOK = false; bool isProjNameOK = false; bool isLangsOK = false; QMap<QString,QString> projectProperties = QMap<QString,QString>(); if(!projectBaseFolder.isEmpty()){ projectPathLine->setText(projectBaseFolder); //inform the main window about the project's base path //emit setProjectPath(projectBaseFolder); projectProperties.insert(PROJ_CONFIG_BASE_PATH, projectBaseFolder); isDirOK = true; } else{ Utils::showWarningDialog(this, "Project base directory does not exists or is empty!"); isDirOK = false; } QString pName = projectNameLine->text(); if(!pName.isEmpty()){ //emit setProjectName(pName); projectProperties.insert(PROJ_CONFIG_NAME, pName); isProjNameOK = true; } else{ Utils::showWarningDialog(this, "Project name could not be empty!"); isProjNameOK = false; } if(rightLanguageList->count() != 0){ isLangsOK = true; } else{ Utils::showWarningDialog(this, "You must select at least 1 language!"); isLangsOK = false; } if(isLangsOK && isProjNameOK && isDirOK){ //close config window... this->close(); //save configurations to the project's basic configuration. XMLProjectExport *xmlExport = new XMLProjectExport(this); bool isSavedProject = false; isSavedProject = xmlExport->writeProjectDefinitionXml(projectNameLine->text(), projectDescriptionText->toPlainText(), projectPathLine->text(), CONFIG_XML_FILE, supportedLangs); if(isSavedProject){ // progressDialog->setWindowTitle(tr("Creating Project")); // progressDialog->setMinimum(0); // progressDialog->setMaximum(0); //// int steps = 0; //// progressDialog->setValue(steps++); // progressLabel->setText(tr("Creating languages...")); // progressDialog->show(); // qApp->processEvents(); // for(int i=0; i<rightLanguageList->count();i++){ // QString str = supportedLangs.at(i); // if(str.contains(ENGLISH)){ // emit setSupportedLanguage(ENGLISH_VALUE); // progressDialog->setValue(steps++); // } // if(str.contains(SPANISH)){ // emit setSupportedLanguage(SPANISH_VALUE); // progressDialog->setValue(steps++); // } // if(str.contains(CATALAN)){ // emit setSupportedLanguage(CATALAN_VALUE); // progressDialog->setValue(steps++); // } // if(str.contains(ITALIAN)){ // emit setSupportedLanguage(ITALIAN_VALUE); // progressDialog->setValue(steps++); // } // } const QString langs = supportedLangs.join(":"); projectProperties.insert(PROJ_CONFIG_LANGS, langs); emit setProjectProperties(projectProperties); //tell the main window to create the GUI with the give configs progressLabel->setText(tr("Creating subtitle windows...")); emit generateGUI(); // progressDialog->close(); } } } /****************************************************************************** * <Slot>: opens a file dialog to setup the project's base path. ******************************************************************************/ void ProjectSetUpConfig::setUpProjectBaseDir(){ projectBaseFolder = QFileDialog::getExistingDirectory(0,tr("Choose Directory")); projectPathLine->setText(projectBaseFolder); }
true
3c279d5d9d6e0b23909385b4caa5f3334a9cf6ab
C++
BruceleeThanh/Backup_CppBasicTLU
/Special_Cac bai tap ve Mang/Bai 5_chi chay duoc tren Dev C/Source.cpp
UTF-8
645
2.65625
3
[]
no_license
#include <iostream> #include <string> using namespace std; string S, S1; int giaTri[1000], N, i, j; void sapXep(); void sapXep() { int temp; for (i = 0; i < N - 1; i++) { for (j = i + 1; j < N; j++) { if (giaTri[i]>giaTri[j]) { temp = giaTri[i]; giaTri[i] = giaTri[j]; giaTri[j] = temp; } } } } int main() { cout << "Nhap xau ky tu S: "; cin >> S; cout << endl; N = S.length(); for (i = 0; i < N; i++) { giaTri[i] = S[i]; } sapXep(); for (i = 0; i < N; i++) { S1[i] = giaTri[i]; } cout << "Xau ky tu sau khi sap xep la: "; for (i = 0; i < N; i++) { cout << S1[i]; } cout << endl; return 0; }
true
2184f21f4b353f8bfb506f2e3e3783d2cd808333
C++
tblenahan/CSCI1300-Library
/Library.hpp
UTF-8
1,142
2.515625
3
[]
no_license
/* CS1300 Spring 2018 Author: Timothy Lenahan Recitation: 205 - Harshini Muthukrishnan Cloud Workspace Editor Link: http://ide.c9.io/tblenahan/tl_csci_1300 Hmwk7 - partII */ #ifndef LIBRARY_HPP #define LIBRARY_HPP #include "Book.hpp" #include "User.hpp" using namespace std; class Library { private: Book books[60]; int numBooks; User users[100]; int numUsers; public: Library(Book nBooks[], int nNumBooks, User nUsers[], int nNumUsers); Library(); Book getBookAt(int bookIdx); string setBookAt(Book addBook, int bookIdx); int getNumBooks(); void setNumBooks(int nNumBooks); User getUserAt(int userIdx); string setUserAt(User setUser, int userIdx); void addUser(User addUser); int getNumUsers(); void setNumUsers(int nNumUsers); void loadData(string booksFile, string usersFile); string Login(string name); char menu(); void viewRatings(string curUserName); void rateBook(string curUserName); void getRecommendations(string curUserName); void quit(); }; #endif
true
56e990f43552e864b34b5b54a506d1f9a10c07d7
C++
runguanner/C-Programme
/010. 正则表达式匹配(Hard).cpp
UTF-8
3,552
3.890625
4
[]
no_license
// 递归 // '*'表示之前那个字符可以有0个,1个或是多个,就是说,字符串a*b,可以表示b或是aaab,即a的个数任意。 // '.'表示匹配任意单个字符。 class Solution { public: bool isMatch(string s, string p) { if(p.empty()) return s.empty(); //(1)若p为空,若s也为空,返回true,反之返回false。 if(p.size() == 1) { //(2)若p的长度为1,若s长度也为1,且相同或是p为'.'则返回true,反之返回false。 return (s.size() == 1 && (s[0] == p[0] || p[0] == '.')); } if(p[1] != '*') { //(3)若p的第二个字符不为*,若此时s为空返回false,否则判断首字符是否匹配,且从各自的第二个字符开始调用递归函数匹配。 if (s.empty()) return false; return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1)); } while(!s.empty() && (s[0] == p[0] || p[0] == '.')) { //(4)若p的第二个字符为*,进行下列循环,条件是若s不为空且首字符匹配(包括p[0]为点)。 if (isMatch(s, p.substr(2))) return true; //调用递归函数匹配s和去掉前两个字符的p(假设此时的星号作用是让前面字符出现0次,验证是否匹配) s = s.substr(1); //(5)否则s去掉首字母(因为首字母匹配了可以去掉s的首字母,而p由于星号的作用,可以有任意个首字母,不需要去掉)继续进行循环。 } return isMatch(s, p.substr(2)); //(5)比如s="", p="a*",由于s为空,不会进入任何的if和while,只能到最后的return来比较了,返回true。 } }; // 法(1)中substr()函数有2种用法: // string s = "0123456789"; // string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = "56789" // string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = "567" 法(1)简化: class Solution { public: bool isMatch(string s, string p) { if (p.empty()) return s.empty(); //(1) if (p.size() > 1 && p[1] == '*') { //(4)(5) return isMatch(s, p.substr(2)) || (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p)); } else { //(3) return !s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1)); } } }; // DP动态规划 // This problem has a typical solution using Dynamic Programming. We define the state P[i][j] to be true if s[0..i) matches p[0..j) and false otherwise. Then the state equations are: // P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.'); // P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times; // P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times. // Putting these together, we will have the following code. class Solution { public: bool isMatch(string s, string p) { int m = s.length(), n = p.length(); vector<vector<bool> > dp(m + 1, vector<bool> (n + 1, false)); dp[0][0] = true; for (int i = 0; i <= m; i++) for (int j = 1; j <= n; j++) if (p[j - 1] == '*') dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]); else dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.'); return dp[m][n]; } };
true
f693457d6d49523e6727b9fea0073063e4890dff
C++
Humungus-Fungus/project-swyft
/NEA_Project_Swyft/CPP_files/Looper.cpp
UTF-8
1,128
3.25
3
[]
no_license
#include <iostream> #include <vector> #include "../FunctionDeclarations.h" // This method will be be responsible for getting the final seq // This method is complicated // "seqs" represents the vector holding all other vectors // "vals" represents the items we are looking for within seqs (the ideal sequence) // "final" will hold the final completed list (as close to the ideal as possible) // "inc" is used to measure the recursion depth // "le" represents leniency (how far you can deviate from the ideal) vector<int> get_final_seq(vector<vector<int>> seqs, vector<int> vals, vector<int> final, const int le/*=5*/, int inc/*=0*/) { int val = vals[inc]; double lower_bound; double upper_bound; if (inc > seqs.size()-1) return final; else { for (int i{0}; i < seqs[inc].size(); i++) { if (final.size()==0) lower_bound = val-le; else lower_bound = max(val-le, final[final.size()-1]); upper_bound = val+le; if (lower_bound < seqs[inc][i] && seqs[inc][i] < upper_bound) { final.push_back(seqs[inc][i]); final = get_final_seq(seqs, vals, final, le, inc+1); } } } return final; }
true
da62739e17bd072c43c01e829c5b7f2a23d1a8e8
C++
osoman2/Compiladores
/Semana 0/grafo/grafo.cpp
UTF-8
801
3.109375
3
[]
no_license
#ifndef GRAPH_H #define GRAPH_H #include "vertice.cpp" template<class N,class A> class Grafo { private: vector <Arista<N,A>*> aristas; vector <Vertice<N,A>*> vertices; public: Grafo(){ aristas.clear(); vertices.clear(); } ~Grafo(); void makelink(Vertice<N,A>&p,Vertice<N,A>&ll,A a_dato){ Arista<N,A> *arista = new Arista<N,A>(p,ll,a_dato); aristas.insert(arista); } void addnode(const Vertice<N,A> &nuevo){ this.vertices.insert(nuevo); } void addnode_value(N nuevo){ Vertice<N,A> *nodo= new Vertice<N,A>(nuevo); this.vertices.insert(nodo); } void printnodos(){ for(int i = 0;i<vertices.capacity();i++){ cout<<vertices.at(i)->get_data()<<" "; } } }; #endif
true
15855b2c0be1f51fc7376bc1419ce135b4501ec8
C++
Jaoxvalen/mcs.imageprocessing
/camera_cal4/t1/SelectorFrame.h
UTF-8
5,080
2.546875
3
[]
no_license
#include <map> #include "RingsDetector.h" #include "ProcManager.h" using namespace std; using namespace cv; namespace vision { struct classcomp { bool operator() (const Rect& lhs, const Rect& rhs) const { if (lhs.x != rhs.x ) return lhs.x < rhs.x; if (lhs.y != rhs.y ) return lhs.y < rhs.y; return true; } }; static void calcBoardCornerPositions(Size boardSize, float squareSize, vector<Point3f>& corners) { corners.clear(); for ( int i = 0; i < boardSize.height; ++i ) for ( int j = 0; j < boardSize.width; ++j ) corners.push_back(Point3f(j * squareSize, i * squareSize, 0)); } void get_FramesBySquare(map<Rect, vector<pair<Mat, int> >, classcomp> &_r2mat, int _framesBySquare, vector<int> & _frameIndex, Mat camera_matrix = Mat() , Mat dist_coeffs = Mat(), double min_rot = 0.0, double max_rot = 20.0) { vector<int> indexes; for (auto & _pair : _r2mat) { //by square int frames_by_square = 0; if (!camera_matrix.empty() && !dist_coeffs.empty() ) { //Output rotation and translation cv::Mat rotation_vector; cv::Mat translation_vector; for (pair<Mat, int> _pm : _pair.second) { //by frame vector<Point2f> image_points; //fill image points RingsDetector rd; Mat clone = _pm.first; //imshow("_pm.first", _pm.first); //waitKey(); bool found = rd.findPattern(clone, image_points); cout << "found: " << found << endl; vector<Point3f> model_points; //Fill model points double squareSize = 44; calcBoardCornerPositions(Size(5, 4), squareSize, model_points); //Solve for pose cout << "size model image: " << model_points.size() << " " << image_points.size() << endl; solvePnP(model_points, image_points, camera_matrix, dist_coeffs, rotation_vector, translation_vector); const double*angles = rotation_vector.ptr<double>(); cout << "mat rotation: " << endl << rotation_vector << endl; double angleX = rotation_vector.at<double>(0, 0) * (180.0 / 3.141592653589793238463); double angleY = rotation_vector.at<double>(0, 1) * (180.0 / 3.141592653589793238463); double angleZ = rotation_vector.at<double>(0, 2) * (180.0 / 3.141592653589793238463); //angles on x if ( abs(angles[0]) > min_rot && abs(angles[0]) < max_rot && abs(angles[1]) > min_rot && abs(angles[1]) < max_rot && abs(angles[2]) > min_rot && abs(angles[2]) < max_rot ) { cout<< angleX<<" "<<angleY<<" "<<angleZ<<endl; //imshow("_pm.first", _pm.first); //waitKey(0); indexes.push_back(_pm.second); cout << "_pm.second " << _pm.second << endl; frames_by_square++; } if (frames_by_square >= _framesBySquare) { break; } } continue; } else { cout << "no camera matrix given " << endl; } } _frameIndex = indexes; } void get_centroid(vector<Point2f>& _pointBuf, Point2f& centroid) { centroid.x = 0; centroid.y = 0; for ( int i = 0; i < _pointBuf.size(); i++) { centroid += _pointBuf[i]; } centroid /= (float)_pointBuf.size(); } void getIndexesFromVideo(const string & _filename, vector<int>& indexes, Mat camera_matrix = Mat(), Mat dist_coeffs = Mat(), int nFrames = 54, double min_angle = 0.0, double max_angle = 20.0) { VideoCapture cap(_filename); if (!cap.isOpened()) return ; int sh = 3; int sw = 3; float dh = 480 / sh; float dw = 640 / sw; map<Rect, vector< pair<Mat, int> > , classcomp> r2mat; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { r2mat[Rect(j * dw, i * dh, dw, dh)] = vector<pair<Mat, int>>(); } } int global_index = 0; for (;;) { Mat frame; cap >> frame; waitKey(2); if (frame.empty()) break; Point2f centroid; vector<Point2f> _pointBuf; RingsDetector rd; Mat copy = frame.clone(); bool found = rd.findPattern(copy, _pointBuf); Mat copy2; //bool found = findConcentricCirclesCenters(frame, Size(5, 4), _pointBuf); if (found) { copy2 = frame.clone(); ProcManager ch; ch.drawControlPoints(copy2, _pointBuf); //imshow("video", copy2); get_centroid(_pointBuf, centroid); for (auto & _pair : r2mat) { if (_pair.first.contains(centroid)) { //_pair.second.push_back( centroid); _pair.second.push_back(make_pair(frame, global_index)); cout << global_index << endl; break; } } } global_index++; /* if( global_index >200 ) { break; }*/ } for( auto _pair : r2mat ) { cout<<_pair.first<<" "<<_pair.second.size()<<endl; } int framesBySquare = nFrames / (sh * sw); get_FramesBySquare(r2mat, framesBySquare, indexes, camera_matrix , dist_coeffs, min_angle, max_angle); } }
true
2a40d047f9b886061c091e34f439ac7f88405c3c
C++
15757170756/All-Code-I-Have-Done
/hihoCode/[Offer收割]编程练习赛31/题目3-数组分拆II.cpp
UTF-8
2,785
3
3
[]
no_license
/* 题目3 : 数组分拆II 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定一个包含N个整数的数组A=[A1, A2, ... AN]。小Ho想将A拆分成若干连续的子数组,使得每个子数组中的整数都是两两不同的。 在满足以上条件的前提下,小Ho想知道子数组数量最少是多少。 同时他还想知道,在数量最少的前提下有多少中不同的拆法。 例如对于[1, 2, 3, 1, 2, 1],最少需要3个子数组。有5种不同的拆法: [1], [2, 3, 1], [2, 1] [1, 2], [3, 1], [2, 1] [1, 2], [3, 1, 2], [1] [1, 2, 3], [1], [2, 1] [1, 2, 3], [1, 2], [1] 输入 第一行包含一个整数N。 第二行包含N个整数A1, A2, ... AN。 对于30%的数据,满足1 ≤ N ≤ 10 对于60%的数据,满足1 ≤ N ≤ 1000 对于100%的数据,满足1 ≤ N ≤ 100000, 1 ≤ Ai ≤ 100000 输出 输出两个整数。第一个表示子数组最少的数量,第二个表示在数量最少的前提下有多少种拆法。 由于拆法可能非常多,你只需要输出答案除以1000000007的余数。 样例输入 6 1 2 3 1 2 1 样例输出 3 5 */ #include <map> #include <cmath> #include <queue> #include <ctime> #include <string> #include <cstdio> #include <vector> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int n, p1[101111], p2[101111], f[101111], a[101111], cur[101111], p[101111]; long long g[101111], Sum[101111]; long long MOD = 1000000007; bool v[101111]; void work() { scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); } memset(cur, -1, sizeof(cur)); for (int i = 0; i < n; ++i) { p1[i] = cur[a[i]]; cur[a[i]] = i; } memset(cur, -1, sizeof(cur)); for (int i = n - 1; i >= 0; --i) { p2[i] = cur[a[i]]; cur[a[i]] = i; } int prev = -1; for (int i = 0; i < n; ++i) { if (v[a[i]]) { prev++; while (a[prev] != a[i]) { v[a[prev]] = false; prev++; } } p[i] = prev; v[a[i]] = true; } memset(f, -1, sizeof(f)); for (int i = 0; i < n; ++i) { if (p[i] == -1) { f[i] = 1; } else { if (f[i] == -1) f[i] = f[p[i]] + 1; else f[i] = min(f[i], f[p[i]] + 1); } } prev = 0; for (int i = 0; i < n; ++i) { // g[i] = sum(g[j], f[j]+1=f[i] && j>=p[i]) if (p[i] == -1) { g[i] = 1; Sum[f[i]] += g[i]; Sum[f[i]] %= MOD; } else { for (int j = max(0, p[i - 1]); j < p[i]; ++j) { Sum[f[j]] -= g[j]; Sum[f[j]] %= MOD; } g[i] += Sum[f[i] - 1]; Sum[f[i]] += g[i]; Sum[f[i]] %= MOD; } } printf("%d %lld\n", f[n - 1], (g[n - 1] + MOD) % MOD); } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif int TestCase = 1; //scanf("%d", &TestCase); while (TestCase--) { work(); } return 0; }
true
f77f4ec3a1f5fb778c35683a2389cc1397482865
C++
dmpots/ra-chow
/rc.h
UTF-8
1,252
2.59375
3
[]
no_license
#ifndef __GUARD_RC_H #define __GUARD_RC_H #include <Shared.h> #include "types.h" namespace RegisterClass { /* types */ enum RC {INT, FLOAT}; //this struct holds information about the registers reserved for a //given class. these reserved registers are used during register //assignment to provide machine registers to any variable that was //spilled struct ReservedRegsInfo { Register* regs; /* array of temporary registers */ int cReserved; /* count of number reserved */ /* count of number hidden at the front, for all but INT reg class * this is the same as reserved, but ints need an extra hidden reg * for the frame pointer */ int cHidden; }; /* variables */ extern std::vector<RC> all_classes; /* functions */ const ReservedRegsInfo& GetReservedRegInfo(RC rc); void Init(Arena arena, int cReg, Boolean fEnableClasses, int* cReserved); void InitRegWidths(); RC InitialRegisterClassForLRID(LRID lrid); int NumMachineReg(RC); Register MachineRegForColor(RC, Color); VectorSet TmpVectorSet(RC rc); int FirstRegister(RegisterClass::RC); Color ColorForMachineReg(RC rc, Register r); int RegWidth(Def_Type dt); } #endif
true
84c1beff9716d73dbfd38b3e6ee0084ad5bc2708
C++
rkrupka/uefa2021
/Match.h
UTF-8
370
2.515625
3
[]
no_license
#ifndef MATCH_H #define MATCH_H ////////////////////////////////////////// // Plik: Match.h ////////////////////////////////////////// #include "team.h" struct LineUp { Team* team; std::vector<Player*> playing; int score; }; class Match { public: Match(); Team* winner() const; private: LineUp _team1; LineUp _team2; }; #endif // MATCH_H
true
3a26eaf4210ccff9ba080dcaacf664371c299ed4
C++
Naruse27/Haguruma
/Sources/GameSources/Character.h
SHIFT_JIS
2,883
2.65625
3
[]
no_license
#ifndef CHARACTER #define CHARACTER #include "GameLibSource/Vector.h" #include "GameLibSource/Model.h" #include "GimmickManager.h" class Character { public: Character() {} virtual ~Character() {} // sXV void UpdateTransform(); const Vector3& GetPosition() const { return position; } void SetPosition(const Vector3& position) { this->position = position; } const Vector3& GetAngle() const { return angle; } void SetAngle(const Vector3& angle) { this->angle = angle; } const Vector3& GetScale() const { return scale; } void SetScale(const Vector3& scale) { this->scale = scale; } const Vector3& GetVelocity() const { return velocity; } // float GetHeight() const { return height; } // a擾 float GetWidth() const { return width; } // nʂɐڒnĂ邩 bool IsGround() const { return isGround; } // NԂ擾 int GetHealth() const { return health; } // ő匒NԂ擾 int GetMaxHealth() const { return maxHealth; } // Ռ^ void AddImpulse(const Vector3& impulse); // _[W^ bool ApplyDamage(int damage, float invincibleTime); // bZ[WMƂ̏ bool HandleMessage(const Telegram& msg); // 󂯎 virtual bool OnMessage(const Telegram& telegram); private: // ͍XV void UpdateVerticalVelocitiy(float elapsedFrame); // ړXV void UpdateVerticalMove(float elapsedTime); // ͍XV void UpdateHorizontalVelocity(float elapsedTime); // ړXV void UpdateHorizontalMove(float elapsedTime); protected: void Move(float vx, float vz, float speed); void Turn(float elapsedTime, float vx, float vz, float speed); void Jump(float speed); void UpdateVelocity(float elapsedTime); void UpdateInvincibleTimer(float elapsedTime); virtual void OnLanding() {} // _[W󂯂ɌĂ΂ virtual void OnDamaged() {} // SɌĂ΂ virtual void OnDead() {} // nʂ痎ɌĂ΂ virtual void DropProcessing() {} protected: Model* model = nullptr; Vector3 position = { 0,0,0 }; Vector3 angle = { 0,0,0 }; Vector3 scale = { 1,1,1 }; DirectX::XMFLOAT4X4 transform = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 }; Vector3 normal = { 0,0,0 }; float gravity = -1.0f; Vector3 velocity = { 0,0,0 }; Vector3 velocityMax = { 0, -20, 0 }; bool isGround = false; float height = 4.0f; float width = 4.0f; int health = 5; int maxHealth = 5; float invincibleTimer = 1.0f; float friction = 0.5f; float acceleration = 1.0f; float maxMoveSpeed = 30.0f; float moveVecX = 0.0f; float moveVecZ = 0.0f; float airControl = 0.3f; float stepOffset = 1.0f; float slopeRate = 1.0f; float deathbed = -40.0f; bool deathFlag = false; }; #endif // !CHARACTER
true
6bdd0489a44cdc65d283e7fa0e0601888ab30f8e
C++
ekverma26/Stack-queue-and-Linked-lists
/DOUBLY.CPP
UTF-8
4,248
3.109375
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<alloc.h> #include<stdlib.h> # define NULL 0 void inla(); void inbeg(); void inbet(); void display(); void input(); void dela(); void debeg(); void debet(); void count(); void search(); void hmax(); void secmax(); void reverse(); void sort(); int co=0; struct node { int data; struct node *pre; struct node *next; }*start,*tmp2,*newnode,*tmp,*t; void main() { clrscr(); int n,c; start=NULL; while(1) { clrscr(); printf("1.Insert Last\n2.Insert Beginning\n3.Insert Between\n4.Delete Last\n5.Delete Beginning\n6.Delete Between\n7.Count Linked list\n8.Highest Number\n9.Second Highest\n10.Search\n11.Print in Reverse Direction\n12.Sorting\n13.Display\n14.Exit\n"); printf("enter you choice:"); scanf("%d",&c); switch(c) { case 1: inla(); getch(); break; case 2: inbeg(); getch(); break; case 3: inbet(); getch(); break; case 4: dela(); getch(); break; case 5: debeg(); getch(); break; case 6: debet(); getch(); break; case 7: count(); getch(); break; case 8: hmax(); getch(); break; case 9: secmax(); getch(); break; case 10:search(); getch(); break; case 11:reverse(); getch(); break; case 12:sort(); getch(); break; case 13:display(); getch(); break; case 14:exit(0); } } } void input() { co++; newnode=(struct node*)malloc(sizeof(struct node )); newnode->pre=NULL; newnode->next=NULL; printf("enter newnode:- "); scanf("%d",&newnode->data); } void inla() { input(); if(start==NULL) start=newnode; else { tmp=start; while(tmp->next!=NULL) { tmp=tmp->next; } newnode->pre=tmp; tmp->next=newnode; } display(); } void inbeg() { input(); if(start==NULL) start=newnode; else { tmp=start; start=newnode; newnode->next=tmp; tmp->pre=newnode; } display(); } void inbet() { int value; input(); printf("\nenter the value after which value is to be inserted:"); scanf("%d",&value); tmp=start; while(tmp->data!=value &&tmp!=NULL) { tmp=tmp->next; } tmp2=tmp->next; if(tmp->data==value) { newnode->pre=tmp; newnode->next=tmp->next; tmp->next=newnode; tmp2->pre=newnode; } display(); } void dela() { co--; tmp=start; while(tmp->next!=NULL) { tmp=tmp->next; } t=tmp->pre; t->next=NULL; free(tmp); display(); } void debeg() { co--; tmp=start; tmp2=tmp->next; start=tmp->next; tmp2->pre=NULL; free(tmp); display(); } void debet() { co--; int key; printf("enter the value to be deleted:"); scanf("%d",&key); tmp=start; while(tmp->data!=key &&tmp!=NULL) { tmp=tmp->next; } tmp2=tmp->next; t=tmp->pre; if(tmp->data==key) { t->next=tmp->next; tmp2->pre=tmp->pre; free(tmp); } else printf("\nvalue does not exist in the linklist."); display(); } void count() { printf("the total number of nodes in linked list:%d",co); } void hmax() { int max; tmp=start; max=-32768; while(tmp!=NULL) { if(max<tmp->data) { max=tmp->data; tmp=tmp->next; } else tmp=tmp->next; } printf("the highest value:%d",max); } void secmax() { int max,secmax; tmp=start; max=-32768; secmax=-32767; while(tmp!=NULL) { if(max<tmp->data) { secmax=max; max=tmp->data; tmp=tmp->next; } else if(secmax<tmp->data && max>tmp->data) { secmax=tmp->data; tmp=tmp->next; } else tmp=tmp->next; } printf("the second highest value:%d",secmax); } void search() { int i=0,n; printf("enter the number to be searched:"); scanf("%d",&n); tmp=start; while(tmp->data!=n &&tmp!=NULL) { i++; tmp=tmp->next; } if(tmp->data==n) printf("number found at,%d position",i+1); else printf("number does not exist in the linked list."); } void reverse() { tmp=start; while(tmp->next!=NULL) { tmp=tmp->next; } while(tmp!=NULL) { printf("\ndata=%d",tmp->data); tmp=tmp->pre; } } void sort() { int s; tmp=start; while(tmp!=NULL) { tmp2=tmp->next; while(tmp2!=NULL) { if(tmp2->data<tmp->data) { s=tmp->data; tmp->data=tmp2->data; tmp2->data=s; tmp=tmp->next; } else tmp2=tmp2->next; } tmp=tmp->next; } display(); } void display() { printf("\nthelinklist is:"); tmp=start; while(tmp!=NULL) { printf("\ndata=%d",tmp->data); tmp=tmp->next; } }
true
8b36a41f49e5980dcf2e05282a7b36542de9d2e7
C++
fzls/CLRS
/chapt12~13/testBST.cpp
UTF-8
1,435
3
3
[]
no_license
/* +---------------------------------------------------------- * * @authors: 风之凌殇 <1054073896@qq.com> * @FILE NAME: testBST.cpp * @version: * @Time: 2015-11-30 19:41:40 * @Description: test the BinarySearchTree Class * +---------------------------------------------------------- */ #include <algorithm> #include <functional> #include <iostream> #include <string> #include <vector> #include <random> #include <ctime> #include "BinarySearchTree.h" #include <typeinfo> using namespace std; //TODO //1、create a redBlackTreeNode<class dataType> class by inheriting the BinarySearchTreeNode<class dataType> //2、create a redBlackTree<class TreeNode> by inheriting the BinarySearchTree<class TreeNode> {namely to add the change the insert and delete mothod and add the corresponding fixup method} //3、instantialize the redBlackTree<class TreeNode> by using redBlackTreeNode<class dataType> as its TreeNode int main() { freopen("test.in", "r", stdin); freopen("test.out", "w", stdout); BinarySearchTree<BinarySearchTreeNode<int>> bst; cout << "max: " << bst.maximum() << endl; cout << "min: " << bst.minimum() << endl; bst.preorder(); bst.inorder(); bst.postorder(); for (int i = 1; i < 25; i += 3) if (bst.search(i)) cout << i << " is found" << endl; else cout << i << " is not found" << endl; for (int i = 1; i < 25; i ++) { bst.remove(i); bst.preorder(); } cout << endl; system("pause"); return 0; }
true
e70bd85fa888eb434e062be0a0756bbe5c1a08de
C++
suraj021/Codeforces-Solutions
/cf600C.cpp
UTF-8
1,156
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; char ans[200005]; int freq[10000]; bool exist[27]; int main(){ memset( freq, 0, sizeof freq ); memset( exist, 0, sizeof exist ); string s; cin >> s; for( int i= 0; i< (int)s.length(); ++i ){ freq[ s[i] - 'a' ]++; exist[ s[i] - 'a' ]= true; } //for( int i= 0; i< 26; ++i ){ // cout << char( 'a' + i ) << " " << exist[i] << endl; //} int first= 0; int last= 25; while( first < last ){ while( !exist[first] ){ first++; } //cout << endl; while( !exist[last] ){ last--; } while( freq[first]%2== 0 ) first++; while( freq[last]%2== 0 ) last--; if( first > last ) break; freq[first]++; freq[last]--; first++; last--; } //for( int i= 0; i< 26; ++i ) // cout << freq[i] << " "; //cout << endl; int here= 0; last= s.length()-1; char left; for( int i= 0; i< 26; ++i ){ if( exist[i] ){ if( freq[i]%2!= 0 ){ left= 'a' + i; freq[i]--; } for( int j= 0; j< freq[i]/2; ++j ){ ans[here]= ans[last-here]= 'a' + i ; here++; } } } if( s.length()%2!= 0 ) ans[s.length()/2]= left; printf("%s\n", ans ); }
true
dc732cef1a084aeac9a8a5354a6a072f432d72b7
C++
thetimeofblack/USC-EE569-Digital-Image-Processing-Spring-2017
/Homework-1/prob2a/Prob2a.cpp
UTF-8
10,842
2.890625
3
[]
no_license
// ------------------------------------------------------------------------------------ // EE569 Homework Assignment #1 Prob2a // Date: February 5, 2017 // Name : Chinmay Chinara // USC-ID : 2527-2374-52 // email : chinara@usc.edu // ------------------------------------------------------------------------------------ #include <iostream> #include <fstream> #include <math.h> #include <cmath> #include <algorithm> #include "MyImgHeaders.h" using namespace std; int main(int argc, char* argv[]) { /* condition to ensure that correct parameters are passed in the command line */ if (argc != 11 && strcmp(argv[8],"mb")==0 || strcmp(argv[5], " ")==0 || strcmp(argv[5], " ") == 0 || strcmp(argv[5], " ") == 0) { cout << "-----------------------------------------------------------------------------------------------" << endl; cout << "Syntax Error - Incorrect parameter usage" << endl; cout << "-----------------------------------------------------------------------------------------------" << endl; cout << "Make sure the parameters passed are in the following format:" << endl; cout << "<program_name> <inp_image>.raw <inp_hist>.txt <out_image>.raw <out_hist>.txt <ImgWidth> <ImgHeight> <BytesPerPixel> <method_name> <tfdata_filename>.txt <tf_pixelmapping_mb>.txt" << endl; cout << "-----------------------------------------------------------------------------------------------" << endl; cout << "Details of the above parameters:" << endl; cout << "program_name: the name of the .exe file generated" << endl; cout << "inp_image: the name of the .raw file along with path to be taken as input for processing" << endl; cout << "inp_hist: the name of the .txt file along with path to to which input image histogram data is saved" << endl; cout << "out_image: the name of the .raw file along with path to which the processesed image is saved" << endl; cout << "out_hist: the name of the .txt file along with path to to which output image histogram data is saved" << endl; cout << "ImgWidth: Width of the image" << endl; cout << "ImgHeight: Height of the image" << endl; cout << "BytesPerPixel: bytes per pixel (for RGB = 3 and for GRAY = 1)" << endl; cout << "method_name: ma = Method-A, mb = Method-B" << endl; cout << "tfdata_filename: the name of the .txt file along with path to to which transfer function data is saved" << endl; cout << "tf_pixelmapping_mb: the name of the .txt file along with path to to which pixel mapped transfer function data for Method-B is saved (this parameter is only required for Method-B)" << endl; cout << "-----------------------------------------------------------------------------------------------" << endl; return 0; } /* initialization of variables */ int ImgWidth = atoi(argv[5]); /* number of rows in the image */ int ImgHeight = atoi(argv[6]); /* number of columns in the image */ int BytesPerPixel = atoi(argv[7]); /* bytes per pixel (RGB = 3, GRAY = 1) */ /* Allocate OriginalImage1d in heap */ unsigned char* OriginalImage1d = new unsigned char[ImgHeight*ImgWidth*BytesPerPixel](); /* Allocate OriginalImage2d in heap */ unsigned char** OriginalImage2d = NULL; OriginalImage2d = AllocHeap2d(OriginalImage2d, ImgHeight, ImgWidth); /* Allocate HistEqlImage1d in heap */ unsigned char* HistEqlImage1d = new unsigned char[ImgHeight*ImgWidth*BytesPerPixel](); /* Allocate HistEqlImage3d in heap */ unsigned char** HistEqlImage2d = NULL; HistEqlImage2d = AllocHeap2d(HistEqlImage2d, ImgHeight, ImgWidth); /* Read OriginalImage1d from file */ FileRead(argv[1], OriginalImage1d, ImgHeight*ImgWidth*BytesPerPixel); /* Convert OriginalImage 1D to 2D so that image traversal becomes easier */ OriginalImage2d = Img1dTo2d(OriginalImage1d, ImgHeight, ImgWidth); /* initialize histogram variable and store data to it from image */ unsigned long HistData[256]; Histogram2d(HistData, OriginalImage2d, ImgHeight, ImgWidth); /* store data for input image histogram */ FileWriteHist2d(argv[2], HistData); //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- /* Histogram equalization by linear transfer function logic */ /* Find maximum and minimum value of input image pixel */ if (strcmp("ma", argv[8]) == 0) { int InpMax = 0; int InpMin = 255; int OutMin = 0; int OutMax = 255; for (int i = 0; i < ImgHeight; i++) { for (int j = 0;j < ImgWidth;j++) { if ((int)OriginalImage2d[i][j] < InpMin) InpMin = (int)OriginalImage2d[i][j]; if ((int)OriginalImage2d[i][j] > InpMax) InpMax = (int)OriginalImage2d[i][j]; } } double slope = (OutMax - OutMin) / (1.0 * (InpMax - InpMin)); for (int i = 0; i < ImgHeight; i++) { for (int j = 0;j < ImgWidth;j++) { HistEqlImage2d[i][j] = (unsigned char)(slope * ((int)OriginalImage2d[i][j] - InpMin)) + OutMin; } } /* write data to plot transfer function */ FILE *file; file = fopen(argv[9], "w"); if (file != NULL) { for (int i = 0; i < ImgHeight; i++) { for (int j = 0;j < ImgWidth;j++) { fprintf(file, "%d\t%d\n", (int)OriginalImage2d[i][j], (int)HistEqlImage2d[i][j]); } } fclose(file); cout << "File " << argv[9] << " written successfully !!!" << endl; } else { cout << "Cannot open file " << argv[9] << endl; } cout << "The transfer function using Method-A is:" << endl; cout << "G = " << OutMin << " + " << slope << " * (F - " << InpMin << " )" << endl; } /* Histogram equalization by linear transfer function logic ends here */ //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- /* Histogram equalization by cumulative probability logic */ else if (strcmp("mb", argv[8]) == 0) { double Prob[256]; double CumProb[256]; double NewPixelVal[256]; for (int i = 0;i < 256;i++) { CumProb[256] = 0; } for (int i = 0;i < 256;i++) { HistData[i]; // number of pixels Prob[i] = HistData[i] / (1.0 * ImgHeight * ImgWidth); // Probability if (i == 0) CumProb[i] = Prob[i]; else CumProb[i] = CumProb[i - 1] + Prob[i]; NewPixelVal[i] = CumProb[i] * 255.0; NewPixelVal[i] = floor(NewPixelVal[i]); } /* write new pixel values to image */ for (int r = 0;r < 256;r++) { for (int i = 0;i < ImgHeight; i++) { for (int j = 0;j < ImgWidth; j++) { if (OriginalImage2d[i][j] == r) { HistEqlImage2d[i][j] = NewPixelVal[r]; } } } } /* write data to plot transfer function wrt mapped pixels */ FILE *file; file = fopen(argv[10], "w"); if (file != NULL) { for (int i = 0; i < 256; i++) { fprintf(file, "%d\t%d\n", i, (int)NewPixelVal[i]); } fclose(file); cout << "File " << argv[10] << " written successfully !!!" << endl; } else { cout << "Cannot open file " << argv[10] << endl; } /* write data to plot transfer function showing distribution of all pixels in the image*/ FILE *file1; file1 = fopen(argv[9], "w"); if (file != NULL) { for (int i = 0; i < ImgHeight; i++) { for (int j = 0;j < ImgWidth;j++) { fprintf(file1, "%d\t%d\n", (int)OriginalImage2d[i][j], (int)HistEqlImage2d[i][j]); } } fclose(file1); cout << "File " << argv[9] << " written successfully !!!" << endl; } else { cout << "Cannot open file " << argv[9] << endl; } } /* Histogram equalization by cumulative probability logic ends here*/ //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- /* error handler */ else { cout << "-----------------------------------------------------------------------------------------------" << endl; cout << "Syntax Error - Incorrect parameter usage" << endl; cout << "-----------------------------------------------------------------------------------------------" << endl; cout << "Make sure the parameters passed are in the following format:" << endl; cout << "<program_name> <inp_image>.raw <inp_hist>.txt <out_image>.raw <out_hist>.txt <ImgWidth> <ImgHeight> <BytesPerPixel> <method_name> <tfdata_filename>.txt <tf_pixelmapping_mb>.txt" << endl; cout << "-----------------------------------------------------------------------------------------------" << endl; cout << "Details of the above parameters:" << endl; cout << "program_name: the name of the .exe file generated" << endl; cout << "inp_image: the name of the .raw file along with path to be taken as input for processing" << endl; cout << "inp_hist: the name of the .txt file along with path to to which input image histogram data is saved" << endl; cout << "out_image: the name of the .raw file along with path to which the processesed image is saved" << endl; cout << "out_hist: the name of the .txt file along with path to to which output image histogram data is saved" << endl; cout << "ImgWidth: Width of the image" << endl; cout << "ImgHeight: Height of the image" << endl; cout << "BytesPerPixel: bytes per pixel (for RGB = 3 and for GRAY = 1)" << endl; cout << "method_name: ma = Method-A, mb = Method-B" << endl; cout << "tfdata_filename: the name of the .txt file along with path to to which transfer function data is saved" << endl; cout << "tf_pixelmapping_mb: the name of the .txt file along with path to to which pixel mapped transfer function data for Method-B is saved (this parameter is only required for Method-B)" << endl; cout << "-----------------------------------------------------------------------------------------------" << endl; delete[] OriginalImage1d; delete[] HistEqlImage1d; DeallocHeap2d(OriginalImage2d, ImgHeight); DeallocHeap2d(HistEqlImage2d, ImgHeight); return 0; } /* initialize histogram variable and store data to it from image */ unsigned long HistDataEq[256]; Histogram2d(HistDataEq, HistEqlImage2d, ImgHeight, ImgWidth); /* store data for ouptput image histogram */ FileWriteHist2d(argv[4], HistDataEq); /* Convert HistEqlImage2d 2D to 1D so that it can be written to file */ HistEqlImage1d = Img2dTo1d(HistEqlImage2d, ImgHeight, ImgWidth); /* Write MirrorImage to file */ FileWrite(argv[3], HistEqlImage1d, ImgHeight*ImgWidth*BytesPerPixel); delete[] OriginalImage1d; delete[] HistEqlImage1d; DeallocHeap2d(OriginalImage2d, ImgHeight); DeallocHeap2d(HistEqlImage2d, ImgHeight); return 0; }
true
99bcd7f0ee8b532d509b0d00ed62ed7de35cd90c
C++
cuby-tec/mitoPrinter
/statuslabel.cpp
UTF-8
1,889
2.625
3
[]
no_license
#include "statuslabel.h" #include <QDebug> StatusLabel::StatusLabel(QWidget *parent) : QWidget(parent) , ui(new Ui::StatusLabel) { // this->parent = parent; ui->setupUi(parent); } void StatusLabel::statusFailed() { // qDebug()<<__FILE__<<__LINE__<<"statusFailed"; indicateTemperature(eiFail,QString("Can't open device. maybe module not loaded. Use: $sudo insmod ./eclipse-workspace/usbtest/test1.ko \n \t or device dosn't connected.")); } void StatusLabel::updateStatus(const Status_t* status) { // qDebug()<<__FILE__<<__LINE__; indicateTemperature(eiGood,QString("now: %1").arg(status->temperature)); } const QString message1("Can't open device. maybe module not loaded. Use: $sudo insmod ./eclipse-workspace/usbtest/test1.ko \n \t or device dosn't connected."); const QString message2("Can't open device."); const QString message3("Temperature in Hotend.(grad Celsium)"); void StatusLabel::indicateTemperature(eIndicate ind, QString message) { // QWidget* pa = plot->nativeParentWidget(); // QLabel* label = pa->findChild<QLabel *>("temperatureIcon");//temperatureLabel // QLabel * tempLabel = pa->findChild<QLabel*>("temperatureLabel"); // qDebug()<<__FILE__<<__LINE__<<"indicateTemperature:"; QLabel *label = ui->temperatureIcon; QLabel * tempLabel = ui->temperatureLabel; switch (ind) { case eiFail: if(label) { label->setPixmap(QPixmap(":/images/write.png")); label->setScaledContents(true); tempLabel->setText(message2); tempLabel->setToolTip(message1); } break; case eiGood: if(label) { label->setPixmap(QPixmap(":/images/copy.png")); label->setScaledContents(true); tempLabel->setText(message); tempLabel->setToolTip(message3); } break; } }
true
e027ed7c5dfdefa8790120ceab69fedec62ef219
C++
jiadaizhao/LeetCode
/0901-1000/0929-Unique Email Addresses/0929-Unique Email Addresses.cpp
UTF-8
713
2.734375
3
[ "MIT" ]
permissive
class Solution { public: int numUniqueEmails(vector<string>& emails) { unordered_set<string> table; for (string email : emails) { auto it = email.begin(); bool ignore = false; string s; for (; *it != '@'; ++it) { char c = *it; if (c == '.') { continue; } if (c == '+') { ignore = true; } if (!ignore) { s += c; } } s.append(it, email.end()); table.insert(s); } return table.size(); } };
true
e572cbe117ebe90e6b5783cbf8c70d2674d115db
C++
NCTU-Kemono/CodeBook
/Graph/MMC.cpp
UTF-8
1,438
2.84375
3
[]
no_license
const int MAXN = 55; const double INF = 0x3f3f3f3f; const double EPS = 1e-4; double min_mean_cycle(vector<vector<pii> > &G) { int n = G.size(); G.resize(n + 1); for (int i = 0 ; i < n ; i++) G[n].push_back(MP(i, 0)); double d[MAXN][MAXN]; // dp[i][j] := 從起點到j走i條的最短路徑 int s = n++; for (int i = 0 ; i <= n ; i++) for (int j = 0 ; j < n ; j++) d[i][j] = INF; d[0][s] = 0; for (int k = 0 ; k < n ; k++) for (int i = 0 ; i < n ; i++) for (auto p : G[i]) if (d[k][i] + p.S < d[k + 1][p.F]) d[k + 1][p.F] = d[k][i] + p.S; double ans = INF; for (int i = 0 ; i < n ; i++) { if (fabs(d[n][i] - INF) < EPS) continue; double maxW = -INF; for (int k = 0 ; k < n - 1 ; k++) { maxW = max(maxW, (d[n][i] - d[k][i]) / (n - k)); } ans = min(ans, maxW); } return ans; } int main() { int kase = 0; int t; cin >> t; while (t--) { cout << "Case #" << ++kase << ": "; int n, m; cin >> n >> m; vector<vector<pii > > G(n); while (m--) { int a, b, c; cin >> a >> b >> c; a--, b--; G[a].push_back(MP(b, c)); } double ans = min_mean_cycle(G); if (fabs(ans - INF) < EPS) cout << "No cycle found.\n"; else printf("%f\n", ans + EPS); } }
true
29e6f9b6552d9da74ac4b6298a575bca745c8f6b
C++
davidlove/omrp
/regularized_decomposition/src/history.cpp
UTF-8
5,058
2.6875
3
[]
no_license
/*------------------------------------------------------------------------------ MODULE TYPE: Project core code. PROJECT CODE: Simplex PROJECT FULL NAME: Advanced implementation of revised simplex method for large scale linear problems. MODULE AUTHOR: Artur Swietanowski. PROJECT SUPERVISOR: prof. Andrzej P. Wierzbicki, dr Jacek Gondzio. -------------------------------------------------------------------------------- SOURCE FILE NAME: history.cpp CREATED: 1993.10.24 LAST MODIFIED: 1994.08.16 DEPENDENCIES: history.cpp, stdtype.h, history.h, solvcode.h, error.h <assert.h> -------------------------------------------------------------------------------- SOURCE FILE CONTENTS: x -------------------------------------------------------------------------------- PUBLIC INTERFACE: x STATIC FUNCTIONS: x STATIC DATA: x -------------------------------------------------------------------------------- USED AND THEIR MEANING: XXXXX - x ------------------------------------------------------------------------------*/ #include <assert.h> #ifndef __STDTYPE_H__ # include "stdtype.h" #endif #ifndef __ERROR_H__ # include "error.h" #endif #ifndef __HISTORY_H__ # include "history.h" #endif #ifndef __SOLVCODE_H__ # include "solvcode.h" #endif /*------------------------------------------------------------------------------ Auxiliary class: Class HistoryEvent A single object of this class stores information sufficient to go back one step in history. ------------------------------------------------------------------------------*/ class HistoryEvent { Int_T in, out; HistoryEvent( void ) : in( SLV_HIST_LIST_EMPTY ), out( SLV_HIST_LIST_EMPTY ) {}; friend class History; }; /*------------------------------------------------------------------------------ History::~History( void ) PURPOSE: Class 'History' destructor. Deallocates storage. PARAMETERS: None. RETURN VALUE: None. SIDE EFFECTS: None. ------------------------------------------------------------------------------*/ History::~History( void ) { if( h ) delete [] h; } /*------------------------------------------------------------------------------ void History::ResetHistory( void ) PURPOSE: Clear the history list. PARAMETERS: None. RETURN VALUE: None. SIDE EFFECTS: None. ------------------------------------------------------------------------------*/ void History::ResetHistory( void ) { start = end = 0; empty = True; } /*------------------------------------------------------------------------------ History::History( Int_T hLen ) PURPOSE: Class 'History' constructor. Allocates storage necessary during operation. Initializes the class to represent an empty list. PARAMETERS: Int_T hLen Maximum number of history list entries to be stored. If the limit is exceeded, the oldest entries are removed and replaced with new ones. RETURN VALUE: None. SIDE EFFECTS: None. ------------------------------------------------------------------------------*/ History::History( Int_T hLen ) : start( 0 ), end( 0 ), empty( True ) { assert( hLen > 0 ); h = new HistoryEvent[ len = hLen ]; if( !h ) FatalError( "history.cpp: History: Out of memory" ); } /*------------------------------------------------------------------------------ void History::PushStep( Int_T in, Int_T out ) PURPOSE: Stores pair (in, out) on the list. If necessary removes the oldest entry from the list. The list is accessed as a stack would be (FIFO type access), but is actually a fixed maximum length cyclical list. Therefore when an attempt is made to store more then 'len' entries on the list, an oldest entry is replaced with the new one and the 'start' and 'end' markers are shifted one position. PARAMETERS: Int_T in, Int_T out Data to be stored. RETURN VALUE: None. SIDE EFFECTS: None. ------------------------------------------------------------------------------*/ void History::PushStep( Int_T in, Int_T out ) { if( start == end && !empty ) ( start < len - 1 ) ? start++ : (start = 0); empty = False; h[ end ].in = in; h[ end ].out = out; ( end < len - 1 ) ? end++ : (end = 0); } /*------------------------------------------------------------------------------ Bool_T History::PopStep( Int_T &in, Int_T &out ) PURPOSE: This function retrieves the latest information stored on the history list and removes it from the list. PARAMETERS: Int_T &in, Int_T &out These two parameters are used only to return the information to the caller. Their values on entry is not important. On failure they are both assigned -1. RETURN VALUE: Boolean succes status (True - if an entry was successfully retrieved, False if the list is empty). SIDE EFFECTS: None. ------------------------------------------------------------------------------*/ Bool_T History::PopStep( Int_T &in, Int_T &out ) { if( empty ) { in = out = SLV_HIST_LIST_EMPTY; return False; } if( start == end ) empty = True; else ( end > 0 ) ? end-- : (end = Int_T( len - 1 ) ); in = h[ end ].in; out = h[ end ].out; return True; }
true
3da4abba25d471f55539e1de3918169f6b859625
C++
bwbruno/projeto-lp1
/src/animal_silvestre/animal_exotico.cpp
UTF-8
794
2.546875
3
[ "MIT" ]
permissive
#include "animal_silvestre/animal_exotico.h" using namespace std; // ------------------------------------------------------------------------ // Construtores e destrutor // ------------------------------------------------------------------------ AnimalExotico::AnimalExotico(){ pais_origem = "País não definido"; } // ------------------------------------------------------------------------ // Getters // ------------------------------------------------------------------------ string AnimalExotico::getPaisOrigem(){ return pais_origem; } // ------------------------------------------------------------------------ // Setters // ------------------------------------------------------------------------ void AnimalExotico::setPaisOrigem(string PO){ pais_origem = PO; }
true
ad9c96c6a539ac34cb268cbf523fc440f539e6df
C++
WireLife/FightingCode
/2020备战蓝桥/王浩杰/第十一次作业/11.1.cpp
UTF-8
627
2.9375
3
[]
no_license
#include<iostream> #include<cstdio> #include<conio.h> #include<string> using namespace std; void f() { } int main() { int n=0,a1=0,a2=0,a3=0,a4=0,a5=0; char a='0'; while(a!='\n') { a = cin.get(); if (65 <= a && a <= 90)a1++; else if (97 <= a&& a <= 122)a2++; else if (48 <= a && a <= 57)a3++; else if (a == ' ')a4++; else if (a == '\n'); else a5++; } cout << "大写字母个数:" << a1 << endl; cout << "小写字母个数:" << a2 << endl; cout << "数字个数:" << a3 << endl; cout << "空格个数:" << a4 << endl; cout << "其他个数:" << a5 << endl; system("pause"); return 0; }
true
7b866a70e042ec14ac1ce07c4e9aec358030995f
C++
gshanbhag525/CP_Practice
/FacePrep/TestYourSkill/Strings/SpecialSchool.cpp
UTF-8
1,331
3.90625
4
[]
no_license
#include <iostream> #include <string.h> using namespace std; int main() { char str[50], str1[50], rev[50]; cin >> str >> str1; int size = strlen(str); // Swap character starting from two // corners for (int i = 0; i < size / 2; i++) swap(str[i], str[size - i - 1]); if (strcmp(str1, rev) == 0) cout << "It is correct" << endl; else cout << "It is wrong" << endl; return 0; } /* Special school A special school is run by an NGO for kids with Dyslexia. We all know these children will start writing the letters backward or in reverse. Once special care is taken to correct this issue and once they are introduced to words, they will start writing the words in the proper format. The teachers do not want to discourage the children at the start itself and they have decided to mark the words written in reverse also as correct. Can you please help the teacher in correcting the answer sheets by writing a C++ program? Write a C++ program to check whether the second word is the reverse of the first word. Do not use strrev() function. Input Format: Input consists of 2 strings. Assume that the maximum length of the string is 50. Output format: Refer sample input and output for formatting specifications. Sample input &output Excellent tnellecxE It is correct */
true
c14a79dc80cb8e594ccd3928d0a77102a12f798b
C++
qypluobo/leetcode-solution
/14.Longest_Common_Prefix.cpp
UTF-8
1,441
3.140625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "uthash.h" char * longestCommonPrefix(char ** strs, int strsSize){ if (strsSize <= 0) { return strdup(""); } int i, j; int tmpLen; int minLen = strlen(strs[0]); char cur; char* ans; bool find = false; for (i = 1; i < strsSize; i++) { tmpLen = strlen(strs[i]); minLen = tmpLen < minLen ? tmpLen : minLen; } if (minLen <= 0) { return strdup(""); } for (i = 0; i < minLen; i++) { cur = strs[0][i]; for (j = 1; j < strsSize; j++) { if (cur != strs[j][i]) { find = true; break; } } if (find) { break; } } ans = (char*)malloc(sizeof(char) * (i + 1)); memset(ans, 0, sizeof(char) * (i + 1)); strncpy(ans, strs[0], i); return ans; } void test1() { char str1[] = "flower"; char str2[] = "flow"; char str3[] = "flight"; char* strs[] = { str1, str2, str3 }; char* ans = longestCommonPrefix(strs, 3); printf("%s, %s\n", __func__, ans); } void test2() { char str1[] = "dog"; char str2[] = "racecar"; char str3[] = "car"; char* strs[] = { str1, str2, str3 }; char* ans = longestCommonPrefix(strs, 3); printf("%s, %s\n", __func__, ans); } int main() { test1(); test2(); return 0; }
true
b4aec09734d7795bd69850b7de465b194cf9182c
C++
nksymsym/atcoder
/abc/121/c.cpp
UTF-8
759
2.578125
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stack> #include <queue> using namespace std; typedef long long ll; typedef vector<ll> vll; typedef pair<ll, ll> pr; typedef priority_queue<pr> pq; int main() { ll n, m; cin >> n >> m; vll a(n), b(n); pq q; for (ll i = 0; i < n; i++) { cin >> a[i] >> b[i]; q.push(pr(-a[i], i)); } ll money = 0; ll rest = m; while (rest > 0) { ll i = q.top().second; q.pop(); ll price = a[i]; ll amount = b[i]; if (rest < amount) { amount = rest; } money += price * amount; rest -= amount; } cout << money << endl; return 0; }
true
00aef92056b8d5d0ef3a024cf1ac0a4566bdeaa0
C++
per1234/SirHenry
/examples/example5/example5.ino
UTF-8
1,891
2.6875
3
[]
no_license
#include <Servo.h> #include <NewPing.h> #include <SirHenry.h> /* Sir Henry example5. * By Cobus Truter (20 Jan 2017) * * Demo code for 21 January 2017. * * TODO: Explanation. * */ SirHenry bot; int head_straight = 0; // Head alignment offset int repeat_right = 0; int repeat_left = 0; long rand_num; uint8_t bumper_arr[4]; void setup() { Serial.begin(115200); // Bluetooth module setup to communicate at bot.rotateHead(head_straight); // Reset head bot.colourEye(0,0,0); //White randomSeed(analogRead(0)); } void loop() { if (bot.left_bumper() == 0 || bot.front_bumper() == 0 || bot.rear_bumper() == 0 || bot.right_bumper() == 0){ // IF front or back bumper switch is pressed bot.colourEye(255,0,0); //Red delay(250); } int dist = bot.getDist(); if (dist < 20){ bot.colourEye(40,205,240); //Turquiose blue } else if ((dist >= 20)&&(dist<=45)) { bot.colourEye(240,40,255); //Purpleish } else if ((dist >= 45)&&(dist<=75)) { bot.colourEye(140,255,40); //Yellowish-Green } else{ bot.colourEye(0,0,0); //OFF } if (dist < 10){ bot.rotateHead(head_straight); // Reset head delay(150); if (dist < 10){ rand_num = random(100); if ((rand_num > 49 || repeat_left >= 2) && repeat_right < 2){ repeat_right++; repeat_left = 0; bot.rotateHead(-40); //Turn head right delay(150); dist = bot.getDist(); if (dist < 10){ bot.rotateHead(-75); //Turn head far right delay(150); } } else{ repeat_left++; repeat_right = 0; bot.rotateHead(40); //Turn head left delay(150); dist = bot.getDist(); if (dist < 10){ bot.rotateHead(75); //Turn head far left delay(150); } } }//End first dist sense }//End main IF } // End main
true
7dfc63e387f51be854bf5f4600aa972a2d184a6d
C++
PascualPhil/CSC-5_40107_Winter_2017
/Homework/Assignment_2/Gaddis_8thEd_Ch3_Pr3_TestAverage/main.cpp
UTF-8
1,330
3.734375
4
[]
no_license
/* File: main.cpp Author: Phillip Pascual Created on January 9, 2017, 1:00 PM Purpose: Test average calculator. */ //System Libraries #include <iostream> #include <iomanip> //For setprecision using namespace std; //User Libraries //Global Constants //Such as PI, Vc, -> Math/Science values //as well as conversions from system of units to //another //Function Prototypes //Executable code begins here!!! int main(int argc, char** argv) { //Declare Variables int testOne, //Test 1 score testTwo, //Test 2 score testThr, //Test 3 score testFou, //Test 4 score testFiv; //Test 5 score float avg; //Average of scores 1-5 //Input values cout<<"This program will calculate the average of 5 input test scores."<<endl; cout<<"Enter Test 1 Score:"<<endl; cin>>testOne; cout<<"Enter Test 2 Score:"<<endl; cin>>testTwo; cout<<"Enter Test 3 Score:"<<endl; cin>>testThr; cout<<"Enter Test 4 Score:"<<endl; cin>>testFou; cout<<"Enter Test 5 Score:"<<endl; cin>>testFiv; //Process by mapping inputs to outputs avg=(testOne+testTwo+testThr+testFou+testFiv)/5.0; //Output values cout<<"The average of the five test scores is: "<<fixed<<setprecision(2)<<avg<<"%"<<endl; //Exit stage right! return 0; }
true
da436eeb2db971f2dc0e4c71dc62be8b02ee3bc9
C++
matangeorgi/SuperMario-Bros-1
/src/Enemys/Tortoise.cpp
UTF-8
1,610
2.578125
3
[]
no_license
#include "Tortoise.h" Tortoise::Tortoise(int row, int col) : Enemy(TextureHolder::instance().getEnemy(I_TORTOISE), LEFT, TORTOISE_SIZE, row ,col), m_shell(false), m_jumped(false) { m_sprite.setPosition((float)(col * ICON_SIZE), (float)((row * ICON_SIZE)) + TORTOISE_Y_POS); } //----------------------------------------------------------------------------- void Tortoise::move(sf::Time deltaTime) { if (!m_shell) { sideMove(deltaTime, ENEMY_SPEED); m_animation.staticShift(deltaTime, SWITCH); m_animation.setDirection(m_dir); } else if (m_jumped) sideMove(deltaTime, SHELL_SPEED); if (m_tortoiseKill) handleDeathTortoise(deltaTime); } //----------------------------------------------------------------------------- void Tortoise::setShell() { m_shell = true; m_animation.setDeadSprite(); } //----------------------------------------------------------------------------- bool Tortoise::getShell() const { return m_shell; } //----------------------------------------------------------------------------- void Tortoise::setJumped(bool condition) { m_jumped = condition; } //----------------------------------------------------------------------------- bool Tortoise::getJumped() const { return m_jumped; } //----------------------------------------------------------------------------- void Tortoise::setDirection(float playerPosX) { if (playerPosX > getPos().x) m_dir = LEFT; else m_dir = RIGHT; } //----------------------------------------------------------------------------- Tortoise::~Tortoise() { }
true
4f4b27a5b7cad638745becc3ca82fd80e162bb55
C++
sswroom/SClass
/src/Crypto/Hash/SuperFastHash.cpp
UTF-8
1,304
2.671875
3
[]
no_license
#include "Stdafx.h" #include "MyMemory.h" #include "Crypto/Hash/SuperFastHash.h" #include "Text/MyString.h" extern "C" { UInt32 SuperFastHash_Calc(const UInt8 *buff, UOSInt buffSize, UInt32 currVal); } Crypto::Hash::SuperFastHash::SuperFastHash(UInt32 len) { this->currVal = len; } Crypto::Hash::SuperFastHash::~SuperFastHash() { } UTF8Char *Crypto::Hash::SuperFastHash::GetName(UTF8Char *sbuff) { return Text::StrConcatC(sbuff, UTF8STRC("SuperFastHash")); } Crypto::Hash::IHash *Crypto::Hash::SuperFastHash::Clone() { Crypto::Hash::SuperFastHash *sfh; NEW_CLASS(sfh, Crypto::Hash::SuperFastHash(this->currVal)); return sfh; } void Crypto::Hash::SuperFastHash::Clear() { this->currVal = 0; } void Crypto::Hash::SuperFastHash::Calc(const UInt8 *buff, UOSInt buffSize) { this->currVal = SuperFastHash_Calc(buff, buffSize, this->currVal); } void Crypto::Hash::SuperFastHash::GetValue(UInt8 *buff) { UInt32 hash = this->currVal; hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; *(UInt32*)buff = hash; } UOSInt Crypto::Hash::SuperFastHash::GetBlockSize() { return 4; } UOSInt Crypto::Hash::SuperFastHash::GetResultSize() { return 4; }
true
2cd44862f0c169e7f59ebf6ac1435e7b21097a51
C++
CompaqDisc/chippy
/src/chippy.cc
UTF-8
6,177
2.53125
3
[ "BSD-3-Clause" ]
permissive
#define OLC_PGE_APPLICATION #include <stdint.h> #include "olcPixelGameEngine.h" #include "display.h" #include "chip8.h" #define CANVAS_OFFSET 8 namespace Chippy { class Chippy : public olc::PixelGameEngine { public: enum EmulatorState { STATE_INIT, STATE_MENU, STATE_RUNNING, STATE_EXITING }; Display* display; Chip8* chip; uint16_t n_hexview_base_addr; uint32_t n_emu_state; const char* s_test_fname; Chippy() { this->sAppName = "Chippy"; this->n_emu_state = STATE_INIT; this->n_hexview_base_addr = 0x200; this->display = new Display(); this->chip = new Chip8(); this->s_test_fname = "Pong [Paul Vervalin, 1990].ch8"; } bool OnUserCreate() override { display->init(Display::MODE_CHIP8); chip->setmode(Chip8::MODE_CHIP8); chip->reset(); if (!chip->loadmem(this->s_test_fname)) return false; return true; } bool OnUserUpdate(float fElapsedTime) override { Clear(olc::VERY_DARK_GREY); if (GetKey(olc::Key::ESCAPE).bPressed) { delete display; delete chip; return false; } if (GetKey(olc::Key::PGDN).bHeld) { if (!(n_hexview_base_addr >= (0xfff - 0x1d0))) n_hexview_base_addr += 8; } if (GetKey(olc::Key::PGUP).bHeld) { if (!(n_hexview_base_addr <= 0x000)) n_hexview_base_addr -= 8; } if (GetKey(olc::Key::HOME).bPressed) { display->init(Display::MODE_CHIP8); chip->setmode(Chip8::MODE_CHIP8); chip->reset(); n_emu_state = STATE_INIT; } if (GetKey(olc::Key::END).bPressed) { display->init(Display::MODE_CHIP48); chip->setmode(Chip8::MODE_CHIP48); chip->reset(); n_emu_state = STATE_INIT; } if (GetKey(olc::Key::SPACE).bPressed) { if(!chip->step()) return false; } // If we are in vanilla chip8 mode copy display memory to the display. if (chip->n_current_mode == Chip8::MODE_CHIP8) { for (uint16_t i = 0xf00; i < 0x1000; i++) { display->n_display_buffer_data[i - 0xf00] = chip->n_memory[i]; } } /******** * Oh boy... * * If ya couldn't tell, this takes the bitmapped array * `n_display_buffer_data`, and loops over its bits, * it then scales these 'pixels' by the scalar value onto the canvas. */ for (int n_buffer_idx = 0; n_buffer_idx < display->n_display_buffer_len; n_buffer_idx++) { for (int n_position = 0; n_position < 8; n_position++) { // Ensures most significant bit is leftmost. uint8_t mask = 1 << 7 - n_position; for (int n_offset_x = 0; n_offset_x < display->n_display_scale; n_offset_x++) { for (int n_offset_y = 0; n_offset_y < display->n_display_scale; n_offset_y++) { Draw( (n_buffer_idx * 8 + n_position) % display->n_display_width * display->n_display_scale + n_offset_x + CANVAS_OFFSET, (n_buffer_idx * 8 + n_position) / display->n_display_width * display->n_display_scale + n_offset_y + CANVAS_OFFSET, (display->n_display_buffer_data[n_buffer_idx] & mask) ? olc::GREEN : olc::BLACK ); } // n_offset_y } // n_offset_x } // n_position } // n_buffer_idx // Draw hexview. for (uint16_t pc = n_hexview_base_addr; pc < n_hexview_base_addr + 0x1d0; pc += 8) { char str[32]; sprintf( str, "%03X: %02X %02X %02X %02X %02X %02X %02X %02X", pc, chip->n_memory[pc + 0], chip->n_memory[pc + 1], chip->n_memory[pc + 2], chip->n_memory[pc + 3], chip->n_memory[pc + 4], chip->n_memory[pc + 5], chip->n_memory[pc + 6], chip->n_memory[pc + 7] ); DrawString( display->n_display_width * display->n_display_scale + CANVAS_OFFSET * 2, ((pc - n_hexview_base_addr) + CANVAS_OFFSET), str ); } // Draw scrollbar background. FillRect( display->n_display_width * display->n_display_scale + CANVAS_OFFSET * 30.5, CANVAS_OFFSET, CANVAS_OFFSET / 2, CANVAS_OFFSET * 58, olc::BLACK ); // Draw scrollbar innards. FillRect( display->n_display_width * display->n_display_scale + CANVAS_OFFSET * 30.5, CANVAS_OFFSET + n_hexview_base_addr / 8, CANVAS_OFFSET / 2, CANVAS_OFFSET * 1.25, olc::WHITE ); // Draw dissasembly. for (uint16_t pc = chip->n_program_counter; pc < chip->n_program_counter + 50; pc += 2) { char str[32]; chip->disassemble(str, pc); DrawString( CANVAS_OFFSET, display->n_display_height * display->n_display_scale + CANVAS_OFFSET * ((pc - chip->n_program_counter) / 2 + 2), (pc == chip->n_program_counter) ? "*" : " ", (pc == chip->n_program_counter) ? olc::CYAN : olc::WHITE ); DrawString( CANVAS_OFFSET * 2, display->n_display_height * display->n_display_scale + CANVAS_OFFSET * ((pc - chip->n_program_counter) / 2 + 2), str, (pc == chip->n_program_counter) ? olc::CYAN : olc::WHITE ); } // Draw program counter. { char str[8]; sprintf(str, "PC: %03x", chip->n_program_counter); DrawString( CANVAS_OFFSET * 23, display->n_display_height * display->n_display_scale + CANVAS_OFFSET * 2, str ); } // Draw I register contents. { char str[12]; sprintf(str, "I : %03x", chip->n_i_register); DrawString( CANVAS_OFFSET * 23, display->n_display_height * display->n_display_scale + CANVAS_OFFSET * 3, str ); } // Draw stack pointer. { char str[8]; sprintf(str, "SP: %02x", chip->n_stack_pointer); DrawString( CANVAS_OFFSET * 23, display->n_display_height * display->n_display_scale + CANVAS_OFFSET * 4, str ); } // Draw generic register contents. for (uint16_t i = 0; i < 16; i++) { char str[12]; sprintf(str, "V[%X]: %02X", i, chip->n_register[i]); DrawString( CANVAS_OFFSET * 23, display->n_display_height * display->n_display_scale + CANVAS_OFFSET * (i + 11), str ); } return true; } }; } int main(int argc, char** argv) { Chippy::Chippy* emulator = new Chippy::Chippy(); if (emulator->Construct(768, 480, 1, 1, false)) emulator->Start(); return 0; }
true
eb05ff51cfbcf316e27b3574b8f28c4c785a9cef
C++
artheadsweden/cpp_fund_mar_2021
/day1/dynamic.cpp
UTF-8
208
2.734375
3
[]
no_license
#include <iostream> using namespace std; int main() { { int x = 10; } { int* ip = new int; *ip = 20; cout << *ip << endl; delete ip; } return 0; }
true
fa739316ccdfb8d2f2f0923931f7892cd460c6de
C++
rmoswela/cppBootcamp
/day04/ex01/SuperMutant.hpp
UTF-8
323
2.734375
3
[]
no_license
#ifndef SUPERMUTANT_HPP #define SUPERMUTANT_HPP #include "Enemy.hpp" class SuperMutant : public Enemy { public: SuperMutant(void); ~SuperMutant(void); SuperMutant(SuperMutant const & target); SuperMutant &operator=(SuperMutant const & target); virtual void takeDamage(int amount); }; #endif
true
ad8a6a006c3fe5d0d04fca157080660b03fbd1de
C++
Batishavo/codeforces
/A. Splitting into digits.cpp
UTF-8
223
2.765625
3
[]
no_license
#include<cstdio> int n,num; int main(){ scanf("%d",&n); for(int i=9;i>=1;i--){ if(n%i==0){ num=i; break; } } printf("%d\n",n/num); while(n>0){ n-=num; printf("%d ",num); } return 0; }
true
1a954567b95173fd6a6f419350e7fee65432c390
C++
nonocodebox/computer-graphics
/ex3-ray-tracing/polygon.h
UTF-8
2,739
3.25
3
[]
no_license
// // polygon.h // cg-projects // // Created by HUJI Computer Graphics course staff, 2012-2013. // Purpose : A class that represents a convex polygon on the 3d space. // Inherits from Object class, implementing the method to // test intersection of a given ray with the polygon. // #ifndef _POLYGON_HH #define _POLYGON_HH ////////////////////////////// // Library Includes // ////////////////////////////// #include <vector> ////////////////////////////// // Project Includes // ////////////////////////////// #include "general.h" #include "object.h" #include "triangle.h" ////////////////////////////// // Class Decleration // ////////////////////////////// using namespace std; class Polygon : public Object { public: // Creates a default polygon Polygon(); // Gets rid of a polygon virtual ~Polygon(); // Creates a polygon from the given vertices Polygon(vector<Point3d> & vertices); // Creates a polygon from the given vertices, using the given normal Polygon(vector<Point3d> & vertices, Vector3d & normal); // Creates a polygon from the given vertices, using the given texture map coordinates Polygon(vector<Point3d> & vertices, vector<Point2d> textices); // Creates a polygon from the given vertices, using the given normal and texture map coordintes Polygon(vector<Point3d> & vertices, vector<Point2d> textices, Vector3d & normal); // Ray intersection with the convex polygon virtual int intersect(IN Ray& ray, IN double tMax, OUT double& t, OUT Point3d& P, OUT Vector3d& N, OUT Color3d& texColor, IN bool nearest = true); // Returns the color of the object at point P according to the texture map virtual Color3d texture_diffuse(const Point3d& P) const; // Returns a bounding box for the object virtual const BoundingBox & getBoundingBox() const; private: // Triangulate the polygon into triangles void triangulate(); // Calculate the polygon's normal void calculateNormal(); // Create the polygon's bounding box void createBoundingBox(); // Ray intersection with a plane int intersectPlane(IN Ray& ray, IN double tMax, OUT double& t, OUT Point3d& P); private: vector<Point3d> _vertices; // The polygon's vertices vector<Point2d> _textices; // The polygon's texture map coordinates Vector3d _normal; // The polygon's normal bool _textured; // Does the polygon have a texture map coordinates vector<Triangle*> _triangles; // The polygon's triangles BoundingBox _boundingBox; // The polygon's bounding box }; #endif /* _POLYGON_HH */
true
5a2a1440d21d3e552c4fb8ec29272150ac2f221f
C++
yingziyu-llt/OI
/c/杂项/评分系统.cpp
GB18030
1,331
2.59375
3
[]
no_license
#include<stdio.h> //ϵͳ int main() { int a[12][6],i,j,max[12],min[12];//ans[a][x] a=0ave[x] a=1: a=2 float ave[12]={0},b[12],temp,ans[3][12]; freopen(".in","r",stdin); freopen("ֽ.ans","w",stdout); for(i=0;i<12;i++) { for(j=0;j<6;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<12;i++) { max[i]=0; min[i]=120; for(j=0;j<6;j++) { if(max[i]<a[i][j]) max[i]=a[i][j]; if(min[i]>a[i][j]) min[i]=a[i][j]; } ave[i]=(double)(a[i][0]+a[i][1]+a[i][2]+a[i][3]+a[i][4]+a[i][5]-max[i]-min[i])/4.0; } for(i=0;i<12;i++) b[i]=ave[i]; for(i=0;i<12;i++) { for(j=i+1;j<12;j++) { if(b[i]<b[j]) { temp=b[i]; b[i]=b[j]; b[j]=temp; } } } for(i=0;i<12;i++) { ans[0][i]=ave[i]; for(j=0;j<12;j++) { if(ave[i]==b[j]) {ans[1][i]=j+1;break;} } if(ans[1][i]==1) ans[2][i]=1; else if(ans[1][i]<=3) ans[2][i]=2; else if(ans[1][i]<=5) ans[2][i]=3; else ans[2][i]=4; } for(i=0;i<3;i++) { for(j=0;j<4;j++) { printf("%d꼶%d %d %d %.3lf %.0lf %.0lf\n",i+7,j+1,max[i*4+j],min[i*4+j],ans[0][i*4+j],ans[1][i*4+j],ans[2][i*4+j]); temp=i*4+j; } } fclose(stdin); fclose(stdout); return 0; }
true
74b290b6f74393f8aaf381f48b0a4321eddc3258
C++
kuflex/ofxKu
/src/ofxKuDrawUtils.cpp
UTF-8
426
2.625
3
[]
no_license
#include "ofxKuDrawUtils.h" //-------------------------------------------------------------- void ofxKuDrawTextureFit(ofTexture &tex, float x, float y, float w, float h) { float tw = tex.getWidth(); float th = tex.getHeight(); if (tw>0 && th>0) { float scl = min(w/tw,h/th); tw *= scl; th *= scl; tex.draw(x+w/2-tw/2, y+h/2-th/2, tw, th); } } //--------------------------------------------------------------
true
066133ae420994a6af867e106a589f5492d34b96
C++
CMilby/Game_Engine
/Game_Engine/Core/Math/math3d.h
UTF-8
9,490
2.875
3
[]
no_license
// // math3d.h // Game_Engine_New // // Created by Craig Milby on 10/14/16. // Copyright © 2016 Craig Milby. All rights reserved. // #ifndef __MATH3D_H__ #define __MATH3D_H__ #include <cmath> #include "matrix.h" #include "quaternion.h" #include "vector.h" #define ToRadian(x) (float)(((x) * 3.1415926536f / 180.0f)) #define ToDegree(x) (float)(((x) * 180.0f / 3.1415926536f)) namespace Math3D { template<class T> inline T Clamp( const T &value, const T &min, const T &max ) { if ( value > max ) { return max; } if ( value < min ) { return min; } return value; } template<class T> inline T Distance( const Vector3<T> &vect1, const Vector3<T> &vect2 ) { return sqrtf( powf( vect2.GetX() - vect1.GetX(), 2.0f ) + powf( vect2.GetY() - vect1.GetY(), 2.0f ) + powf( vect2.GetZ() - vect1.GetZ(), 2.0f ) ); } template<class T> inline Vector3<T> Midpoint( const Vector3<T> &p_v1, const Vector3<T> &p_v2 ) { return Vector3<T>( ( p_v1.GetX() + p_v2.GetX() ) / T( 2 ), ( p_v1.GetY() + p_v2.GetY() ) / T( 2 ), ( p_v1.GetZ() + p_v2.GetZ() ) / T( 2 ) ); } inline int FastFloor( const float x ) { return x > 0 ? ( int ) x : ( int ) x - 1 ; } inline float Dot( const int *pG, const float pX, const float pY ) { return pG[ 0 ] * pX + pG[ 1 ] * pY; } inline float Dot( const int *g, const float x, const float y, const float z ) { return g[ 0 ] * x + g[ 1 ] * y + g[ 2 ] * z; } inline float Scale( const float x, const float a, const float b, const float min, const float max ) { return ( ( ( b - a ) * ( x - min ) ) / ( max - min ) ) + a; } inline float Max( const float pX, const float pY ) { if ( pX > pY ) { return pX; } return pY; } inline float Min( const float x, const float y ) { if ( x < y ) return x; return y; } inline bool IsPointWithinCone( const Vector3<float> &pConeTipPosition, const Vector3<float> &pConeCenterLine, const Vector3<float> &pPoint, const float pFOVRadians ) { Vector3<float> myDifferenceVector = pPoint - pConeTipPosition; myDifferenceVector = myDifferenceVector.Normalized(); return ( pConeCenterLine.Dot( myDifferenceVector ) >= cos( pFOVRadians ) ); } inline Quaternion LookAt( const Vector3<float> &pSourcePoint, const Vector3<float> &pDestPoint ) { Vector3<float> forwardVector = ( pDestPoint - pSourcePoint ).Normalized(); float dot = Vector3<float>( 0.0f, 0.0f, -1.0f ).Dot( forwardVector ); if ( fabsf( dot - ( -1.0f ) ) < 0.000001f ) { return Quaternion( Vector3<float>( 0.0f, 1.0f, 0.0f ), M_PI); } if ( fabsf( dot - ( 1.0f ) ) < 0.000001f ) { return Quaternion( 0.0f, 0.0f, 0.0f, 1.0f ); } float rotAngle = ( float ) acosf(dot); Vector3<float> rotAxis = Vector3<float>( 0.0f, 0.0f, -1.0f ).Cross( forwardVector ); rotAxis = rotAxis.Normalized(); return Quaternion( rotAxis, rotAngle ); } inline Vector2<float> RotatePoint( const Vector2<float> &pPoint, const Vector2<float> &pCenter, float pAngle ) { pAngle = ToRadian( pAngle ); float s = sinf( pAngle ); float c = cosf( pAngle ); Vector2<float> myPoint( pPoint.GetX() - pCenter.GetX(), pPoint.GetY() - pCenter.GetY() ); float xNew = myPoint.GetX() * c - myPoint.GetY() * s; float yNew = myPoint.GetX() * s + myPoint.GetY() * c; myPoint.SetX( xNew + pCenter.GetX() ); myPoint.SetY( yNew + pCenter.GetY() ); return myPoint; } inline float AngleBetween( const Vector2<float> &pPoint1, const Vector2<float> &pPoint2 ) { return atan2f( pPoint1.GetY() - pPoint2.GetY(), pPoint1.GetX() - pPoint2.GetX() ); } // Code From... // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf inline void InvertMatrix( float *mat, float *dst ) { float tmp[ 12 ]; /* temp array for pairs */ float src[ 16 ]; /* array of transpose source matrix */ float det; /* determinant */ /* transpose matrix */ for ( unsigned int i = 0; i < 4; i++ ) { src[ i ] = mat[ i * 4 ]; src[ i + 4 ] = mat[ i * 4 + 1 ]; src[ i + 8 ] = mat[ i * 4 + 2 ]; src[ i + 12 ] = mat[ i * 4 + 3 ]; } /* calculate pairs for first 8 elements (cofactors) */ tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; /* calculate first 8 elements (cofactors) */ dst[0] = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7]; dst[0] -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7]; dst[1] = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7]; dst[1] -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7]; dst[2] = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7]; dst[2] -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7]; dst[3] = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6]; dst[3] -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6]; dst[4] = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3]; dst[4] -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3]; dst[5] = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3]; dst[5] -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3]; dst[6] = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3]; dst[6] -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3]; dst[7] = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2]; dst[7] -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2]; /* calculate pairs for second 8 elements (cofactors) */ tmp[0] = src[2]*src[7]; tmp[1] = src[3]*src[6]; tmp[2] = src[1]*src[7]; tmp[3] = src[3]*src[5]; tmp[4] = src[1]*src[6]; tmp[5] = src[2]*src[5]; tmp[6] = src[0]*src[7]; tmp[7] = src[3]*src[4]; tmp[8] = src[0]*src[6]; tmp[9] = src[2]*src[4]; tmp[10] = src[0]*src[5]; tmp[11] = src[1]*src[4]; /* calculate second 8 elements (cofactors) */ dst[8] = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15]; dst[8] -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15]; dst[9] = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15]; dst[9] -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15]; dst[10] = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15]; dst[10]-= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15]; dst[11] = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14]; dst[11]-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14]; dst[12] = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9]; dst[12]-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10]; dst[13] = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10]; dst[13]-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8]; dst[14] = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8]; dst[14]-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9]; dst[15] = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9]; dst[15]-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8]; /* calculate determinant */ det=src[0]*dst[0]+src[1]*dst[1]+src[2]*dst[2]+src[3]*dst[3]; /* calculate matrix inverse */ det = 1/det; for (int j = 0; j < 16; j++) dst[j] *= det; } template<class T> inline Matrix4<T> Matrix4FromPointer( float *mat ) { Matrix4<T> mat4; for ( unsigned int i = 0; i < 16; i++ ) { mat4[ i % 4 ][ i / 4 ] = mat[ i ]; } return mat4; } inline Vector3<float> Rotate( const Vector3<float> &vect, const Quaternion &quat ) { Quaternion w = quat * vect * quat.Conjugate(); return Vector3<float>( w.GetX(), w.GetY(), w.GetZ() ); } inline Vector3<float> Rotate( const Vector3<float> &vect, float angle, const Vector3<float> &axis ) { return Math3D::Rotate( vect, Quaternion( axis, angle ) ); } inline void SetBit( uint64_t &number, uint64_t bit, uint64_t x ) { number ^= ( -x ^ number ) & ( 1ULL << bit ); } inline unsigned int GetBit( uint64_t number, uint64_t bit ) { return ( number >> bit ) & 1ULL; } inline uint64_t GetBits( uint64_t number, unsigned int a, unsigned int b ) { uint64_t r = 0; for ( unsigned i = a; i <= b; i++ ) { Math3D::SetBit( r, i, Math3D::GetBit( number, i ) ); } return r >> a; } inline void SetBits( uint64_t &number, uint64_t mask, unsigned int a, unsigned int b ) { for ( unsigned int i = a; i <= b; i++ ) { SetBit( number, i, GetBit( mask, i - a ) ); } } } #endif /* math3d_h */
true
172768276604772dde914b3fed58c46496a369ec
C++
mugisaku/gamebaby-20170912-dumped
/rogie/rogie_piece__autoplay.cpp
UTF-8
3,193
2.8125
3
[]
no_license
#include"rogie_piece.hpp" #include"rogie_field.hpp" void Piece:: autoplay() { if(action_currency > 0) { for(auto cb: callback_list) { (this->*cb)(); if(own_task.callback || task_stack.size()) { return; } } action_currency = 0; } } void Piece:: chase_hero() { auto hero = current_field->master; if(!hero) { return; } hero->current_square->search(this); Direction d; Square* candidate = nullptr; for(int i = 0; i < number_of_directions; ++i) { auto ln = current_square->link[i]; if(ln && !ln->current_piece) { if(!candidate || (ln->distance < candidate->distance)) { candidate = ln; d = static_cast<Direction>(i); } } } if(candidate) { if(d == direction) { own_task = Task(move_to_direction); } else { auto l = get_left( direction); auto r = get_right(direction); auto l_dist = get_distance(d,l); auto r_dist = get_distance(d,r); if(l_dist < r_dist){own_task = Task(turn_left );} else {own_task = Task(turn_right);} } } } void Piece:: runaway_from_hero() { auto hero = current_field->master; if(!hero) { return; } hero->current_square->search(this); Direction d; Square* candidate = nullptr; for(int i = 0; i < number_of_directions; ++i) { auto ln = current_square->link[i]; if(ln && !ln->current_piece) { if(!candidate || (ln->distance > candidate->distance)) { candidate = ln; d = static_cast<Direction>(i); } } } if(candidate) { if(d == direction) { own_task = Task(move_to_direction); } else { auto l = get_left( direction); auto r = get_right(direction); auto l_dist = get_distance(d,l); auto r_dist = get_distance(d,r); if(l_dist < r_dist){own_task = Task(turn_left );} else {own_task = Task(turn_right);} } } } void Piece:: attack_hero() { auto hero = current_field->master; if(!hero) { return; } Direction d; Square* sq = nullptr; for(int i = 0; i < number_of_directions; ++i) { auto ln = current_square->link[i]; if(ln && (ln->current_piece == hero)) { sq = ln; d = static_cast<Direction>(i); break; } } if(sq) { if(d == direction) { own_task = Task(use_weapon); } else { auto l = get_left( direction); auto r = get_right(direction); auto l_dist = get_distance(d,l); auto r_dist = get_distance(d,r); if(l_dist < r_dist){own_task = Task(turn_left );} else {own_task = Task(turn_right);} } } }
true
c5d25102972eeb503d7d8580adf57db21cb152fe
C++
xSpacklesx/CSI230-lab10.2
/src/earth_utils.cpp
UTF-8
1,710
2.71875
3
[]
no_license
//Author: Hunter Spack //File: earth_utils.cpp //Breif: defines functions #include "earth_utils.h" #include <sstream> int processCSV(std::ifstream& inFile, std::string kmlFileName) { int recordsWrit = 0; std::string strCountry, strCapital, strLat, strLong, strName; std::string strLine; std::ofstream kmlOut; kmlOut.open(kmlFileName, std::ios_base::app); if (kmlOut) { kmlOut << KMLHEADER; } kmlOut.close(); if (inFile) { std::getline(inFile, strLine); while(std::getline(inFile, strLine)) { std::stringstream s_stream(strLine); std::getline(s_stream, strCountry, ','); std::getline(s_stream, strCapital, ','); std::getline(s_stream, strLat, ','); std::getline(s_stream, strLong, ','); strName = strCapital + ", " + strCountry; kmlOut.open(kmlFileName, std::ios_base::app); if (kmlOut) { writePlacemark(kmlOut,strName, strLat, strLong); recordsWrit++; } kmlOut.close(); } kmlOut.open(kmlFileName, std::ios_base::app); if (kmlOut) { kmlOut << KMLFOOTER; } kmlOut.close(); return recordsWrit; } else { return recordsWrit; } } void writePlacemark(std::ofstream& kmlFile, std::string name, std::string latitude, std::string longitutde) { kmlFile << "<Placemark>\n"; kmlFile << "<name>" << name << "</name>\n"; kmlFile << "<Point><coordinates>" << longitutde << "," << latitude << "</coordinates></Point>\n"; kmlFile << "</Placemark>\n"; }
true
6c79f0b9d556f8a492c889c6e6054c289907d54e
C++
QuanHBui/OpenGL-Compute
/src/PrototypePhysicsEngine/P3CpuNarrowPhase.h
UTF-8
2,059
2.578125
3
[ "MIT" ]
permissive
/** * 3D Triangle-triangle intersection test * There are 2 special cases to worry about: (1) Degenerate tri input, (2) coplanar tri-tri * * @author: Quan Bui * @version: 04/28/2020 * @reference: Tomas Moller, "A Fast Triangle-Triangle Intersection Test" * https://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/pubs/tritri.pdf */ #pragma once #ifndef P3_CPU_NARROW_PHASE_H #define P3_CPU_NARROW_PHASE_H #include <glm/glm.hpp> #include "P3NarrowPhaseCommon.h" struct BoxColliderGpuPackage; struct CollisionPairGpuPackage; struct ManifoldGpuPackage; bool coplanarTriTriTest(glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &); bool fastTriTriIntersect3DTest(glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &); void computeIntersectInterval(float, float, float, float, float, float, float, float, float &, float &, bool &); bool edgeEdgeTest(glm::vec3 const &, glm::vec3 const &, glm::vec3 const &); bool edgeTriTest(glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &); bool pointInTriTest(glm::vec3 const &, glm::vec3 const &, glm::vec3 const &, glm::vec3 const &); namespace P3 { class CpuNarrowPhase { public: void init() { mpManifoldPkg[0] = new ManifoldGpuPackage(); mpManifoldPkg[1] = new ManifoldGpuPackage(); } ManifoldGpuPackage *step(BoxColliderGpuPackage const &, const CollisionPairGpuPackage *); ManifoldGpuPackage *getPManifoldPkg() { return mpManifoldPkg[mFrontBufferIdx]; } ManifoldGpuPackage *getPBackManifoldPkg() { return mpManifoldPkg[!mFrontBufferIdx]; } void swapBuffers() { mFrontBufferIdx = !mFrontBufferIdx; } ~CpuNarrowPhase() { delete mpManifoldPkg[0]; delete mpManifoldPkg[1]; } private: ManifoldGpuPackage *mpManifoldPkg[2]; int mFrontBufferIdx = 0; }; } #endif // P3_CPU_NARROW_PHASE_H
true
80c1c6c3eb917f984c0da10cbf1e3a0072ee6f3e
C++
maple-ysd/data_structure_and_algorithm
/Sort/PrimarySort/main.cpp
GB18030
2,619
3.6875
4
[]
no_license
#include <iostream> #include <string> #include <ctime> #include <random> #include "PrimarySort.h" using namespace std; // Եʱ clock_t runTime(string str, double *arr, int n) { char c; if (str == "selectSort") c = 's'; else if (str == "insertSort") c = 'i'; else if (str == "insertSortWithSentinel") c = 'b'; else if (str == "insertSortWithSentinel2") c = 'B'; clock_t start = clock(); switch (c) { case 's': selectSort(arr, n); case 'i': insertSort(arr, n); case 'b': insertSortWithSentinel(arr, n); case 'B': insertSortWithSentinel2(arr, n); } clock_t duration = clock() - start; return duration; // return 1.0 * duration / CLOCKS_PER_SEC; // in seconds } // Tʱ double repeat(string str, double *arr, int n, int T) { default_random_engine e(time(0)); uniform_real_distribution<double> u(-100000, 100000); clock_t total = 0.0; for (int i = 0; i < T; ++i) { for (int j = 0; j < n; ++j) { arr[i] = u(e); }; // // // for (int i = 0, j = n; i < n; ++i, --j) // arr[i] = j; total += runTime(str, arr, n); } return 1.0 * total / CLOCKS_PER_SEC; } int main() { int n, t; cout << "please enter the size of array to be sorted, and how many times you want to repeat:\n"; cin >> n >> t; double arr[n]; // double t2 = repeat("insertSort", arr, n, t); // cout << "insert sort time: " << t2 << endl; //// double t1 = repeat("selectSort", arr, n, t); //// cout << "select sort time: " << t1 << endl; // // // ڱ // double t3 = repeat("insertSortWithSentinel", arr, n, t); // cout << "insert sort with sentinel: " << t3 << endl; // // // // һλ潻 // double t4 = repeat("insertSortWithSentinel2", arr, n, t); // cout << "insert sort with sentinel2: " << t4 << endl; // ȣbernoulli_distribution0 1 default_random_engine e(time(0)); bernoulli_distribution bd(0.5); double tot5 = 0.0; double tot6 = 0.0; for (int i = 0; i < t; ++i) { for (int i = 0; i < n; ++i) arr[i] = bd(e); tot5 += runTime("selectSort", arr, n); } cout << "select sort time: " << tot5 / CLOCKS_PER_SEC << endl; for (int i = 0; i < t; ++i) { for (int i = 0; i < n; ++i) arr[i] = bd(e); tot6 += runTime("insertSort", arr, n); } cout << "insert sort time: " << tot6 / CLOCKS_PER_SEC << endl; return 0; }
true
192d8ba1eae080f8a1537e601363bee99f4c142f
C++
sauravstark/Preparations
/013 - Sum Tree.cpp
UTF-8
927
3.390625
3
[]
no_license
#include <tuple> struct Node { int data; Node *left, *right; }; std::tuple<int, bool> sumTree(Node* root) { if (root == nullptr) return std::make_tuple(0, true); else if ((root->left == nullptr) && (root->right == nullptr)) return std::make_tuple(root->data, true); auto left_tuple = sumTree(root->left); auto right_tuple = sumTree(root->right); int left_sum = std::get<0>(left_tuple); int right_sum = std::get<0>(right_tuple); bool is_left_sum = std::get<1>(left_tuple); bool is_right_sum = std::get<1>(right_tuple); int sum = root->data + left_sum + right_sum; bool is_sum = is_left_sum && is_right_sum && (root->data == left_sum + right_sum); return std::make_tuple(sum, is_sum); } // Should return true if tree is Sum Tree, else false bool isSumTree(Node* root) { // Your code here return std::get<1>(sumTree(root)); }
true
209dc1cc5822253c00de52d5e6bc14b6b4dadf72
C++
CJHMPower/Fetch_Leetcode
/data/Submission/240 Search a 2D Matrix II/Search a 2D Matrix II_1.cpp
UTF-8
927
3.140625
3
[]
no_license
//-*- coding:utf-8 -*- // Generated by the Fetch-Leetcode project on the Github // https://github.com/CJHMPower/Fetch-Leetcode/ // 240 Search a 2D Matrix II // https://leetcode.com//problems/search-a-2d-matrix-ii/description/ // Fetched at 2018-07-24 // Submitted 2 years ago // Runtime: 212 ms // This solution defeats 10.18% cpp solutions class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty()) { return false; } const int m = matrix.size(); const int n = matrix[0].size(); int inx = 0, iny = n - 1; while (true) { if (matrix[inx][iny] == target) { return true; } if (matrix[inx][iny] > target) { if (iny == 0) { return false; } else iny--; } else { if (inx >= m - 1) { return false; } else inx++; } } return false; } };
true
244db96c5d2bf5d147a2dd15a00a405f1ff0b694
C++
Olysold/ArenaShooter-SFML
/extlibs/Thor/include/Thor/Particles/ParticleInterfaces.hpp
UTF-8
4,108
2.5625
3
[ "Zlib" ]
permissive
///////////////////////////////////////////////////////////////////////////////// // // Thor C++ Library // Copyright (c) 2011-2013 Jan Haller // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////// /// @file /// @brief Interfaces thor::Emitter, thor::Affector #ifndef THOR_PARTICLEINTERFACES_HPP #define THOR_PARTICLEINTERFACES_HPP #include <Thor/Config.hpp> #include <memory> #include <SFML/System/Time.hpp> namespace thor { class Particle; /// @addtogroup Particles /// @{ /// @brief Abstract base class for particle affectors. /// @details Affectors are classes that influence emitted particles over time. /// @n Inherit from this class and override affect() to implement custom affectors. class THOR_API Affector { // --------------------------------------------------------------------------------------------------------------------------- // Public types public: /// @brief Shared pointer type referring to derivates of Affector /// typedef std::shared_ptr<Affector> Ptr; // --------------------------------------------------------------------------------------------------------------------------- // Public member functions public: /// @brief Virtual destructor /// virtual ~Affector(); /// @brief Affects particles. /// @param particle The particle currently being affected. /// @param dt Time interval during which particles are affected. virtual void affect(Particle& particle, sf::Time dt) = 0; }; /// @brief Abstract base class for particle emitters. /// @details Emitters are classes which create particles (using particular initial conditions) and insert them into a particle system. /// @n Inherit from this class and override emit() to implement custom emitters. class THOR_API Emitter { // --------------------------------------------------------------------------------------------------------------------------- // Public types public: /// @brief Shared pointer type referring to derivates of Emitter /// typedef std::shared_ptr<Emitter> Ptr; /// @brief Class that connects emitters with their corresponding particle system. /// @details Provides a virtual method that adds particles to the system. struct THOR_API Adder { /// @brief Virtual destructor /// virtual ~Adder() {} /// @brief Adds a particle to the system. /// @param particle Particle to add. virtual void addParticle(const Particle& particle) = 0; }; // --------------------------------------------------------------------------------------------------------------------------- // Public member functions public: /// @brief Virtual destructor /// virtual ~Emitter(); /// @brief Emits particles into a particle system. /// @details Override this method in your emitter class to implement your own functionality. If your emitter /// does only emit the particles in a different area, you should have a look at RandomOffset(). /// @param system Indirection to the particle system that stores the particles. /// @param dt Time interval during which particles are emitted. virtual void emit(Adder& system, sf::Time dt) = 0; }; /// @} } // namespace thor #endif // THOR_PARTICLEINTERFACES_HPP
true
3f614f0dcf5f7ef1fe2b0a58e6ada1d79e878858
C++
tallerify/app-server
/src/api/domain/Track.cpp
UTF-8
277
2.5625
3
[]
no_license
#include "Track.h" #include <ostream> Track::Track(int id, std::string fileLocation) : id(id), fileLocation(fileLocation) { } Track::~Track() { } int Track::getId() const { return id; } const std::string &Track::getFileLocation() const { return fileLocation; }
true
a8c1f590f82130b7ecc192556bdddb7e59aa6024
C++
glennychen/cp3
/leetcode/sink/2114.cpp
UTF-8
651
3.40625
3
[]
no_license
//https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/ #include <string> #include <vector> #include <cctype> #include <sstream> using namespace std; class Solution { public: int mostWordsFound(vector<string>& sentences) { int max_words=0; for(const auto& elem: sentences){ int count=0; string word; stringstream ss(elem); while(ss>>word){ ++count; } max_words=max(max_words, count); ss.clear(); } return max_words; } }; int main() { Solution s; vector<string> v{"alice and bob love leetcode", "i think so too", "this is great thanks very much"}; s.mostWordsFound(v); return 0; }
true
d57e53d27163d00555c1afb2e7a12f3a0f09dc07
C++
dhanendraverma/InterviewBit-Solutions
/Flip.cpp
UTF-8
1,122
3.484375
3
[]
no_license
vector<int> Solution::flip(string A) { int count = 0, maxcount = 0, left=-1, right, ansleft=0, ansright=0; int n = A.length(); vector<int> ans; for(int i=0;i<n;i++) { if(A[i]=='0') //whenevr encounter '0' increase the count of substring having 0 and set the right index at which //we are getting that count { if(left<0) left = i+1; right = i+1; count++; } else count--; //whenever encounter 0 decrease count is rthe sequece if(count<0) //when count goes below 0 means there are more no of ones in the substring so reset the left //index to start again { count = 0; left = -1; } if(maxcount < count) //keep track of longest substring { ansleft = left; ansright = right; maxcount = count; } } if(ansleft>0) { ans.push_back(ansleft); ans.push_back(ansright); } return ans; }
true
0054f63cd3352bf9dc07e0d5fea93a0b05af38bb
C++
lemon123456/ksc-archive
/cs225/CProgAss04A_PetroulesJ/GridFormatter.cpp
UTF-8
5,665
3.203125
3
[]
no_license
/* * File: GridFormatter.cpp * Author: Jake Petroules * * Created on February 22, 2011, 11:21 AM */ #include "GridFormatter.h" #include <cstdarg> #include <algorithm> #include <cctype> GridFormatter::GridFormatter(int columns) : m_columnCount(columns), m_padding(2), m_nullDisplayText(""), m_upperCaseHeaders(true) { if (columns <= 0) { // columns must be greater than 0. throw new exception(); } } GridFormatter::GridFormatter(const vector<string> headers) : m_columnCount(headers.size()), m_padding(2), m_nullDisplayText(""), m_upperCaseHeaders(true) { if (this->m_columnCount <= 0) { // columns must be greater than 0. throw new exception(); } this->setHeader(headers); } GridFormatter::~GridFormatter() { } int GridFormatter::columnCount() const { return this->m_columnCount; } int GridFormatter::padding() const { return this->m_padding; } void GridFormatter::setPadding(int padding) { this->m_padding = padding; } string GridFormatter::nullDisplayText() const { return this->m_nullDisplayText; } void GridFormatter::setNullDisplayText(string text) { this->m_nullDisplayText = text; } bool GridFormatter::isUpperCaseHeaders() const { return this->m_upperCaseHeaders; } void GridFormatter::setUpperCaseHeaders(bool upperCaseHeaders) { this->m_upperCaseHeaders = upperCaseHeaders; } const vector<string> GridFormatter::header() const { return this->m_header; } void GridFormatter::setHeader(const vector<string> headers) { if (headers.size() != this->columnCount()) { // Length of argument list must be equal to the column count. throw new exception(); } for (int i = 0; i < headers.size(); i++) { if (headers.at(i) == "") { // Header labels cannot be null or be the empty string. throw new exception(); } } this->m_header = headers; } void GridFormatter::addRow(const vector<string> data) { if (data.size() != this->columnCount()) { // Length of argument list must be equal to the column count. throw new exception(); } this->m_rows.push_back(data); } string GridFormatter::toString() const { // Create an array to store the longest lengths of each column int maxColumnLengths[this->columnCount()]; // We'll initialize this array with the header lengths, // if there is a header. We need two arrays so we can // later determine how many tabs to print after each // header label if (this->header().size() > 0) { for (int i = 0; i < this->columnCount(); i++) { int headerLength = this->header()[i].length() + this->padding(); maxColumnLengths[i] = headerLength; } } // Loop through each row in the table to determine // the maximum length for each column for (int i = 0; i < this->m_rows.size(); i++) { // Loop through each column in the table, determining // whether to update the max for each one for (int j = 0; j < this->columnCount(); j++) { // Get the row we're working with vector<string> row = this->m_rows.at(i); // Get the column data length - initially it's zero, // and if we determine that is is not null, we get // its length and set that int columnDataLength = this->nullDisplayText().length() + this->padding(); if (row.at(j) != "") { columnDataLength = row[j].length() + this->padding(); } // If the column data in this row is longer than the // current maximum corresponding column length, replace it if (columnDataLength > maxColumnLengths[j]) { maxColumnLengths[j] = columnDataLength; } } } // Now that we've determined the maximum lengths required // for each column, we can begin printing the table, but // first we should determine the max length of any row int sumOfColumnLengths = 0; for (int i = 0; i < this->columnCount(); i++) { sumOfColumnLengths += maxColumnLengths[i]; } string returnData; // Start with the header for (int i = 0; i < this->columnCount(); i++) { string currentHeader = this->header()[i]; if (this->isUpperCaseHeaders()) { std::transform(currentHeader.begin(), currentHeader.end(), currentHeader.begin(), (int(*)(int)) std::toupper); } this->appendWithPadding(returnData, currentHeader, maxColumnLengths[i]); } // Add a newline after the header returnData.append("\n"); for (int i = 0; i < this->m_rows.size(); i++) { for (int j = 0; j < this->columnCount(); j++) { this->appendWithPadding(returnData, this->m_rows.at(i)[j], maxColumnLengths[j]); } // Add a newline after each row returnData.append("\n"); } return returnData; } void GridFormatter::appendWithPadding(string &builder, string data, int maxFieldLength) const { // Add the data to the field if it's not null, // because we don't actually want "null" printed if (data != "") { builder.append(data); } else { builder.append(this->nullDisplayText()); } // Determine the number of spaces we'd need string x = (data != "" ? data : this->nullDisplayText()); int spaces = maxFieldLength - x.length(); // Append all the spaces for (int i = 0; i < spaces; i++) { builder.append(" "); } }
true
20a3fbacbc32950e12d407e0752a09180fd51a38
C++
sooyun429/Learn-C-plus-plus
/C++ self study/inflearn_두들낙서/inflearn_두들낙서/day03_연산자.cpp
UHC
597
3.515625
4
[]
no_license
// inflearn | C C++ ÿ - ε鳫 C/C++ // #include <stdio.h> int main() { // : // + = * / % = // += -= *= /= %= // ++ -- // ġ ġ - ++a a++ ϴ int a = 10; int b; printf(" === ġ === \n"); b = ++a; printf("a: %d\n", a); //11 printf("b: %d\n", b); //11 printf(" === ġ === \n"); b = a++; printf("a: %d\n", a); //12 printf("b: %d\n", b); //11 // : < > <= >= == != // : && || ! }
true
4e6b2c7cab1b0cacd7a7d14a53228a322ddc91fa
C++
byapparov/CarND-Extended-Kalman-Filter-Project
/src/tools.cpp
UTF-8
2,895
3.359375
3
[ "MIT" ]
permissive
#include "tools.h" #include <iostream> using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; using std::cout; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { /** * Calculates the RMSE. */ VectorXd rmse(4); rmse << 0,0,0,0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if (estimations.size() == 0 || ground_truth.size() == 0 || ground_truth.size() != estimations.size()) { return rmse; } // accumulate squared residuals // int observations = estimations.size(); VectorXd err(4); VectorXd err_square(4); for (int i=0; i < estimations.size(); ++i) { err = estimations[i] - ground_truth[i]; err_square = err.array() * err.array(); rmse += err_square; } // calculating the mean rmse = rmse / estimations.size(); // calculating the squared root rmse = rmse.array().sqrt(); return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { /** * Calculates a Jacobian Matrix. */ MatrixXd Hj(3, 4); // recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); // check division by zero if(px == 0 && py == 0) { cout << "CalculateJacobian() - Error - Division by Zero"; return Hj; } // compute the Jacobian matrix float l_2 = px * px + py * py; float l = sqrt(l_2); // p Hj(0,0) = px / l; Hj(0,1) = py / l; Hj(0,2) = 0; Hj(0,3) = 0; // phi Hj(1,0) = -py / l_2; Hj(1,1) = px / l_2; Hj(1,2) = 0; Hj(1,3) = 0; // p_speed Hj(2,0) = py * (vx * py - vy * px) / pow(l, 3); Hj(2,1) = px * (vy * px - vx * py) / pow(l, 3); Hj(2,2) = px / l; Hj(2,3) = py / l; return Hj; } /** * Calculates position in polar coordinates * @param x estimate of the position */ VectorXd Tools::PolarCoordinates(const Eigen::VectorXd &x) { float l = sqrt(pow(x[0], 2) + pow(x[1], 2)); VectorXd z = VectorXd(3); z << l, atan2(x[1], x[0]), (x[0] * x[2] + x[1] * x[3]) / l; return z; } /** * Adjusts angle of the position to be within -pi to pi * @param z polar coordinates position */ VectorXd Tools::ConformPolarPosition(const Eigen::VectorXd &z) { float angle = z[1]; if (angle > M_PI || angle < -M_PI) { // adjust the angle to the (-pi, pi) range expected // by the calculation in the Kalman Filter angle = atan2(sin(angle), cos(angle)); VectorXd res = VectorXd(3); res << z[0], angle, z[2]; return res; } else { return z; } }
true
e54d9f63f45898d5f79321fccb8adf1d42408dde
C++
neveza/EconomyGame
/Line.h
UTF-8
806
2.6875
3
[]
no_license
#ifndef LINE_H #define DATE_H const int MAX_X = 25; const int MAX_Y = 20; const double FE_GDP = 180; //Economy data, may change into a proper table struct Economy { double marketPrice = 10; //y double priceIndex = 100; double realGDP = FE_GDP; //x char aggGraph[MAX_X][MAX_Y]; }; //generates lines based on the linear equation y=mx+c class Line { const int X = 0; const int Y = 1; double slope; double yIntercept; double lineMid[2]; double xMin; double xMax; //double yMin; //double yMin; char symbol; public: //Line(); Line(double, double, double, char); void updateLine(Economy&, Line&, double); void updateCurve(Economy&); double calcY(double); double calcX(double); }; #endif
true
da4d29e8789a97b42326e627cf7f1b655343544f
C++
ruchirsharma1993/SPOJ-Codes
/nicenessofthestring.cpp
UTF-8
566
2.765625
3
[]
no_license
#include<stdio.h> #include<string> #include<vector> #include<iostream> using namespace std; int main() { int t; scanf("%d",&t); for(int i=0;i<t;i++) { char s[1005]; vector<char *>v; int count=0; cin.getline(s,1004); int count=0; char *tok=strtok(s," ,\t"); while(tok!=NULL) { int flag=0; for(int k=0;k<v.size();k++) { if(strcmp(v[k],tok)==0) { flag=1; break; } } if(flag==0) { count++; v.push_back(tok); } tok = strtok(s,NULL); } printf("%d",count); printf("\n"); } return 0; }
true
39d8d1cfd3d69b95f22e5fcc83bbecc67e0c274c
C++
andyanidas/Saraa
/25FEB/10.cpp
UTF-8
394
3.203125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int given; cout<<"Enter amount: "; cin>>given; // 587 if(given>=100){ cout<<"100: "<<given/100; given = given - given/100*100; } if(given>=50){ cout<<"50: "<<given/50; given = given - given/50*50; } if(given>=20){ cout<<"20: "<<given/20; given = given - given/20*20; } return 0; }
true
d4f98bf91ebae8569d60fa4b6d32d7ac2ac80475
C++
MarcSeebold/simpleRacerAdmin
/SRAdmin/ClientConnectionManager.cc
UTF-8
1,343
2.703125
3
[]
no_license
#include "ClientConnectionManager.hh" ClientConnectionManager::ClientConnectionManager(QObject *_parent) : QAbstractListModel(_parent) { } SharedClientConnection ClientConnectionManager::makeNew() { _ c = std::make_shared<ClientConnection>(this); mClients.push_back(c); insertRow(rowCount()); connect(c.get(), &ClientConnection::stateChanged, this, &ClientConnectionManager::onClientStateChanged); return c; } void ClientConnectionManager::remove(const ClientConnection *_client) { removeRow(rowCount()); for (_ it = mClients.begin(); it != mClients.end(); ++it) { if ((*it).get() == _client) { mClients.erase(it); return; } } } QVariant ClientConnectionManager::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= (int)mClients.size()) return QVariant(); if (role == Qt::DisplayRole) { const _ c = mClients.at(index.row()); return c->getAddress() + ": " + c->getStateString(); } return QVariant(); } int ClientConnectionManager::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return mClients.size()+1; // why the hell +1??? } void ClientConnectionManager::onClientStateChanged() { emit dataChanged(index(0), index(rowCount())); }
true
1a9475ecfa5040fd2a02ea1898d07969f1c71477
C++
stoimenoff/oop16-17
/week05/practicum/tasks/task.h
UTF-8
582
2.921875
3
[]
no_license
#ifndef __TASK_H__ #define __TASK_H__ #include <cstddef> #include <cstring> #include <iostream> class Task { public: Task(const char* name, int priority, const char* desc); ~Task(); Task(const Task& other); Task& operator= (const Task& other); const char* getName() const; int getPriority() const; const char* getDesc() const; private: void create(const char* name, int priority, const char* desc); void destroy(); char* name; char* desc; int priority; }; std::ostream& operator<< (std::ostream& os, const Task& task); #endif
true
c6dd2dfe286423799ca6b7cb02f5b09a3dd6d8fe
C++
PriyanshBordia/CodeForces
/979A.cpp
UTF-8
440
2.828125
3
[]
no_license
#include <iostream> typedef long long ll; #define sci(x) scanf("%d", &x); #define pfi(x) printf("%d\n", x); #define scll(x) scanf("%lld", &x); #define pfll(x) printf("%lld\n", x); #define scs(s) scanf("%s", &s); #define pfs(s) printf("%s\n", s); using namespace std; int main() { ll n; scll(n); if (n == 0) cout << n << endl; else if (n % 2 == 1) cout << (n + 1) / 2 << endl; else cout << n + 1 << endl; return 0; }
true
2a831269c3650c85f5a2abb369656eb026578a1d
C++
tomduval/complexity-oslo-model
/OsloModelPy/OsloModelPy/OsloModelPy.cpp
UTF-8
1,248
2.8125
3
[]
no_license
#include "stdafx.h" #include <iostream> #include <vector> #include <ctime> #include <fstream> #include <iterator> #include <sstream> using namespace std; int randNum(float p) { float random = ((float)rand()) / (float)RAND_MAX; if (random <= p) { return 1; } else { return 2; } } void randsSet(int L, int *rands, float p) { for (int i = 0; i < L; i++) { rands[i] = randNum(p); vector<int> second(4, 100); } } extern "C" __declspec(dllexport) void iterations(int N, int L, float p, int *system, int *rands, int *avalancheSize, int *dropSize, int *heights, int *critical) { srand(time(0)); randsSet(L, rands, p); bool foundCritical = false; for (int n = 0; n < N; n++) { system[0] += 1; bool relaxed = false; int s = 0; int d = 0; while (!relaxed) { relaxed = true; for (int i = 0; i < L; i++) { int z = system[i] - system[i + 1]; if (z > rands[i]) { system[i] -= 1; if (i < L - 1) { system[i + 1] += 1; } else { if (!foundCritical) { critical[0] = n; foundCritical = true; } d += 1; } rands[i] = randNum(p); s += 1; relaxed = false; } } } avalancheSize[n] = s; dropSize[n] = d; heights[n] = system[0]; } }
true
0c292a1a0676af642caef6d5421b2909a2938983
C++
tenso/subphonic
/subphonic/sig/window.h
UTF-8
988
2.6875
3
[]
no_license
#ifndef WINDOW_H # define WINDOW_H #include "defines.h" //FIXME: names w_ or something namespace spl{ template<class T=smp_t> class Window { public: enum TYPE {BLACKMAN, HAMMING, HANN, RECTANGLE, TRIANGLE}; Window(TYPE type, uint len); ~Window(); Window(const Window& f); Window& operator=(const Window& r); uint getLen() const; //WARNING: unchecked op's T& operator[](uint i); T operator[](uint i) const; T& get(uint i); T get(uint i) const; private: T* data; uint len; }; //bell from 0 to 1 to 0 template<class T> void win_blackman(T* data, uint len); //"hann & hamming" //bell from 0 to 1 to 0 template<class T> void win_hann(T* data, uint len); //bell from about 0.1 to 1 to 0.1 template<class T> void win_hamming(T* data, uint len); template<class T> void win_rectangle(T* data, uint len); template<class T> void win_triangle(T* data, uint len); //} # include "window_T.h" } #endif
true
1f327a2a79c932cd1508ee8ddac08234c87e8e9d
C++
kartikarcot/ParticleFilter
/include/LogReader.hpp
UTF-8
1,122
2.65625
3
[]
no_license
#ifndef LOGREADER_H #define LOGREADER_H #include <iostream> #include <vector> #include <fstream> #include <string> #include <boost/optional.hpp> #include <ParticleFilter.hpp> enum LogType {ODOM, LASER}; #define LASER_SIZE 180 struct Log { public: LogType logType; std::vector<int> laserdata; Pose2D robotPose; double timestamp; Pose2D laserPose; Log(const LogType &recordType, const double &_x, const double &_y, const double &_theta, const double &_xl, const double &_yl, const double &_thetal, const double &_ts, const std::vector<int> &_laser) : logType(recordType), robotPose(_x,_y,_theta), laserPose(_xl,_yl,_thetal), timestamp(_ts), laserdata(_laser) {}; Log() = delete; }; class LogReader { public: std::fstream fsm; LogReader(const std::string &fName); // do not want to deal with copying and assignment. Lets make it singleton LogReader(const LogReader &rhs) = delete; LogReader& operator= (const LogReader &rhs) = delete; // we wish to retain move constructor. with default semantics. boost::optional<Log> getLog(); }; #endif
true
79480084191438287c4fc2d0a15a26b0935e50ee
C++
intel/lms
/CIM_Framework/CimFrameworkUntyped/include/CimDateTime.h
UTF-8
5,921
2.75
3
[ "Apache-2.0" ]
permissive
//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2003 - 2021 All Rights Reserved. // // File: CimDateTime.h // // Contents: Classes for working with times and intervals, definitions. // //---------------------------------------------------------------------------- #ifndef CIMDATETIME_H #define CIMDATETIME_H 1 #include <string> #include <sstream> #include <memory> #include "CimUtils.h" namespace Intel { namespace Manageability { namespace Cim { using std::string; using std::shared_ptr; using Untyped::CimSerializer; class CIMUNTYPEDFRAMEWORK_API CimDateTimeBase { public: // Destructor. virtual ~CimDateTimeBase() {} // Properties virtual void DateTimeString(const string &value) = 0; virtual string DateTimeString() const = 0; protected: // Functions static bool IsValid(const string& date_time); template <typename T> static void SetField(const string& value, T& field) { std::istringstream stream(value); if (value.find_first_not_of('*') != string::npos) { stream >> field; } else { field = -1; } if (stream.fail()) { throw std::invalid_argument("String is not a valid DateTime"); } } }; class CIMUNTYPEDFRAMEWORK_API CimDateTimeInterval : public CimDateTimeBase { public: // Ctors / Dtors explicit CimDateTimeInterval(long days = -1, short hours = -1, short minutes = -1, short seconds = -1, long microseconds = -1) : CimDateTimeBase(), _days(days), _hours(hours), _minutes(minutes), _seconds(seconds), _microseconds(microseconds) { Validate(); } explicit CimDateTimeInterval(const string &interval_string); // Properties void Days(long days); const long Days() const { return _days; } void Hours(short hours); const short Hours() const { return _hours; } void Minutes(short minutes); const short Minutes() const { return _minutes; } void Seconds(short seconds); const short Seconds() const { return _seconds; } void Microseconds(long microseconds); const long Microseconds() const { return _microseconds; } virtual void DateTimeString(const string &value); virtual string DateTimeString() const; private: // Data long _days; short _hours; short _minutes; short _seconds; long _microseconds; // Functions void Validate() const; }; class CIMUNTYPEDFRAMEWORK_API CimDateTimeAbsolute : public CimDateTimeBase { public: // Ctors / Dtors explicit CimDateTimeAbsolute(short year = -1, short month = -1, short day = -1, short hour = -1, short minute = -1, short second = -1, long microsecond = -1, short utc_offset = 0) : CimDateTimeBase(), _year(year), _month(month), _day(day), _hour(hour), _minute(minute), _second(second), _microsecond(microsecond), _utc_offset(utc_offset) { Validate(); } explicit CimDateTimeAbsolute(const string &date_time); // Properties void Year(short year); const short Year() const { return _year; } void Month(short month); const short Month() const { return _month; } void Day(short day); const short Day() const { return _day; } void Hour(short hour); const short Hour() const { return _hour; } void Minute(short minute); const short Minute() const { return _minute; } void Second(short second); const short Second() const { return _second; } void Microsecond(long microsecond); const long Microsecond() const { return _microsecond; } void UtcOffset(short utc_offset) { _utc_offset = utc_offset; } const short UtcOffset() const { return _utc_offset; } virtual void DateTimeString(const string &value); virtual string DateTimeString() const; private: // Data short _year; short _month; short _day; short _hour; short _minute; short _second; long _microsecond; short _utc_offset; // Functions void Validate() const; }; class CIMUNTYPEDFRAMEWORK_API CimDateTime { public: enum DateTimeType { DT_INTERVAL, DT_ABSOLUTE, DT_UNKNOWN }; // Ctors / Dtors CimDateTime() : _type(DT_UNKNOWN) {} CimDateTime(const CimDateTimeAbsolute& date_time) : _type(DT_ABSOLUTE), _pImpl(new CimDateTimeAbsolute(date_time)) {} CimDateTime(const CimDateTimeInterval& date_time) : _type(DT_INTERVAL), _pImpl(new CimDateTimeInterval(date_time)) {} CimDateTime(const CimDateTime& other) : _type(other._type), _pImpl(Init_pImpl(other._pImpl)) {} virtual ~CimDateTime() {} // Operators // operator= param passed by value for swapping. CimDateTime& operator=(CimDateTime other); // Properties DateTimeType Type() const { return _type; } string DateTimeString() const; void DateTimeString(const string &value); // Functions void swap(CimDateTime& other); const CimDateTimeInterval& AsInterval() const; CimDateTimeInterval& AsInterval(); const CimDateTimeAbsolute& AsAbsolute() const; CimDateTimeAbsolute& AsAbsolute(); // Serialization functions string Serialize() const; void Deserialize(const string &str); private: // Data DateTimeType _type; shared_ptr<CimDateTimeBase> _pImpl; // Functions CimDateTimeBase* Init_pImpl(shared_ptr<CimDateTimeBase> other) const; // Type conversion member function templates for internal _pImpl casts template<typename T> const T& AsType() const { return dynamic_cast<const T&>(*_pImpl); } }; void swap(CimDateTime& a, CimDateTime& b); } } } namespace std { template<> void swap(Intel::Manageability::Cim::CimDateTime& a, Intel::Manageability::Cim::CimDateTime& b); } #endif // CIMDATETIME_H
true
be22dfc84dd23156d273f0b3f2e41ff76750eb44
C++
kaito1111/GameTemplete
/GameTemplate/myEngine/ksEngine/graphics/GPUBuffer/VertexBuffer.cpp
UTF-8
859
2.5625
3
[]
no_license
#include "stdafx.h" #include "graphics/GPUBuffer/VertexBuffer.h" VertexBuffer::VertexBuffer() { } VertexBuffer::~VertexBuffer() { Release(); } bool VertexBuffer::Create(int numVertex, int stride, const void * pSrcVertexBuffer) { Release(); D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = numVertex * stride; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitDate; ZeroMemory(&InitDate, sizeof(InitDate)); InitDate.pSysMem = pSrcVertexBuffer; HRESULT hr = g_graphicsEngine->GetD3DDevice()->CreateBuffer(&bd, &InitDate, &m_vertexBuffer); if (FAILED(hr)) { return false; } m_stride = stride; return true; return true; } void VertexBuffer::Release() { if (m_vertexBuffer != nullptr) { m_vertexBuffer->Release(); m_vertexBuffer = nullptr; } }
true
0f95138fb74ca1c45138845c43884c514f12e709
C++
williamisfranciscodasilva/vendas-c
/vendas.cpp
UTF-8
461
2.609375
3
[]
no_license
#include <conio.h> #include <stdio.h> main() { float salario_fixo, vendas_mes, comissao, salario_total; salario_fixo = 800; printf("Figite o valor das vendas do mes: "); scanf("%f",&vendas_mes); comissao = (vendas_mes / 100) * 15; salario_total = salario_fixo + comissao; printf("Salario fixo: %f",salario_fixo); printf("\nVendas do Mes: %f",vendas_mes); printf("\nComissao: %f",comissao); printf("\nSalario total: %f",salario_total); getch(); }
true
ea4ba54b1273bc545f275c00d92358597e53a400
C++
jb1717/BombAERman
/src/graphics/GraphicString.cpp
UTF-8
2,771
2.765625
3
[]
no_license
// // GraphicString.cpp for CPP_BOMBERMAN in /home/Jamais/cpp_bomberman // // Made by Jamais // Login <Jamais@epitech.net> // // Started on Wed Jun 3 11:24:34 2015 Jamais // Last update Fri Jun 12 00:12:18 2015 Jamais // #include "GraphicString.hh" #include "AssetManager.hh" GraphicString::GraphicString() : ComplexObject(), _text(""), _size(1) {} GraphicString::GraphicString(std::string const& text) : ComplexObject(), _text(text), _size(1) { GeometryFactory *factory = GeometryFactory::instanciate(); render(*factory); } GraphicString::GraphicString(std::string const& text, unsigned int size) : ComplexObject(), _text(text), _size(size) { GeometryFactory *factory = GeometryFactory::instanciate(); render(*factory); } GraphicString::~GraphicString() {} GraphicString& GraphicString::operator=(std::string const& modelString) { GeometryFactory *factory = GeometryFactory::instanciate(); _text = modelString; clear(); render(*factory); return *this; } GraphicString& GraphicString::operator=(GraphicString const& model) { GeometryFactory *factory = GeometryFactory::instanciate(); _text = model.getText(); clear(); render(*factory); return *this; } Geometric* GraphicString::operator[](unsigned int index) { return _spareParts[index]; } GraphicString& GraphicString::operator+(std::string const& modelString) { _text += modelString; return *this; } std::string GraphicString::getText() const { return _text; } void GraphicString::setText(std::string const& text) { _spareParts.clear(); _text = text; auto factory = GeometryFactory::instanciate(); render(*factory); } bool GraphicString::render(UNUSED GeometryFactory& factory) { auto asset = AssetManager::instance(); Geometric* graphicChar; gdl::Texture* charTexture; int x; unsigned int i; x = _text.size() / 2 * -1; for (i = 0; i < _text.size(); i++) { if (_text.substr(i, 1) != " " && _text.substr(i, 1) != ".") { try { charTexture = (*THEME((*THEME_HANDLER(asset["themes"]))["fonts"]))[_text.substr(i, 1)]; } catch (std::out_of_range e) { std::cout << e.what() << std::endl;} // if (i > _spareParts.size()) graphicChar = new Geometric(glm::vec3(_position.x - x, _position.y, _position.z)); // else // { // graphicChar = _spareParts[i]; // graphicChar->translate(glm::vec3(_position.x - x, _position.y, _position.z)); // } graphicChar->setGeometry(factory.getGeometry(GeometryFactory::VERTICAL_PLANE)); graphicChar->setTexture(*charTexture); graphicChar->initialize(); push_back(graphicChar); } x++; } return true; } void GraphicString::scale(glm::vec3 const& scale) { ComplexObject::scale(scale); } void GraphicString::clear() { }
true
97521b165157c52af573e0f34906ee22d6faa895
C++
MehrdadAP/acm_codes
/UVa/The Knights Of Round Table - 10195.cpp
UTF-8
681
2.59375
3
[]
no_license
/*ba yade oo */ #include <iostream> #include <string> #include <string.h> #include <algorithm> #include <stdio.h> #include <math.h> #include <cstring> #include <sstream> #include <queue> #include <vector> using namespace std; #define PI 3.14159265358997 #define absol(x) ((x)>(0) ? (x):(-1)*(x)) #define INF 0x7FFFFFFF #define EPS 1e-7 #define pow2(x) (x*x) int main () { double a,b,c; double p,area,r; while (scanf("%lf %lf %lf",&a,&b,&c)==3)//ls { p=(a+b+c)/2.0; area=sqrt(p*(p-a)*(p-b)*(p-c)); r=(2*area)/(a+b+c); if (a*b*c==0) r=0; printf("The radius of the round table is: %.3lf\n",r+EPS); } return 0; }
true
9d4d780e90d13cc6ba91d409f029450157ac2c66
C++
HSE-SWB2-OOS/OOS-LB5
/Aufgabe 3/MyList.hpp
UTF-8
648
2.8125
3
[]
no_license
#include "MyData.hpp" #include <iostream> using namespace std; #pragma once class MyList { public: MyList(); MyList(MyList & list); ~MyList(); class MyListElement; int listSize; MyListElement *first; MyListElement *last; void push_back(const MyData & content); void pop_back(); MyData & front(); MyData & back(); void clear(); bool empty(); int size(); void print(); MyList & operator= (const MyList &list); MyList operator+ (const MyList &list); class MyListElement { public: MyListElement(); ~MyListElement(); MyData *data; MyListElement *next; //void print(bool newLine) const; private: }; private: };
true
6cb9ed0736a97504a8a3b227725c0054af61215f
C++
Kenneth-Nicholas/COSC-1560-03-C-Plus-Plus-Programming-II
/Programming_II_HELP/5139145_54863694_Fall+2016+COSC+1550+Homework+Solutions/Homework Solutions/Homework5/Centigrade2Fahrenheit.cpp
UTF-8
775
3.6875
4
[]
no_license
// Paul Biolchini // COSC 1550 // Homework 5 Assignment 1 // Chapter 3, Problem 11 // Convert Centigrade temperatures to Fahrenheit. #include <iostream> #include <iomanip> using namespace std; int main() { double tempCen, tempFah, convert; convert = 9./5; // 9./5. => 1.8 cout << "Please enter the temperature in Celsius: "; cin >> tempCen; // tempFah = 1.8 * tempCen + 32; // 1.8 => 9./5. // tempFah = 9 * tempCen / 5 + 32; tempFah = convert * tempCen + 32; cout << fixed << setprecision(1); cout << setw(5) << tempCen << " degrees Celsius is " << setw(5) << tempFah << " degrees Fahrenheit.\n"; return 0; } // Result: //Please enter the temperature in Celsius : 100 //100.0 degrees Celsius is 212.0 degrees Fahrenheit. //Press any key to continue . . .
true
b31d2c46f8a9e7922887bd68c33a53c12e13bd6a
C++
Kicer86/sudoku_solver
/rules/row_rule.cpp
UTF-8
1,289
3.296875
3
[]
no_license
#include "row_rule.hpp" #include "utils.hpp" RowRule::RowRule(const IGrid<int>& grid) : m_grid(grid) { } std::vector<int> RowRule::validNumbers(int row, int col) const { std::vector<int> valid; const int columns = m_grid.columns(); const int numbers = columns; // possible numbers == number of columns in grid valid.reserve(numbers); valid = utils::fill(numbers); for(int i = 0; i < columns; i++) { const int cell_value = m_grid.get(row, i); if (cell_value > 0) utils::erase(valid, cell_value); } return valid; } std::vector<std::pair<int, int>> RowRule::possibleLocations(int row, int col, int value) const { std::vector<std::pair<int, int>> locations; const int columns = m_grid.columns(); bool contains_value = false; for(int i = 0; i < columns; i++) { const int cell_value = m_grid.get(row, i); if (cell_value == value) { contains_value = true; break; } } if (contains_value == false) for(int i = 0; i < columns; i++) { const int cell_value = m_grid.get(row, i); if (cell_value == 0) locations.emplace_back(row, i); } return locations; }
true
4e113cc9370ba783ce9ea52f79091cea15b87794
C++
funemy/TAP-Predictor
/my_predictor_perceptron.h
UTF-8
8,532
2.59375
3
[]
no_license
// my_predictor.h // This file contains a my_predictor class. // It has a perceptron-based TAP indirect branch predictor #include <vector> #include <map> #include <iostream> #include <bitset> // a BTB-set is indexed by a branch address // 32-way associated // using the LFU replacement policy when the set is full class btb_set { #define SUB_PREDICTOR_NUM 5 public: unsigned int targets[1<<SUB_PREDICTOR_NUM]; int counter[1<<SUB_PREDICTOR_NUM]; // int mru[1<<SUB_PREDICTOR_NUM] btb_set () { memset(targets, 0 , sizeof(targets)); memset(counter, 0 , sizeof(counter)); } }; class my_update : public branch_update { public: int index; int tap; int output; int outputs[SUB_PREDICTOR_NUM] = {0,0,0,0,0}; }; class my_predictor : public branch_predictor { //History length for each sub-predictor #define HISTORY_LENGTH 256 //Number of perceptrons #define PERCPETRON_NUM 10000 //The total weight vector length #define LONG_HISTORY_LENGTH ((HISTORY_LENGTH+1)*SUB_PREDICTOR_NUM) // threshold for perceptron training const double threshold = 1.93 * HISTORY_LENGTH + 14; public: my_update u; branch_info bi; // Global History Register std::vector<char> history_vec; std::vector<std::vector<char>> local_history_vec; // a weight matrix for sub predictor perceptrons int wsub[PERCPETRON_NUM][LONG_HISTORY_LENGTH]; // Branch target buffer // indexed by indirect branch address std::map<unsigned int, btb_set> btb; my_predictor (void) : history_vec(LONG_HISTORY_LENGTH-1, false){ memset(wsub, 0, sizeof(wsub)); } void vec_unshift (std::vector<char> &vec) { vec.erase(vec.begin()+0); } // push new history to the GHR // while keeping the GHR at the same length void vec_push (std::vector<char> &vec, char value) { if (vec.size() >= LONG_HISTORY_LENGTH-1) { vec_unshift(vec); } vec.push_back(value); } // conditional branch prediction bool perceptron_predict(unsigned int pc) { int i,j,output; i = pc % PERCPETRON_NUM; int *wrow = wsub[i]; output = 0; for (j = 0; j <= LONG_HISTORY_LENGTH; j++) { if (j == 0) { output += wrow[j]; } else { if (history_vec[j-1]) { output += wrow[j]; } else { output -= wrow[j]; } } } u.index = i; u.output = output; return output >= 0; } // conditional update void train (int i, int output, bool prediction, bool taken) { int j; int *wrow = wsub[i]; if ( (prediction!=taken) || (abs(output)<threshold) ) { if (taken) { wrow[0] += 1; } else { wrow[0] -= 1; } for (j=1; j<=LONG_HISTORY_LENGTH; j++) { if (taken == history_vec[j-1]) { wrow[j] += 1; } else { wrow[j] -= 1; } } } } // indirect branch prediction unsigned int indirect_prediction(unsigned int pc) { int i, j, k, w_len, output, tap; i = pc % PERCPETRON_NUM; w_len = HISTORY_LENGTH + 1; int *wrow = wsub[i]; tap = 0; for (j=0; j<SUB_PREDICTOR_NUM; j++) { output = 0; for (k=w_len*j; k<w_len*(j+1); k++) { if ( (k % w_len) == 0 ) { output += wrow[k]; } else { int index = (k%w_len)-1 + w_len*(SUB_PREDICTOR_NUM-1); if (history_vec[index]) { output += wrow[k]; } else { output -= wrow[k]; } } } if (output >= 0) { tap <<= 1; tap |= 1; } else { tap <<= 1; } u.outputs[j] = output; } u.index = i; u.tap = tap; return btb[pc].targets[tap]; } // indirect branch prediction void sub_predictor_train(int i, int outputs[], int tap, unsigned int prediction, unsigned int target){ int j, k, w_len; int *wrow = wsub[i]; w_len = HISTORY_LENGTH + 1; // condition 1: // prediction equals to target // only update the BTB // using LFU replacement policy if (prediction == target) { btb_set *set = &btb[bi.address]; set->counter[tap] += 1; // the commented code below is LRU replacement policy // beaten by LFU // int tap_i = 0; // for (j=0; j<(1<<SUB_PREDICTOR_NUM); j++) { // if (set->mru[j] == tap) { // tap_i = j; // break; // } // } // for (k=tap_i; k>0; k--) { // set->mru[k] = set->mru[k-1]; // } // set->mru[0] = tap; // condition 2: // prediction is not equal to target } else { btb_set *set = &btb[bi.address]; int real_tap = 0; // LFU policy for (j = 0; j < (1 << SUB_PREDICTOR_NUM); j++) { if (set->targets[j] == target) { real_tap = j; break; } if (set->counter[j] < set->counter[real_tap]) { real_tap = j; } } set->counter[real_tap] += 1; set->targets[real_tap] = target; // LRU policy // int real_tap_i=0; // for (j=0; j<(1<<SUB_PREDICTOR_NUM); j++) { // if (set->targets[j] == target) { // real_tap = j; // break; // } // } // if (set->targets[real_tap] != target) { // real_tap_i = (1<<SUB_PREDICTOR_NUM) - 1; // real_tap = set->mru[real_tap_i]; // set->targets[real_tap] = target; // } else { // for (j=0; j<(1<<SUB_PREDICTOR_NUM); j++) { // if (set->mru[j] == real_tap) { // real_tap_i = j; // break; // } // } // } // for (k=real_tap_i; k>0; k--) { // set->mru[k] = set->mru[k-1]; // } // set->mru[0] = real_tap; // training perceptrons for (j=0; j<SUB_PREDICTOR_NUM; j++) { bool tap_bit = tap & (1<<(SUB_PREDICTOR_NUM-j-1)); bool taken = real_tap & (1<<(SUB_PREDICTOR_NUM-j-1)); // not comparing the threshold can get a better MKPI if ( (tap_bit != taken) ) { for (k=w_len*j; k<w_len*(j+1); k++) { if ( (k % w_len) == 0 ) { if (taken) wrow[k] += 1; else wrow[k] -= 1; } else { int index = (k%w_len)-1 + w_len*(SUB_PREDICTOR_NUM-1); if (taken == history_vec[index]) { wrow[k] += 1; } else { wrow[k] -= 1; } } } } } } } branch_update *predict (branch_info & b) { bi = b; if (b.br_flags & BR_CONDITIONAL) { // bool direction = perceptron_predict(b.address); // u.direction_prediction(direction); } else { u.direction_prediction (true); } if (b.br_flags & BR_INDIRECT) { unsigned int target = indirect_prediction(b.address); u.target_prediction(target); } return &u; } void update (branch_update *u, bool taken, unsigned int target) { if (bi.br_flags & BR_CONDITIONAL) { // train(((my_update*)u)->index, ((my_update*)u)->output, u->direction_prediction(), taken); vec_push(history_vec, taken); } if (bi.br_flags & BR_INDIRECT) { sub_predictor_train( ((my_update*)u)->index, ((my_update*)u)->outputs, ((my_update*)u)->tap, u->target_prediction(), target ); } } };
true
a04aa44272a14955939c14e89c35d2a3fed4aa29
C++
frozenbanana/3Dproject
/openGLHenryAlone/src/InputHandler.h
UTF-8
537
2.65625
3
[]
no_license
#pragma once #include <SDL2\SDL.h> #include "Camera.h" class InputHandler { public: InputHandler(); void Update(Camera* camPtr); bool IsKeyPressed(); bool IsMouseButtonPressed(int mouseButton); ~InputHandler(); private: enum { MOUSE_LEFT, MOUSE_CENTER, MOUSE_RIGHT, NUM_BUTTONS }; bool m_mouseButtons[NUM_BUTTONS]; const Uint8* m_keyboardState; // Array to check the states of the keys on keyboard float m_anglePitch, m_angleYaw; SDL_Event m_event; void GetButtonStates(); };
true
13ea246601589e5b68e9ea7ad6d9dfb9e647fcf2
C++
yucucsd/poj
/3264_RMQ_ST.cpp
UTF-8
1,379
2.640625
3
[]
no_license
#define _CRT_SECURE_NO_DEPRECATE #include <cstdio> #include <math.h> #include <algorithm> using namespace std; #define maxn 50002 int minh[maxn][21]; int maxh[maxn][21]; void init_st(int row) { for (int i = 1; (1 << i) < row; i++) { for (int j = 0; j < row; j++) { minh[j][i] = (j + (1<<(i - 1))) >= row ? minh[j][i - 1] : min(minh[j][i - 1], minh[j + (1 << (i - 1))][i - 1]); maxh[j][i] = (j + (1 << (i - 1))) >= row ? maxh[j][i - 1] : max(maxh[j][i - 1], maxh[j + (1 << (i - 1))][i - 1]); } } } int query(bool m, int l, int r) { int k = 0; while ((1 << (k + 1)) <= r - l + 1) k++; if (m) return max(maxh[l][k], maxh[r - (1 << k) + 1][k]); //2^(k + 1) > r - l + 1 else return min(minh[l][k], minh[r - (1 << k) + 1][k]); } int main() { int N, Q; scanf("%d %d", &N, &Q); for (int i = 0; i < N; i++) { scanf("%d", &minh[i][0]); maxh[i][0] = minh[i][0]; } init_st(N); while (Q--) { int l, r; scanf("%d %d", &l, &r); l--, r--; int valmax = query(true, l, r); int valmin = query(false, l, r); //printf("min= %d, max = %d, %d\n", valmin, valmax, valmax - valmin); printf("%d\n", valmax - valmin); } //scanf("%d", &N); }
true
a05700801766964ea453863721f01f4ef4461ac6
C++
Mehedi-Hassan/Competitive-Programming
/atcoder/abc159/B.cpp
UTF-8
722
2.703125
3
[]
no_license
#include<bits/stdc++.h> #define ll long long #define pii pair<int, int> #define f first #define s second using namespace std; int main() { string t, s, rev, r2; cin>>s; int n = s.size(); t = s.substr(0, (n-1)/2); // cout<<t<<endl; rev = t; reverse(rev.begin(), rev.end()); string t2 = s.substr((n+3)/2 - 1, n - ((n+3)/2) + 1); // cout<<t2<<endl; string rev2 = t2; reverse(rev2.begin(), rev2.end()); r2 = s; reverse(r2.begin(), r2.end()); // cout<<t.size()<<" "<<rev.size()<<endl; // cout<<t2.size()<<" "<<rev2.size()<<endl; if(t == rev && t2 == rev2 && s == r2){ cout<<"Yes"; } else{ cout<<"No"; } }
true
bdf309910469ca5c00d7799f753e8d8c521edc98
C++
Sidewinder22/SideFileEditor
/src/log/Logger.cpp
UTF-8
1,066
3.15625
3
[]
no_license
/** * @author {\_Sidewinder22_/} * @date 02.01.2019 * * @brief Class responsible for application logging. */ #include <cstring> #include "Logger.hpp" namespace log { Logger::Logger( std::string prefix ) : prefix_( prefix ) , beginLine_( true ) { } template<> Logger& operator<<( Logger& log, std::string str ) { log.writeIndex(); std::cout << str; if ( str == "\n" ) { log.beginLine_ = true; } return log; } template<> Logger& operator<<( Logger& log, QString info ) { log.writeIndex(); std::string str = info.toStdString(); std::cout << str; if ( str == "\n" ) { log.beginLine_ = true; } return log; } template<> Logger& operator<<( Logger& log, const char* str ) { log.writeIndex(); std::cout << str; int result = std::strcmp( str, "\n" ); if ( result == 0 ) { log.beginLine_ = true; } return log; } void Logger::writeIndex() { if ( beginLine_ ) { std::cout << "[" << prefix_ << "] "; beginLine_ = false; } } } // ::log
true
c415fae46fc703534644b8749a26be111842c685
C++
Renardjojo/FuzzyLogic
/include/AI/FuzzyLogic/FuzzySets/Point2D.hpp
UTF-8
2,633
3.109375
3
[ "MIT" ]
permissive
/* * Project : FuzzyLogic * Editing by Six Jonathan * Date : 2021-01-07 - 13 h 33 * * Copyright (C) 2021 Six Jonathan * This file is subject to the license terms in the LICENSE file * found in the top-level directory of this distribution. */ #pragma once #include "Macro/ClassUtility.hpp" namespace AI::FuzzyLogic::FuzzySet { /** * @brief Point2D Is basic point with overload of operator< that compare only the X position. Usfull for the FuzzyLogic * * @tparam TPrecisionType */ template <typename TPrecisionType = float> class Point2D { private: protected: #pragma region attribut TPrecisionType m_x; TPrecisionType m_y; #pragma endregion //!attribut public: #pragma region constructor/destructor constexpr inline Point2D () noexcept = default; constexpr inline Point2D (const Point2D<TPrecisionType>& other) noexcept = default; constexpr inline Point2D (Point2D<TPrecisionType>&& other) noexcept = default; inline ~Point2D () noexcept = default; constexpr inline Point2D& operator=(Point2D<TPrecisionType> const& other) noexcept = default; constexpr inline Point2D& operator=(Point2D<TPrecisionType>&& other) noexcept = default; #pragma endregion //!constructor/destructor #pragma region methods explicit constexpr inline Point2D(TPrecisionType in_x, TPrecisionType in_y) noexcept : m_x {in_x}, m_y {in_y} {} std::string toString() const noexcept { return std::string("(" + std::to_string(m_x) + ";" + std::to_string(m_y) + ")"); } #pragma endregion //!methods #pragma region mutator/accessor DEFAULT_SETTER(X, m_x) DEFAULT_SETTER(Y, m_y) DEFAULT_GETTER(X, m_x) DEFAULT_GETTER(Y, m_y) DEFAULT_CONST_GETTER(X, m_x) DEFAULT_CONST_GETTER(Y, m_y) #pragma endregion //!mutator/accessor #pragma region operator [[nodiscard]] constexpr inline bool operator<(const Point2D<TPrecisionType>& other) const noexcept { return m_x < other.getX(); } [[nodiscard]] constexpr inline bool operator==(const Point2D<TPrecisionType>& other) const noexcept { return m_x == other.getX(); } #pragma endregion //!operator }; } /*namespace AI::FuzzyLogic::FuzzySet*/
true
84fc3c59fe6cdbc623b2884bee961b23fd027cc9
C++
alexandraback/datacollection
/solutions_2449486_1/C++/lambdapioneer/b.cpp
UTF-8
1,520
2.5625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <list> #include <map> #include <set> #include <stack> #include <queue> using namespace std; typedef pair<int, int> PII; typedef vector<int> VI; typedef vector<vector<int> > VII; typedef vector<PII> VPII; typedef vector<double> VD; typedef vector<string> VS; typedef long long LL; int rowMax[200]; int colMax[200]; int lawn[200][200]; int R, C; int main(){ int cases; scanf("%d\n", &cases); for(int caseNr = 1; caseNr <= cases; caseNr++){ // go for it! printf("Case #%d: ", caseNr); // READ scanf("%d %d\n", &R, &C); for(int i=0; i<R; i++){ for(int j=0; j<C; j++){ scanf("%d", &lawn[i][j]); } } // CALC for(int r=0; r<R; r++){ rowMax[r] = 0; for(int c=0; c<C; c++) rowMax[r] = max(rowMax[r], lawn[r][c]); } for(int c=0; c<C; c++){ colMax[c] = 0; for(int r=0; r<R; r++) colMax[c] = max(colMax[c], lawn[r][c]); } // CHECK bool valid = true; for(int r=0; r<R; r++){ for(int c=0; c<C; c++){ if(min(colMax[c], rowMax[r]) != lawn[r][c]){ // no way we can cut yo lawn, bro! valid = false; break; } } } if (valid) printf("YES\n"); else printf("NO\n"); fflush(stdout); } return 0; }
true
ac7a030d8dfc0053fc908e6d84fc5b5af3cf133d
C++
Mindjolt2406/Competitive-Programming
/Codeforces/GYM/2020_Shenyeng/I_Brute.cpp
UTF-8
4,656
2.59375
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; typedef long long ll; template <typename T> std::ostream & operator << (std::ostream & os, const std::vector<T> & vec); template <typename T> std::ostream & operator << (std::ostream & os, const std::set<T> & vec); template <typename T> std::ostream & operator << (std::ostream & os, const std::unordered_set<T> & vec); template <typename T> std::ostream & operator << (std::ostream & os, const std::multiset<T> & vec); template <typename T> std::ostream & operator << (std::ostream & os, const std::unordered_multiset<T> & vec); template<typename T1, typename T2> std::ostream & operator << (std::ostream & os, const std::pair<T1,T2> & p); template<typename T1, typename T2> std::ostream & operator << (std::ostream & os, const std::map<T1,T2> & p); template<typename T1, typename T2> std::ostream & operator << (std::ostream & os, const std::unordered_map<T1,T2> & p); template <typename T> std::ostream & operator << (std::ostream & os, const std::vector<T> & vec){ os<<"{"; for(auto elem : vec) os<<elem<<","; os<<"}"; return os; } template <typename T> std::ostream & operator << (std::ostream & os, const std::set<T> & vec){ os<<"{"; for(auto elem : vec) os<<elem<<","; os<<"}"; return os; } template <typename T> std::ostream & operator << (std::ostream & os, const std::unordered_set<T> & vec){ os<<"{"; for(auto elem : vec) os<<elem<<","; os<<"}"; return os; } template <typename T> std::ostream & operator << (std::ostream & os, const std::multiset<T> & vec){ os<<"{"; for(auto elem : vec) os<<elem<<","; os<<"}"; return os; } template <typename T> std::ostream & operator << (std::ostream & os, const std::unordered_multiset<T> & vec){ os<<"{"; for(auto elem : vec) os<<elem<<","; os<<"}"; return os; } template<typename T1, typename T2> std::ostream & operator << (std::ostream & os, const std::pair<T1,T2> & p){ os<<"{"<<p.first<<","<<p.second<<"}"; return os; } template<typename T1, typename T2> std::ostream & operator << (std::ostream & os, const std::map<T1,T2> & p){ os<<"{"; for(auto x: p) os<<x.first<<"->"<<x.second<<", "; os<<"}"; return os; } template<typename T1, typename T2> std::ostream & operator << (std::ostream & os, const std::unordered_map<T1,T2> & p){ os<<"{"; for(auto x: p) os<<x.first<<"->"<<x.second<<", "; os<<"}"; return os; } /*-------------------------------------------------------------------------------------------------------------------------------------*/ #define t1(x) cerr<<#x<<"="<<x<<endl #define t2(x, y) cerr<<#x<<"="<<x<<" "<<#y<<"="<<y<<endl #define t3(x, y, z) cerr<<#x<<"=" <<x<<" "<<#y<<"="<<y<<" "<<#z<<"="<<z<<endl #define t4(a,b,c,d) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<endl #define t5(a,b,c,d,e) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<" "<<#e<<"="<<e<<endl #define t6(a,b,c,d,e,f) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<" "<<#e<<"="<<e<<" "<<#f<<"="<<f<<endl #define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME #ifndef ONLINE_JUDGE #define tr(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__) #else #define tr(...) #endif /*-------------------------------------------------------------------------------------------------------------------------------------*/ #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define fastio() ios::sync_with_stdio(0);cin.tie(0) #define MEMS(x,t) memset(x,t,sizeof(x)); mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); /*-------------------------------------------------------------------------------------------------------------------------------------*/ // #define MOD 1000000007 // #define MOD 998244353 #define endl "\n" #define int long long #define inf 1e18 #define ld long double /*-------------------------------------------------------------------------------------------------------------------------------------*/ signed main() { fastio(); int h,m,a; cin>>h>>m>>a; ld eps = 1e-9; vector<pair<ld,ld>> good; for(int i=1;i<=h-1;i++) { good.push_back({(m*h*i-(a+eps))/(h-1),(m*h*i+(a+eps))/(h-1)}); } tr(good); set<int> timestamps;//minutes in goodranges for(int i=0;i<=1+good.back().second;i++) { bool flag = 0; for(auto x: good){ if(i>=x.first && i<=x.second) flag = 1; } tr(h * m); if(flag) timestamps.insert(i % (h * m)); } tr(timestamps); cout<<timestamps.size()<<endl; }
true
c3c6a7aa1ac3993975d6b591de91c6a59a3f2729
C++
MaxMade/ARMOS
/kernel/device_tree/property.cc
UTF-8
943
2.578125
3
[]
no_license
#include <kernel/utility.h> #include <kernel/device_tree/property.h> #include <kernel/device_tree/definition.h> using namespace DeviceTree; Property::Property() : valid(false), ptr(nullptr), stringBlock(nullptr) {} Property::Property(void* ptr, const char* stringBlock) : valid(false), ptr(static_cast<uint32_t*>(ptr)), stringBlock(stringBlock) { if (ptr != nullptr && util::bigEndianToHost(*this->ptr) == FDT_PROP) valid = true; } bool Property::isValid() const { return valid; } Property::operator bool() const { return valid; } const char* Property::getName() const { auto prop = reinterpret_cast<FDTProp*>(ptr + 1); return &stringBlock[util::bigEndianToHost(prop->nameoff)]; } lib::pair<void*, size_t> Property::getData() const { auto prop = reinterpret_cast<FDTProp*>(ptr + 1); void* addr = reinterpret_cast<void*>(prop->vals); size_t size = util::bigEndianToHost<uint32_t>(prop->len); return lib::pair(addr, size); }
true
1f9b1ca7e82b6a6917a974cca9738254bbe8550b
C++
thomoncik/hexadoku
/src/State/BoardCreator/ConfirmExitBoardCreatorState.cpp
UTF-8
1,181
2.59375
3
[ "MIT" ]
permissive
// // Created by Jakub Kiermasz on 2019-06-10. // #include "State/BoardCreator/ConfirmExitBoardCreatorState.hpp" #include <State/Menu/MainMenuState.hpp> #include <State/BoardCreator/InsertionBoardCreatorState.hpp> #include <State/BoardCreator/MoveBoardCreatorState.hpp> #include <View/BoardCreator/ConfirmExitBoardCreatorView.hpp> ConfirmExitBoardCreatorState::ConfirmExitBoardCreatorState(bool wasInsertionEnabled, std::shared_ptr<BoardCreator> boardCreator) : wasInsertionEnabled(wasInsertionEnabled), AbstractBoardCreatorState(std::move(boardCreator)) {} void ConfirmExitBoardCreatorState::HandleInput(StateContext &stateContext, char input) { if (input == 'y') { stateContext.SetState(std::make_shared<MainMenuState>()); } else if (input == 'n') { if (wasInsertionEnabled) { stateContext.SetState(std::make_shared<InsertionBoardCreatorState>(std::move(boardCreator))); } else { stateContext.SetState(std::make_shared<MoveBoardCreatorState>(std::move(boardCreator))); } } } void ConfirmExitBoardCreatorState::Draw(StateContext &stateContext) { ConfirmExitBoardCreatorView view(boardCreator); view.Draw(); }
true
c4f648b22200bdea922f8d0d414143d69fb876b2
C++
xBece/DGIIM
/FP/Sesión 5/Casa/18 - Potencia.cpp
ISO-8859-1
1,032
3.59375
4
[]
no_license
/* Calcular mediante un programa en C++ la funcin potencia x^n, y la funcin factorial n! con "n" un valor entero y ""x un valor real. No pueden usarse las funciones de la biblioteca cmath. */ #include <iostream> using namespace std; int main () { // DECLARACIN DE LAS VARIABLES A GUARDAR double x, aux; int n; double resultado_fac = 1; // ENTRADA cout << "Este programa calcular la funcin x^n y la funcin factorial n!."; cout << "\n\n\tIntroduzca el valor deseado para x : "; cin >> x; cout << "\n\tIntroduzca el valor deseado para n : "; cin >> n; aux = x; // BUCLES - FUNCIN POTENCIA Y FACTORIAL if ( n == 0 ) x = resultado_fac = 1; else for ( int i = 1; i < n; i++ ) { x = x * aux; resultado_fac = resultado_fac * (i + 1); } cout << "\nEl valor de la funcin potencia es " << x << " y el de la funcin factorial " << resultado_fac << "."; cout << "\n\n"; system ("PAUSE"); return 0; }
true
762b69513c89ad01d369658a9a8f067bd22ea829
C++
Something-Specific/SpecificEngine
/Gin/src/Utils/Log.h
UTF-8
629
2.796875
3
[]
no_license
#pragma once #include "spdlog/spdlog.h" #include "spdlog/fmt/ostr.h" namespace Gin { class Log { public: static void Init(); // For multiple args, use {} as a placeholder in the first arg and the remaining args are placed inside. // Example CORE_INFO("This is a {}", "test") outputs: "This is a test" inline static std::shared_ptr<spdlog::logger> &GetCoreLogger() { return coreLogger; } inline static std::shared_ptr<spdlog::logger> &GetGameLogger() { return gameLogger; } private: static std::shared_ptr<spdlog::logger> coreLogger; static std::shared_ptr<spdlog::logger> gameLogger; }; } // namespace Gin
true
b6ccdc8424b06c51d19d15c92781e7234d76f816
C++
eunho5751/BarrageShooting
/source files/ResourceMgr.cpp
UHC
2,057
2.75
3
[]
no_license
#include "PCH.h" #include "ResourceMgr.h" #include "Game.h" #include "def.h" CResourceMgr::CResourceMgr() { LoadImages(CHAR_RESOURCE_FOLDER); LoadImages(ENEMY_RESOURCE_FOLDER); LoadImages(BULLET_RESOURCE_FOLDER); LoadImages(BACKGROUND_RESOURCE_FOLDER); LoadImages(ETC_RESOURCE_FOLDER); } CResourceMgr::~CResourceMgr() { } void CResourceMgr::LoadImages(const string& _folderName) { // ̹ о map Ѵ. _finddata_t fd; string path = _folderName + "/*.*"; intptr_t handle = _findfirst(path.c_str(), &fd); if (handle != -1) { do { if (!strcmp(fd.name, ".") || !strcmp(fd.name, "..")) continue; Image* image; WCHAR fileName[32], filePath[128]; int length1 = MultiByteToWideChar(CP_ACP, 0, fd.name, strlen(fd.name), fileName, sizeof(fileName)); int length2 = MultiByteToWideChar(CP_ACP, 0, _folderName.c_str(), strlen(_folderName.c_str()), filePath, sizeof(filePath)); fileName[length1] = '\0'; filePath[length2] = '\0'; wstring file = filePath, name = fileName; file += '/'; file += name; //Ȯ Ȯ if (name.substr(name.find('.') + 1, name.length()) != L"bmp") image = Image::FromFile(file.c_str()); else image = Bitmap::FromFile(file.c_str()); if (image->GetLastStatus() == Ok) m_Images.emplace(fd.name, image); else GAME::Destroy(fileName, TEXT("̹ ε "), MB_OK | MB_ICONERROR); } while (_findnext(handle, &fd) == 0); } } void CResourceMgr::UnloadImages() { for (auto it : m_Images) delete it.second; } Image* CResourceMgr::GetImage(const string& _imageName) { // ó ؾ auto it = m_Images.find(_imageName); if (it != m_Images.end()) return m_Images.at(_imageName); else { GAME::Destroy(TEXT("GetImage Լ"), TEXT("ʴ ̹ Ͽϴ.\nα׷ մϴ."), MB_OK | MB_ICONERROR); return nullptr; } } void CResourceMgr::Clear() { UnloadImages(); }
true
64805c7d90a436b11b96535e63e49d21102f150a
C++
NicoG60/NumPyCpp
/test/test_npz.cpp
UTF-8
2,181
2.6875
3
[]
no_license
#include <catch2/catch.hpp> #include <numpycpp/numpycpp.h> #include "global.h" TEMPLATE_TEST_CASE("Open npz file", "[npz]", bool, int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t, float, double) { np::npz z = np::npz_load(NPZ_TYPES); for(auto& p : z) { np::array& a = p.second; REQUIRE(a.dimensions() == 1); REQUIRE(a.size() == 5); if(std::type_index(typeid (TestType)) == a.type().index()) { if(typeid (TestType) == typeid (bool)) { bool b0 = a[0].value<bool>(); bool b1 = a[1].value<bool>(); bool b2 = a[2].value<bool>(); bool b3 = a[3].value<bool>(); bool b4 = a[4].value<bool>(); REQUIRE(b0); REQUIRE_FALSE(b1); REQUIRE(b2); REQUIRE(b3); REQUIRE(b4); } else { TestType t0 = a[0].value<TestType>(); TestType t1 = a[1].value<TestType>(); TestType t2 = a[2].value<TestType>(); TestType t3 = a[3].value<TestType>(); TestType t4 = a[4].value<TestType>(); REQUIRE(t0 == static_cast<TestType>(-1)); REQUIRE(t1 == static_cast<TestType>(0)); REQUIRE(t2 == static_cast<TestType>(1)); REQUIRE(t3 == static_cast<TestType>(2)); REQUIRE(t4 == static_cast<TestType>(3)); } } else REQUIRE_THROWS(a[0].value<TestType>()); a = np::array(np::descr_t::make<TestType>(), {3, 3, 3}); REQUIRE(a.dimensions() == 3); REQUIRE(a.size(0) == 3); REQUIRE(a.size(1) == 3); REQUIRE(a.size(2) == 3); REQUIRE(a.size() == 27); const TestType* d = a.data_as<TestType>(); for(size_t i = 0; i < a.size(); i++) REQUIRE(d[i] == 0); REQUIRE_THROWS(a.at(3, 3, 3)); REQUIRE_NOTHROW(a.at(0, 1, 2)); } }
true
0c97c3f0a439ad5428618e6e9c192ce62d9e30ba
C++
katya-varlamova/4-sem-oop
/lab_02/matrix/matrix_base.cpp
UTF-8
500
2.578125
3
[]
no_license
// // MatrixBase.cpp // lab_02 // // Created by Екатерина on 18.04.2021. // Copyright © 2021 Екатерина. All rights reserved. // #include "matrix_base.hpp" MatrixBase::MatrixBase(size_t rows, size_t columns): rows(rows), cols(columns) { } size_t MatrixBase::get_cols() const noexcept { return cols; } size_t MatrixBase::get_rows() const noexcept { return rows; }; MatrixBase::operator bool() const noexcept { return cols && rows; } MatrixBase::~MatrixBase() {}
true
9e0a77df2627269ed35a58fbb70bcf0e44368751
C++
mstraughan86/Undergraduate-Studies
/UMUC - CMSC405/Project 1/graphic.cpp
UTF-8
486
3.09375
3
[]
no_license
// CMSC 405 Computer Graphics // Project 1 // Duane J. Jarc // August 1, 2013 // Function bodies of class that defines all graphic objects #include "stdafx.h" // Constructor that can only be called by the subclasses to initialize the color Graphic::Graphic(Color color) { this->color = color; } // Sets the color of the graphic to be draw. Must be called first by the draw function of the subclasses void Graphic::colorDrawing() const { glColor3d(color.red, color.green, color.blue); }
true
bf4586ec0219155b9d6647800efcaa840285207c
C++
holy-bit/LinkedList_Example
/List.h
ISO-8859-10
1,441
3.09375
3
[]
no_license
#pragma once template<typename E> class List { private: class Node { public: Node* prev; E elem; Node* next; Node(Node*, const E&, Node*); Node(Node*, E&&, Node*); Node() = delete; Node(const Node&)=delete; Node(Node&&) = delete; Node& operator=(const Node&) = delete; Node& operator=(Node&&) = delete; bool& operator==(const Node&) = delete; bool& operator!=(const Node&) = delete; bool& operator==(Node&) = delete; bool& operator!=(Node&) = delete; ~Node() = default; }; public: class iterator { public: friend class List; iterator(const iterator&); iterator(iterator&&); ~iterator iterator operator=(const iterator&); iterator operator=(iterator&&); iterator& operator++(); iterator& operator--() : bool operator!=(); bool operator==(); E& operator*(); E* operator->(); private: Node* node_ptr; iterator(Node*); }; List(); explicit List(const sdt::vector<E>&); List(conts T[], const std::size_t); List(const List&); List(List&&); iterator begin() const; iterator end() const; iterator addFirst(const E&); iterator addFirst(E&&); iterator addLast(const E&); iterator addLast(const E&&); iterator addAfter(const iterator, const E&); iterator addAfter(iterator, E&&); E remove(const iterator); void clear(); private: size_t size_; //Tamao de la lista Node* head; //Primer nodo de la lista Node* tail; //Ultimo nodo de la lista };
true
60d2eb244cfd0b225889a33a60f0e568e2cfed95
C++
InsightSoftwareConsortium/ITK
/Modules/IO/NIFTI/test/itkNiftiImageIOTest3.cxx
UTF-8
11,002
2.578125
3
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", ...
permissive
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkNiftiImageIOTest.h" #include <type_traits> // for enable_if #include <limits> template <typename ScalarType> void Decrement(ScalarType & value, std::enable_if_t<!std::numeric_limits<ScalarType>::is_signed, ScalarType> * = nullptr) { if (value > 1) { value--; } } template <typename ScalarType> void Decrement(ScalarType & value, std::enable_if_t<std::numeric_limits<ScalarType>::is_signed, ScalarType> * = nullptr) { if (value > -std::numeric_limits<ScalarType>::max() + 1) { value--; } } template <typename ScalarType, unsigned int TVecLength, unsigned int TDimension> int TestImageOfVectors(const std::string & fname, const std::string & intentCode = "") { constexpr int dimsize = 2; /** Deformation field pixel type. */ using FieldPixelType = typename itk::Vector<ScalarType, TVecLength>; /** Deformation field type. */ using VectorImageType = typename itk::Image<FieldPixelType, TDimension>; // // swizzle up a random vector image. typename VectorImageType::RegionType imageRegion; typename VectorImageType::SizeType size; typename VectorImageType::IndexType index; typename VectorImageType::SpacingType spacing; typename VectorImageType::PointType origin; // original test case was destined for failure. NIfTI always writes out 3D // orientation. The only sensible matrices you could pass in would be of the form // A B C 0 // D E F 0 // E F G 0 // 0 0 0 1 // anything in the 4th dimension that didn't follow that form would just come up scrambled. // NOTE: Nifti only reports up to 3D images correctly for direction cosigns. It is implicitly assumed // that the direction for dimensions 4 or greater come diagonal elements including a 1 in the // direction matrix. const typename VectorImageType::DirectionType myDirection = PreFillDirection<TDimension>(); std::cout << " === Testing VectorLength: " << TVecLength << " Image Dimension " << static_cast<int>(TDimension) << std::endl; std::cout << "======================== Initialized Direction" << std::endl; std::cout << myDirection << std::endl; for (unsigned int i = 0; i < TDimension; ++i) { size[i] = dimsize; index[i] = 0; spacing[i] = 1.0; origin[i] = 0; } imageRegion.SetSize(size); imageRegion.SetIndex(index); typename VectorImageType::Pointer vi = itk::IOTestHelper::AllocateImageFromRegionAndSpacing<VectorImageType>(imageRegion, spacing); vi->SetOrigin(origin); vi->SetDirection(myDirection); size_t dims[7]; size_t _index[7]; for (unsigned int i = 0; i < TDimension; ++i) { dims[i] = size[i]; } for (unsigned int i = TDimension; i < 7; ++i) { dims[i] = 1; } ScalarType value = std::numeric_limits<ScalarType>::max(); // for(fillIt.GoToBegin(); !fillIt.IsAtEnd(); ++fillIt) for (size_t l = 0; l < dims[6]; ++l) { _index[6] = l; for (size_t m = 0; m < dims[5]; ++m) { _index[5] = m; for (size_t n = 0; n < dims[4]; ++n) { _index[4] = n; for (size_t p = 0; p < dims[3]; ++p) { _index[3] = p; for (size_t i = 0; i < dims[2]; ++i) { _index[2] = i; for (size_t j = 0; j < dims[1]; ++j) { _index[1] = j; for (size_t k = 0; k < dims[0]; ++k) { _index[0] = k; FieldPixelType pixel; for (size_t q = 0; q < TVecLength; ++q) { // pixel[q] = randgen.drand32(lowrange,highrange); Decrement(value); pixel[q] = value; } for (size_t q = 0; q < TDimension; ++q) { index[q] = _index[q]; } vi->SetPixel(index, pixel); } } } } } } } if (!intentCode.empty()) { itk::MetaDataDictionary & dictionary = vi->GetMetaDataDictionary(); itk::EncapsulateMetaData<std::string>(dictionary, "intent_code", intentCode); } try { itk::IOTestHelper::WriteImage<VectorImageType, itk::NiftiImageIO>(vi, fname); } catch (const itk::ExceptionObject & ex) { std::string message; message = "Problem found while writing image "; message += fname; message += "\n"; message += ex.GetLocation(); message += "\n"; message += ex.GetDescription(); std::cout << message << std::endl; itk::IOTestHelper::Remove(fname.c_str()); return EXIT_FAILURE; } // // read it back in. typename VectorImageType::Pointer readback; try { readback = itk::IOTestHelper::ReadImage<VectorImageType>(fname); } catch (const itk::ExceptionObject & ex) { std::string message; message = "Problem found while reading image "; message += fname; message += "\n"; message += ex.GetLocation(); message += "\n"; message += ex.GetDescription(); std::cout << message << std::endl; itk::IOTestHelper::Remove(fname.c_str()); return EXIT_FAILURE; } bool same = true; if (!intentCode.empty()) { const itk::MetaDataDictionary & dictionary = readback->GetMetaDataDictionary(); std::string readIntentCode; if (itk::ExposeMetaData<std::string>(dictionary, "intent_code", readIntentCode)) { if (readIntentCode != intentCode) { std::cout << "intent_code is different: " << readIntentCode << " != " << intentCode << std::endl; same = false; } } else { std::cout << "The read image should have an intent_code in its dictionary" << std::endl; same = false; } } if (readback->GetOrigin() != vi->GetOrigin()) { std::cout << "Origin is different: " << readback->GetOrigin() << " != " << vi->GetOrigin() << std::endl; same = false; } if (readback->GetSpacing() != vi->GetSpacing()) { std::cout << "Spacing is different: " << readback->GetSpacing() << " != " << vi->GetSpacing() << std::endl; same = false; } for (unsigned int r = 0; r < TDimension; ++r) { for (unsigned int c = 0; c < TDimension; ++c) { if (itk::Math::abs(readback->GetDirection()[r][c] - vi->GetDirection()[r][c]) > 1e-7) { std::cout << "Direction is different:\n " << readback->GetDirection() << "\n != \n" << vi->GetDirection() << std::endl; same = false; break; } } } std::cout << "Original vector Image ?= vector Image read from disk " << std::endl; for (size_t l = 0; l < dims[6]; ++l) { _index[6] = l; for (size_t m = 0; m < dims[5]; ++m) { _index[5] = m; for (size_t n = 0; n < dims[4]; ++n) { _index[4] = n; for (size_t p = 0; p < dims[3]; ++p) { _index[3] = p; for (size_t i = 0; i < dims[2]; ++i) { _index[2] = i; for (size_t j = 0; j < dims[1]; ++j) { _index[1] = j; for (size_t k = 0; k < dims[0]; ++k) { _index[0] = k; FieldPixelType p1, p2; for (size_t q = 0; q < TDimension; ++q) { index[q] = _index[q]; } p1 = vi->GetPixel(index); p2 = readback->GetPixel(index); if (p1 != p2) { same = false; std::cout << p1 << " != " << p2 << " ERROR! " << std::endl; } else { std::cout << p1 << " == " << p2 << std::endl; } } } } } } } } if (same) { itk::IOTestHelper::Remove(fname.c_str()); } else { std::cout << "Failing image can be found at: " << fname << std::endl; } return same ? 0 : EXIT_FAILURE; } /** Test writing and reading a Vector Image */ int itkNiftiImageIOTest3(int argc, char * argv[]) { // // first argument is passing in the writable directory to do all testing if (argc > 1) { char * testdir = *++argv; itksys::SystemTools::ChangeDirectory(testdir); } else { return EXIT_FAILURE; } int success(0); success |= TestImageOfVectors<unsigned char, 3, 1>(std::string("testVectorImage_unsigned_char_3_1.nii.gz")); success |= TestImageOfVectors<char, 3, 1>(std::string("testVectorImage_char_3_1.nii.gz")); success |= TestImageOfVectors<unsigned short, 3, 1>(std::string("testVectorImage_unsigned_short_3_1.nii.gz")); success |= TestImageOfVectors<short, 3, 1>(std::string("testVectorImage_short_3_1.nii.gz")); success |= TestImageOfVectors<unsigned int, 3, 1>(std::string("testVectorImage_unsigned_int_3_1.nii.gz")); success |= TestImageOfVectors<int, 3, 1>(std::string("testVectorImage_int_3_1.nii.gz")); success |= TestImageOfVectors<unsigned long, 3, 1>(std::string("testVectorImage_unsigned_long_3_1.nii.gz")); success |= TestImageOfVectors<long, 3, 1>(std::string("testVectorImage_long_3_1.nii.gz")); success |= TestImageOfVectors<unsigned long long, 3, 1>(std::string("testVectorImage_unsigned_long_long_3_1.nii.gz")); success |= TestImageOfVectors<long long, 3, 1>(std::string("testVectorImage_long_long_3_1.nii.gz")); success |= TestImageOfVectors<float, 3, 1>(std::string("testVectorImage_float_3_1.nii.gz")); success |= TestImageOfVectors<float, 3, 2>(std::string("testVectorImage_float_3_2.nii.gz")); success |= TestImageOfVectors<float, 3, 3>(std::string("testVectorImage_float_3_3.nii.gz")); success |= TestImageOfVectors<float, 4, 3>(std::string("testVectorImage_float_4_3.nii.gz")); success |= TestImageOfVectors<float, 4, 4>(std::string("testVectorImage_float_4_4.nii.gz")); success |= TestImageOfVectors<double, 3, 3>(std::string("testVectorImage_double_3_3.nii.gz")); // Test reading/writing as displacement field (NIFTI intent code = 1006) success |= TestImageOfVectors<double, 3, 1>(std::string("testDispacementImage_double.nii.gz"), std::string("1006")); success |= TestImageOfVectors<float, 3, 1>(std::string("testDisplacementImage_float.nii.gz"), std::string("1006")); return success; }
true
c472413eb0062b2cb4ddd430f31e62698eae0455
C++
yami/DBricks
/src/diagram/ZoomWindow.hxx
UTF-8
1,115
2.515625
3
[]
no_license
#ifndef ZOOMWINDOW_HXX #define ZOOMWINDOW_HXX #include <geom/Point.hxx> #include <geom/Rect.hxx> #include <sigc++/sigc++.h> namespace DBricks { class ZoomWindow { public: ZoomWindow(const Rect& visible, double factor); double to_display_length(double length) const; Point to_display_coord(const Point& point) const; Rect to_display_rect(const Rect& rect) const; double to_real_length(double length) const; Point to_real_coord(const Point& point) const; Rect to_real_rect(const Rect& rect) const; double x1() const; double y1() const; double x2() const; double y2() const; double width() const; double height() const; Rect visible() const; double factor() const; void set(double factor, const Rect& visible); sigc::signal<void, const ZoomWindow&>& signal_changed(); private: Rect m_visible; // visible area: rectangle in real double m_factor; // zoom factor = visible/real sigc::signal<void, const ZoomWindow&> m_signal_changed; }; } // namespace DBricks #endif // ZOOMWINDOW_HXX
true
c8920ba2adff4acd3ebc7135bf757a2459b2198e
C++
Fiereu/SimpleCheatLoader
/Loader/Crypt.cpp
UTF-8
136
2.828125
3
[]
no_license
#include "Crypt.h" void XOR(BYTE* data, DWORD size) { for (int i = 0; i < size; i++) { data[i] = data[i] ^ 0x83FE + i; } }
true
ffa49dc34e91bdceee9147e3fc694ff7be0c2a0e
C++
najosky/darkeden-v2-serverfiles
/src/server/gameserver/quest/ActionOriginalDeleteGetItem.h
UHC
1,775
2.890625
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Filename : ActionPcGetItem.h // Written By : excel96 // Description : // Creature PC . NPC ȭâ µȴ. ////////////////////////////////////////////////////////////////////////////// #ifndef __ACTION_ORIGINAL_DELETE_GETITEM_H__ #define __ACTION_ORIGINAL_DELETE_GETITEM_H__ #include "Types.h" #include "Exception.h" #include "Action.h" #include "ActionFactory.h" #include "Item.h" ////////////////////////////////////////////////////////////////////////////// // class ActionPcGetItem ////////////////////////////////////////////////////////////////////////////// class ActionOriginalDeleteGetItem : public Action { public: virtual ActionType_t getActionType() const throw() { return ACTION_ORIGINAL_DELETE_GETITEM; } virtual void read(PropertyBuffer & propertyBuffer) throw(Error); virtual void execute(Creature* pCreature1, Creature* pCreature2 = NULL) throw(Error); virtual string toString() const throw(); public: private: // ᰡ Ǵ . Item::ItemClass m_ItemClass; ItemType_t m_ItemType; ItemNum_t m_ItemNum; }; ////////////////////////////////////////////////////////////////////////////// // class ActionPcGetItemFactory; ////////////////////////////////////////////////////////////////////////////// class ActionOriginalDeleteGetItemFactory : public ActionFactory { public: virtual ActionType_t getActionType() const throw() { return Action::ACTION_ORIGINAL_DELETE_GETITEM; } virtual string getActionName() const throw() { return "OriginalDeleteGetItem"; } virtual Action* createAction() const throw() { return new ActionOriginalDeleteGetItem(); } }; #endif
true
9249d5de008513977254bd75f7324a1119ba797a
C++
Sometrik/sqldb
/include/MySQL.h
UTF-8
779
2.546875
3
[ "MIT" ]
permissive
#ifndef _SQLDB_MYSQL_H_ #define _SQLDB_MYSQL_H_ #include "Connection.h" #include <mysql.h> namespace sqldb { class MySQL : public Connection { public: MySQL() { } ~MySQL(); void connect(std::string host_name, int port, std::string user_name, std::string password, std::string db_name); void connect(); std::unique_ptr<SQLStatement> prepare(std::string_view query) override; bool ping() override; void begin() override; void commit() override; void rollback() override; std::pair<size_t, size_t> execute(std::string_view query) override; bool isConnected() const { return conn_ != 0; } private: MYSQL * conn_ = 0; std::string host_name_, user_name_, password_, db_name_; int port_ = 0; }; }; #endif
true
a23fedda0d3e068776e618a4d632b8c6403eb5d0
C++
kazuuuuuuuuui/RaceGame
/第4ターム作品審査会/Vec3.cpp
SHIFT_JIS
3,891
3.28125
3
[]
no_license
#include"Vec3.h" #include<math.h> #include<assert.h> namespace oka { //------------------------------------- //ftHgRXgN^ Vec3::Vec3(): m_x(0), m_y(0), m_z(0) {} //------------------------------------- //tRXgN^ //ƂĎ󂯎lŃo Vec3::Vec3(const float _x, const float _y, const float _z): m_x(_x), m_y(_y), m_z(_z) {} //------------------------------------- //Zq̃I[o[[h //vec3+vec3 Vec3 Vec3::operator+(const Vec3 &_v)const { Vec3 out; out.m_x = this->m_x + _v.m_x; out.m_y = this->m_y + _v.m_y; out.m_z = this->m_z + _v.m_z; return out; } //vec3-vec3 Vec3 Vec3::operator-(const Vec3 &_v)const { Vec3 out; out.m_x = this->m_x - _v.m_x; out.m_y = this->m_y - _v.m_y; out.m_z = this->m_z - _v.m_z; return out; } //vec3*vec3 Vec3 Vec3::operator*(const Vec3 &_v)const { Vec3 out; out.m_x = this->m_x * _v.m_x; out.m_y = this->m_y * _v.m_y; out.m_z = this->m_z * _v.m_z; return out; } //vec3 / vec3 Vec3 Vec3::operator/(const Vec3 &_v)const { Vec3 out; out.m_x = this->m_x / _v.m_x; out.m_y = this->m_y / _v.m_y; out.m_z = this->m_z / _v.m_z; return out; } //vec3+=vec3 Vec3 &Vec3::operator +=(const Vec3 &_v) { this->m_x += _v.m_x; this->m_y += _v.m_y; this->m_z += _v.m_z; return *this; } //vec3-=vec3 Vec3 &Vec3::operator -=(const Vec3 &_v) { this->m_x -= _v.m_x; this->m_y -= _v.m_y; this->m_z -= _v.m_z; return *this; } //vec3*=vec3 Vec3 &Vec3::operator *=(const Vec3 &_v) { this->m_x *= _v.m_x; this->m_y *= _v.m_y; this->m_z *= _v.m_z; return *this; } //vec3/=vec3 Vec3 &Vec3::operator /=(const Vec3 &_v) { this->m_x /= _v.m_x; this->m_y /= _v.m_y; this->m_z /= _v.m_z; return *this; } //vec3 = vec3 + float Vec3 Vec3::operator+(const float _s)const { Vec3 out; out.m_x = this->m_x + _s; out.m_y = this->m_y + _s; out.m_z = this->m_z + _s; return out; } //vec3 = vec3 - float Vec3 Vec3::operator-(const float _s)const { Vec3 out; out.m_x = this->m_x - _s; out.m_y = this->m_y - _s; out.m_z = this->m_z - _s; return out; } //vec3 = vec3 * float Vec3 Vec3::operator*(const float _s)const { Vec3 out; out.m_x = this->m_x * _s; out.m_y = this->m_y * _s; out.m_z = this->m_z * _s; return out; } //vec3 = vec3 / float Vec3 Vec3::operator/(const float _s)const { Vec3 out; out.m_x = this->m_x / _s; out.m_y = this->m_y / _s; out.m_z = this->m_z / _s; return out; } //vec3 += float Vec3 &Vec3::operator +=(const float _s) { this->m_x += _s; this->m_y += _s; this->m_z += _s; return *this; } //vec3 -= float Vec3 &Vec3::operator -=(const float _s) { this->m_x -= _s; this->m_y -= _s; this->m_z -= _s; return *this; } //vec3 *= float Vec3 &Vec3::operator *=(const float _s) { this->m_x *= _s; this->m_y *= _s; this->m_z *= _s; return *this; } //vec3 /= float Vec3 &Vec3::operator /=(const float _s) { this->m_x /= _s; this->m_y /= _s; this->m_z /= _s; return *this; } //------------------------------------- //g̃xNg̒Ԃ float Vec3::Length()const { return sqrtf((m_x*m_x) + (m_y*m_y) + (m_z*m_z)); } //----------------------------------------------- //xNg̐K //xNg̒0̏ꍇKoȂ̂assert void Vec3::Normalize() { float length = this->Length(); assert(length); m_x /= length; m_y /= length; m_z /= length; } //------------------------------------- //xNg̊OόvZ Vec3 Vec3::Cross(const Vec3 &_v1, const Vec3 &_v2) { Vec3 out; out.m_x = _v1.m_y*_v2.m_z - _v1.m_z*_v2.m_y; out.m_y = _v1.m_z*_v2.m_x - _v1.m_x*_v2.m_z; out.m_z = _v1.m_x*_v2.m_y - _v1.m_y*_v2.m_x; return out; } }
true
00954865409f4a05122caec8032acef104b29e45
C++
hhcoder/StudyTMP
/std_function.cpp
UTF-8
3,082
3.4375
3
[]
no_license
#include <iostream> #include <cmath> #include <vector> template <typename Container> void PrintAllElements(Container& c) { std::cout << std::endl << "("; for (auto i = c.begin(); i!=c.end(); i++) std::cout << *i << ","; std::cout << ")" << std::endl; } #include <chrono> #include <utility> namespace Profiling { struct MeasureTime { MeasureTime(const std::string& in_title) : start(std::chrono::system_clock::now()), title(in_title){}; ~MeasureTime() { auto end = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end-start; std::cout << title << ": " << diff.count() << " s" << std::endl; } decltype(std::chrono::system_clock::now()) start; std::string title; }; template <typename FxnType, typename... Args> void FxnTime(const std::string& str, FxnType f, Args&&... args) { MeasureTime m(str); f(std::forward<decltype(args)>(args)...); } } // Pay attention to the "ForEach" syntax, it works for both FxnPtr and Functor! template <typename InputContainer, typename OutputContainer, typename Operation, typename... Args> void ForEach(InputContainer& in_value, OutputContainer& out_value, Operation& op, Args&&... args) { for (auto i = in_value.begin(), j=out_value.begin(); i!=in_value.end(); i++, j++) *j = op(*i, std::forward<decltype(args)>(args)...); } namespace FxnPtrApproach { int MultiplyFloat(int ia, const float ratio) { return static_cast<int>(std::round(ia * ratio)); } void Exe(std::vector<int>& in_value, std::vector<int>& out_value, const float ratio) { PrintAllElements(in_value); ForEach(in_value, out_value, MultiplyFloat, ratio); PrintAllElements(out_value); } }; namespace FunctorApproach { struct MultiplyFloatLut { MultiplyFloatLut(const float ratio) : lut(new int[1024]) { for (int i=0; i<1024; i++) lut[i] = static_cast<int>(std::round(i*ratio)); } ~MultiplyFloatLut() { delete[] lut; } int operator()(int in) { return lut[in]; } int* lut; }; void Exe(std::vector<int>& in_value, std::vector<int>& out_value, const float ratio) { PrintAllElements(in_value); MultiplyFloatLut lut(ratio); ForEach(in_value, out_value, lut); PrintAllElements(out_value); } } // How about Lambda function? int main(int argc, char* argv[]) { std::vector<int> a = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; std::vector<int> b(a.size()); const float ratio = 2.37808; Profiling::FxnTime("Function Pointer Approach", FxnPtrApproach::Exe, a, b, ratio); Profiling::FxnTime("Functor Approach", FunctorApproach::Exe, a, b, ratio); // Can I do this? int sum = 0; for (auto i=0, j=0; i<1024; i++) sum += i; return 0; }
true
6c6e2a7b4bb7fc94cc474f8f865de76d214ebeed
C++
Parveen-jangra/hacktoberfest-competitiveprogramming
/Binary Tree/Verify Preorder Serialization of a Binary Tree/main.cpp
UTF-8
734
3.015625
3
[ "MIT" ]
permissive
#include <iostream> #include <bits/stdc++.h> using namespace std; class Solution { public: bool isValidSerialization(string preorder) { stringstream ss(preorder); string curr; int nodes = 1; while (getline(ss, curr, ',')) { nodes--; if (nodes < 0) return false; if (curr != "#") nodes += 2; } return nodes == 0; } }; int main() { Solution s; cout << s.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#") << endl; cout << s.isValidSerialization("1,#") << endl; cout << s.isValidSerialization("9,#,#,1") << endl; cout << s.isValidSerialization("1,#,#,#") << endl; return 0; }
true
7632cb1cfc6e335e9efba4e2e16289e2dbe91ba3
C++
hbruintjes/ceema
/src/protocol/data/Poll.h
UTF-8
4,326
2.515625
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2017 Harold Bruintjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <types/bytes.h> #include <json/src/json.hpp> #include <encoding/hex.h> #include <protocol/data/Client.h> using json = nlohmann::json; namespace ceema { /** * ID used by poll owner */ struct poll_id : byte_array<8> { using byte_array::byte_array; }; /** * Unique poll ID, both the owner ID and poll ID */ struct poll_uid : byte_array<client_id::array_size + poll_id::array_size> { using byte_array::byte_array; poll_id pid() const { return poll_id(slice_array<client_id::array_size, poll_id::array_size>(*this)); } client_id cid() const { return client_id(slice_array<0, client_id::array_size>(*this)); } }; enum class PollSelection { SINGLE = 0x00, MULTIPLE = 0x01 }; enum class PollType { TEXT = 0x00 }; enum class PollDisclose { ON_CLOSE = 0x00, INTERMEDIATE = 0x01 }; enum class PollStatus { OPEN = 0x00, CLOSED = 0x01 }; struct PollChoice { std::string name; unsigned id; unsigned order; // Contains the votes from each of the respondees std::vector<bool> votes; }; inline void to_json(json& j, PollChoice const& c) { json votes; for(bool v: c.votes) { votes.push_back(v?1:0); } j = json{{"i", c.id}, {"n", c.name}, {"o", c.order}, {"r", votes}}; } inline void from_json(json const& j, PollChoice& c) { c.name = j["n"].get<std::string>(); c.id = j["i"].get<unsigned>(); c.order = j["o"].get<unsigned>(); for(auto const& vote: j["r"]) { c.votes.push_back(vote.get<unsigned>()?true:false); } } struct Poll { std::string description; PollSelection selection; PollType type; PollDisclose disclose; PollStatus status; std::vector<PollChoice> choices; std::vector<client_id> respondees; }; inline void to_json(json& j, Poll const& p) { j = json::object({ {"d", p.description}, {"s", static_cast<unsigned>(p.status)}, {"a", static_cast<unsigned>(p.selection)}, {"t", static_cast<unsigned>(p.disclose)}, {"o", static_cast<unsigned>(p.type)}, {"c", json::array()}, {"p", json::array()} }); json& jchoices = j["c"]; for(auto const& choice: p.choices) { jchoices.push_back(json{choice}); } json& participants = j["p"]; for(auto const& responder: p.respondees) { participants.push_back(responder.toString()); } } inline void from_json(json const& j, Poll& p) { p.description = j["d"].get<std::string>(); p.status = static_cast<PollStatus>(j["s"].get<unsigned>()); p.selection = static_cast<PollSelection>(j["a"].get<unsigned>()); p.disclose = static_cast<PollDisclose>(j["t"].get<unsigned>()); p.type = static_cast<PollType>(j["o"].get<unsigned>()); for(json const& choice: j["c"]) { p.choices.push_back(choice.get<PollChoice>()); } for(auto const& participant: j["p"]) { p.respondees.push_back(client_id::fromString(participant)); } } struct PollVoteChoice { unsigned id; bool chosen; }; inline void to_json(json& j, PollVoteChoice const& c) { j = json::array({c.id, c.chosen?1:0}); } inline void from_json(json const& j, PollVoteChoice& c) { c.id = j[0].get<unsigned>(); c.chosen = j[1].get<unsigned>()?true:false; } }
true
cf3e49aeb12ecc32b1e14971696479bfda6adf87
C++
rechhabra/Cattis
/enlarginghashtables.cpp
UTF-8
1,297
3.078125
3
[]
no_license
#include <iostream>//std #include <cstring>//strlen #include <algorithm>//math stuff #include <math.h>//pow,ceil,sin,cos,etc. #include <vector>//vector #include <string>//string opers #include <stack> //stack list #include <sstream> //split asst., string to int #include <stdio.h>//extra #include <iomanip>//round n digit: cout<<setprecision(n)<<fixed<< #include <bits/stdc++.h>//permutations using namespace std; //removes use of const long double PI= 3.141592653589793238L; bool isPrime (int num) { if (num <=1) return false; else if (num == 2) return true; else if (num % 2 == 0) return false; else { bool prime = true; int divisor = 3; double num_d = static_cast<double>(num); int upperLimit = static_cast<int>(sqrt(num_d) +1); while (divisor <= upperLimit) { if (num % divisor == 0) prime = false; divisor +=2; } return prime; } } int main(){ while (1){ int num; cin>>num; if (num==0){break;} int bigger = num*2; for (int i = num*2+1; true; i++){ if (isPrime(i)){ cout<<i; break; } } if (not isPrime(num)){ cout<<" ("<<num<<" is not prime)"; } cout<<endl; } return 0; }
true
4e81b23df59741f1c41eca376cf99ca6c7f1e99a
C++
weidi0629/general_coding
/lc/general.data.management.vector.etc/300 1187 longest increasing subsequence/solution.cpp
UTF-8
1,976
3.75
4
[]
no_license
/* 首先先做300, lis。 方法1是building tail in the fly (1) if x is larger than all tails, append it, increase the size by 1 (2) if tails[i-1] < x <= tails[i], update tails[i] tail[i] 表示len = i 的数组,最小的tail 比如 [4,5] [4,5,6] 现在来一个7, 他不会去更新len=2的数组,因为7比6还大,所以至少要更新len=3的数组 */ public int lengthOfLIS(int[] nums) { int[] tails = new int[nums.length]; // int size = 0; for (int x : nums) { int i = 0, j = size; while (i != j) { // i,j都是index,本题中代表长度 int m = (i + j) / 2; if (tails[m] < x) i = m + 1; else j = m; } tails[i] = x; // 其实binary search停在的是i-1的位置,所以是更新 i(i是长度) if (i == size) ++size; } return size; } /* 方法2是dp dp[i]表示截止到i,最长的数组是多少, 应该是比较好理解的 */ public int lengthOfLIS(int[] nums) { // Base case if(nums.length <= 1) return nums.length; // This will be our array to track longest sequence length int dp[] = new int[nums.length]; // Fill each position with value 1 in the array for(int i=0; i < nums.length; i++) dp[i] = 1; // Mark one pointer at i. For each i, start from j=0. for(int i=1; i < nums.length; i++) { for(int j=0; j < i; j++) { // It means next number contributes to increasing sequence. if(nums[j] < nums[i]) { // But increase the value only if it results in a larger value of the sequence than T[i] // It is possible that T[i] already has larger value from some previous j'th iteration if(dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; } } } } // Find the maximum length from the array that we just generated int longest = 0; for(int i=0; i < T.length; i++) longest = Math.max(longest, dp[i]); return longest; }
true