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
40576f7e83511e899f8b539d01ffd511c3328841
C++
Iktwo/hk
/src/healthdataworkout.h
UTF-8
2,460
2.8125
3
[ "MIT" ]
permissive
#ifndef HEALTHDATAWORKOUT_H #define HEALTHDATAWORKOUT_H #include <QObject> #include <QDateTime> class HealthDataWorkout : public QObject { Q_OBJECT public: explicit HealthDataWorkout(QObject *parent = nullptr); Q_PROPERTY(HealthDataActivityType activityType READ activityType NOTIFY activityTypeChanged) Q_PROPERTY(double duration READ duration NOTIFY durationChanged) Q_PROPERTY(QString durationUnit READ durationUnit WRITE setDurationUnit NOTIFY durationUnitChanged) Q_PROPERTY(double distance READ distance NOTIFY distanceChanged) Q_PROPERTY(QString distanceUnit READ distanceUnit WRITE setDistanceUnit NOTIFY distanceUnitChanged) Q_PROPERTY(double energyBurned READ energyBurned NOTIFY energyBurnedChanged) Q_PROPERTY(QString energyBurnedUnit READ energyBurnedUnit WRITE setEnergyBurnedUnit NOTIFY energyBurnedUnitChanged) Q_PROPERTY(QDateTime startDate READ startDate NOTIFY startDateChanged) enum class HealthDataActivityType { Other, Walking, Cycling, Running, Soccer, HighIntensityIntervalTraining, Swimming, Rowing }; Q_ENUM(HealthDataActivityType) static HealthDataActivityType stringToActivityType(const QString & string); HealthDataActivityType activityType() const; double duration() const; QString durationUnit() const; double distance() const; QString distanceUnit() const; double energyBurned() const; QString energyBurnedUnit() const; QDateTime startDate() const; void setActivityType(HealthDataActivityType activityType); void setDuration(double duration); void setDistance(double distance); void setEnergyBurned(double energyBurned); void setStartDate(QDateTime startDate); void setDurationUnit(QString durationUnit); void setDistanceUnit(QString distanceUnit); void setEnergyBurnedUnit(QString energyBurnedUnit); signals: void activityTypeChanged(); void durationChanged(); void durationUnitChanged(); void distanceChanged(); void distanceUnitChanged(); void energyBurnedChanged(); void energyBurnedUnitChanged(); void startDateChanged(); private: HealthDataActivityType m_activityType; double m_duration; double m_distance; double m_energyBurned; QDateTime m_startDate; QString m_durationUnit; QString m_distanceUnit; QString m_energyBurnedUnit; }; #endif // HEALTHDATAWORKOUT_H
true
40e1dbdcb34db5065dcf0a00acba7bf3b86f38a0
C++
Merisho/comprog
/codeforces/round-684-div-2/c.cpp
UTF-8
2,058
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; vector<vector<int>> ans; vector<string> a; vector<pair<int, int>> o; vector<pair<int, int>> z; vector<int> tr; void invert(vector<int>& coords) { for (int i = 0; i < coords.size(); i += 2) { int x = coords[i]; int y = coords[i + 1]; a[x][y] = (((a[x][y] - '0') + 1) % 2) + '0'; } } void make_zero() { if (o.size() == 0) { return; } tr = vector<int>(6); if (o.size() >= 3) { for (int i = 0; i < 3; ++i) { tr[i * 2] = o[o.size() - 1].first; tr[i * 2 + 1] = o[o.size() - 1].second; z.push_back(o[o.size() - 1]); o.pop_back(); } ans.push_back(tr); } else if (o.size() == 2) { tr[0] = o[1].first; tr[1] = o[1].second; tr[2] = z[0].first; tr[3] = z[0].second; tr[4] = z[1].first; tr[5] = z[1].second; ans.push_back(tr); auto z1 = z[0]; auto z2 = z[1]; z.pop_back(); z[0] = o[1]; o.pop_back(); o.push_back(z1); o.push_back(z2); } else if (o.size() == 1) { tr[0] = o[0].first; tr[1] = o[0].second; tr[2] = z[1].first; tr[3] = z[1].second; tr[4] = z[2].first; tr[5] = z[2].second; ans.push_back(tr); auto z1 = z[1]; auto z2 = z[2]; z.pop_back(); z[1] = o[0]; o.pop_back(); o.push_back(z1); o.push_back(z2); } invert(tr); return make_zero(); } int main() { int T; cin >> T; for (int test_case = 1; test_case <= T; ++test_case) { int n, m; cin >> n >> m; a = vector<string>(n); for (string& ai : a) { cin >> ai; } ans = vector<vector<int>>(); for (int x = 0; x < n - 1; ++x) { for (int y = 0; y < m - 1; ++y) { o = vector<pair<int, int>>(); z = vector<pair<int, int>>(); for (int i = x; i <= x + 1; ++i) { for (int j = y; j <= y + 1; ++j) { if (a[i][j] == '1') { o.push_back({i, j}); } else { z.push_back({i, j}); } } } make_zero(); } } cout << ans.size() << endl; for (vector<int> a : ans) { for (int aa : a) { cout << (aa + 1) << " "; } cout << endl; } } return 0; }
true
03d55957dc9cdfc998b8d10781e9af831fb58c7c
C++
Hydraz320/CPP-Primer-Practice
/chapter4/4.22.cpp
UTF-8
688
3.546875
4
[]
no_license
#include <iostream> #include <string> #include <vector> #include <iterator> #include <cstring> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; using std::begin; using std::end; using std::strcat; using std::strcpy; string grade(int point) { string final_grade = (point < 75) ? ((point < 60) ? ("fail") : ("low pass")) : ((point < 90) ? ("pass") : ("high pass")); return final_grade; } int main() { vector<int> points{ 66, 100, 48, 88 }; for (auto i : points) cout << i << ": " << grade(i) << endl; getchar(); getchar(); return 0; }
true
f7ee53f15ab9616fb46b3f60132d44eb69c7cd72
C++
mehulthakral/logic_detector
/backend/CDataset/isValidBST/isValidBST_63.cpp
UTF-8
512
3.140625
3
[]
no_license
class Solution { public:class TreeNode{ public: TreeNode* left; TreeNode* right; int val; }; bool isValidBST(TreeNode* root) { return helper(root, numeric_limits<long long int>::min(), numeric_limits<long long int>::max()); } bool helper(TreeNode* root, long long int lower, long long int upper) { return !root || root->val > lower && root->val < upper && helper(root->left, lower, root->val) && helper(root->right, root->val, upper); } };
true
4104c5f417e42904c24d122adda82382beb4a2d3
C++
rack-leen/qt-example
/myproject/ExtensionDialog/ExtensionDialog/dialog.cpp
UTF-8
3,261
2.921875
3
[]
no_license
#include "dialog.h" #include <QVBoxLayout> #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QHBoxLayout> #include <QPushButton> #include <QDialogButtonBox> #include <QGridLayout> Dialog::Dialog(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("ExtensionDialog")); //设置窗口标题 createBaseInfor(); //创建基本窗口 createDetailInfor(); //创建详细窗口 QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addWidget(baseWidget); mainLayout->addWidget(detailWidget); mainLayout->setSizeConstraint(QLayout::SetFixedSize); //固定尺寸 mainLayout->setSpacing(10); } void Dialog::createBaseInfor() { baseWidget = new QWidget ; //创建基本窗口对象 QLabel *nameLabel = new QLabel(tr("姓名:")); QLineEdit *nameLineEdit = new QLineEdit ; QLabel *sexLabel = new QLabel(tr("性别:")); QComboBox *sexComboBox = new QComboBox ; sexComboBox->insertItem(0,tr("男")); sexComboBox->insertItem(1,tr("女")); sexComboBox->insertItem(2,tr("妖")); QGridLayout *leftLayout = new QGridLayout ; leftLayout->addWidget(nameLabel,0,0); leftLayout->addWidget(nameLineEdit,0,1); leftLayout->addWidget(sexLabel,1,0); leftLayout->addWidget(sexComboBox,1,1); QPushButton *okButton = new QPushButton(tr("确定")) ; QPushButton *detailButton = new QPushButton(tr("详细")) ; QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Vertical); //按钮盒子使用垂直布局 buttonBox->addButton(okButton,QDialogButtonBox::ActionRole); buttonBox->addButton(detailButton,QDialogButtonBox::ActionRole); QHBoxLayout *mainLayout = new QHBoxLayout(baseWidget); mainLayout->addLayout(leftLayout); mainLayout->addWidget(buttonBox); connect(detailButton , &QPushButton::clicked , this , &Dialog::showDetailInfor); } void Dialog::createDetailInfor() { detailWidget = new QWidget ; //创建详细窗体部分 QLabel *ageLabel = new QLabel(tr("年龄:")); QLineEdit *ageLineEdit = new QLineEdit ; ageLineEdit->setText(tr("18")); //设置默认年龄 QLabel *departmentLabel = new QLabel(tr("部门:")); QComboBox *departmentComboBox = new QComboBox ; departmentComboBox->addItem(tr("销售部")); departmentComboBox->addItem(tr("营销部")); departmentComboBox->addItem(tr("市场部")); departmentComboBox->addItem(tr("人事部")); departmentComboBox->insertItem(4,tr("后勤部")); //两种方法增加都可以 QLabel *emailLabel = new QLabel(tr("Email:")); QLineEdit *emailLineEdit = new QLineEdit ; emailLineEdit->setText(tr("1214236547@qq.com")); QGridLayout *mainLayout = new QGridLayout(detailWidget); mainLayout->addWidget(ageLabel,0,0); mainLayout->addWidget(ageLineEdit,0,1); mainLayout->addWidget(departmentLabel,1,0); mainLayout->addWidget(departmentComboBox,1,1); mainLayout->addWidget(emailLabel,2,0); mainLayout->addWidget(emailLineEdit,2,1); detailWidget->hide(); } void Dialog::showDetailInfor() { if(detailWidget->isHidden()) //如果detail窗口被隐藏 { detailWidget->show(); } else { detailWidget->hide() ; } } Dialog::~Dialog() { }
true
e5d98c01a76c6c39350de6c8b24e76667e7219f3
C++
SoilRos/dune-copasi
/dune/copasi/common/factory.hh
UTF-8
1,028
2.9375
3
[]
no_license
#ifndef DUNE_COPASI_FACTORY_HH #define DUNE_COPASI_FACTORY_HH #include <memory> #include <dune/common/typetraits.hh> namespace Dune::Copasi { /** @defgroup Factory Factory @{ @brief Class instance creator A factory should be able to create an instance of a type out of @ref DataContext. This is done by the definition of an specialization of the class Factory and a static function create. One thing to take into account is that data context can only store unique values of certain data type. This is quite restrictive is the contructor of T contains repeated or very common types (e.g. `T{int,int,double}`), in shuch case, is best to wrap these values in a unique struct that contains all of these. @} */ /** * @brief Class Factory * * @tparam T Type to be created */ template<class T> struct Factory { // Factory for type T has not been instantiated static_assert(Dune::AlwaysFalse<T>::value, "Factory does not exist"); }; } // namespace Dune::Copasi #endif // DUNE_COPASI_FACTORY_HH
true
e5336c52c4b661f75d882286ddb96f8731b23fdd
C++
farqnyy8/C-Practice-1
/for loop class.cpp
UTF-8
1,013
3.546875
4
[]
no_license
/* Write a C++ program to create the following menu: Please select form the menu: 1. French Fries.................$5.00 2. Caesar Salad...............$8.00 3. Mushroom Soup........$10.00 Enter you choice here=> Then find the total cost for the meal. */ #include <iostream> using namespace std; int main() { //local var int order; double total=0; //code do { system("cls"); cout<<"Please select form the menu:\n1. French fries.................$5.00\n2. Caesar Salad...............$8.00\n3. Mushroom Soup........$10.00\n"<<endl; cout<<"Enter you choice here=> "; cin>>order; switch(order) { case 1: total+=5.99;break; case 2: total+=8.50;break; case 3: total+=10.00;break; case 4: system("exit"); break; default: cout<<"Invalid order, Please order again."; } }while(order!=4); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout<<"\nTotal: $"<<total<<endl; }
true
5033cd977f028b23a50a56945864f509444a9f0d
C++
Neomer/pathfinder
/game_server/game/cards/armors/MagicChainMail.cpp
UTF-8
967
2.640625
3
[]
no_license
// // Created by vinokurov on 29.06.2019. // #include "MagicChainMail.h" std::string_view MagicChainMailMetadata::getCardTitle() const { return "Волшебная кольчуга"; } const char *MagicChainMailMetadata::getTypeName() const { return "MagicChainMail"; } const char *MagicChainMailMetadata::getDescription() const { return CardMetadata::getDescription(); } std::shared_ptr<Card> MagicChainMailMetadata::createInstance() const { return std::shared_ptr<Card>(new MagicChainMail()); } bool MagicChainMailMetadata::isBeginnerLevel() const { return false; } int MagicChainMailMetadata::TypeId() const { return 100; } void MagicChainMailMetadata::fillAttributes(std::vector<ActiveCardMetadata::CardAttribute> &attributes) { attributes.push_back(CardAttribute::Magic); attributes.push_back(CardAttribute::HeavyArmor); } MagicChainMail::~MagicChainMail() { } int MagicChainMail::getTypeId() const { return 100; }
true
2fb274930c0b2a9e57fb1162000f5547da797cb8
C++
TinyCowry/MySTL
/dataStuct/BinarySearchTree.cpp
UTF-8
6,996
3.703125
4
[]
no_license
/* *二叉搜索树 *http://www.cnblogs.com/skywang12345/p/3576373.html */ #ifndef _BINARYSEARCHTREE_ #define _BINARYSEARCHTREE_ #include <iostream> using namespace std; template<class T> struct TreeNode{ T val; TreeNode* left; TreeNode* right; TreeNode* parent; TreeNode(T val, TreeNode* left, TreeNode* right, TreeNode* parent) : val(value), left(l), right(r), parent() {} } template<class T> class BinarySearchTree{ public: BSTree(); ~BSTree(); //遍历 void preOrder(); void inOrder(); void postOrder(); TreeNode<T>* search(T x);//递归搜索 TreeNode<T>* iteraorsearch(T x);//非递归搜索 // 最大值和最小值 T minimum();//返回最小值,为T类型 T maximum();//返回最大值,为T类型 TreeNode<class T>* successor(TreeNode<T>* node);//后继节点是该节点的右子树中的最小节点 TreeNode<class T>* predecessor(TreeNode<T>* node);//前驱节点是该节点的左子树中的最大节点 void insert(T x); void remove(T x); void destroy(); void print(); private: //三种遍历方式 void preOrder(TreeNode<T>* root) const; void inOrder(TreeNode<T>* root) const; void postOrder(TreeNode<T>* root) const; TreeNode<T>* search(TreeNode<T>* x, T key);//递归方式 TreeNode<T>* iteraorsearch(TreeNode<T>* x, T key);//非递归方式 TreeNode<T>* minimum(TreeNode<T>* node);//二叉树中的最小值,此处返回的是最小点的指针 TreeNode<T>* maximum(TreeNode<T>* node);//二叉树中的最大值,此处返回的是最大点的指针 void insert(TreeNode<T>* node, TreeNode<T>* x);//插入 TreeNode<T>* remove(TreeNode<T>* root, TreeNode<T>* x);//移除 void destroy(TreeNode<T>* root);//销毁二叉树 void print(TreeNode<T>* root);//打印二叉树 private: TreeNode<T>* m_root; }; template<class T> void BSTree<T>::preOrder(TreeNode<class T>* root) const { if(root != NULL) { cout << root->val; preOrder(root->left); preOrder(root->right); } } template<class T> void BSTree<T>::preOrder() { preOrder(m_root); } template<class T> void BSTree<T>::inOrder(TreeNode<class T>* root) const { if(root != NULL) { inOrder(root->left); cout << root->val; inOrder(root->right); } } template<class T> void BSTree<T>::inOrder() { inOrder(m_root); } template<class T> void BSTree<T>::postOrder(TreeNode<class T>* root) const { if(root != NULL) { postOrder(root->left); postOrder(root->right); cout << root->val; } } template<class T> void BSTree<T>::postOrder() { postOrder(m_root); } template<class T> TreeNode<T>* BSTree<T>::search(TreeNode<class T>* node, T key) { bool findFlag = false; while((!findFlag) || node == NULL) { if(node->val == key) findFlag = true; else if(key < node->val) { node = node->left; } else { node = node->right; } } template<class T> TreeNode<T>* BSTree<T>::search(T key) { return search(m_root, key); } template<class T> TreeNode<T>* BSTree<T>::minimum(TreeNode<T>* node) { if(node == NULL) return NULL; while(node->right != NULL) { node = node->right; } return node; } template<class T> T BSTree<T>::minimum() { BSTree<T>* node = minimum(m_root); if(node != NULL) return node->val; else return (T)NULL; } template<class T> TreeNode<T>* BSTree<T>::maximum(TreeNode<T>* node) { if(node == NULL) return NULL; while(node->left != NULL) { node = node->left; } return node; } template<class T> T BSTree<T>::maximum() { BSTree<T>* node = maximum(m_root); if(node != NULL) return node->val; else return (T)NULL; } template<class T> TreeNode<T>* BSTree<T>::successor(TreeNode<T>* node) { if(node->right != NULL) return minimum(node->right);//寻找以右孩子为树的最小节点 //如果没有右孩子两种情况 //1.是左孩子,则后继是父节点 //2.是右孩子,最低的父节点,且父节点有左孩子 TreeNode<T>* p = node->parent; while(p != NULL && p->right == node) { node = p; p = p->parent; } return p; } template<class T> TreeNode<T>* BSTree<T>::predecessor(TreeNode* node) { if(node->left != NULL) return maximum(node->left);//寻找以左孩子为树的最大节点 //如果没有左孩子两种情况 //1.是右孩子,则后继是父节点 //2.是左孩子,最低的父节点,且父节点有右孩子 TreeNode<T>* p = node->parent; while(p != NULL && p->right == node) { node = p; p = p->parent; } return p; } template<class T> void insert(TreeNode<T>* node, TreeNode<T>* x) { TreeNode<T>* p = NULL; while(node != NULL) { p = node; if(x->val < node->val) node = node->left; else node = node->right;//此处允许插入重复的节点 } x->parent = p;//确定父节点 if(p == NULL)//根节点为空则将插入的节点作为根节点 m_root = x; if(x->val < p->val)//如果小于父节点则作为父节点的左孩子 p->left = x; else p->right = x;//如果大于父节点则作为父节点的右孩子 } template<class T> void insert(T x) { //先创造一个值为x的节点指针 TreeNode<T>* node = new TreeNode<T>{x, NULL, NULL, NULL}; insert(m_root, node); } template<class T> void remove(T x) { TreeNode<T>* p = search(T); if(p != NULL) cout << "该元素不存在" << x << endl; delete q; } template<class T> TreeNode<T>* remove(TreeNode<T>* root, TreeNode<T>* p) { if(p->left == NULL && p->right == NULL)//为单叶子节点 if(p->parent == NULL)//为根节点 else //不是根节点 if(p->parent->left == p) p->parent->left = NULL; else p->parent->right = NULL; else if(p->left == NULL || p->right == NULL)//为单支子树 if(p == m_root)//为根节点,将子树作为根节点 if(p->left == NULL) m_root = p->right; else m_root = p->left; else //不是根节点,将子树连到父节点上 if(p->left == NULL) p->right->parent = p->parent; else p->left->parent = p->parent; else //左右子树都不为空,将后继移到该位置 TreeNode<T>* q = successor(p);//后继左子树必为空 if(q->right != NULL) //右子树不为空 q->right->parent = q->parent;//将右子树的父节点连到后继的父节点 p->val = q->val; } #endif //_BINARYSEARCHTREE_
true
58e2c218fe6d2eece3baab504b35fe58601513f7
C++
wwwwodddd/Zukunft
/CF/1228C.cpp
UTF-8
604
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const int mod = 1000000007; typedef long long ll; int x; ll n, z = 1; ll pw(ll x, ll y) { ll re = 1; for (; y > 0; y >>= 1) { if (y & 1) { re = re * x % mod; } x = x * x % mod; } return re; } ll gao(ll n, int p) { ll re = 0; while (n > 0) { n /= p; re += n; } return re; } int main() { cin >> x >> n; for (int i = 2; i * i <= x; i++) { if (x % i == 0) { while (x % i == 0) { x /= i; } z = z * pw(i, gao(n, i)) % mod; } } if (x > 1) { z = z * pw(x, gao(n, x)) % mod; } printf("%lld\n", z); return 0; }
true
ca550924bf73d29004af910655cc200d8fb0ec8c
C++
former7/7j523game-developing-
/server/seat.h
UTF-8
686
2.65625
3
[]
no_license
#include <inttypes.h> #include <map> class seat { public: seat(); seat(int8_t n); void newRound(); int8_t getNumber() { return seatNumber; }; int getRemainingChips() { return remainingChips; }; void wins(int n); void setFD(int n) { fd = n; }; int getFD() { return fd; }; void setName(unsigned char *_name) { name = _name; }; unsigned char* getName() { return name; }; vector<int>& getHandCards(){return handCards;}; int getHandNum(){return handCards.size();} ~seat(); private: unsigned char *name; int8_t seatNumber; int fd; int remainingChips; map<int,int> handCards; int score; };
true
2c412d6b47ae2c80ede3c84ba721a42a551650a1
C++
DragonClawz/RC_Cars
/big_rc_car.ino
UTF-8
10,849
2.546875
3
[]
no_license
#include <LiquidCrystal.h>//For the LCD I2C #include <Wire.h> #include<LCD.h> #include <LiquidCrystal_I2C.h> #include <SoftwareSerial.h> //I2C pins declaration LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); SoftwareSerial BT(10, 11); //TX, RX respetively String readdata; //LiquidCrystal lcd(8,9,4,5,6,7); //defining lcd pins const int dataIN = 2; //IR sensor INPUT const int headlight_r = 12; const int headlight_l = 13; //speed = 3.15159*(D/100000)*(rpm*60) // speed in km/hr unsigned long prevmillis; // To store time unsigned long duration; // To store time difference unsigned long lcdrefresh; // To store time for lcd to refresh float rpm; // RPM value float speedy; //value of speed //int h_r; //int h_l; int nana; boolean currentstate; // Current state of IR input scan boolean prevstate; // State of IR sensor in previous scan void setup() { pinMode(dataIN,INPUT); lcd.begin(16,2); lcd.backlight(); prevmillis = 0; prevstate = LOW; BT.begin(9600); Serial.begin(9600); pinMode(6, OUTPUT); // connect to input 1 of l293d pinMode(5, OUTPUT); // connect to input 4 of l293d pinMode(4, OUTPUT); // connect to input 3 of l293d pinMode(3, OUTPUT); // connect to input 2 of l293d pinMode (headlight_r, OUTPUT); pinMode (headlight_l, OUTPUT); } void loop() { while (BT.available()){ //Check if there is an available byte to read delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read readdata += c; //build the string- "forward", "reverse", "left" and "right" } if (readdata.length() > 0) { Serial.println(readdata); // print data to serial monitor // if data received as forward move robot forward if (readdata == "reverse"){ nana = 1; } else if (readdata == "forward") { nana = 2; } else if (readdata == "right") { nana = 3; } else if (readdata == "left") { nana = 4; } else if (readdata == "stop") { nana = 0; } else if (readdata == "1") { Serial.println(readdata); digitalWrite(headlight_r, HIGH); digitalWrite(headlight_l, HIGH); } else if (readdata == "2") { Serial.println(readdata); digitalWrite(headlight_r, LOW); digitalWrite(headlight_l, LOW); } while (nana = 1) { while (BT.available()){ //Check if there is an available byte to read delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read readdata += c; //build the string- "forward", "reverse", "left" and "right" } Serial.println(readdata); // RPM Measurement currentstate = digitalRead(dataIN); // Read IR sensor state //Serial.println(dataIN); if (readdata != "right") { nana = 0; digitalWrite (3, LOW); digitalWrite (5, LOW); digitalWrite (4, LOW); digitalWrite (6, LOW); delay(100); break; } if( prevstate != currentstate) // If there is change in input { if( currentstate == HIGH ) // If input only changes from LOW to HIGH { duration = ( micros() - prevmillis ); // Time difference between revolution in microsecond rpm = (60000000/duration); // rpm = (1/ time millis)*1000*1000*60; speedy = (3.14*(0.9)*(rpm/60)); // speed in m/s prevmillis = micros(); // store time for next revolution calculation } } prevstate = currentstate; // store this scan (prev scan) data for next scan // LCD Display if( ( millis()-lcdrefresh ) >= 100 ) { //speedy = 3.14159*(38/100)*(rpm/60); // speed in m/s // lcd.begin(16,2); //lcd.backlight(); /*lcd.setCursor(0,0); lcd.print(" VISIT THE"); lcd.setCursor(0,1); lcd.print(" ECE BOOTH");*/ lcd.setCursor(0,0); lcd.print("SURVEILLANCE CAR "); //lcd.print(rpm); lcd.setCursor(0,1); lcd.print("Speed = "); lcd.print(speedy); } digitalWrite (6, HIGH); digitalWrite (5, LOW); digitalWrite (4, LOW); digitalWrite (3, HIGH); delay(100); } // if data received as reverse move robot reverse while (nana = 2) { while (BT.available()){ //Check if there is an available byte to read delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read readdata += c; //build the string- "forward", "reverse", "left" and "right" } Serial.println(readdata); // RPM Measurement currentstate = digitalRead(dataIN); // Read IR sensor state //Serial.println(dataIN); if (readdata != "left") { nana = 0; digitalWrite (3, LOW); digitalWrite (5, LOW); digitalWrite (4, LOW); digitalWrite (6, LOW); delay(100); break; } if( prevstate != currentstate) // If there is change in input { if( currentstate == HIGH ) // If input only changes from LOW to HIGH { duration = ( micros() - prevmillis ); // Time difference between revolution in microsecond rpm = (60000000/duration); // rpm = (1/ time millis)*1000*1000*60; speedy = (3.14*(0.3)*(rpm/60)); // speed in m/s prevmillis = micros(); // store time for next revolution calculation } } /*if ( currentstate == 0) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Speed of Motor"); lcd.setCursor(0,1); lcd.print("RPM = "); lcd.print(0); lcdrefresh = 0; } */ prevstate = currentstate; // store this scan (prev scan) data for next scan // LCD Display if( ( millis()-lcdrefresh ) >= 100 ) { //speedy = 3.14159*(38/100)*(rpm/60); // speed in m/s // lcd.begin(16,2); //lcd.backlight(); lcd.setCursor(0,0); lcd.print("SURVEILLANCE CAR "); //lcd.print(rpm); lcd.setCursor(0,1); lcd.print("Speed = "); lcd.print(speedy); /*lcd.setCursor(0,1); lcd.print("RPM = "); lcd.print(rpm); lcdrefresh = millis(); */ } digitalWrite (6, HIGH); digitalWrite (5, LOW); digitalWrite (4, HIGH); digitalWrite (3, LOW); delay(100); } while (nana = 3) { while (BT.available()){ //Check if there is an available byte to read delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read readdata += c; //build the string- "forward", "reverse", "left" and "right" } Serial.println(readdata); // RPM Measurement currentstate = digitalRead(dataIN); // Read IR sensor state //Serial.println(dataIN); if (readdata != "forward") { nana = 0; digitalWrite (3, LOW); digitalWrite (5, LOW); digitalWrite (4, LOW); digitalWrite (6, LOW); delay(100); break; } //rhu and kai was heeereeee if( prevstate != currentstate) // If there is change in input { if( currentstate == HIGH ) // If input only changes from LOW to HIGH { duration = ( micros() - prevmillis ); // Time difference between revolution in microsecond rpm = (60000000/duration); // rpm = (1/ time millis)*1000*1000*60; speedy = (3.14*(0.3)*(rpm/60)); // speed in m/s prevmillis = micros(); // store time for next revolution calculation } } /*if ( currentstate == 0) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Speed of Motor"); lcd.setCursor(0,1); lcd.print("RPM = "); lcd.print(0); lcdrefresh = 0; } */ prevstate = currentstate; // store this scan (prev scan) data for next scan // LCD Display if( ( millis()-lcdrefresh ) >= 100 ) { //speedy = 3.14159*(38/100)*(rpm/60); // speed in m/s // lcd.begin(16,2); //lcd.backlight(); lcd.setCursor(0,0); lcd.print("SURVEILLANCE CAR "); //lcd.print(rpm); lcd.setCursor(0,1); lcd.print("Speed = "); lcd.print(speedy); /*lcd.setCursor(0,1); lcd.print("RPM = "); lcd.print(rpm); lcdrefresh = millis(); */ } digitalWrite (6, HIGH); digitalWrite (5, LOW); digitalWrite (4, LOW); digitalWrite (3, LOW); delay(100); } while (nana = 4) { while (BT.available()){ //Check if there is an available byte to read delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read readdata += c; //build the string- "forward", "reverse", "left" and "right" } Serial.println(readdata); // RPM Measurement currentstate = digitalRead(dataIN); // Read IR sensor state //Serial.println(dataIN); if (readdata != "reverse") { nana = 0; digitalWrite (3, LOW); digitalWrite (5, LOW); digitalWrite (4, LOW); digitalWrite (6, LOW); delay(100); break; } if( prevstate != currentstate) // If there is change in input { if( currentstate == HIGH ) // If input only changes from LOW to HIGH { duration = ( micros() - prevmillis ); // Time difference between revolution in microsecond rpm = (60000000/duration); // rpm = (1/ time millis)*1000*1000*60; speedy = (3.14*(0.3)*(rpm/60)); // speed in m/s prevmillis = micros(); // store time for next revolution calculation } } /*if ( currentstate == 0) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Speed of Motor"); lcd.setCursor(0,1); lcd.print("RPM = "); lcd.print(0); lcdrefresh = 0; } */ prevstate = currentstate; // store this scan (prev scan) data for next scan // LCD Display if( ( millis()-lcdrefresh ) >= 100 ) { //speedy = 3.14159*(38/100)*(rpm/60); // speed in m/s // lcd.begin(16,2); //lcd.backlight(); lcd.setCursor(0,0); lcd.print("SURVEILLANCE CAR "); //lcd.print(rpm); lcd.setCursor(0,1); lcd.print("Speed = "); lcd.print(speedy); /*lcd.setCursor(0,1); lcd.print("RPM = "); lcd.print(rpm); lcdrefresh = millis(); */ } digitalWrite (6, LOW); digitalWrite (5, HIGH); digitalWrite (4, LOW); digitalWrite (3, LOW); delay(100); } } /*else if (readdata == "1") { digitalWrite (headlight_r, HIGH); digitalWrite (headlight_l, HIGH); } else if (readdata == "2") { digitalWrite (headlight_r, LOW); digitalWrite (headlight_l, LOW); }*/ readdata=""; lcd.setCursor(0,0); lcd.print("SURVEILLANCE CAR "); //lcd.print(rpm); lcd.setCursor(0,1); lcd.print("Speed = "); lcd.print ("0.00"); }
true
d3fb76ad8848c10ff0bd70635f0418b4d0201047
C++
lb2616/all_descriptions_of_pdfs
/各种pdf/上嵌/C++上课内容/c++第5天/720上午/虚拟继承顺序.cc
UTF-8
647
3.375
3
[]
no_license
#include<iostream> using namespace std; class A1 { public: A1() { cout <<"A1"<<endl; } ~A1() { cout << "~A1"<<endl; } }; class A2 { public: A2() { cout <<"A2"<<endl; } ~A2() { cout<< "~A2"<<endl; } }; class A3 { public: A3() { cout <<"A3"<<endl; } ~A3() { cout<<"~A3"<<endl; } }; class Test :virtual public A2,public A3,virtual public A1 //加了virtual的先调用构造函数,所以A2,A1,后来才是A3 { public: Test(){cout <<"Test "<<endl;} ~Test(){cout <<"~Test"<<endl;} }; int main(int argc ,char **argv) { Test t; cout <<"================="<<endl; return 0; }
true
564e78a82bb622bdd2ab374332e8c8d516bfd97f
C++
grayd4/Arduino-PC-Monitor
/monitor/monitor.ino
UTF-8
6,596
2.703125
3
[]
no_license
//www.elegoo.com //2016.12.9 /* LiquidCrystal Library - Hello World Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints "Hello World!" to the LCD and shows the time. The circuit: * LCD RS pin to digital pin 7 * LCD Enable pin to digital pin 8 * LCD D4 pin to digital pin 9 * LCD D5 pin to digital pin 10 * LCD D6 pin to digital pin 11 * LCD D7 pin to digital pin 12 * LCD R/W pin to ground * LCD VSS pin to ground * LCD VCC pin to 5V * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) Library originally added 18 Apr 2008 by David A. Mellis library modified 5 Jul 2009 by Limor Fried (http://www.ladyada.net) example added 9 Jul 2009 by Tom Igoe modified 22 Nov 2010 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/LiquidCrystal potential rgb source: https://forum.arduino.cc/t/color-changing-rgb-led-rainbow-spectrum/8561 */ // include the library code: #include <LiquidCrystal.h> #include <Wire.h> // Define Pins #define BLUE 3 #define GREEN 5 #define RED 6 // initialize the library with the numbers of the interface pins LiquidCrystal lcd(7, 8, 9, 10, 11, 12); String inData; // Number of colors used for animating, higher = smoother and slower animation) int numColors = 511; int counter = 0; // The combination of numColors and animationDelay determines the // animation speed, I recommend a higher number of colors if you want // to slow down the animation. Higher number of colors = smoother color changing. int animationDelay = 10; // number milliseconds before RGB LED changes to next color // PC vars int recentCPULoad = 0; int recentCPUTemp = 0; int recentRAMLoad = 0; int recentRAMUsed = 0; void setLight(unsigned char red, unsigned char green, unsigned char blue) { if (recentCPULoad > 80 || recentCPUTemp > 100 || recentRAMLoad > 80) { digitalWrite(RED, HIGH); digitalWrite(GREEN, LOW); digitalWrite(BLUE, LOW); } else if (recentCPULoad > 60 || recentCPUTemp > 80 || recentRAMLoad > 60) { digitalWrite(RED, HIGH); digitalWrite(GREEN, HIGH); digitalWrite(BLUE, LOW); } else { //digitalWrite(RED, LOW); //digitalWrite(GREEN, HIGH); //digitalWrite(BLUE, LOW); // If we aren't d isplaying a warning light, just continue to cycle RGB setColor(red, green, blue); } } void setColor(unsigned char red, unsigned char green, unsigned char blue) { analogWrite(RED, red); analogWrite(GREEN, green); analogWrite(BLUE, blue); } // Translate all our params to a hard rgb value long HSBtoRGB(float _hue, float _sat, float _brightness) { float red = 0.0; float green = 0.0; float blue = 0.0; if (_sat == 0.0) { red = _brightness; green = _brightness; blue = _brightness; } else { if (_hue == 360.0) { _hue = 0; } int slice = _hue / 60.0; float hue_frac = (_hue / 60.0) - slice; float aa = _brightness * (1.0 - _sat); float bb = _brightness * (1.0 - _sat * hue_frac); float cc = _brightness * (1.0 - _sat * (1.0 - hue_frac)); switch(slice) { case 0: red = _brightness; green = cc; blue = aa; break; case 1: red = bb; green = _brightness; blue = aa; break; case 2: red = aa; green = _brightness; blue = cc; break; case 3: red = aa; green = bb; blue = _brightness; break; case 4: red = cc; green = aa; blue = _brightness; break; case 5: red = _brightness; green = aa; blue = bb; break; default: red = 0.0; green = 0.0; blue = 0.0; break; } } long ired = red * 255.0; long igreen = green * 255.0; long iblue = blue * 255.0; return long((ired << 16) | (igreen << 8) | (iblue)); } void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); Serial.begin(9600); pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); digitalWrite(RED, LOW); digitalWrite(GREEN, HIGH); digitalWrite(BLUE, LOW); } void loop() { // This part takes care of displaying the // color changing in reverse by counting backwards if counter // is above the number of available colors float colorNumber = counter > numColors ? counter - numColors: counter; // Play with the saturation and brightness values // to see what they do float saturation = 1; // Between 0 and 1 (0 = gray, 1 = full color) float brightness = .05; // Between 0 and 1 (0 = dark, 1 is full brightness) float hue = (colorNumber / float(numColors)) * 360; // Number between 0 and 360 long color = HSBtoRGB(hue, saturation, brightness); // Get the red, blue and green parts from generated color int red = color >> 16 & 255; int green = color >> 8 & 255; int blue = color & 255; while (Serial.available() > 0) { char received = Serial.read(); lcd.setCursor(0,0); inData += received; if (received == 42) // * { inData.remove(inData.length() - 1, 1); lcd.setCursor(0,0); lcd.print("CPU: " + inData + "% "); recentCPULoad = inData.toInt(); inData = ""; } if (received == 35) // # { inData.remove(inData.length() - 1, 1); lcd.setCursor(10,0); lcd.print(inData + char(223) + "C"); recentCPUTemp = inData.toInt(); inData = ""; } if (received == 36) // $ { inData.remove(inData.length() - 1, 1); lcd.setCursor(0,1); lcd.print("RAM: " + inData + "% "); recentRAMLoad = inData.toInt(); inData = ""; } if (received == 38) // & { inData.remove(inData.length() - 1, 1); lcd.setCursor(11,1); lcd.print(inData + "GB"); inData = ""; } } setLight(red, green, blue); // Counter can never be greater then 2 times the number of available colors // the colorNumber = line above takes care of counting backwards (nicely looping animation) // when counter is larger then the number of available colors counter = (counter + 1) % (numColors * 2); // If you uncomment this line the color changing starts from the // beginning when it reaches the end (animation only plays forward) // counter = (counter + 1) % (numColors); delay(animationDelay); }
true
8b1d35a49f6ca4b2f6893996206c7768db129e4e
C++
SanyaAttri/LeetCode
/00895. Maximum Frequency Stack.cpp
UTF-8
2,808
3.1875
3
[]
no_license
// // main.cpp // LeetCode // // Created by 郭妙友 on 17/2/5. // Copyright © 2017年 miaoyou.gmy. All rights reserved. // #include <cmath> #include <cstdio> #include <cstring> #include <cstdlib> #include <set> #include <map> #include <list> #include <stack> #include <queue> #include <cmath> #include <vector> #include <string> #include <iterator> #include <numeric> #include <iostream> #include <unordered_map> #include <algorithm> #include <functional> using namespace std; /** 895. Maximum Frequency Stack Implement FreqStack, a class which simulates the operation of a stack-like data structure. FreqStack has two functions: push(int x), which pushes an integer x onto the stack. pop(), which removes and returns the most frequent element in the stack. If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned. Example 1: Input: ["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"], [[],[5],[7],[5],[7],[4],[5],[],[],[],[]] Output: [null,null,null,null,null,null,null,5,7,5,4] Explanation: After making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top. Then: pop() -> returns 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. pop() -> returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. pop() -> returns 5. The stack becomes [5,7,4]. pop() -> returns 4. The stack becomes [5,7]. Note: Calls to FreqStack.push(int x) will be such that 0 <= x <= 10^9. It is guaranteed that FreqStack.pop() won't be called if the stack has zero elements. The total number of FreqStack.push calls will not exceed 10000 in a single test case. The total number of FreqStack.pop calls will not exceed 10000 in a single test case. The total number of FreqStack.push and FreqStack.pop calls will not exceed 150000 across all test cases. */ /** 36 / 36 test cases passed. Status: Accepted Runtime: 156 ms */ static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); return 0; }(); class FreqStack { private: unordered_map<int, int> feq; unordered_map<int, stack<int>> feq_stk; int maxFeq; public: FreqStack() { feq.clear(); feq_stk.clear(); maxFeq = -1; } void push(int x) { int f = ++feq[x]; maxFeq = max(maxFeq,f); if(feq_stk.find(f) == feq_stk.end()){ stack<int> st; feq_stk[f] = st; } feq_stk[f].push(x); } int pop() { int f = feq_stk[maxFeq].top(); --feq[f]; feq_stk[maxFeq].pop(); if(feq_stk[maxFeq].empty()) --maxFeq; return f; } }; int main(){ return 0; }
true
aa7b8ff0ee7205e3fc5f970426f3bc2fe748dc74
C++
lootsy/sputnik-win
/Sputnik/StudioLinkAPIConnector/StudioLinkAPIConnector.h
UTF-8
890
2.765625
3
[]
no_license
#pragma once using namespace System; using namespace System::Collections::Generic; namespace StudioLinkAPI { public ref class Device { public: Device(const int channels, const double sampleRate, const String^ name); inline int Channels(); inline double SampleRate(); inline const String^ Name(); private: const int channels_; const double sampleRate_; const String^ name_; }; inline int Device::Channels() { return channels_; } inline double Device::SampleRate() { return sampleRate_; } inline const String^ Device::Name() { return name_; } public enum DeviceType { INPUT_DEVICE, OUTPUT_DEVICE }; public ref class Connector { public: IEnumerable<Device^>^ EnumBuiltinDevices(const DeviceType type); }; }
true
89773ed1c13da9fac812f0f927fdf742eacb2845
C++
simonsayspark/arduino-library
/samples/lcd/sample_lcd.ino
UTF-8
2,433
3.703125
4
[]
no_license
/** * This file is a small sample showing some basic setup and functionality for the * LCD display. The setup() function sets up the LCD display, and the loop() * function shows how many iterations have been performed on the display. * * Be sure to check the wiring guide for how to hook up the LCD. * * IMPORTANT: Make sure you bridge the two pins specified in the diagram. * One side of the display connector has 4 pins that connect to the arduino. * The other side has 2 pins that MUST be bridged. * * The first few lines of the setup() function can be copied directly into * your program. Don't worry about the seemingly random sequence of numbers; * those have been pre-determined and don't need to be changed. * * The LCD is made up of 2 rows and 16 columns. Like a text document, there's * a "cursor" that you can move. When you write a value, like an int, float, * or string of characters, it starts writing wherever your cursor currently * sits. You'll see in the loop() function that we specify exactly where * we want to print values on the LCD screen. * * NOTE: rows and columns are 0-index-based. As in, to print on column 1 row 1, * you'll move your cursor to 0 and 0. To print on column 8 row 2, move the * cursor to 7 and 1. COLUMN GOES FIRST, FOLLOWED BY ROW. * * The print() function lets you print the following types: int, double, char*, long. * * !! NOTE !!: The LCD Address can either be 0x27 or 0x3F depending on the version * of LCD screen. */ #include <LiquidCrystal_I2C.h> int lcdAddress = 0x27; //or 0x3F int loopCount = 0; LiquidCrystal_I2C *lcd; void setup() { lcd = new LiquidCrystal_I2C(lcdAddress, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); lcd->begin(16, 2); // initialize the lcd. Don't worry about the int values above. lcd->home(); // go to the top line lcd->print("SMU Lyle KNW2300"); // Print a welcome message delay(3000); // Let the message show for 3 seconds } void loop() { lcd->clear(); // Clear out the screen every iteration lcd->setCursor(0, 0); // Moves the cursor to column 0, row 0 lcd->print("Loop count:"); // Print out a title on row 0 lcd->setCursor(0, 1); // Moves the cursor to column 0, row 1 lcd->print(loopCount); // Print out the number of times we've looped loopCount++; // Increment the loop counter delay(2000); // Delay for two seconds }
true
aa05151fc92a348d9d847f8ed025208d0d03b4a9
C++
15831944/liuwanbing
/棋牌/PlatForm/Client/MainFrame/Socket32.cpp
GB18030
9,827
2.515625
3
[]
no_license
#include "stdafx.h" #include "Socket32.h" #include <assert.h> #include <Tlhelp32.h>// DWORD GetProcessIdFromName(LPCTSTR name) 2012.08.16 yyf // ܵ߳ ͣĶϢ. DWORD WINAPI SimpleSocketThread(LPVOID param) { CSocket32 * SimpleSocket = (CSocket32 *)param; BYTE BYTE_Read[10240] ; while(NULL != SimpleSocket && SimpleSocket->bSimpleSocketThread) { int nRead; memset(&BYTE_Read,0,10240); nRead = SimpleSocket->Receive((void*)BYTE_Read,10240); if( nRead >0 ) { SimpleSocket->ReadSimpleSocket((LPVOID)BYTE_Read,nRead); } else { OutputDebugString("yyf: SimpleSocket->Receive(..) 󣬿ܶ."); Sleep(500); } } return 0; } /**/////////////////////////////////////////////////////////////////////// // Construction/Destruction /**/////////////////////////////////////////////////////////////////////// // CSocket32::CSocket32() { //#ifdef _WIN32 WSAData wsaData; int err =WSAStartup(0x0202,&wsaData); if ( err != 0 ) return; if ( LOBYTE( wsaData.wVersion ) != 2 ||HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); return; } //#endif m_hSocket = INVALID_SOCKET; bSimpleSocketThread = false; } // CSocket32::~CSocket32() { Close(); } /**//**********************************************************************/ //1.׽ BOOL CSocket32::Create( UINT nSocketPort, int nSocketType ,LPCTSTR lpszSocketAddress,bool bisServer ) { m_hSocket = socket(AF_INET,nSocketType,IPPROTO_IP);//Ȼٴ if( m_hSocket == INVALID_SOCKET) return FALSE; sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(nSocketPort); if (!lpszSocketAddress) //ûָϵͳ addr.sin_addr.s_addr = htonl(INADDR_ANY); else addr.sin_addr.s_addr = inet_addr(lpszSocketAddress); if(!bisServer) { return TRUE; } if (!bind(m_hSocket,(sockaddr*)&addr,sizeof(addr))) { if (0 == nSocketPort) m_addr = addr; return TRUE;//If no error occurs, bind returns zero } Close(); return FALSE; } //2.ͣUDP int CSocket32::SendTo( const void* lpBuf, int nBufLen, UINT nHostPort, LPCSTR lpszHostAddress , int nFlags) { sockaddr_in addr = {AF_INET,htons(nHostPort),}; assert(lpszHostAddress);//UDP ָĿĵַ addr.sin_addr.s_addr = inet_addr(lpszHostAddress); return sendto(m_hSocket,(char*)lpBuf,nBufLen,nFlags,(sockaddr*)&addr,sizeof(addr)); } //3.գUDP int CSocket32::ReceiveFrom( void* lpBuf, int nBufLen, char *rSocketAddress, UINT& rSocketPort, int nFlags ) { sockaddr_in from;//һʱڴ棬Ϣ socklen_t fromlen = sizeof(from);//Ȼܼڴ泤 int nRet = recvfrom(m_hSocket,(LPSTR)lpBuf,nBufLen,nFlags,(sockaddr*)&from,&fromlen); if(nRet <= 0) return nRet; if(rSocketAddress) { strcpy(rSocketAddress,inet_ntoa(from.sin_addr));//out rSocketPort = htons(from.sin_port);//out } return nRet; } //4.(TCP) BOOL CSocket32::Accept( CSocket32& rConnectedSocket, LPSTR lpSockAddr ,UINT *nPort ) { sockaddr_in addr = {AF_INET}; socklen_t nLen = sizeof(addr); rConnectedSocket.m_hSocket = accept(m_hSocket,(sockaddr*)&addr,&nLen); if(rConnectedSocket.m_hSocket == INVALID_SOCKET) return FALSE; if(lpSockAddr) { strcpy(lpSockAddr,inet_ntoa(addr.sin_addr)); *nPort = htons(addr.sin_port); } return TRUE; } //5.(TCP) BOOL CSocket32::Connect( LPCTSTR lpszHostAddress, UINT nHostPort ) { sockaddr_in addr = {AF_INET,htons(nHostPort)}; addr.sin_addr.s_addr = inet_addr(lpszHostAddress); if (addr.sin_addr.s_addr == INADDR_NONE)//޹㲥ַñַ֮һ { hostent * lphost = gethostbyname(lpszHostAddress); if (lphost != NULL) addr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr; else { //WSAGetLastError(); // WSASetLastError(WSAEINVAL); return FALSE; } } return !connect(m_hSocket,(sockaddr*)&addr,sizeof(addr)); } //6.õ׽֣IPPort BOOL CSocket32::GetSockName( char* rSocketAddress, UINT& rSocketPort ) { sockaddr_in addr; socklen_t nLen = sizeof(addr); if(SOCKET_ERROR == getsockname(m_hSocket, (sockaddr*)&addr, &nLen)) return FALSE; if(rSocketAddress) { strcpy(rSocketAddress,inet_ntoa(addr.sin_addr)); rSocketPort = htons(addr.sin_port); } return TRUE; } //7.õԷ׽֣IPPort BOOL CSocket32::GetPeerName( char* rPeerAddress, UINT& rPeerPort ) { sockaddr_in addr; socklen_t nLen = sizeof(addr); if(SOCKET_ERROR == getpeername(m_hSocket, (sockaddr*)&addr, &nLen)) return FALSE; if(rPeerAddress) { strcpy(rPeerAddress,inet_ntoa(addr.sin_addr)); rPeerPort = htons(addr.sin_port); } return TRUE; } void CSocket32::ReadSimpleSocket(LPVOID lpBuffer, DWORD dwNumberOfBytesToRead) { if(NULL != pSimpleSocket ) {//ûص pSimpleSocket->ReadSimpleSocket(lpBuffer, dwNumberOfBytesToRead); } } void CSocket32::SetSimpleSocket(ISimpleSocket * pSimpleSocket)//ʼصĽӿָ 2012.08.17 yyf { this->pSimpleSocket = pSimpleSocket; } // //һ 2012.08.17 yyf bool CSocket32:: OpenProcess(LPCSTR lpApplicationName) { strProcessName = lpApplicationName;// if(0 == GetProcessIdFromName(strProcessName) && NULL != pSimpleSocket && !bSimpleSocketThread) {//ûʼ bSimpleSocketThread = false; STARTUPINFO sui; //PROCESS_INFORMATION pi; ZeroMemory(&sui,sizeof(STARTUPINFO)); sui.cb=sizeof(STARTUPINFO); sui.dwFlags=STARTF_USESTDHANDLES; sui.hStdError=GetStdHandle(STD_ERROR_HANDLE); if(!CreateProcess(strProcessName,NULL,NULL,NULL, TRUE,0,NULL,NULL,&sui,&pi)) { //MessageBox("ӽʧܣ"); return false; } FindFreePort(); SetFreePortToBcf(); if (0 == m_addr.sin_port) return false; // if (Create(m_addr.sin_port)) { if (Listen()) { CString strPort; strPort.Format("rende123: port no: %d",m_addr.sin_port); OutputDebugString(strPort); SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); //ȴͻ m_hSocketServer = m_hSocket; m_hSocket = accept(m_hSocketServer, (SOCKADDR*)&addrClient, &len);//sockConnӵ׽ } else { return false; } } else { return false; } //̣ܵ߳ʼ bSimpleSocketThread = true; DWORD dwThreadID = 0; HANDLE hThread = CreateThread(0,0,SimpleSocketThread,this,0,&dwThreadID); if (hThread) { OutputDebugString("yyf: ܵ߳̿ʼ."); ::CloseHandle(hThread); } return true; } return true; } // void CSocket32::SetFreePortToBcf() { DWORD dwCfgFile = ::cfgOpenFile(CBcfFile::GetAppPath() + "bzgame.bcf"); //bcfļʧܷ if(dwCfgFile < 0x10) return; ::cfgSetValue(dwCfgFile,_T("GameSet"),_T("UpdateSetPort"),m_addr.sin_port); ::cfgSetKeyMemo(dwCfgFile,_T("GameSet"),_T("UpdateSetPort"),_T("ظ¶˿")); //5.رbcfļ ::cfgClose(dwCfgFile); } //ȡ˿ ULONG CSocket32::GetFreePort() { DWORD dwCfgFile = ::cfgOpenFile(CBcfFile::GetAppPath() + "bzgame.bcf"); //bcfļʧܷ if(dwCfgFile < 0x10) return 0; ULONG ulRet = ::cfgGetValue(dwCfgFile,_T("GameSet"),_T("UpdateSetPort"),6123); //5.رbcfļ ::cfgClose(dwCfgFile); return ulRet; } //ҿ˿ void CSocket32::FindFreePort() { if (Create()) { int len = sizeof(m_addr); if(0 == getsockname(m_hSocket, (struct sockaddr *)&m_addr, &len)) { closesocket(m_hSocket); } } } // //ÿͻ 2012.08.17 yyf int CSocket32:: SetClientSimpleSocket(void) { //׽ m_hSocket = socket( AF_INET,SOCK_STREAM, 0 ); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(m_addr.sin_port); CString strPortNo; strPortNo.Format("rende123: client port no: %d", m_addr.sin_port); OutputDebugString(strPortNo); // connect( m_hSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); return 0; } // ʼ߳ void CSocket32:: StartThread(void) { bSimpleSocketThread = true;//߳̿ DWORD dwThreadID = 0; HANDLE hThread = CreateThread(0,0,SimpleSocketThread,this,0,&dwThreadID); if (hThread) { ::CloseHandle(hThread); } else { OutputDebugString("yyf: update.exe ߳ʧ."); } } //2012.08.16 yyf ؽ̵PID DWORD CSocket32::GetProcessIdFromName(LPCTSTR name) //Уؽ̵PIDûз0 //Լ޸ĺеĽ̵ĸ { PROCESSENTRY32 pe; DWORD id = 0; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); pe.dwSize = sizeof(PROCESSENTRY32); if( !Process32First(hSnapshot,&pe) ) { return 0; } while(1) { pe.dwSize = sizeof(PROCESSENTRY32); if( Process32Next(hSnapshot,&pe)==FALSE ) break; if(_stricmp(pe.szExeFile,name) == 0) //ԴСдĸȽ { id = pe.th32ProcessID; break; } } CloseHandle(hSnapshot); return id; } //ʼͻ. bool CSocket32::InitClientSimpleSocket(ISimpleSocket * pSimpleSocket) { SetSimpleSocket(pSimpleSocket);//ʼ if (0 == SetClientSimpleSocket()) { StartThread(); return true; } return false; }
true
84dc589ab5ca63df322f5611b20acc518ac89cfc
C++
BTHStoraSpelprojektet/Stora-Spelprojektet
/Shurikenjutsu/Shurikenjutsu/PointOfInterest.h
UTF-8
827
2.515625
3
[]
no_license
#ifndef POINTOFINTEREST_H_ #define POINTOFINTEREST_H_ #include "MovingObject.h" class ParticleEmitter; class PointOfInterest : public MovingObject { public: PointOfInterest(); ~PointOfInterest(); bool Initialize(POINTOFINTERESTTYPE p_type, const char* p_filepath, DirectX::XMFLOAT3 p_pos, DirectX::XMFLOAT3 p_dir, float p_speed, DirectX::XMFLOAT3 p_lightColor); void Shutdown(); void Update(); void Render(); void SetPosition(DirectX::XMFLOAT3 p_pos); void SparkleState(bool p_stateOn); bool IsActive(); void SetActive(bool p_active); void SpawnLight(); void PickedUp(); POINTOFINTERESTTYPE GetType(); private: void Sparkle(); ParticleEmitter* m_sparkles; bool m_active; DirectX::XMFLOAT3 m_positionLight; DirectX::XMFLOAT3 m_lightColor; POINTOFINTERESTTYPE m_type; }; #endif // !POINTOFINTEREST_H_
true
8a771e2a17756fe556685984e30d8774f87d69be
C++
tzach420/SPLFLIX
/include/User.h
UTF-8
2,582
3.28125
3
[]
no_license
#ifndef USER_H_ #define USER_H_ #include <vector> #include <string> #include <unordered_set> #include <unordered_map> #include <map> class Watchable; class Session; class LengthRecommenderUser; class User{ public: User(const std::string& name);//constructor. virtual~User();//destructor. virtual Watchable* getRecommendation(Session& s) = 0; virtual User* clone()=0;//deep copy void addToHistory(Watchable* toAdd);//add Watchable to the history of the user. void printHistory();//prints user history. void setName(const std::string& name); std::vector<Watchable*> get_history() ; std::vector<Watchable*> &getHistoryByRef() ;//returns the user history. std::string getName() const; protected: std::vector<Watchable*> history; bool userDidntWatch(Watchable* & content);//return true if the user didnt watch content, false otherwise. private: std::string name; }; class LengthRecommenderUser : public User {//prefer to watch content whose length is closest to the avg length of all the things he watched so far. public: LengthRecommenderUser(const std::string& name);//constructor. virtual Watchable* getRecommendation(Session& s);// return the next recommendation. virtual User* clone(); private: }; class RerunRecommenderUser : public User {//recommned by cycle: first recommend the first WATCHABLE, then second, third..... n.(saves the index of the last recomandation) public: RerunRecommenderUser(const std::string& name);//constructor. virtual Watchable* getRecommendation(Session& s);// return the next recommendation. virtual User* clone(); private: int index_of_next_recommendation;//holds the id of the next recommendation. }; class GenreRecommenderUser : public User {//recommend content based on the most popular tag in the user WATCH HISTORY. if a set of tags has the same value, it will recommand by lex order. recommand on content that the user didnt watch already. If no such content exists, it will try with the second most popular tag, and so on. public: GenreRecommenderUser(const std::string& name);//constructor. virtual Watchable* getRecommendation(Session& s);// return the next recommendation. virtual User* clone(); std::map<std::string,int>* initTagMap();//return map of [tag name][number_of_appearance] of the user current history. std::string findTagToSearch(std::map<std::string,int>*& mymap);//find the tag with the highest number of appearance in user history. private: }; #endif
true
f5d4f8368f0ce2d056658b7fc7c2893e32b4aed8
C++
kornel-schrenk/DiveIno
/PoC/DiveInoTouch/DiveInoTouch/Components/PressureDisplay.h
UTF-8
418
2.546875
3
[ "MIT" ]
permissive
#ifndef PRESSUREDISPLAY_H_ #define PRESSUREDISPLAY_H_ #include <Adafruit_ILI9341.h> // Hardware-specific library #include "..\Utils\ScreenUtils.h" class PressureDisplay { public: PressureDisplay(Adafruit_ILI9341* adafruitTft); void init(float pressureInMilliBar); void update(float pressureInMilliBar); int currentPressure(); private: Adafruit_ILI9341* tft; int pressure; }; #endif /* PRESSUREDISPLAY_H_ */
true
23f2e2e34bde9aeceff22f6cabe01a08c806646e
C++
DHaoYu/ali_cloud
/IO/Select/SelectTest/SelectTest.cc
UTF-8
626
2.78125
3
[]
no_license
#include<iostream> #include<sys/select.h> #include<unistd.h> using namespace std; int main() { fd_set rfd; FD_ZERO(&rfd); FD_SET(0, &rfd); for(;;) { int ret = select(1, &rfd, NULL, NULL, NULL); if(ret < 0) { cerr<<"select error"<<endl; continue; } if(FD_ISSET(0, &rfd)) { char buf[1024]; ssize_t s = read(0, buf, sizeof(buf)); if(s < 0) { cerr<<"read error"<<endl; continue; } else cout<<buf<<endl; } else { cerr<<"fd error"<<endl; continue; } FD_ZERO(&rfd); FD_SET(0, &rfd); } }
true
3522215715bf84905301b92f54c2390fb32287ae
C++
bjakubie/Kraj
/Kraj-2/Polityka.cpp
UTF-8
1,171
3.109375
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include "Polityka.h" using namespace std; string nazwa_pliku_p = "Polityka.txt"; //<Nazwa pliku do zapisu stanu obiektu //konstruktor Polityka::Polityka() { #ifdef DEBUG cout << "Wywolano konstruktor Param_urzadzenia" << endl; #endif zadlozenie_kraju = 838; wodz_kraju = "ja"; } void Polityka::zapiszStan(Polityka &polit){ #ifdef _DEBUG cout << "Zapisano stan obiektu klasy Polityka" << endl; #endif ofstream plik(nazwa_pliku_p); plik << polit; plik.close(); } void Polityka::wczytajStan(Polityka &polit){ #ifdef _DEBUG cout << "Wczytano stan obiektu klasy Polityka" << endl; #endif ifstream plik(nazwa_pliku_p); plik >> polit; plik.close(); } ///Zdefiniowany operator strumieniowy std::ostream& operator << (std::ostream &s, Polityka &polit){ s << polit.zadlozenie_kraju << endl << polit.wodz_kraju; return s; } ///Zdefiniowany operator strumieniowy std::istream& operator >> (std::istream& s, Polityka &polit){ s >> polit.zadlozenie_kraju >> polit.wodz_kraju; return s; } //destruktor Polityka::~Polityka() { #ifdef _DEBUG cout << "Wywolano destruktor ~Polityka" << endl; #endif }
true
9eb58489296a96a14a8d4bd89a050bebfa67673b
C++
bruceoutdoors/CG-Assignment
/OpenGL-Utilities/utilities/GlutManager.hpp
UTF-8
935
2.671875
3
[ "MIT" ]
permissive
/******************************************** Course : TGD2151 Computer Graphics Fundamentals / TCS2111 Computer Graphics Session: Trimester 2, 2015/16 ID and Name #1 : 1141125087 Hii Yong Lian Contacts #1 : 016-4111005 yonglian146@gmail.com ID and Name #2 : 112272848 Lee Zhen Yong Contacts #2 : 016-3188854 bruceoutdoors@gmail.com ********************************************/ #pragma once #include <map> class GlutWindow; class GlutManager { public: static void addGlutWindow(int id, GlutWindow* gw); static void displayFunc(); static void reshapeFunc(int width, int height); static void keyboardFunc(unsigned char key, int x, int y); static void specialFunc(int key, int x, int y); static void motionFunc(int x, int y); static void mouseFunc(int button, int state, int x, int y); private: static void updateActiveGlutWindow(); static std::map<int, GlutWindow*> idToWindow; static GlutWindow *activeGlutWindow; };
true
b49526d1a6633b557f63fa4b7ecb2410f29ee5bf
C++
linkhack/Molecular_VIS
/Molecular_VIS/src/Light/Light.h
UTF-8
902
2.828125
3
[]
no_license
#pragma once #include "../Shader/Shader.h" /*! * \brief Base class for lights * */ class Light { protected: /*! * Uniforms to update for a particular light and shader. Has to be overwritten. * * \param shader shader to be updated. * \param index index index of the light among lights of the same type (used in shader to index light) */ virtual void setUniform(std::shared_ptr<Shader>& shader, int index); public: Light(); virtual ~Light(); /*! * Updates all light related uniform for all shaders in shaders-vector for this light. * Internally calls void setUniform(std::shared_ptr<Shader>& shadeer, int index); * * \param shaders Vectors of all shaders to be uodated. * \param index index of the light among lights of the same type (used in shader to index light) */ virtual void setUniforms(const std::vector<std::shared_ptr<Shader>>& shaders, int index) final; };
true
6571047818d85c7d5fc472e2e1178f59ee241fa6
C++
chronics/PhysX
/PhysXed togeather/MyPhysicsEngine.h
UTF-8
13,349
2.5625
3
[]
no_license
#pragma once #include "BasicActors.h" #include "MyActors.h" #include <iostream> #include <iomanip> namespace PhysicsEngine { using namespace std; //a list of colours: Circus Palette static const PxVec3 color_palette[] = { PxVec3(255.f / 255.f,.0f / 255.f,.0f / 255.f), //red 0 PxVec3(255.f / 255.f,255.f / 255.f,.0f / 255.f), //yellow 1 PxVec3(.0f / 255.f,.0f / 255.f,255.f / 255.f), //blue 2 PxVec3(128.f / 255.f,.0f / 255.f,128.f / 255.f), //purple 3 PxVec3(.0f / 255.f,255.f / 255.f,.0f / 255.f), //green 4 PxVec3(255.f / 255.f,50.f / 255.f,.0f / 255.f), //orange 5 PxVec3(46.f / 255.f,9.f / 255.f,39.f / 255.f), //pink 6 PxVec3(217.f / 255.f,0.f / 255.f,0.f / 255.f), //salmon pink 7 PxVec3(139.f / 255.f,69.f / 255.f,19.f / 255.f), //brown 8 PxVec3(255.f / 255.f,140.f / 255.f,54.f / 255.f), //cream 9 PxVec3(4.f / 255.f,117.f / 255.f,111.f / 255.f), //turquoise 10 PxVec3(147.f / 255.f,112.f / 255.f,219.f / 255.f), //mediumpurple 11 PxVec3(.0f / 255.f,102.f / 255.f,0.f / 255.f), //Dark Green 12 PxVec3(.0f / 255.f,102.f / 255.f,204.f / 255.f) //skyish blue 13 }; //pyramid vertices static PxVec3 pyramid_verts[] = { PxVec3(0,1,0), PxVec3(1,0,0), PxVec3(-1,0,0), PxVec3(0,0,1), PxVec3(0,0,-1) }; //pyramid triangles: a list of three vertices for each triangle e.g. the first triangle consists of vertices 1, 4 and 0 //vertices have to be specified in a counter-clockwise order to assure the correct shading in rendering static PxU32 pyramid_trigs[] = { 1, 4, 0, 3, 1, 0, 2, 3, 0, 4, 2, 0, 3, 2, 1, 2, 4, 1}; class Pyramid : public ConvexMesh { public: Pyramid(PxTransform pose=PxTransform(PxIdentity), PxReal density=1.f) : ConvexMesh(vector<PxVec3>(begin(pyramid_verts),end(pyramid_verts)), pose, density) { } }; class PyramidStatic : public TriangleMesh { public: PyramidStatic(PxTransform pose=PxTransform(PxIdentity)) : TriangleMesh(vector<PxVec3>(begin(pyramid_verts),end(pyramid_verts)), vector<PxU32>(begin(pyramid_trigs),end(pyramid_trigs)), pose) { } }; struct FilterGroup { enum Enum { ACTOR0 = (1 << 0), ACTOR1 = (1 << 1), ACTOR2 = (1 << 2), ACTOR3 = (2 << 2) //add more if you need }; }; ///An example class showing the use of springs (distance joints). class Trampoline { vector<DistanceJoint*> springs; Box *bottom, *top; public: Trampoline(const PxVec3& dimensions=PxVec3(1.f,1.f,1.f), PxReal stiffness=1.f, PxReal damping=1.f) { PxReal thickness = .1f; bottom = new Box(PxTransform(PxVec3(0.f,thickness,0.f)),PxVec3(dimensions.x,thickness,dimensions.z)); top = new Box(PxTransform(PxVec3(0.f,dimensions.y+thickness,0.f)),PxVec3(dimensions.x,thickness,dimensions.z)); springs.resize(4); springs[0] = new DistanceJoint(bottom, PxTransform(PxVec3(dimensions.x,thickness,dimensions.z)), top, PxTransform(PxVec3(dimensions.x,-dimensions.y,dimensions.z))); springs[1] = new DistanceJoint(bottom, PxTransform(PxVec3(dimensions.x,thickness,-dimensions.z)), top, PxTransform(PxVec3(dimensions.x,-dimensions.y,-dimensions.z))); springs[2] = new DistanceJoint(bottom, PxTransform(PxVec3(-dimensions.x,thickness,dimensions.z)), top, PxTransform(PxVec3(-dimensions.x,-dimensions.y,dimensions.z))); springs[3] = new DistanceJoint(bottom, PxTransform(PxVec3(-dimensions.x,thickness,-dimensions.z)), top, PxTransform(PxVec3(-dimensions.x,-dimensions.y,-dimensions.z))); for (unsigned int i = 0; i < springs.size(); i++) { springs[i]->Stiffness(stiffness); springs[i]->Damping(damping); } } void AddToScene(Scene* scene) { scene->Add(bottom); scene->Add(top); } ~Trampoline() { for (unsigned int i = 0; i < springs.size(); i++) delete springs[i]; } }; ///A customised collision class, implemneting various callbacks class MySimulationEventCallback : public PxSimulationEventCallback { public: //an example variable that will be checked in the main simulation loop bool trigger; int collisions = 0; //create a new int for later use int level = 1; MySimulationEventCallback() : trigger(false) {} ///Method called when the contact with the trigger object is detected. virtual void onTrigger(PxTriggerPair* pairs, PxU32 count) { //you can read the trigger information here for (PxU32 i = 0; i < count; i++) { //filter out contact with the planes if (pairs[i].otherShape->getGeometryType() != PxGeometryType::ePLANE) { //check if eNOTIFY_TOUCH_FOUND trigger if (pairs[i].status & PxPairFlag::eNOTIFY_TOUCH_FOUND) { cerr << "onTrigger::eNOTIFY_TOUCH_FOUND " << endl; trigger = true; collisions++; //incriment this int when a collision is detected } //check if eNOTIFY_TOUCH_LOST trigger if (pairs[i].status & PxPairFlag::eNOTIFY_TOUCH_LOST) { cerr << "onTrigger::eNOTIFY_TOUCH_LOST " << endl; trigger = false; collisions--; // reset when collision is lost } } } } ///Method called when the contact by the filter shader is detected. virtual void onContact(const PxContactPairHeader &pairHeader, const PxContactPair *pairs, PxU32 nbPairs) { cerr << "Contact found between " << pairHeader.actors[0]->getName() << " " << pairHeader.actors[1]->getName() << endl; //check all pairs for (PxU32 i = 0; i < nbPairs; i++) { //check eNOTIFY_TOUCH_FOUND if (pairs[i].events & PxPairFlag::eNOTIFY_TOUCH_FOUND) { cerr << "onContact::eNOTIFY_TOUCH_FOUND" << endl; } //check eNOTIFY_TOUCH_LOST if (pairs[i].events & PxPairFlag::eNOTIFY_TOUCH_LOST) { cerr << "onContact::eNOTIFY_TOUCH_LOST" << endl; } } } virtual void onConstraintBreak(PxConstraintInfo *constraints, PxU32 count) {} virtual void onWake(PxActor **actors, PxU32 count) {} virtual void onSleep(PxActor **actors, PxU32 count) {} }; //A simple filter shader based on PxDefaultSimulationFilterShader - without group filtering static PxFilterFlags CustomFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { // let triggers through if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1)) { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; return PxFilterFlags(); } pairFlags = PxPairFlag::eCONTACT_DEFAULT; //enable continous collision detection // pairFlags |= PxPairFlag::eCCD_LINEAR; //customise collision filtering here //e.g. // trigger the contact callback for pairs (A,B) where // the filtermask of A contains the ID of B and vice versa. if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1)) { //trigger onContact callback for this pair of objects pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND; pairFlags |= PxPairFlag::eNOTIFY_TOUCH_LOST; // pairFlags |= PxPairFlag::eNOTIFY_CONTACT_POINTS; } return PxFilterFlags(); }; ///Custom scene class class MyScene : public Scene { public: //specify your custom filter shader here //PxDefaultSimulationFilterShader by default MyScene() : Scene() {}; ///A custom scene class void SetVisualisation() { px_scene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); px_scene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); } PxReal gForceStrength = 20; Plane* plane; Box* box, * box2, *box3, *box4; MySimulationEventCallback* my_callback; backWall* _backWall; Wall1x1x1* smallWall_1, *LVL3_smallWall1, *LVL3_smallWall2, *LVL3_smallWall3, *LVL3_smallWall4; Wall2x1x1* midWall_1, *LVL2_midWall_1, *LVL3_midWall2; Wall3x1x1* longWall_1, *LVL1_LongWall_1, *LVL1_LongWall_2, *LVL2_LongWall_1; Wall3x2x1* bigWall_1, *LVL2_bigWall_1; Goal* goal1; PxRigidBody* a, *b; PxMaterial* Floor, *box3Mat; RevoluteJoint* joint1, *joint2; DistanceJoint* DJoint; CylinderStatic* cyl1, *cyl2; //Custom scene initialisation virtual void CustomInit() { SetVisualisation(); GetMaterial()->setDynamicFriction(.2f); Floor = CreateMaterial(0.f, 2.f, 1.f); box3Mat = CreateMaterial(.0f, .0f, 1.0f); //static , dynamic, enery transeral (bounce) ///Initialise and set the customised event callback my_callback = new MySimulationEventCallback(); px_scene->setSimulationEventCallback(my_callback); //floor plane = new Plane(); plane->Color(color_palette[12]); //plane->SetTrigger(my_callback); // set the trigger so the blocks reset on contact Add(plane); _backWall = new backWall(PxTransform(PxVec3(.0f, .0f, -1.1f))); // make a back wall so the actors cant go passed it _backWall->Color(color_palette[13]);// make the wall sky blue Add(_backWall); // add it to the scene CustomLevel1(); // init the level CustomActors(); //init actors CustomJoints(); //int the joints } virtual void CustomLevel1() { //level 1 objects LVL1_LongWall_1 = new Wall3x1x1(PxTransform(PxVec3(-2.f, .5f, .0f))); LVL1_LongWall_1->Color(color_palette[8]); Add(LVL1_LongWall_1); LVL1_LongWall_2 = new Wall3x1x1(PxTransform(PxVec3(1.f, .5f, .0f))); LVL1_LongWall_2->Color(color_palette[8]); Add(LVL1_LongWall_2); goal1 = new Goal(PxTransform(PxVec3(-.5f, 1.f, .0f))); goal1->Color(color_palette[1]); goal1->SetTrigger(my_callback); Add(goal1); LVL2_LongWall_1 = new Wall3x1x1(PxTransform(PxVec3(-2.f, 20.5f, .0f))); LVL2_LongWall_1->Color(color_palette[8]); Add(LVL2_LongWall_1); //right start block LVL2_midWall_1 = new Wall2x1x1(PxTransform(PxVec3(3.5f, 20.5f, .0f))); LVL2_midWall_1->Color(color_palette[8]); Add(LVL2_midWall_1); //left of goal LVL2_bigWall_1 = new Wall3x2x1(PxTransform(PxVec3(1.f, 21.f, .0f))); LVL2_bigWall_1->Color(color_palette[8]); Add(LVL2_bigWall_1); } virtual void CustomActors() { box = new Box(PxTransform(PxVec3(-3.f, 2.5f, .0f))); box->Color(color_palette[2]); box->Get()->setName("player1"); Add(box); box2 = new Box(PxTransform(PxVec3(2.f, 2.5f, .0f))); box2->Color(color_palette[3]); box2->Name("palyer1.5"); Add(box2); a = (PxRigidBody*)box->Get(); b = (PxRigidBody*)box2->Get(); } virtual void CustomJoints() { box3 = new Box(PxTransform(PxVec3(.0f, 2.f, .0f))); box3->Material(box3Mat); box3->Color(color_palette[10]); Add(box3); box4 = new Box(PxTransform(PxVec3(.0f, 2.f, .0f))); box4->Material(box3Mat); box4->Color(color_palette[10]); Add(box4); joint1 = new RevoluteJoint(NULL, PxTransform(PxVec3(-1.5f, 4.75f, 0.f), PxQuat(PxPi / 2, PxVec3(.0f, 1.f, .0f))), box3, PxTransform(PxVec3(0.f, 1.5f, 0.f))); // have no object as the spawn point joint1->DriveVelocity(0.5f); joint2 = new RevoluteJoint(NULL, PxTransform(PxVec3(1.5f, 4.75f, 0.f), PxQuat(PxPi / 2, PxVec3(.0f, 1.f, .0f))), box4, PxTransform(PxVec3(0.f, 1.5f, 0.f))); joint2->SetLimits(1, 5); //bad no PxPi but stopes it from over rotationg // DJoint = new DistanceJoint(NULL, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPi / 2, PxVec3(0.f, 1.f, 0.f))), box3, PxTransform(PxVec3(0.f, 5.f, 0.f))); } //Custom udpate function virtual void CustomUpdate() { a->addForce(PxVec3(0, 0, -1)); //lazy way of trying to keep it on the same axis b->addForce(PxVec3(0, 0, -1)); //lazy way of trying to keep it on the same axis if (my_callback->collisions >= 2) //find out if this variable within this class is 2 if so... { cerr << "two collisions there for level complete " << endl; // just to make sure the callback is working a->setGlobalPose(PxTransform(PxVec3(-3.f, 3.5f, .0f))); //move actor a b->setGlobalPose(PxTransform(PxVec3(4.f, 3.5f, .0f))); //move actor b //move walls to change the levels LVL1_LongWall_1->GetShape()->setLocalPose(PxTransform(PxVec3(.0f, -4.0f, .0f))); LVL1_LongWall_2->GetShape()->setLocalPose(PxTransform(PxVec3(.0f, -4.0f, .0f))); LVL2_LongWall_1->GetShape()->setLocalPose(PxTransform(PxVec3(.0f, -20.0f, .0f))); LVL2_midWall_1->GetShape()->setLocalPose(PxTransform(PxVec3(.0f, -20.0f, .0f))); LVL2_bigWall_1->GetShape()->setLocalPose(PxTransform(PxVec3(.0f, -20.0f, .0f))); goal1->GetShape()->setLocalPose(PxTransform(PxVec3(2.f, 1.25f, .0f))); // move the goal to teh new location } } /// An example use of key release handling void ExampleKeyReleaseHandler() { //cerr << "I am realeased!" << endl; } /// An example use of key presse handling void ExampleKeyPressHandlerD() { //cerr << "I am pressed! : D " << endl; a->addForce(PxVec3(1, 0, 0)*gForceStrength); //add force in direction *20 b->addForce(PxVec3(-1, 0, 0)*gForceStrength); } /// An example use of key presse handling void ExampleKeyPressHandlerA() { //cerr << "I am pressed! : A " << endl; a->addForce(PxVec3(-1, 0, 0)*gForceStrength); b->addForce(PxVec3(1, 0, 0)*gForceStrength); } /// An example use of key presse handling void ExampleKeyPressHandlerW() { //cerr << "I am pressed! : W " << endl; a->addForce(PxVec3(0, 260, 0)); b->addForce(PxVec3(0, 260, 0)); } }; }
true
f81476b9e70bcb8f349983de44b0fae978a64ff7
C++
AugustoCalaca/competitive-programming
/codeforces/981A.cpp
UTF-8
631
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <string> #define pb push_back using namespace std; typedef long long ll; typedef unsigned long long ull; void fast() { cout.sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); } int main() { fast(); string s; cin >> s; int ans = s.size(); int n = ans; for(int i = 0, j = n - 1; i < n / 2;) { if(s[i] == s[j]) { i++, j--; } else{ cout << ans << "\n"; return 0; } } int i = 0; while(s[i] == s[n - 1]) i++; if(i == n) cout << "0\n"; else cout << ans - 1 << "\n"; return 0; }
true
e24364af0087a23944325f7b9bcdf1c8c832a271
C++
haruponponpopon/MAC_cpp_Samples
/string/src/string_upper.hpp
UTF-8
1,124
3.71875
4
[]
no_license
#pragma once /** * C++ string sample * 2020-03-01 K.OHWADA */ // convert string to uppercase / lowercase // reference : https://en.cppreference.com/w/cpp/algorithm/transform #include<iostream> #include <algorithm> #include <cctype> // protytype char char2upper(char c); char char2lower(char c); void str2upper(std::string src, std::string &dst); void str2lower(std::string src, std::string &dst); /** * char2upper */ char char2upper(char c) { char ret; if(isalpha(c)) { ret = toupper(c); } else { ret = c; } return ret; } /** * char2lower */ char char2lower(char c) { char ret; if(isalpha(c)) { ret = tolower(c); } else { ret = c; } return ret; } /** * str2upper */ void str2upper(std::string src, std::string &dst) { dst.resize(src.size()); std::transform(src.begin(), src.end(), dst.begin(), char2upper ); return; } /** * str2lower */ void str2lower(std::string src, std::string &dst) { dst.resize(src.size()); std::transform(src.begin(), src.end(), dst.begin(), char2lower ); return; }
true
cd454f0e4733bdee05a02784aa1a9fe5c3dae825
C++
Mahonghui/AmNet
/src/net/iobuffer.cpp
UTF-8
1,086
2.71875
3
[]
no_license
// // Created by amisher on 18-12-10. // #include <sys/uio.h> #include <unistd.h> #include <stdint.h> #include <errno.h> #include "iobuffer.h" const size_t IOBuffer::PREPEND_SIZE; const size_t IOBuffer::INITIAL_SIZE; const char IOBuffer::CRLF[] = "\r\n"; ssize_t IOBuffer::ReadIntoFd(int fd, int *saved_errno) { char ex_buf[UINT16_MAX]; struct iovec vec[2]; const size_t writeable = GetWriteableSize(); vec[0].iov_base = GetBegin() + write_index_; vec[0].iov_len = writeable; vec[1].iov_base = ex_buf; vec[1].iov_len = sizeof(ex_buf); // 如果缓冲区大于ex_buf, 则使用缓冲区,否则使用ex_buf const int iov_idx = (writeable > sizeof(ex_buf))?1:2; const ssize_t n = readv(fd, vec, iov_idx); if(n<0) *saved_errno = errno; else if((size_t)(n) <= writeable) write_index_ += n; else{ // 要写的数据比缓冲区可写空间大 write_index_ = buffer_.size(); // append 会扩充空间 Append(ex_buf,n-writeable); } return n; }
true
9036cd5cb1142a7bc0a5ae3048f934a603154cf0
C++
ray7yu/cses
/Introductory Problems/two-sets.cpp
UTF-8
874
3.15625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { long n; int count = 0; cin >> n; vector<bool> elems(n+1, false); long sum = n * (n+1) / 2; if(sum % 2 != 0){ cout << "NO"; } else { cout << "YES" << endl; sum /= 2; long temp = n; while(sum != 0){ temp = min(sum, temp); sum -= temp; elems[temp] = true; count++; temp -= 1; } cout << count << endl; for(unsigned int i = 1; i < elems.size(); i++){ if(elems[i]){ cout << i << " "; } } cout << endl; cout << n - count << endl; for(unsigned int i = 1; i < elems.size(); i++){ if(!elems[i]){ cout << i << " "; } } } return 0; }
true
4550e9ac972f91cc45a6f7744a27be140a9b5617
C++
SiliGuo/RCC
/CSC-17A/Project 2/Player.cpp
UTF-8
4,336
3.296875
3
[]
no_license
/* * File: Player.cpp * Author: siliguo * * Created on December 8, 2016, 11:08 AM */ #include <cstring> #include "Player.h" int Player::Tbet = 0; Player::Player() { rank = 0; money = 1000; bet = 0; card = NULL; } void Player::setCard(PlyNum p) { card = new Card[3]; for (int i = 0; i < 3; i++) { this->card[i].setNum(p.num[i]); card[i].setNum(p.num[i]); } } void Player::setRank() { char *suit = new char[3]; int *val = new int[3]; for (int i = 0; i < 3; i++) { suit[i] = card[i].getSuit(); val[i] = card[i].getValue(); } //Check for rank 0 if (val[0] == 1 && val[1] == 2 && val[2] == 4) { rank = 0; } //Check for rank 1 if (val[0] != val[1] && val[1] != val[2]) { rank = 1; } //Check for rank 2 if ((val[0] == val[1] && val[1] != val[2]) || (val[1] == val[2] && val[0] != val[1])) { rank = 2; } //Check for rank 3, 4, 5 if (suit[0] == suit[1] && suit[1] == suit[2]) { if (val[0] + 1 == val[1] && val[1] + 1 == val[2]) { rank = 5; } else { rank = 4; } } else { if (val[0] + 1 == val[1] && val[1] + 1 == val[2]) { rank = 3; } } //Check for rank 6 if (val[0] == val[1] && val[1] == val[2]) { rank = 6; } delete [] suit; delete [] val; } void Player::setTbet(int a) { if (a < 1) { throw TooSmall(); } else if (a > 10) { throw TooLarge(); } else { Tbet += a * 10; } } bool Player::operator>(const Player &right) { //Declare variables bool win = false; if (rank == 0 && right.rank == 6) { win = true; } else if (rank == 6 && right.rank == 0) { win = false; } else { if (rank > right.rank) { win = true; } else if (rank < right.rank) { win = false; } else {//Rank equals //If same cards if (card[0].getValue() == right.card[0].getValue() && card[1].getValue() == right.card[1].getValue() && card[2].getValue() == right.card[2].getValue()) { win = false; } else {//Not same cards if (rank == 3 || rank == 5 || rank == 6) {//Rank 3, 5, 6 if (card[2].getValue() > right.card[2].getValue()) { win = true; } else { win = false; } } else if (rank == 1 || rank == 4) {//Rank 2, 4 if (card[2].getValue() > right.card[2].getValue()) { win = true; } else if (card[2].getValue() < right.card[2].getValue()) { win = false; } else { if (card[1].getValue() > right.card[1].getValue()) { win = true; } else if (card[1].getValue() < right.card[1].getValue()) { win = false; } else { if (card[0].getValue() > right.card[0].getValue()) { win = true; } else { win = false; } } } } else if (rank == 2) { if (card[1].getValue() > right.card[1].getValue()) { win = true; } else if (card[1].getValue() < right.card[1].getValue()) { win = false; } else { if (card[2].getValue() > right.card[2].getValue()) { win = true; } else if (card[2].getValue() < right.card[2].getValue()) { win = false; } else { if (card[1].getValue() > right.card[1].getValue()) { win = true; } else { win = false; } } } } }//Not same cards }//Rank equals } return win; }
true
5081fdaf593d55c3a3f61d663a3b4d1eb083a35a
C++
yuzec/luogu
/P1032/main.cpp
UTF-8
998
2.71875
3
[]
no_license
#include <iostream> #include <cstring> #include <queue> #include <map> using namespace std; int n; string a,b,orginal[6],translated[6]; struct node{ string str; int step; }ans; queue<node> q; map<string,int> m; node bfs(string a) { int i,pos; node s,t; s.str=a; s.step=0; q.push(s); while(!q.empty()) { s=q.front(),q.pop(); if(s.str==b||s.step>10) break; if(m[s.str]==1) continue; for(i=0,pos=-1;i<n-1;++i) { while((pos=s.str.find(orginal[i],pos+1))!=string::npos) { t=s; t.str.replace(pos,orginal[i].length(),translated[i]); t.step=s.step+1; q.push(t); } } m[s.str]=1; } return s; } int main() { cin>>a>>b; while(cin>>orginal[n]>>translated[n++]); ans=bfs(a); if(ans.step<=10&&ans.str==b) cout<<ans.step<<endl; else cout<<"NO ANSWER!"<<endl; return 0; }
true
c115439a045d8018946c60d8da9f8a9d65dccf9b
C++
kuerina/persistent_unordered_map
/persistent.h
UTF-8
3,425
2.84375
3
[]
no_license
#include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/managed_mapped_file.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <boost/unordered/unordered_map.hpp> #include <boost/functional/hash.hpp> #include <boost/algorithm/string.hpp> #include <boost/fusion/support/pair.hpp> // debugging #include <iostream> struct non_persistent_t {}; struct persistent_t {}; static const non_persistent_t non_persistent = non_persistent_t(); //!Value to indicate that the unordered_map must //!be non-persistent static const persistent_t persistent = persistent_t(); //!Value to indicate that the unordered_map must //!be persistent template<typename KeyType, typename MappedType> class unordered_map{ const char *ManagedFile; const char *map_name; typedef std::pair<const KeyType, MappedType> ValueType; typedef boost::interprocess::allocator<ValueType, boost::interprocess::managed_mapped_file::segment_manager> ShmemAllocator; typedef boost::interprocess::managed_mapped_file managed_segment; typedef boost::unordered_map < KeyType , MappedType , boost::hash<KeyType> ,std::equal_to<KeyType> , ShmemAllocator> MyHashMap; MyHashMap *myhashmap; boost::interprocess::managed_mapped_file::handle_t file_handler; long file_size; bool is_persistent = true; boost::interprocess::managed_mapped_file segment; public: unordered_map(persistent_t,const char *FileName, const char *map_nam ,long size, int num_buckets); unordered_map(non_persistent_t,const char *FileName, int size, int num_buckets); bool insert(KeyType,MappedType); MappedType get(KeyType); }; template<typename KeyType, typename MappedType> unordered_map<KeyType,MappedType>::unordered_map(persistent_t p,const char *FileName, const char *map_nam, long size,int num_buckets){ ManagedFile = FileName; file_size = size; is_persistent = true; map_name = map_nam; segment = boost::interprocess::managed_mapped_file(boost::interprocess::open_or_create, ManagedFile, file_size); myhashmap = segment.find_or_construct<MyHashMap>(map_name) ( num_buckets, boost::hash<int>(), std::equal_to<int>() , segment.get_allocator<ValueType>()); } template<typename KeyType, typename MappedType> unordered_map<KeyType,MappedType>::unordered_map(non_persistent_t p,const char *FileName, int size,int num_buckets){ ManagedFile = FileName; file_size = size; is_persistent = false; boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only, ManagedFile, file_size); myhashmap = segment.construct<MyHashMap>("MyHashMap") ( num_buckets, boost::hash<int>(), std::equal_to<int>() , segment.get_allocator<ValueType>()); } template<typename KeyType, typename MappedType> bool unordered_map<KeyType,MappedType>::insert(KeyType key,MappedType data){ try{ myhashmap->insert(ValueType(key,data)); //segment.flush(); }catch(const boost::interprocess::bad_alloc &){ return false; } return true; } template<typename KeyType, typename MappedType> MappedType unordered_map<KeyType,MappedType>::get(KeyType key){ auto mydata = myhashmap->find(key); if ( mydata == myhashmap->end() ){ return nullptr; } else{ return mydata->second; } }
true
c2ace39469faaed587bafe792049f5995c8a606f
C++
LittleVolcano/MY-PAT
/A1093.cpp
UTF-8
513
2.609375
3
[]
no_license
#include <algorithm> #include<stdio.h> #include <cstring> using namespace std; char str[100010]; int main() { int countp[100010]; int len; int num=0; long long ans = 0; gets(str); len = strlen(str); for(int i = 0;i < len; ++i) { if(str[i] == 'P') { countp[i+1] = countp[i]+1; num++; } else countp[i+1] = countp[i]; } num = 0; for(int i = len-1;i > 0;--i) { if(str[i] == 'T') num++; if(str[i] == 'A') ans += countp[i] * num; } printf("%ld",ans%1000000007); return 0; }
true
f009211affaab8db6351d6c51ad57be696281665
C++
ithsarasak/Programming
/Compettitive programming/BUU camp #14/camp#2/Problem/Daily#3/NC_optimization.cpp
UTF-8
1,732
2.640625
3
[]
no_license
#include<bits/stdc++.h> #define mod 1000000007 using namespace std; long long t, st[3] = { 14,15,63 }; struct A{ long long mat[4][4]; A operator*(const A &o){ A temp; for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ temp.mat[i][j] = 0; for(int k=0;k<3;k++){ temp.mat[i][j] += mat[i][k] * o.mat[k][j]; temp.mat[i][j] %= mod; temp.mat[i][j] += mod; temp.mat[i][j] %= mod; } } } return temp; } }; A start, temp; void mul( long long n ) { if( n == 1 ) return ; mul( n / 2 ); temp = temp * temp; if( n % 2 ) temp = temp * start; return ; } int main() { scanf("%lld",&t); for( int z = 1 ; z <= t ; z++ ){ long long a; scanf("%lld",&a); start.mat[0][0] = 0; start.mat[0][1] = 1; start.mat[0][2] = 0; start.mat[1][0] = 0; start.mat[1][1] = 0; start.mat[1][2] = 1; start.mat[2][0] = 6; start.mat[2][1] = 5; start.mat[2][2] = -2; temp = start; if( a == 0 ){ printf("Case #%d: 14\n",z); continue; } else if( a == 1 ){ printf("Case #%d: 15\n",z); continue; } else if( a == 2 ){ printf("Case #%d: 63\n",z); continue; } a -= 2; mul( a ); long long ans = 0; for( int j = 0 ; j < 3 ; j++ ){ ans += st[j] * temp.mat[2][j]; ans %= mod; ans += mod; ans %= mod; } printf("Case #%d: %lld\n",z,ans); } return 0; }
true
e7c2f3e1d584c7695f0ff02d1135d6a290a0cd1d
C++
harudes/Unlimited-Bit-Works-IV
/listas enlazadas ppp.cpp
UTF-8
1,044
3.390625
3
[]
no_license
#include <iostream> using namespace std; template <class T> class nodo{ public: T valor; nodo *next; nodo(){} nodo(T val):valor(val){next=NULL;} nodo(T val, nodo* siguiente):valor(val),next(siguiente){} }; template <class T> class lista{ private: nodo<T> *head; public: lista(){head=NULL;} lista(nodo<T>* cabeza):head(cabeza){} bool buscar(T dato, nodo<T>**& p){ while(*p&&dato>(*p)->valor){ p=&((*p)->next); } if(*p&&(*p)->valor==dato) return 1; else return 0; } void insertar(T valor){ nodo<T>** p = &head; if(!(buscar(valor,p))){ nodo<T>* a = new nodo<T>(valor,*p); (*p)=a; } } void eliminar(T valor){ nodo<T>** p = &head; if(buscar(valor,p)){ nodo<T>* temp=&(**p); *p=(*p)->next; delete temp; } } void imprimir(){ nodo<T>* temp=head; while(temp){ cout<<temp->valor<<", "; temp=temp->next; } cout<<endl; } nodo<T>** getHead(){return &head;} }; int main(int argc, char *argv[]) { lista<int> list; return 0; }
true
b8e2320824c6c9c66d26000ed6584206f11ecac9
C++
imulan/procon
/atcoder/abc015/c.cpp
UTF-8
564
2.609375
3
[]
no_license
#include <cstdio> #include <cmath> #include <iostream> using namespace std; int n, k, t[5][5]; int nums[5000]; int ct=0; void dfs(int a, int b){ if(a==n-1) for(int i=0; i<k; ++i) nums[ct++]=b^t[a][i]; else for(int i=0; i<k; ++i) dfs(a+1, b^t[a][i]); } int main(){ scanf(" %d %d", &n, &k); for(int i=0; i<n; ++i) for(int j=0; j<k; ++j) scanf(" %d", &t[i][j]); dfs(0,0); bool ans=true; for(int i=0; i<pow(k, n); ++i){ if(nums[i]==0){ ans=false; break; } } if(ans) printf("Nothing\n"); else printf("Found\n"); return 0; }
true
0743f75057a12fe277ae56f3b4d1efedf81f8d89
C++
danilotuzita/programacao-cientifica
/Aula1/Aula1/main.cpp
UTF-8
5,092
3.234375
3
[]
no_license
#include <iostream> #include <fstream> #include "Stack.hpp" #include "Queue.hpp" #include <time.h> #include <stack> #include <queue> using namespace std; int stackManual() { cout << "Teste STACK\n"; Stack<string> boolStack; string val; cout << "Digite um valor (0 para parar): "; cin >> val; while (val != "0") { cout << "Inserindo '" << val << "' na pilha\n"; boolStack << val; cout << "Topo da pilha agora eh: " << boolStack.top() <<endl; cout << "Digite um valor (0 para parar): "; cin >> val; } cout << "O tamanho da pilha eh: " << boolStack.count() << endl; while (!boolStack.isEmpty()) cout << "Desemplihando topo: " << --boolStack << endl; system("pause"); return 0; } int queueManual() { cout << "Teste QUEUE\n"; Queue<string> boolStack; string val; cout << "Digite um valor (0 para parar): "; cin >> val; while (val != "0") { cout << "Inserindo '" << val << "' na fila\n"; boolStack << val; cout << "O primeiro da fila agora eh: " << boolStack.first() << endl; cout << "Digite um valor (0 para parar): "; cin >> val; } cout << "O tamanho da fila eh: " << boolStack.count() << endl; while (!boolStack.isEmpty()) cout << "Desenfileirando: " << --boolStack << endl; system("pause"); return 0; } int _stack(ofstream* file) { printf("==============================\n"); printf("++++++ TESTE MEU STACK ++++++\n"); clock_t tStart = clock(); Stack<int> intStack; printf("Empilhando 1000000 de itens\n"); for (int i = 0; i < 1000000; i++) intStack.push(i); printf("Desemplilhando 500000 itens\n"); for (int i = 0; i < 500000; i++) intStack.pop(); printf("Empilhando 1000 de itens\n"); for (int i = 0; i < 1000; i++) intStack.push(i); printf("Desemplilhando todos os itens\n"); while (intStack.count()) intStack.pop(); clock_t tEnd = clock(); printf("\n\n==============================\n"); printf("++++++ TESTE STACK CPP ++++++\n"); clock_t tStartCpp = clock(); stack<int> intStackCpp; printf("Empilhando 1000000 de itens\n"); for (int i = 0; i < 1000000; i++) intStackCpp.push(i); printf("Desemplilhando 500000 itens\n"); for (int i = 0; i < 500000; i++) intStackCpp.pop(); printf("Empilhando 1000 de itens\n"); for (int i = 0; i < 1000; i++) intStackCpp.push(i); printf("Desemplilhando todos os itens\n"); while (intStackCpp.size()) intStackCpp.pop(); clock_t tEndCpp = clock(); printf("\n\n==============================\n"); printf("++++++ RESULTADOS MEU STACK ++++++\n"); clock_t t0 = tEnd - tStart; printf("Levou %d ticks (%f s)\n", t0, ((float)t0) / CLOCKS_PER_SEC); printf("\n\n==============================\n"); printf("++++++ RESULTADOS STACK CPP ++++++\n"); clock_t t1 = tEndCpp - tStartCpp; printf("Levou %d ticks (%f s)\n\n", t1, ((float)t1) / CLOCKS_PER_SEC); *file << t0 << "\t" << ((float)t0) / CLOCKS_PER_SEC << "\t" << t1 << "\t" << ((float)t1) / CLOCKS_PER_SEC << "\n"; printf("\n\n"); return 0; } int _queue(ofstream* file) { printf("==============================\n"); printf("++++++ TESTE MEU QUEUE ++++++\n"); clock_t tStart = clock(); Queue<int> intQueue; printf("Enfileirando 1000000 de itens\n"); for (int i = 0; i < 1000000; i++) intQueue.push(i); printf("Desenfileirando 500000 itens\n"); for (int i = 0; i < 500000; i++) intQueue.pop(); printf("Enfileirando 1000 de itens\n"); for (int i = 0; i < 1000; i++) intQueue.push(i); printf("Desenfileirando todos os itens\n"); while (intQueue.count()) intQueue.pop(); clock_t tEnd = clock(); printf("\n\n==============================\n"); printf("++++++ TESTE QUEUE CPP ++++++\n"); clock_t tStartCpp = clock(); queue<int> intQueueCpp; printf("Enfileirando 1000000 de itens\n"); for (int i = 0; i < 1000000; i++) intQueueCpp.push(i); printf("Desenfileirando 500000 itens\n"); for (int i = 0; i < 500000; i++) intQueueCpp.pop(); printf("Enfileirando 1000 de itens\n"); for (int i = 0; i < 1000; i++) intQueueCpp.push(i); printf("Desenfileirando todos os itens\n"); while (intQueueCpp.size()) intQueueCpp.pop(); clock_t tEndCpp = clock(); printf("\n\n==============================\n"); printf("++++++ RESULTADOS MEU QUEUE ++++++\n"); clock_t t0 = tEnd - tStart; printf("Levou %d ticks (%f s)\n", t0, ((float)t0) / CLOCKS_PER_SEC); printf("\n\n==============================\n"); printf("++++++ RESULTADOS QUEUE CPP ++++++\n"); clock_t t1 = tEndCpp - tStartCpp; printf("Levou %d ticks (%f s)\n\n", t1, ((float)t1) / CLOCKS_PER_SEC); *file << t0 << "\t" << ((float)t0) / CLOCKS_PER_SEC << "\t" << t1 << "\t" << ((float)t1) / CLOCKS_PER_SEC << "\n"; printf("\n\n"); return 0; } int main() { ofstream stackFile, queueFile; stackFile.open("stack.csv"); queueFile.open("queue.csv"); stackFile << "ticks[42]\ttempo(s)[42]\tticks[CPP]\ttempo(s)[CPP]\n"; queueFile << "ticks[42]\ttempo(s)[42]\tticks[CPP]\ttempo(s)[CPP]\n"; for (int i = 0; i < 100; i++) _stack(&stackFile); stackFile.close(); for (int i = 0; i < 100; i++) _queue(&queueFile); queueFile.close(); string s; cin >> s; return 0; }
true
d07c2c0a004f6a7b234f37708dc5e842e2f96ca2
C++
vglad/Reference-User-DLL
/User_DLL/Table.inl
UTF-8
13,440
2.71875
3
[]
no_license
#pragma once #include "Table.h" inline Table::Table() = default; inline Table::~Table() = default; //inline std::string Table::evaluate_equity_result(const double hand_equity, const double break_even_equity) { // std::string message; // if (hand_equity > break_even_equity) { // message.append("..........................[Table] Enough equity to continue. Returning TRUE.\n"); // } // else { // message.append("..........................[Table] Not enough equity to continue. Returning FALSE.\n"); // } // return message; //} // //inline std::string Table::evaluate_sample(const int stat_opportunities_sample, const int min_samples_needed) { // std::string sample_massage; // if (stat_opportunities_sample == -1 || stat_opportunities_sample == 0) { // sample_massage.append(".........................[Table] No samples at all. Skipping exploit bot...\n"); // } // else if (stat_opportunities_sample < min_samples_needed) { // sample_massage.append(".........................[Table] No enough samples. Skipping exploit bot...\n"); // } // else { // sample_massage.append(".........................[Table] Sample size is OK. Starting exploit bot...\n"); // } // return sample_massage; //} // //inline std::string Table::get_stat_name(const int sit_position, const int stack_range, // const int one_all_in_position, const int one_allin_position_chair) { // std::string stat_name = "pt_"; // switch (one_all_in_position) { // case POSITION_CO: { // stat_name.append("co"); // break; // } // case POSITION_BU: { // stat_name.append("bu"); // break; // } // case POSITION_SB: { // stat_name.append("sb"); // break; // } // default: return EMPTY_STRING; // } // switch (stack_range) { // case STACK_RANGE_105: { // stat_name.append("105_rfi"); // break; // } // case STACK_RANGE_135: { // stat_name.append("135_rfi"); // break; // } // case STACK_RANGE_160: { // stat_name.append("160_rfi"); // break; // } // default: return EMPTY_STRING; // } // switch (one_allin_position_chair) { // case CHAIR_0: { // stat_name.append("0"); // break; // } // case CHAIR_1: { // stat_name.append("1"); // break; // } // case CHAIR_2: { // stat_name.append("2"); // break; // } // case CHAIR_3: { // stat_name.append("3"); // break; // } // default: return EMPTY_STRING; // } // return stat_name; //} inline int Table::positions_info(const int allin_situation) { switch (allin_situation) { case FIRST_TO_ACT: { return first_to_act_positions_info(); } case ONE_ALLIN: { return one_allin_positions_info(); } case TWO_ALLINS: { return two_allin_positions_info(); } case THREE_ALLINS: { return three_allin_positions_info(); } default: { _oh.write_log("positions_info", "ERROR: Unknown allin situation: [" + std::to_string(allin_situation) + "]"); return 0; } } } inline std::vector<int> Table::stacks_info(const int allin_situation) { switch (allin_situation) { case FIRST_TO_ACT: return stacks_info_for_first_to_act(); case ONE_ALLIN: return stacks_info_for_one_allin(); case TWO_ALLINS: return stacks_info_for_two_allins(); case THREE_ALLINS: return stacks_info_for_three_allins(); default: { _oh.write_log("stacks_info", "ERROR: Unknown allin situation: [" + std::to_string(allin_situation) + "]"); std::vector<int> empty_vector; return empty_vector; } } } inline int Table::player_stack(std::string const& bet_or_balance_symbol, std::string const& position) { const auto chair_bit_number = _player.chair_bit_number(position); if (chair_bit_number == CHAIR_UNKNOWN) { return 0; } return _player.stack_in_bb(bet_or_balance_symbol, position, _conv.chair_bit_number_to_int(chair_bit_number)); } inline void Table::log_hand_number() { _oh.write_log(EMPTY_STRING, LOG_HEADER); _oh.write_log("log_hand_number", "Hand number: " + _oh.read_hand_number()); } inline void Table::log_allin_situation_name(const int allin_situation) { _oh.write_log("log_allin_situation_name", _conv.allin_situation_to_text(allin_situation)); } inline int Table::first_to_act_positions_info() { const auto hero_position = _oh.read_symbol(HERO_POSITION, MEMORY_SYMBOL); if (!(hero_position == POSITION_CO) && !(hero_position == POSITION_BU) && !(hero_position == POSITION_SB)) { _oh.write_log("one_allin_positions_info", "ERROR: Wrong hero position: [" + std::to_string(hero_position) + "]"); return 0; } _oh.write_log("first_to_act_positions_info", "Hero position: [" + _conv.position_to_text(hero_position) + "]"); return 1; } inline int Table::one_allin_positions_info() { const auto one_allin_position = _oh.read_symbol(ONE_ALLIN_POSITION, MEMORY_SYMBOL); if (!(one_allin_position == POSITION_CO) && !(one_allin_position == POSITION_BU) && !(one_allin_position == POSITION_SB)) { _oh.write_log("one_allin_positions_info", "ERROR: Unknown one allin position: [" + std::to_string(one_allin_position) + "]"); return 0; } const auto hero_position = _oh.read_symbol(HERO_POSITION, MEMORY_SYMBOL); if (!(hero_position == POSITION_BU) && !(hero_position == POSITION_SB) && !(hero_position == POSITION_BB)) { _oh.write_log("one_allin_positions_info", "ERROR: Wrong hero position: [" + std::to_string(hero_position) + "]"); return 0; } if (hero_position == POSITION_BU && !(one_allin_position == POSITION_CO)) { _oh.write_log("one_allin_positions_info", "ERROR: Wrong one allin position: [" + std::to_string(one_allin_position) + "]"); _oh.write_log("one_allin_positions_info", "ERROR: Hero on BU, one allin position must be CO"); return 0; } if (hero_position == POSITION_SB && (one_allin_position != POSITION_CO && one_allin_position != POSITION_BU)) { _oh.write_log("one_allin_positions_info", "ERROR: Wrong one allin position: [" + std::to_string(one_allin_position) + "]"); _oh.write_log("one_allin_positions_info", "ERROR: Hero on SB, one allin position must be CO or BU"); return 0; } if (hero_position == POSITION_BB && (one_allin_position != POSITION_CO && one_allin_position != POSITION_BU && one_allin_position != POSITION_SB)) { _oh.write_log("one_allin_positions_info", "ERROR: Wrong one allin position: [" + std::to_string(one_allin_position) + "]"); _oh.write_log("one_allin_positions_info", "ERROR: Hero on BB, one allin position must be CO, BU or SB"); return 0; } _oh.write_log("one_allin_positions_info", _conv.allin_positions_to_text(one_allin_position)); _oh.write_log("one_allin_positions_info", "Hero position: [" + _conv.position_to_text(hero_position) + "]"); return 1; } inline int Table::two_allin_positions_info() { const auto two_allin_positions = _oh.read_symbol(TWO_ALLIN_POSITIONS, MEMORY_SYMBOL); if (!(two_allin_positions == POSITION_CO_BU) && !(two_allin_positions == POSITION_CO_SB) && !(two_allin_positions == POSITION_BU_SB)) { _oh.write_log("two_allin_positions_info", "ERROR: Unknown two allin positions: [" + std::to_string(two_allin_positions) + "]"); return 0; } const auto hero_position = _oh.read_symbol(HERO_POSITION, MEMORY_SYMBOL); if (!(hero_position == POSITION_SB) && !(hero_position == POSITION_BB)) { _oh.write_log("two_allin_positions_info", "ERROR: Wrong hero position: [" + std::to_string(hero_position) + "]"); return 0; } if (hero_position == POSITION_SB && !(two_allin_positions == POSITION_CO_BU)) { _oh.write_log("two_allin_positions_info", "ERROR: Wrong two allin positions: [" + std::to_string(two_allin_positions) + "]"); _oh.write_log("two_allin_positions_info", "ERROR: Hero on SB, two allin positions must be CO and BU"); return 0; } _oh.write_log("two_allin_positions_info", _conv.allin_positions_to_text(two_allin_positions)); _oh.write_log("two_allin_positions_info", "Hero position: [" + _conv.position_to_text(hero_position) + "]"); return 1; } inline int Table::three_allin_positions_info() { const auto three_allin_positions = _oh.read_symbol(THREE_ALLIN_POSITIONS, MEMORY_SYMBOL); if (three_allin_positions != POSITION_CO_BU_SB) { _oh.write_log("three_allin_positions_info", "ERROR: Unknown three allin positions: [" + std::to_string(three_allin_positions) + "]"); return 0; } const auto hero_position = _oh.read_symbol(HERO_POSITION, MEMORY_SYMBOL); if (hero_position != POSITION_BB) { _oh.write_log("three_allin_positions_info", "ERROR: Wrong hero position: [" + std::to_string(hero_position) + "]"); return 0; } _oh.write_log("three_allin_positions_info", _conv.allin_positions_to_text(three_allin_positions)); _oh.write_log("three_allin_positions_info", "Hero position: [" + _conv.position_to_text(hero_position) + "]"); return 1; } inline std::vector<int> Table::stacks_info_for_first_to_act() { std::vector<int> stacks = {0, 0, 0, 0}, empty_vector; const auto hero_position = static_cast<int>(_oh.read_symbol(HERO_POSITION, MEMORY_SYMBOL)); if (hero_position == POSITION_CO) { if ((stacks[0] = player_stack(BALANCE, CUTOFF)) == 0) { return empty_vector; } } if (hero_position == POSITION_CO || hero_position == POSITION_BU) { if ((stacks[1] = player_stack(BALANCE, BUTTON)) == 0) { return empty_vector; } } if (hero_position == POSITION_CO || hero_position == POSITION_BU || hero_position == POSITION_SB) { if ((stacks[2] = player_stack(BALANCE, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } return stacks; } inline std::vector<int> Table::stacks_info_for_one_allin() { std::vector<int> stacks = {0, 0, 0, 0}, empty_vector; const auto one_allin_position = _oh.read_symbol(ONE_ALLIN_POSITION, MEMORY_SYMBOL); if (one_allin_position == POSITION_CO) { if ((stacks[0] = player_stack(BET, CUTOFF)) == 0 || (stacks[1] = player_stack(BALANCE, BUTTON)) == 0 || (stacks[2] = player_stack(BALANCE, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } else if (one_allin_position == POSITION_BU) { if ((stacks[1] = player_stack(BET, BUTTON)) == 0 || (stacks[2] = player_stack(BALANCE, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } else if (one_allin_position == POSITION_SB) { if ((stacks[2] = player_stack(BET, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } return stacks; } inline std::vector<int> Table::stacks_info_for_two_allins() { std::vector<int> stacks = {0, 0, 0, 0}, empty_vector; const auto two_allin_positions = _oh.read_symbol(TWO_ALLIN_POSITIONS, MEMORY_SYMBOL); if (two_allin_positions == POSITION_CO_BU) { if ((stacks[0] = player_stack(BET, CUTOFF)) == 0 || (stacks[1] = player_stack(BET, BUTTON)) == 0 || (stacks[2] = player_stack(BALANCE, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } else if (two_allin_positions == POSITION_CO_SB) { if ((stacks[0] = player_stack(BET, CUTOFF)) == 0 || (stacks[1] = player_stack(BALANCE, BUTTON)) == 0 || (stacks[2] = player_stack(BET, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } else if (two_allin_positions == POSITION_BU_SB) { if ((stacks[1] = player_stack(BET, BUTTON)) == 0 || (stacks[2] = player_stack(BET, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } } return stacks; } inline std::vector<int> Table::stacks_info_for_three_allins() { std::vector<int> stacks = {0, 0, 0, 0}, empty_vector; if ((stacks[0] = player_stack(BET, CUTOFF)) == 0 || (stacks[1] = player_stack(BET, BUTTON)) == 0 || (stacks[2] = player_stack(BET, SMALLBLIND)) == 0 || (stacks[3] = player_stack(BALANCE, BIGBLIND)) == 0) { return empty_vector; } return stacks; }
true
db4e1904f7e4bcfb36ed30b8a702af77d14bb382
C++
gascensio/GordonAscensio_CIS_17a_Spring_2018
/HomeWork/Project1401/numbers.h
UTF-8
835
2.953125
3
[]
no_license
/* /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: numbers.h * Author: Gordon * * Created on May 1, 2018, 2:16 PM */ #ifndef NUMBERS_H #define NUMBERS_H #include <string> using namespace std; class Numbers { private: int number; static string lessThen20[20]; static string hundred; static string thousand; static string TentoNinety[10]; public: Numbers(){this->number = 0;} Numbers(int num); void print()const; void operator=(const int number){ if(number < 0 || number > 9999) this->number = 0; else this->number = number; } }; #endif /* NUMBERS_H */
true
c2b40a9f67f96902d9707c21263e8c1b85348ef6
C++
hyperpace/study_algo_gangnam
/CNK/codePlus_basic/day01/03_10799_main.cpp
UTF-8
540
2.9375
3
[]
no_license
#include <iostream> #include <stack> using namespace std; /* 쇠막대기 https://www.acmicpc.net/problem/10799 */ int main() { stack<int> stk; string line; getline(cin, line); int cnt = 0; for (int i = 0; i < line.size(); i++) { if (line[i] == '(') { stk.push(i); } else { if (i - stk.top() == 1) { // 레이저 stk.pop(); cnt += stk.size(); } else if(!stk.empty()) { // 쇠막대기 끝 stk.pop(); cnt += 1; } } } cout << cnt << '\n'; return 0; }
true
95541ccde3d86dc134c58afcc3aaee87e2de386e
C++
guker/utility
/buffer/CircularBuffer.cpp
UTF-8
2,896
3.125
3
[]
no_license
#include "CircularBuffer.h" #include <cstdio> //for fopen namespace BaseLib { void CircularBuffer::append(const char *data,size_t len) { m_circular_buffer_.insert(m_circular_buffer_.end(),data,data+len); } void CircularBuffer::append(const std::string &sData) { m_circular_buffer_.insert(m_circular_buffer_.end(),sData.begin(),sData.end()); } void CircularBuffer::append(const CircularBuffer &data) { m_circular_buffer_.insert(m_circular_buffer_.end(),data.m_circular_buffer_.begin(), data.m_circular_buffer_.end()); } void CircularBuffer::append(const Buffer& buffer) { m_circular_buffer_.insert(m_circular_buffer_.end(), buffer.peek(),buffer.peek()+buffer.readableBytes()); } int32_t CircularBuffer::appendFromFile(const std::string path,const std::string mode) { FILE *fp = fopen(path.c_str(),mode.c_str()); int32_t nLength = -1; if (fp) { fseek(fp,0,SEEK_END); nLength = ftell(fp); fseek(fp,0,SEEK_SET); int8_t *pContent = new int8_t[nLength+1](); fread(pContent,1,nLength,fp); m_circular_buffer_.assign(&pContent[0],&pContent[nLength]); delete[] pContent; pContent = NULL; } fclose(fp); return nLength; } std::string CircularBuffer::readAllAsString() { std::string sRes(""); sRes.append(m_circular_buffer_.begin(),m_circular_buffer_.end()); return sRes; } std::string CircularBuffer::readAsString(uint32_t nLen, uint32_t nOffset, bool from_end) { std::string sRes; if(nOffset + nLen <= m_circular_buffer_.size() && nOffset >= 0) { if(from_end) { sRes.append(m_circular_buffer_.end()-nOffset-nLen, m_circular_buffer_.end()-nOffset); } else { sRes.append(m_circular_buffer_.begin()+nOffset, m_circular_buffer_.begin()+nOffset+nLen); } } return sRes; } Buffer CircularBuffer::readAllAsBuffer() { Buffer buffer; std::string str = readAllAsString(); if(!str.empty()) { buffer.append(str); } return buffer; } Buffer CircularBuffer::readAsBuffer(uint32_t nLen, uint32_t nOffset, bool from_end) { Buffer buffer; std::string str = readAsString(nLen,nOffset,from_end); if(!str.empty()) { buffer.append(str); } return buffer; } bool CircularBuffer::readAsBuffer(Buffer &out,uint32_t nLen, uint32_t nOffset, bool from_end) { out.retrieveAll(); std::string str = readAsString(nLen,nOffset,from_end); if(!str.empty()) { out.append(str); } return true; } CircularBuffer::CircularBuffer(CircularBuffer &rhs) { m_circular_buffer_ = rhs.m_circular_buffer_; } CircularBuffer& CircularBuffer::operator = (const CircularBuffer &rhs) { m_circular_buffer_ = rhs.m_circular_buffer_; return *this; } }
true
3fd5e0e91c795fdf88f87d3868be6d1728beb853
C++
Chen-Dixi/Leetcode
/1143-longest-common-subsequence.cpp
UTF-8
950
3.21875
3
[]
no_license
#include <cstdio> #include <iostream> #include <cstring> #include <utility> #include <algorithm> using namespace std; class Solution { public: //注意问题是公共子序列 int longestCommonSubsequence(string text1, string text2) { int len1=text1.size(); int len2=text2.size(); if(len1==0 || len2==0){ return 0; } int dp[len1+1][len2+1]; memset(dp,0,sizeof(dp)); for(int i=1;i<=len1;i++) for(int j=1;j<=len2;j++){ if(text1[i-1]==text2[j-1]){ dp[i][j]=dp[i-1][j-1]+1; }else{ dp[i][j]=max(dp[i-1][j], dp[i][j-1]); } } return dp[len1][len2]; } }; int main(){ string text1 = "abcde"; string text2 = "ace"; Solution sol = Solution(); int ans = sol.longestCommonSubsequence(text1, text2); cout<<ans<<endl; }
true
8f54151cf652d387d89df9d66a112a40788ed3d8
C++
merak1t/uniq_counter
/array_checker/array_checker.cpp
UTF-8
2,446
3.375
3
[]
no_license
// // Created by damm1t on 4/30/19. // #include <vector> #include <iostream> #include <unordered_map> #include <assert.h> #include <algorithm> #include "array_checker.h" namespace { struct item_holder { item_holder() = default; void add(int value) { cnt_small[value]++; } bool find(int value) { if (cnt_small.find(value) == cnt_small.end()) { return false; } return (cnt_small[value] != 0); } bool remove(int value) { if (find(value)) { cnt_small[value]--; return true; } return false; } private: std::unordered_map<int, size_t> cnt_small; }; // solve without optimization on borders size_t small_intersection(const vector<int> &small, const vector<int> &large) { size_t res = 0; auto sorted_small = small; sort(sorted_small.begin(), sorted_small.end()); for (int value : large) { auto find = std::lower_bound(sorted_small.begin(), sorted_small.end(), value); if (find != sorted_small.end() && *find == value) { res++; } } return res; } size_t intersection_impl(const vector<int> &small, const vector<int> &large) { if (large.empty()) { return 0; } if (small.size() <= SMALL_SIZE) { return small_intersection(small, large); } int lower_bound = large[0]; int upper_bound = large[0]; for (int value : large) { // find lower and upper bounds of large array lower_bound = std::min(lower_bound, value); upper_bound = std::max(upper_bound, value); } item_holder holder; // search for a pair from a large array to a small for (int value : small) { // add elements of small array to map with borders if (lower_bound <= value && value <= upper_bound) { holder.add(value); } } size_t cnt = 0; for (int value : large) { cnt += (size_t) holder.remove(value); } return cnt; } } size_t intersection(const vector<int> &lhs, const vector<int> &rhs) { if (lhs.size() > rhs.size()) { return intersection_impl(rhs, lhs); } else { return intersection_impl(lhs, rhs); } }
true
392a966465b13b3b88b7b25a3d760297e89dae4c
C++
bmvskii/DataStructuresAndAlgorithms
/Common data structures/8/lab8_1.cpp
WINDOWS-1251
673
3.03125
3
[]
no_license
#include <iostream> #include "integer_vector.hpp" int main() { IntegerVector * pVector = new IntegerVector; IntegerVectorInit(*pVector); IntegerVectorReadTillZero(*pVector,std::cin); IntegerVector v = *pVector; int p; std::cin >> p; // , for (int i = v.m_nUsed - 1; i >= p - 1; i--) std::cout << v.m_pData[i] << " "; // , for (int i = 0; i < p - 1; i++) std::cout << v.m_pData[i] << " "; std::cout << std::endl; IntegerVectorDestroy(*pVector); return 0; }
true
bd5019d6afb44bc7f25ed76c6d4559e03a2e6d32
C++
nitinchaube/Algorithms-and-problems
/codingNinjas/dynamicProgramming1/coinChangeProblem.cpp
UTF-8
2,092
3.796875
4
[]
no_license
/*Coin Change Problem Send Feedback For the given infinite supply of coins of each of denominations, D = {D0, D1, D2, D3, ...... Dn-1}. You need to figure out the total number of ways W, in which you can make the change for Value V using coins of denominations D. Return 0 if the change isn't possible. Input Format The first line of the input contains an integer value N, which denotes the total number of denominations. The second line of input contains N values, separated by a single space. These values denote the value of denomination. The third line of the input contains an integer value, that denotes the value of V. Output Format Print the total total number of ways i.e. W. Constraints : 1 <= n <= 10 1 <= V <= 1000 Time Limit: 1sec Sample Input 1 : 3 1 2 3 4 Sample Output 1 : 4 Explanation to Sample Input 1 : Number of ways are - 4 total i.e. (1,1,1,1), (1,1, 2), (1, 3) and (2, 2). Sample Input 2 : 6 1 2 3 4 5 6 250 Sample Output 2 : 13868903 */ #include <iostream> using namespace std; int countCoin(int *arr,int n,int value,int **temp){ if(n==0){ return 0; } if(value==0){ return 1; } if(value<0){ return 0; } if(temp[n][value]>0){ return temp[n][value]; } int ans1 = countCoin(arr + 1, n - 1, value, temp); int ans2 = countCoin(arr, n, value - arr[0], temp); int ans=ans1+ans2; temp[n][value]=ans; return ans; } int countWaysToMakeChange(int *arr,int n,int value){ int** temp=new int*[11]; for(int i=0;i<11;i++){ temp[i]=new int[1001]; for(int j=0;j<n;j++){ temp[i][j]=0; } } int ans=countCoin(arr,n,value,temp); for(int i=0;i<n;i++){ delete[]temp[i]; } delete[] temp; return ans; } int main() { int numDenominations; cin >> numDenominations; int *denominations = new int[numDenominations]; for (int i = 0; i < numDenominations; i++) { cin >> denominations[i]; } int value; cin >> value; cout << countWaysToMakeChange(denominations, numDenominations, value); delete[] denominations; }
true
739de7a2afb8cdaf863e83f5b4d0d68405845d55
C++
jeff916121/cpluspluspractice
/2018.12.03/NoPointerClass/Complex.h
UTF-8
182
2.609375
3
[]
no_license
//Complex.h #pragma once class Complex { private: int real; int img; public: Complex(); Complex(int real, int img); Complex(const Complex &c1); void display(); ~Complex(); };
true
51302705e3eab3a33d4ecd5b0281799c6a740d75
C++
Wendelize/Derp-fix-code
/GameProject/GameProject/src/Header Files/Player.h
UTF-8
532
2.765625
3
[]
no_license
#pragma once #include "Include.h" class Player { private: string m_name; int m_health; int m_controllerID; float m_weight; float m_speed; public: Object* m_object; Player(); ~Player(); string GetName(); void SetName(string name); int GetHealth(); void SetHealth(int health); float GetSpeed(); void SetSpeed(float speed); float GetWeight(); void SetWeight(float weight); int GetControllerID(); void SetControllerID(int id); Object* GetObject(); void SetObject(Object* object); };
true
b3bb3ee7c47a2d9aa1886b44851cb0e88eab1dcb
C++
GabeMillikan/CSGO_INTERNAL_BASE
/QAngle.hpp
UTF-8
1,227
2.59375
3
[]
no_license
#pragma once #include <math.h> #include "Vector.hpp" namespace SDK { class QAngle { public: QAngle(void); QAngle(float X, float Y, float Z); QAngle(const float* clr); QAngle(Vector From, Vector To); QAngle(Vector Offset); void Init(float ix = 0.0f, float iy = 0.0f, float iz = 0.0f); float operator[](int i) const; float& operator[](int i); QAngle& operator+=(const QAngle& v); QAngle& operator-=(const QAngle& v); QAngle& operator*=(float fl); QAngle& operator*=(const QAngle& v); QAngle& operator/=(const QAngle& v); QAngle& operator+=(float fl); QAngle& operator/=(float fl); QAngle& operator-=(float fl); QAngle& operator=(const QAngle &vOther); QAngle operator-(void) const; QAngle operator+(const QAngle& v) const; QAngle operator-(const QAngle& v) const; QAngle operator*(float fl) const; QAngle operator*(const QAngle& v) const; QAngle operator/(float fl) const; QAngle operator/(const QAngle& v) const; float Length() const; float LengthSqr(void) const; float distanceTo(QAngle other); QAngle NormalizedTo(QAngle other); bool IsZero(float tolerance = 0.01f) const; void Normalize(); void Unit(); float pitch; float yaw; float roll; }; }
true
849cb636ee8feff6650b7583cbbe564177e8a0cd
C++
idris/katamari
/Quaternion/Vector3D.cpp
UTF-8
5,953
3.53125
4
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
//----------------------------------------------------------------------- // File: Vector3D.cpp // Description: Vectors and Points in 3D // Programmer: Dave Mount // For: CMSC 427 - Fall 2009 //----------------------------------------------------------------------- #include "Vector3D.h" using namespace std; // make std:: accessible //---------------------------------------------------------------------- // Constructors and Destructors //---------------------------------------------------------------------- Vector3D::Vector3D(): x(0), y(0), z(0) {} Vector3D::Vector3D(double _x, double _y, double _z): x(_x), y(_y), z(_z) {} Vector3D::Vector3D(const Vector3D& copy): x(copy.x), y(copy.y), z(copy.z) {} Vector3D::~Vector3D() {} //---------------------------------------------------------------------- // Assignment operators //---------------------------------------------------------------------- Vector3D& Vector3D::operator=(const Vector3D& v) { x = v.x; y = v.y; z = v.z; return *this; } Vector3D& Vector3D::operator+=(const Vector3D& v) { x += v.x; y += v.y; z += v.z; return *this; } Vector3D& Vector3D::operator-=(const Vector3D& v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3D& Vector3D::operator*=(double s) { x *= s; y *= s; z *= s; return *this; } //---------------------------------------------------------------------- // Arithmetic operators //---------------------------------------------------------------------- Vector3D operator+(const Vector3D& v1, const Vector3D& v2) { Vector3D res(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); return res; } Vector3D operator-(const Vector3D& v1, const Vector3D& v2) { Vector3D res(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); return res; } Vector3D operator*(double s, const Vector3D& v) { Vector3D res(s*v.x, s*v.y, s*v.z); return res; } Vector3D operator*(const Vector3D& v, double s) { return s * v; } //---------------------------------------------------------------------- // Additional methods //---------------------------------------------------------------------- double Vector3D::length() const { return sqrt(x*x + y*y + z*z); } void Vector3D::clamp(double min, double max) { double len = length(); if (max < GEOM_INF && len > max) { // too long? x *= (max/len); y *= (max/len); z *= (max/len); } else if (min > 0 && len < min) { // too short? x *= (min/len); y *= (min/len); z *= (min/len); } } void Vector3D::normalize() // normalize to unit length { double len = length(); if (len < GEOM_EPS) return; x /= len; y /= len; z /= len; } // functional form Vector3D Vector3D::normalize(const Vector3D& v) { double len = v.length(); if (len < GEOM_EPS) return v; else return (1/len) * v; } //---------------------------------------------------------------------- // Additional utilities //---------------------------------------------------------------------- double Vector3D::dist(const Vector3D& v1, const Vector3D& v2) { return sqrt( (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + (v1.z - v2.z)*(v1.z - v2.z)); } double Vector3D::dot(const Vector3D& v1, const Vector3D& v2) { return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z); } // cross product Vector3D Vector3D::cross(const Vector3D& v1, const Vector3D& v2) { return Vector3D( v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x); } //---------------------------------------------------------------------- // Projection: // project - project v1 orthogonally onto v2 // orthog - orthogonal complement of v1 wrt v2 // // Thus: project(v1, v2) + orthog(v1, v2) == v1 //---------------------------------------------------------------------- Vector3D Vector3D::project(const Vector3D& v1, const Vector3D& v2) { return Vector3D((Vector3D::dot(v1, v2)*(1/Vector3D::dot(v2, v2))) * v2); } Vector3D Vector3D::orthog(const Vector3D& v1, const Vector3D& v2) { return v1 - Vector3D::project(v1, v2); } //---------------------------------------------------------------------- // Converts Cartesian to spherical coords // from (x,y,z) to (radius, theta, phi) in radians, where theta gives // the longitude and phi gives the latitude (start at 0 for north pole) //---------------------------------------------------------------------- Vector3D Vector3D::convertCartesianToSpherical(const Vector3D& v) { double lenXY = sqrt(v.x*v.x + v.y*v.y); Vector3D spherical; spherical.x = v.length(); spherical.y = atan2(v.y, v.x); // theta spherical.z = -atan2(v.z, lenXY); // phi return spherical; } //---------------------------------------------------------------------- // Converts spherical to Cartesian // from (rho, theta, phi) in radians to (x,y,z) //---------------------------------------------------------------------- Vector3D Vector3D::convertSphericalToCartesian(const Vector3D& v) { Vector3D cartesian; cartesian.x = v.x * cos(v.y) * sin(v.z); cartesian.y = v.x * sin(v.y) * sin(v.z); cartesian.z = v.x * cos(v.z); return cartesian; } //---------------------------------------------------------------------- // Common vectors //---------------------------------------------------------------------- Vector3D Vector3D::zero() { return Vector3D(0, 0, 0); } Vector3D Vector3D::yUnit() { return Vector3D(1, 0, 0); } Vector3D Vector3D::xUnit() { return Vector3D(0, 1, 0); } Vector3D Vector3D::zUnit() { return Vector3D(0, 0, 1); } //---------------------------------------------------------------------- // Output operator //---------------------------------------------------------------------- ostream& operator<<(ostream& out, const Vector3D& v) { return out << "[" << v.x << ", " << v.y << ", " << v.z << "]"; }
true
59c53fb2db22fd4a05f210145e98c618ce783612
C++
steptosky/XplnObj
/src/sts/geometry/templates/AxisAngle.inl
UTF-8
9,307
2.609375
3
[ "BSD-3-Clause" ]
permissive
/* ** Copyright(C) 2017, StepToSky ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** ** 1.Redistributions of source code must retain the above copyright notice, this ** list of conditions and the following disclaimer. ** 2.Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and / or other materials provided with the distribution. ** 3.Neither the name of StepToSky nor the names of its contributors ** may be used to endorse or promote products derived from this software ** without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** Contacts: www.steptosky.com */ /**************************************************************************************************/ ////////////////////////////////////* Constructors/Destructor *///////////////////////////////////// /**************************************************************************************************/ template<class Type> AxisAngle<Type>::AxisAngle() : AxisAngle<Type>(Type(0), Type(0), Type(0), Type(0)) {} template<class Type> AxisAngle<Type>::AxisAngle(const Vector3<Type> & inVec, Type inAngleRad) : AxisAngle<Type>(inVec.x, inVec.y, inVec.z, inAngleRad) {} template<class Type> AxisAngle<Type>::AxisAngle(Type inX, Type inY, Type inZ, Type inW) { mData[0] = inX; mData[1] = inY; mData[2] = inZ; mData[3] = inW; } template<class Type> AxisAngle<Type>::~AxisAngle() {} /**************************************************************************************************/ ///////////////////////////////////////////* Operators *//////////////////////////////////////////// /**************************************************************************************************/ template<class Type> bool AxisAngle<Type>::operator !=(const AxisAngle<Type> & inRight) const { return ( !sts::isEqual(mData[0], inRight.mData[0]) || !sts::isEqual(mData[1], inRight.mData[1]) || !sts::isEqual(mData[2], inRight.mData[2]) || !sts::isEqual(mData[3], inRight.mData[3])); } template<class Type> bool AxisAngle<Type>::operator ==(const AxisAngle<Type> & inRight) const { return ( sts::isEqual(mData[0], inRight.mData[0]) && sts::isEqual(mData[1], inRight.mData[1]) && sts::isEqual(mData[2], inRight.mData[2]) && sts::isEqual(mData[3], inRight.mData[3])); } /*! * \details Gets const reference to a cell. * \param [in] i cell index, maximum value is 3 (4 cells). * \return \code return reinterpret_cast<const Type*>(mData)[i]; \endcode */ template<class Type> const Type & AxisAngle<Type>::operator[](size_t i) const { assert(i < 4); return reinterpret_cast<const Type*>(mData)[i]; } /*! * \details Gets reference to a cell. * \param [in] i cell index, maximum value is 3 (4 cells). * \return \code return reinterpret_cast<const Type*>(mData)[i]; \endcode */ template<class Type> Type & AxisAngle<Type>::operator[](size_t i) { assert(i < 4); return reinterpret_cast<Type*>(mData)[i]; } /**************************************************************************************************/ ///////////////////////////////////////////* Functions *//////////////////////////////////////////// /**************************************************************************************************/ template<class Type> void AxisAngle<Type>::setX(const Type inX) { mData[0] = inX; } template<class Type> void AxisAngle<Type>::setY(const Type inY) { mData[1] = inY; } template<class Type> void AxisAngle<Type>::setZ(const Type inZ) { mData[2] = inZ; } template<class Type> void AxisAngle<Type>::setW(const Type inW) { mData[3] = inW; } template<class Type> Type AxisAngle<Type>::x() const { return mData[0]; } template<class Type> Type AxisAngle<Type>::y() const { return mData[1]; } template<class Type> Type AxisAngle<Type>::z() const { return mData[2]; } template<class Type> Type AxisAngle<Type>::w() const { return mData[3]; } /**************************************************************************************************/ ///////////////////////////////////////////* Functions *//////////////////////////////////////////// /**************************************************************************************************/ template<class Type> void AxisAngle<Type>::set(Type inX, Type inY, Type inZ, Type inAngleRad) { mData[0] = inX; mData[1] = inY; mData[2] = inZ; mData[3] = inAngleRad; } template<class Type> void AxisAngle<Type>::set(const Vector3<Type> & inVec, Type inAngleRad) { mData[0] = inVec.x; mData[1] = inVec.y; mData[2] = inVec.z; mData[3] = inAngleRad; } template<class Type> void sts_t::AxisAngle<Type>::clear() { mData[0] = Type(0); mData[1] = Type(0); mData[2] = Type(0); mData[3] = Type(0); } template<class Type> void AxisAngle<Type>::setVector(const Vector3<Type> & inVec) { mData[0] = inVec.x; mData[1] = inVec.y; mData[2] = inVec.z; } /*! * \details Sets angle * \param [in] inAngleRad angle in radians */ template<class Type> void AxisAngle<Type>::setAngle(Type inAngleRad) { mData[3] = inAngleRad; } /*! * \details Gets angle. * \return angle in radians */ template<class Type> double AxisAngle<Type>::angle() const { return mData[3]; } template<class Type> const Vector3<Type> & AxisAngle<Type>::vector() const { return *reinterpret_cast<const Vector3<Type>*>(&mData); } template<class Type> Vector3<Type> & AxisAngle<Type>::vector() { return *reinterpret_cast<Vector3<Type>*>(&mData); } /**************************************************************************************************/ ///////////////////////////////////////////* Functions *//////////////////////////////////////////// /**************************************************************************************************/ /*! * \details Returns the number of revolutions represented by the angle. * \return */ template<class Type> int AxisAngle<Type>::numRevs() const { return static_cast<int>(angle() / (Type(2) * Type(3.14159265358979323846))); } /*! * \details Adds the number of revolution to num. * \param [in] inNum */ template<class Type> void AxisAngle<Type>::addRevs(int inNum) { mData[3] += static_cast<Type>(inNum) * (Type(2) * Type(3.14159265358979323846)); } /**************************************************************************************************/ ///////////////////////////////////////////* Functions *//////////////////////////////////////////// /**************************************************************************************************/ template<class Type> std::string AxisAngle<Type>::toString(const std::string & inFormat /*= "%setX %setY %setZ %ad"*/, uint8_t precision /*= 6*/) { std::stringstream out; out.precision(precision); bool val = false; for (size_t i = 0; i < inFormat.size(); ++i) { if (val) { switch (inFormat[i]) { case 'x': out << mData[0]; break; case 'y': out << mData[1]; break; case 'z': out << mData[2]; break; case 'a': { if (i == inFormat.size() - 1) { out << mData[3]; break; } if (inFormat[i + 1] == 'd') { out << sts::toDegrees(mData[3]); ++i; } else if (inFormat[i + 1] == 'r') { out << mData[3]; ++i; } else { out << mData[3]; } break; } } val = false; continue; } if (inFormat[i] == '%') { val = true; continue; } out << inFormat[i]; } return out.str(); } /**************************************************************************************************/ //////////////////////////////////////////////////////////////////////////////////////////////////// /**************************************************************************************************/
true
bc73e1f666acb595a01511ac25337fa22e5c66aa
C++
kdlqudrb/Exercise
/tutorial/그래프, 산수, 수학/braveduck.cpp
UTF-8
1,841
2.796875
3
[]
no_license
#include <stdio.h> int jump, ret; struct point{ int x; int y; int color = 0; }; point queue[200]; point nonvisit[200]; int qindexf, qindexl, nindexf, nindexl; bool is_jump(point brave, point m){ if ((brave.x - m.x)*(brave.x - m.x) + (brave.y - m.y)*(brave.y - m.y) <= jump * jump) return 1; else return 0; } void across(point last){ int i, j, temp; if (nindexf == nindexl) return; if (qindexf == qindexl) return; if (ret == 1) return; temp = qindexl; for (i = qindexf; i < qindexl; i++){ if (is_jump(queue[i], last)){ ret = 1; return; } } for (i = qindexf; i < qindexl; i++){ for (j = nindexf; j < nindexl; j++){ if (is_jump(queue[i], nonvisit[j]) && nonvisit[j].color == 0){ queue[qindexl] = nonvisit[j]; nonvisit[j].color = 1; qindexl++; } } } qindexf = temp; across(last); } void quecl(point que[]){ int i; for (i = 0; i < 200; i++){ que[i].x = 0; que[i].y = 0; que[i].color = 0; } } int main(){ int n, i, j, dol; point duck, start, last; point stone[100]; scanf("%d", &n); quecl(queue); for (i = 0; i < n; i++){ qindexf = qindexl = nindexf = nindexl = 0; scanf("%d", &jump); scanf("%d %d", &start.x, &start.y); scanf("%d %d", &last.x, &last.y); duck.x = start.x; duck.y = start.y; scanf("%d", &dol); for (j = 0; j < dol; j++){ scanf("%d %d", &stone[j].x, &stone[j].y); } if (is_jump(duck, last)) printf("YES\n"); else{ for (j = 0; j < dol; j++){ if (is_jump(duck, stone[j])){ queue[qindexl].x = stone[j].x; queue[qindexl].y = stone[j].y; stone[j].color = 1; qindexl++; } else{ nonvisit[nindexl].x = stone[j].x; nonvisit[nindexl].y = stone[j].y; nindexl++; } } across(last); if (ret == 1) printf("YES\n"); else printf("NO\n"); ret = 0; quecl(queue); quecl(nonvisit); } } }
true
25a22ecf378ced00fc5608e67e12d6d25894257c
C++
arifkhan1990/UVa-accepted-solutions
/Uva 11364.cpp
UTF-8
360
2.546875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; while(n--){ int ma = 0, mi = 100; int t,p; cin >> t; while(t--){ cin >> p; ma = max(ma,p); mi = min(mi,p); } cout << (ma * 2) - (mi * 2) << endl; } return 0; }
true
ac1080c689f7fd0d4e3a5c51d0f5aa4cd1e784b4
C++
tsopronyuk/RCpp_And_Boost_Library
/findIntersectionsPolygons.cpp
UTF-8
5,024
3.21875
3
[]
no_license
// // [[Rcpp::interfaces(r, cpp)]] // // [[Rcpp::plugins("cpp11")]] // #include <Rcpp.h> // #include <vector> // // put any other includes you need here. // // using namespace Rcpp; // //' intersectPolygons // //' // //' Takes a set of 5 convex polygons from R and returns the intersection of each pair. // //' // //' // //' @param listOfPolygons An R list with 3 to 5 convex polygons. Each polygon is one // //' element of the list and is stored as an R matrix. The x-coordinates for // //' the polygon are the first column, and the y-coordinates are the second // //' column. // //' // //' // //' @return intersections A List where each element is the intersection of two of // //' the provided polygons. For example: If there are 5 polygons the list will contain 10 elements. // //' Each element should be NumericalMatrix with x-coordinates as the first // //' column and y-coordinates as the second column. // //' // //' The elements of the list should be named based on the two polygons // //' that were intersected to find that particular element. For example // //' when listOfPolygons[[1]] and listOfPolygons[[2]] are intersected, // //' the resulting polygon should be stored in the list as "1_intersect_2". // //' // //' @export // //' // We can now use the BH package // [[Rcpp::depends(BH)]] #include <Rcpp.h> using namespace Rcpp; #include <boost/geometry.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/adapted/boost_tuple.hpp> BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian) typedef boost::tuple<double, double> point; typedef boost::geometry::model::polygon<point, true, true> polygon; namespace Rcpp { // `as` converter from R to Boost.Geometry's polygon type template <> polygon as(SEXP pointsMatrixSEXP) { // the coordinates are the rows of the (n x 2) matrix NumericMatrix pointsMatrix(pointsMatrixSEXP); polygon poly; for (int i = 0; i < pointsMatrix.nrow(); ++i) { double x = pointsMatrix(i,0); double y = pointsMatrix(i,1); point p(x,y); poly.outer().push_back(p); } return (poly); } // `wrap` converter from Boost.Geometry's polygon to an R(cpp) matrix // The Rcpp NumericMatrix can be converted to/from a SEXP template <> SEXP wrap(const polygon& poly) { const std::vector<point>& points = poly.outer(); NumericMatrix rmat(points.size(), 2); for(unsigned i = 0; i < points.size(); ++i) { const point& p = points[i]; rmat(i,0) = p.get<0>(); rmat(i,1) = p.get<1>(); } return Rcpp::wrap(rmat); } } // [[Rcpp::export]] NumericMatrix intersectionTwoPolygon(SEXP pointsMatrixSEXP1, SEXP pointsMatrixSEXP2){ // Conversion of pointsMatrix here to boost::geometry polygon polygon poly1 = as<polygon>(pointsMatrixSEXP1); polygon poly2 = as<polygon>(pointsMatrixSEXP2); std::deque<polygon> output; boost::geometry::intersection(poly1, poly2, output); // Convert output polygon into a NumericMatrixsomething that Rcpp can hand back to R return wrap(output[0]); } // [[Rcpp::export]] List findIntersections(List listOfPolygons){ // Here is where you write the code that uses boost::geometry::intersection() to // intersect all possible pairs of the provided polygons. // The intersection of a pair ( example: listOfPolygons[[1]] and listOfPolygons[[2]] ) // should be stored as a matrix, with the x-coorinates as the first column and the // y-coordinates as the second column (in the same way as the polygons that served as the inputs). // The matrix should be stored in a list for output purposes. Each matrix in the list should // be named according to the two polygons that were interesected to generate the matrix. For example // when listOfPolygons[[1]] and listOfPolygons[[2]] are intersected, // the resulting polygon should be stored in the list as "1_intersect_2". Or simply "1_2". List outListOfPolygons; for (unsigned i=0; i<listOfPolygons.size()-1; i++) { for (unsigned j=i+1; j<listOfPolygons.size(); j++) { // Conversion of pointsMatrix here to boost::geometry polygon polygon poly1 = as<polygon>(listOfPolygons[i]); polygon poly2 = as<polygon>(listOfPolygons[j]); //intersection of two polygons std::deque<polygon> output; boost::geometry::intersection(poly1, poly2, output); // create name of the polygon result std::string name; name = boost::lexical_cast<std::string>(i+1)+"_intersect_" +boost::lexical_cast<std::string>(j+1); // checking empty result if( output.size() <= 0) outListOfPolygons[name] = Rcpp::wrap(NumericMatrix()); else // Convert output polygon into a NumericMatrix outListOfPolygons[name] = wrap(output[0]); } } return outListOfPolygons; }
true
de1bf472953fec46f129aa6ce43af721d79ca029
C++
Naoki95957/CPPCS300
/graph_traversal/Stack.h
UTF-8
1,354
3.4375
3
[]
no_license
//============================================================================ // Name : StachADT.h // Author : Fatma C Serce // Version : 1.0 // Description : Stack Abstract Data Type //============================================================================ #ifndef STACK_ADT #define STACK_ADT template <class T> class StackADT{ //Function to add a new item to the stack //Precondition: Stack exists and is not full //Post Condition: Stack is changed and the new item //is added to the top of the stack virtual void push(const T&) = 0; //Function to remove the top element from the stack //Precondition: Stack exists and is not empty //Post Condition: Stack is changed and the top element is removed from the stack virtual void pop() = 0; //Function to return the top element from the stack //Precondition: Stack exists and is not empty //Post Condition: If the stack is empty, the program returns, otherwise, //the top element of the stack is returned virtual T top() = 0; //Function to determine whether the stack is empty //Post Condition: Returns 1 of the stack is empty //otherwise returns 0 virtual bool isEmpty() = 0; //Function to determine whether the stack is full //Post Condition: Returns 1 of the stack is full //otherwise returns 0 virtual bool isFull() = 0; }; #endif
true
4c04370c1d3e1470ab2ddd079e51c6409f5c96fd
C++
davi97zi/ProgettoPAO
/Interfacce/magicInterface.cpp
UTF-8
1,179
2.96875
3
[]
no_license
#include "magicInterface.h" //usato da increaselevel void MagicInterface::increaseMaxMana(unsigned int addVal){ maxMana = addVal; } unsigned int MagicInterface::getMaxMana() const {return maxMana;} unsigned int MagicInterface::getMana() const {return mana;} bool MagicInterface::isThrowable(unsigned int m) const{ //controlla se il mago ha il mana necessario per lanciare l'abilità if(mana < m) return false; return true; } //aggiorna il mana dopo il lancio di un'abilità void MagicInterface::setMana(unsigned int m){ mana -= m; } //per ripristinare il mana alla fine di uno scontro, anche se non è aumentato di livello void MagicInterface::resetMana(){ mana = maxMana; } unsigned int MagicInterface::getCostoA1() const {return costoManaAbilita1;} unsigned int MagicInterface::getCostoA2() const {return costoManaAbilita2;} unsigned int MagicInterface::getCostoA3() const {return costoManaAbilita3;} void MagicInterface::setCostoA1(unsigned int c) { costoManaAbilita1 = c; } void MagicInterface::setCostoA2(unsigned int c) { costoManaAbilita2 = c; } void MagicInterface::setCostoA3(unsigned int c) { costoManaAbilita3 = c; }
true
3c9e674e0844b7208399b842e6ee547566781383
C++
marco-park/problemSolving
/PROGRAMERS/여행경로.cpp
UTF-8
898
2.703125
3
[]
no_license
#include <string> #include <vector> #include <iostream> #include <map> using namespace std; map<pair<string,string>,int>visited; vector<string> answer; int ticketSize; bool foo(string now,map<string,vector<string>>&p){ if(answer.size() == ticketSize+1)return true; for(auto next:p[now]){ if(!visited[{now,next}])continue; visited[{now,next}]--; answer.push_back(next); if(foo(next,p))return true; visited[{now,next}]++; answer.pop_back(); } return false; } vector<string> solution(vector<vector<string>> tickets) { ticketSize = tickets.size(); map<string,vector<string>>p; for(auto x:tickets){ p[x[0]].push_back(x[1]); visited[{x[0],x[1]}]++; } for(auto x:p)sort(p[x.first].begin(),p[x.first].end()); string start = "ICN"; answer.push_back(start); foo(start,p); return answer; }
true
e5ff6ae8d41eef8c0bc18e8a2e28eccd1633e682
C++
Awaluda/Testing
/main.cpp
UTF-8
2,921
3.046875
3
[]
no_license
/*muhammad iqbal awaluda *20.if 02 * 20.11.3418 * gak selesai buk,mumet,masih nub:(,stelah ngikutin yg di jurnal,saya coba ngerjain fungsi malah gk selesai */ #include <iostream> using namespace std; int main() { string nama[100]; string mk[100]; int jmlmk; char nilaihuruf[100]; int nilai; int sks[100]; int jml; int jumlahnilai, jumlahsks; float nr[100]; cout << "Jumlah mahasiswa :"; cin >> jml; for (int i = 1; i <= jml; i++) { cout << "Nama Mahasiswa ke " << i + 0 << ':'; cin >> nama[i]; cout << "Jumlah matakuliah yang diambil :"; cin >> jmlmk; if (jmlmk < 2) { cout << "Jumlah matakuliah kurang dari 2\n"; return 0; } else { for (i = 0; i < jmlmk; i++) { cout << "matakuliah ke " << i + 1 << " \n"; cout << "Matakuliah yang diambil :"; cin >> mk[i]; cout << "Nilai :"; cin >> nilaihuruf[i]; cout << "Jumlah SKS :"; cin >> sks[i]; } if (nilaihuruf[i] == 'A') { nilai = 4 * sks[i]; } else if (nilaihuruf[i] == 'B') { nilai = 3 * sks[i]; } else if (nilaihuruf[i] == 'C') { nilai = 2 * sks[i]; } else if (nilaihuruf[i] == 'D') { nilai = 1 * sks[i]; } else if (nilaihuruf[i] == 'E') { nilai = 0 * sks[i]; } /*else { cout << "Input salah!\n"; return 0; jumlahnilai = jumlahnilai + nilai; jumlahsks = jumlahsks + sks[i]; } /*if (jumlahsks > 100) { cout << "Jumlah SKS semester lebih dari 100\n"; return 0; } else { jumlahsks = jumlahsks; nr[i] = jumlahnilai / jumlahsks; }*/ } cout << "Nama Mahasiswa ke " << i + 0 << ':'; cin >> nama[i]; cout << "Jumlah matakuliah yang diambil :"; cin >> jmlmk; if (jmlmk < 2) { cout << "Jumlah matakuliah kurang dari 2\n"; return 0; } else { for (i = 0; i < jmlmk; i++) { cout << "matakuliah ke " << i + 1 << " \n"; cout << "Matakuliah yang diambil :"; cin >> mk[i]; cout << "Nilai :"; cin >> nilaihuruf[i]; cout << "Jumlah SKS :"; cin >> sks[i]; } if (nilaihuruf[i] == 'A') { nilai = 4 * sks[i]; } else if (nilaihuruf[i] == 'B') { nilai = 3 * sks[i]; } else if (nilaihuruf[i] == 'C') { nilai = 2 * sks[i]; } else if (nilaihuruf[i] == 'D') { nilai = 1 * sks[i]; } else if (nilaihuruf[i] == 'E') { nilai = 0 * sks[i]; } /*else { cout << "Input salah!\n"; return 0; jumlahnilai = jumlahnilai + nilai; jumlahsks = jumlahsks + sks[i]; } /*if (jumlahsks > 100) { cout << "Jumlah SKS semester lebih dari 100\n"; return 0; } else { jumlahsks = jumlahsks; nr[i] = jumlahnilai / jumlahsks; }*/ } } for (int i = 0; i <= jml; i++) { cout << "tampilakan data :"<<endl; cout << "Nama :" << nama[i] << endl; for (int i = 1; i <= jmlmk; i++) { cout << "\nnilai matakuliah " << mk[i] << "adalah\n" << nilaihuruf[i]; } } system("pause"); return 0; }
true
93a8e5d64b71a844e6a581578c2d7da6ddbd4e88
C++
unionyy/samsung-algorithm-21
/bp-greedy-dp/basic-problems/room/main.cpp
UTF-8
912
2.96875
3
[]
no_license
#include<iostream> using namespace std; int main(int argc, char** argv) { int test_case; int T; freopen("input.txt", "r", stdin); cin>>T; int road[200]; for(test_case = 1; test_case <= T; ++test_case) { for(int i = 0; i < 200; i++) road[i] = 0; int N; cin >> N; for(int i = 0; i < N; i++) { int a, b; cin >> a >> b; a--; b--; a /= 2; b /= 2; int small, big; if(a > b) { small = b; big = a; } else { small = a; big = b; } for(int j = small; j <= big; j++) road[j]++; } int max = 0; for(int i = 0; i < 200; i++) { if(road[i] > max) max = road[i]; } cout << '#' << test_case << ' ' << max << endl; } return 0; }
true
0153f7af97d99409d9237f35b62f63078a94e9a1
C++
Kanto065/AIUB_CS
/Courses/Data Structures/Linked list/singly.cpp
UTF-8
4,441
4.0625
4
[]
no_license
//singly linked list #include<iostream> using namespace std; struct node{ int data; node *next; }; //node insert at end void insert(node *s, int data){ while(s->next != NULL){ s = s->next; } s->next = new node(); s->next->data = data; s->next->next = NULL; } //node insert at beginning void insertBeginning(node *s, int data){ node *temp = new node(); temp->data = data; temp->next = NULL; if(s->next != NULL){ temp->next = s->next; } s->next = temp; } //insert at n-th position int insertMiddle(node *s, int n, int data){ node *temp1 = new node(); temp1->data = data; temp1->next = NULL; if(n==1){ temp1->next = s; s = temp1; return 0; } node *temp2 = s; for(int i=0;i<n-1;i++){ temp2 = temp2->next; } temp1->next = temp2->next; temp2->next = temp1; } //node display function void display(node *s){ while(s->next != NULL){ cout<<s->next->data<<" "; s = s->next; } } //node search function void search(node *s, int data){ int count=0; while(s->next != NULL){ if(s->next->data == data){ count++; } s = s->next; } cout<<"Total result found: "<<count<<endl; } //node delete function int deleteNode(node *s, int data){ while(s->next != NULL){ if(s->next->data == data){ s->next = s->next->next; return 0; } s= s->next; } } //delete first node struct node *deleteBegining(node *s){ node *temp = new node(*s); s->next = s->next->next; free(temp); temp = NULL; return s; } //delete last node struct node *deleteEnd(node *s){ node *temp = new node(*s); node *temp2 = new node(*s); while(temp->next != NULL){ temp2 = temp; temp = temp->next; } temp2->next = NULL; free(temp); temp = NULL; return s; } //main function int main(){ node *head = new node(); head->next = NULL; int a, val; bool x = true; while(x){ cout<<" 1.Create list/add data "<<endl; cout<<" 2.Display list "<<endl; cout<<" 3.Search in list "<<endl; cout<<" 4.Delete node"<<endl; cout<<" 5.Exit"<<endl<<endl; cout<<" Enter your choice "<<endl; cin>>a; cout<<endl; switch(a){ case 1: cout<<" 1.enter data at end. "<<endl; cout<<" 2.enter data at beginning. "<<endl; cout<<" 3.enter data at after a specific node. "<<endl; cout<<" Enter your choice "<<endl; int b; cin>>b; switch(b){ case 1: cout<<" enter data: "; cin>>val; insert(head, val); cout<<endl; break; case 2: cout<<" enter data: "; cin>>val; insertBeginning(head, val); cout<<endl; break; case 3: int val2; cout<<" enter position: "; cin>>val2; cout<<" enter data: "; cin>>val; insertMiddle(head, val2, val); cout<<endl; break; } break; case 2: cout<<" listed data: "; display(head); cout<<endl<<endl; break; case 3: cout<<" enter which data to search: "; cin>>val; search(head,val); cout<<endl; break; case 4: cout<<" 1.delete data at beginning. "<<endl; cout<<" 2.delete data at end. "<<endl; cout<<" 3.enter data to delete. "<<endl; cout<<" Enter your choice "<<endl; int c; cin>>c; switch(c){ case 1: deleteBegining(head); break; case 2: deleteEnd(head); break; case 3: cout<<" enter data: "; cin>>val; deleteNode(head, val); break; } cout<<endl; break; case 5: cout<<"exiting.."; x = false; break; default: cout<<"wrong input. chose 1-5."<<endl; break; } } }
true
a2d83c03088b9562680721b0b01c259eaaceea6d
C++
samcragg/Autocrat
/tests/Bootstrap.Tests/tests/ReferenceScannerTests.cpp
UTF-8
5,028
3.265625
3
[ "MIT" ]
permissive
#include "managed_interop.h" #include <algorithm> #include <array> #include <unordered_map> #include <gtest/gtest.h> #include "ManagedObjects.h" struct ObjectCounter : autocrat::detail::reference_scanner { std::optional<void*> get_moved_location(void* object) override { auto it = moved_objects.find(object); if (it == moved_objects.end()) { return std::nullopt; } else { return it->second; } } void* get_reference(void* object, std::size_t offset) override { void* address_of_field = static_cast<std::byte*>(object) + offset; return *static_cast<void**>(address_of_field); } void* move_object(void* object, std::size_t size) override { allocated_bytes += size; references++; return object; } void set_moved_location(void* object, void* new_location) override { moved_objects[object] = new_location; } void set_reference(void*, std::size_t, void*) override { } std::size_t allocated_bytes = 0; std::size_t references = 0; std::unordered_map<void*, void*> moved_objects; }; struct ObjectMover : ObjectCounter { void* move_object(void* object, std::size_t size) override { EXPECT_LT(size, buffer.size() - allocated_bytes); std::byte* new_object = buffer.data() + allocated_bytes; std::copy_n(static_cast<std::byte*>(object), size, new_object); allocated_bytes += size; return new_object; } void set_reference(void* object, std::size_t offset, void* reference) override { if (reference != nullptr) { auto data = static_cast<std::byte*>(object); EXPECT_GE(data, buffer.data()); EXPECT_LT(data + offset + sizeof(void*), buffer.data() + buffer.size()); std::copy_n(reinterpret_cast<std::byte*>(&reference), sizeof(void*), data + offset); } } std::array<std::byte, 1024u> buffer = {}; }; class ReferenceScannerTests : public testing::Test { protected: }; TEST_F(ReferenceScannerTests, MoveShouldHandleNullObjects) { ObjectCounter counter; counter.move(static_cast<void*>(nullptr)); EXPECT_EQ(0u, counter.allocated_bytes); EXPECT_EQ(0u, counter.references); } TEST_F(ReferenceScannerTests, ShouldMoveTheReferencesAndData) { ManagedObject<SingleReference> element; ManagedObject<ReferenceArray<3u>> array; array->references[0] = element.get(); array->references[2] = element.get(); ManagedObject<DerivedClass> original; original->BaseInteger = 123; original->Integer = 456; original->SecondReference = array.get(); ObjectMover mover; mover.move(original.get()); // Clear the originals to prove the copy is independent array = {}; element = {}; original = {}; auto copy = reinterpret_cast<DerivedClass*>(mover.buffer.data()); EXPECT_EQ(copy->BaseInteger, 123); EXPECT_EQ(copy->Integer, 456); auto array_copy = static_cast<ReferenceArray<3u>*>(copy->SecondReference); EXPECT_EQ(array_copy->references[0], array_copy->references[2]); EXPECT_GE(array_copy->references[0], mover.buffer.data()); EXPECT_LT(array_copy->references[0], mover.buffer.data() + mover.allocated_bytes); EXPECT_EQ(nullptr, array_copy->references[1]); } TEST_F(ReferenceScannerTests, ShouldScanEmptyObjects) { ManagedObject<Object> value; ObjectCounter counter; counter.move(value.get()); EXPECT_EQ(24u, counter.allocated_bytes); EXPECT_EQ(1u, counter.references); } TEST_F(ReferenceScannerTests, ShouldScanCircularReferences) { ManagedObject<SingleReference> object; object->Reference = object.get(); ObjectCounter counter; counter.move(object.get()); EXPECT_EQ(24u, counter.allocated_bytes); EXPECT_EQ(1u, counter.references); } TEST_F(ReferenceScannerTests, ShouldScanReferenceArrays) { ManagedObject<SingleReference> element; ManagedObject<ReferenceArray<5u>> array; array->references[2] = element.get(); ManagedObject<SingleReference> object; object->Reference = array.get(); ObjectCounter counter; counter.move(object.get()); EXPECT_EQ(24u + 24u + 40u + 24u, counter.allocated_bytes); EXPECT_EQ(3u, counter.references); } TEST_F(ReferenceScannerTests, ShouldScanInheritedReferences) { ManagedObject<Object> empty; ManagedObject<DerivedClass> derived; derived->BaseReference = empty.get(); ObjectCounter counter; counter.move(derived.get()); EXPECT_EQ(48u + 24u, counter.allocated_bytes); EXPECT_EQ(2u, counter.references); } TEST_F(ReferenceScannerTests, ShouldScanTypesWithValueArrays) { ManagedObject<Int32Array<3u>> array; ManagedObject<SingleReference> object; object->Reference = array.get(); ObjectCounter counter; counter.move(object.get()); EXPECT_EQ(24u + 24u + 12u, counter.allocated_bytes); EXPECT_EQ(2u, counter.references); }
true
0ee07037147c23ce990e5010c7030427e1cbf7a5
C++
nyccowgirl/Starting-Out
/C10/C10_10/C10_10.cpp
UTF-8
532
3.25
3
[]
no_license
/* Program illustrates C-strings. C10_10.cpp Starting Out/C10 Created by nyccowgirl on 10/6/20. Copyright © 2020 nyccowgirl. All rights reserved. */ #include <iostream> #include <cstring> using namespace std; int main(int argc, const char * argv[]) { char place[] = "The Windy City"; if (strstr(place, "Windy") == nullptr) { cout << "Windy not found." << endl; } else { cout << "Windy found." << endl; } return 0; } /* Windy found. Program ended with exit code: 0 */
true
d37ac18a462f5be05b6834c0fc9876925418d47d
C++
gvaxx/CPP
/04/ex03/Character.cpp
UTF-8
1,714
3.171875
3
[]
no_license
#include "Character.hpp" Character::Character(std::string const &name): _name(name), _count(0) { for (int i = 0; i < 4; i++) this->_materia[i] = NULL; } Character::Character(Character const &src): _name(src._name), _count(0) { for (int i = 0; i < src._count; i++) if(src._materia[i]) this->equip(src._materia[i]->clone()); for (int i = this->_count; i < 4; i++) this->_materia[i] = NULL; } Character::~Character() { this->_deleteMateria(); } Character &Character::operator=(Character const &rhs) { this->_name = rhs._name; this->_deleteMateria(); this->_count = 0; for (int i = 0; i < rhs._count; i++) this->equip(rhs._materia[i]->clone()); for (int i = this->_count; i < 4; i++) this->_materia[i] = NULL; return (*this); } std::string const &Character::getName(void) const { return (this->_name); } void Character::equip(AMateria *m) { if (this->_count == 4 || !m) return ; for (int i = 0; i < this->_count; i++) if (this->_materia[i] == m) return ; this->_materia[this->_count] = m; this->_count += 1; } void Character::unequip(int idx) { if (idx < 0 || idx >= this->_count || !this->_materia[idx]) return ; if(idx == this->_count - 1) this->_materia[idx] = NULL; else for (int i = idx; i < this->_count - 1; i++) { this->_materia[i] = this->_materia[i + 1]; this->_materia[i + 1] = NULL; } this->_count--; } void Character::use(int idx, ICharacter &target) { if (idx < 0 || idx >= this->_count || !this->_materia[idx]) return ; this->_materia[idx]->use(target); } void Character::_deleteMateria() { for (int i = 0; i < this->_count; i++) delete this->_materia[i]; }
true
3f6a731a7d87f1f7a107ed07e37b9982fd338e56
C++
shinyawhy/Graphical-SoC-Performance
/graphic/graphicarea.cpp
UTF-8
1,769
2.71875
3
[]
no_license
/* * @Author: MRXY001 * @Date: 2019-11-29 14:46:24 * @LastEditors: MRXY001 * @LastEditTime: 2019-11-29 18:04:20 * @Description: 添加图形元素并且连接的区域 * 即实现电路图的绘图/运行区域 */ #include "graphicarea.h" GraphicArea::GraphicArea(QWidget *parent) : QWidget(parent) { setAcceptDrops(true); } /** * 添加一个形状 * 注意:添加这一类型的形状,而不是添加这一个形状 * @param type 形状类型 * @param point 左上角坐标 */ void GraphicArea::insertShapeByType(ShapeBase* type, QPoint point) { log("insertShapeByType"); ShapeBase *shape = type->newInstanceBySelf(this); shape_lists.append(shape); if (point == QPoint(-1, -1)) point = mapFromGlobal(QCursor::pos()); shape->move(point); shape->show(); } /** * 图形拖拽进来的事件,只支持本程序的图形 * 只判断,不进行其他操作 */ void GraphicArea::dragEnterEvent(QDragEnterEvent *event) { const QMimeData* mime = event->mimeData(); QByteArray ba = mime->data(CHOOSED_SHAPE_MIME_TYPE); if (ba.size() > 0) // 表示有形状(其实是int类型的),允许拖拽 { event->accept(); } return QWidget::dragEnterEvent(event); } /** * 拖放形状事件 */ void GraphicArea::dropEvent(QDropEvent *event) { const QMimeData* mime = event->mimeData(); QByteArray ba = mime->data(CHOOSED_SHAPE_MIME_TYPE); if (ba.size() > 0) // 表示有形状(其实是int类型的) { int value = ByteArrayUtil::bytesToInt(ba); ShapeBase* shape = (ShapeBase*) value; log("拖放:"+shape->getName()); insertShapeByType(shape); event->accept(); } return QWidget::dropEvent(event); }
true
216b34af9256a749228c707ba40fdd3cf4b73796
C++
visit-dav/visit
/src/visit_vtk/full/vtkAccessors.h
UTF-8
10,290
2.5625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. #ifndef VTK_ACCESSORS_H #define VTK_ACCESSORS_H #include <vtkType.h> #include <vtkPoints.h> #include <vtkDataArray.h> // // Functors that let us retrieve points quickly. // // **************************************************************************** // Class: vtkPointAccessor // // Purpose: // This class gets the i'th point from a vtkPoints object. // // Notes: Use faster direct array accesses // // Programmer: Brad Whitlock // Creation: Mon Mar 12 16:17:58 PDT 2012 // // Modifications: // // **************************************************************************** template <typename T> class vtkPointAccessor { public: vtkPointAccessor(vtkPoints *p) : pts((const T *)p->GetVoidPointer(0)) { }; inline void GetPoint(vtkIdType id, double pt[3]) const { const T *ptr = pts + 3 * id; pt[0] = double(ptr[0]); pt[1] = double(ptr[1]); pt[2] = double(ptr[2]); } private: const T *pts; }; // **************************************************************************** // Class: vtkGeneralPointAccessor // // Purpose: // This class gets the i'th point from a vtkPoints object. // // Notes: Use slower GetPoint method. // // Programmer: Brad Whitlock // Creation: Mon Mar 12 16:17:58 PDT 2012 // // Modifications: // // **************************************************************************** class vtkGeneralPointAccessor { public: vtkGeneralPointAccessor(vtkPoints *p) : pts(p) { }; inline void GetPoint(vtkIdType id, double pt[3]) const { return pts->GetPoint(id, pt); } private: vtkPoints *pts; }; // **************************************************************************** // Class: vtkRectPointAccessor // // Purpose: // Access 3 different vtkDataArrays using 1 rectilinear cell index to make // the final point. // // Notes: Uses faster direct array access. // // Programmer: Brad Whitlock // Creation: Mon Mar 12 16:10:26 PDT 2012 // // Modifications: // // **************************************************************************** template <typename T> class vtkRectPointAccessor { public: vtkRectPointAccessor(const int *d, vtkDataArray *Xc, vtkDataArray *Yc, vtkDataArray *Zc) { dims[0] = d[0]; dims[1] = d[1]; dims[2] = d[2]; X = (const T *)Xc->GetVoidPointer(0); Y = (const T *)Yc->GetVoidPointer(0); Z = (const T *)Zc->GetVoidPointer(0); dims01 = dims[0] * dims[1]; } inline void GetPoint(vtkIdType index, double pt[3]) const { vtkIdType cellI = index % dims[0]; vtkIdType cellJ = (index/dims[0]) % dims[1]; vtkIdType cellK = index/dims01; pt[0] = X[cellI]; pt[1] = Y[cellJ]; pt[2] = Z[cellK]; } inline void GetPoint(vtkIdType cellI, vtkIdType cellJ, vtkIdType cellK, double pt[3]) const { pt[0] = X[cellI]; pt[1] = Y[cellJ]; pt[2] = Z[cellK]; } private: vtkIdType dims[3], dims01; const T *X, *Y, *Z; }; // **************************************************************************** // Class: vtkGeneralRectPointAccessor // // Purpose: // Access 3 different vtkDataArrays using 1 rectilinear cell index to make // the final point. // // Notes: Uses slower GetTuple methods. // // Programmer: Brad Whitlock // Creation: Mon Mar 12 16:10:26 PDT 2012 // // Modifications: // // **************************************************************************** class vtkGeneralRectPointAccessor { public: vtkGeneralRectPointAccessor(const int *d, vtkDataArray *Xc, vtkDataArray *Yc, vtkDataArray *Zc) { dims[0] = d[0]; dims[1] = d[1]; dims[2] = d[2]; X = Xc; Y = Yc; Z = Zc; dims01 = dims[0] * dims[1]; } inline void GetPoint(vtkIdType index, double pt[3]) const { vtkIdType cellI = index % dims[0]; vtkIdType cellJ = (index/dims[0]) % dims[1]; vtkIdType cellK = index/dims01; pt[0] = X->GetTuple1(cellI); pt[1] = Y->GetTuple1(cellJ); pt[2] = Z->GetTuple1(cellK); } inline void GetPoint(vtkIdType cellI, vtkIdType cellJ, vtkIdType cellK, double pt[3]) const { pt[0] = X->GetTuple1(cellI); pt[1] = Y->GetTuple1(cellJ); pt[2] = Z->GetTuple1(cellK); } private: vtkIdType dims[3], dims01; vtkDataArray *X, *Y, *Z; }; // **************************************************************************** // Class: vtkAccessor // // Purpose: // Access vtkDataArray using direct memory accesses. // // Notes: We could always add a generic GetTuple to deal with multi- // component arrays. I just didn't need it yet. // // Programmer: Brad Whitlock // Creation: Thu Mar 29 13:10:20 PDT 2012 // // Modifications: // // **************************************************************************** template <typename T> class vtkAccessor { public: vtkAccessor(T *da, bool ownIt = false) : arr(da), own(ownIt) { } vtkAccessor(vtkDataArray *da) : arr((T *)da->GetVoidPointer(0)), own(false) { } ~vtkAccessor() { if(own && arr != NULL) delete [] arr; } inline T GetTuple1(vtkIdType id) const { return arr[id]; } inline void SetTuple1(vtkIdType id, T val) { arr[id] = val; } private: T *arr; bool own; }; // **************************************************************************** // Class: vtkDirectAccessor // // Purpose: // Access vtkDataArray using direct memory accesses. // // *Copied from avtDirectAccessor * // // Programmer: Kathleen Biagas // Creation: September 4, 2012 // // Modifications: // // **************************************************************************** template <typename T> class vtkDirectAccessor { public: vtkDirectAccessor(vtkDataArray *da) : arr(da) { N = arr->GetNumberOfComponents(); ptr = start = (T *)arr->GetVoidPointer(0); end = ptr + (N * arr->GetNumberOfTuples()); } ~vtkDirectAccessor() { } int GetNumberOfTuples() const { return arr->GetNumberOfTuples(); } int GetNumberOfComponents() const { return N; } void SetTuple1(T val) { *ptr = val; } void SetTuple1(vtkIdType i, T val) { start[i*N] = val; } void SetTuple(vtkIdType i, const T *val) { memcpy(start + i*N, val, sizeof(T)*N); } void SetTuple(const T *val) { memcpy(ptr, val, sizeof(T)*N); } T GetTuple1() const { return *ptr; } T GetTuple1(vtkIdType i) const { return start[i*N]; } T *GetTuple(vtkIdType i) const { return start + i*N; } T *GetTuple() const { return ptr; } void SetComponent(vtkIdType tuple, int comp, T val) { start[tuple * N + comp] = val; } void SetComponent(int comp, T val) { ptr[comp] = val; } T GetComponent(vtkIdType tuple, int comp) const { return start[tuple * N + comp]; } T GetComponent(int comp) const { return ptr[comp]; } void InitTraversal() { ptr = start; } bool Iterating() const { return ptr < end; } void operator ++() { ptr += N; } void operator ++(int i) { ptr += N; } private: vtkDataArray *arr; T *start; T *ptr; T *end; int N; }; // **************************************************************************** // Class: vtkGeneralAccessor // // Purpose: // Access vtkDataArray via GetTuple1 calls. // // Notes: Use regular GetTuple methods to access data. // // Programmer: Brad Whitlock // Creation: Thu Mar 29 13:11:41 PDT 2012 // // Modifications: // Kathleen Biagas, Thu Sep 6 11:16:12 MST 2012 // Added more methods (from avtTupleAccessor). // // **************************************************************************** class vtkGeneralAccessor { public: vtkGeneralAccessor(vtkDataArray *da) : arr(da) { index = 0; size = arr->GetNumberOfTuples(); } ~vtkGeneralAccessor() { } int GetNumberOfTuples() const { return arr->GetNumberOfTuples(); } int GetNumberOfComponents() const { return arr->GetNumberOfComponents(); } void SetTuple1(double val) { arr->SetTuple1(index, val); } void SetTuple1(vtkIdType i, double val) { arr->SetTuple1(i, val); } void SetTuple(vtkIdType i, const double *val) { arr->SetTuple(i, val); } void SetTuple(const double *val) { arr->SetTuple(index, val); } double GetTuple1() { return arr->GetTuple1(index); } double GetTuple1(vtkIdType i) { return arr->GetTuple1(i); } double *GetTuple(vtkIdType i) { return arr->GetTuple(i); } double *GetTuple() { return arr->GetTuple(index); } void SetComponent(vtkIdType tuple, int comp, double val) { arr->SetComponent(tuple, comp, val); } void SetComponent(int comp, double val) { arr->SetComponent(index, comp, val); } double GetComponent(vtkIdType tuple, int comp) const { return arr->GetComponent(tuple, comp); } double GetComponent(int comp) const { return arr->GetComponent(index, comp); } void InitTraversal() { index = 0; } bool Iterating() const { return index < size; } void operator ++() { index ++; } void operator ++(int) { index ++; } private: vtkDataArray *arr; vtkIdType index; vtkIdType size; }; #endif
true
54a4979c2aa00f240dded51d4411e04bcb7d3f4a
C++
severinglion/School-Projects
/GameProgrammingA1/src/Utilities/EngineMath.cpp
UTF-8
190
2.59375
3
[]
no_license
#include "EngineMath.h" double distance2d(int x1, int y1, int x2, int y2) { int diffx = x2 - x1; int diffy = y2 - y1; return sqrt((double) (diffx * diffx) + (diffy * diffy)); }
true
b4003e749309baad947f9653ee91dd99b6d6684b
C++
ash-maheriya/mlp-multiclass
/apps/train_model_main.cc
UTF-8
1,148
2.53125
3
[]
no_license
#include <iostream> #include <ostream> #include "core/network.h" using neural_net::Network; int main(int argc, char** argv) { Network network(28); std::string img_dir = "/home/ash/UIUC/CS126/Cinder/my_projects/final-project-ash-maheriya/mnist/train/img/"; std::string lbl_dir = "/home/ash/UIUC/CS126/Cinder/my_projects/final-project-ash-maheriya/mnist/train/lbl/"; std::string test_img_dir = "/home/ash/UIUC/CS126/Cinder/my_projects/final-project-ash-maheriya/mnist/test/img/"; std::string test_lbl_dir = "/home/ash/UIUC/CS126/Cinder/my_projects/final-project-ash-maheriya/mnist/test/lbl/"; std::cout << "Beginning to load data" << std::endl; network.LoadTrainingData(img_dir, lbl_dir); network.LoadTestingData(test_img_dir, test_lbl_dir); std::cout << "Finished loading, beginning training" << std::endl; network.Train(); std::string load_file = "/home/ash/UIUC/CS126/Cinder/my_projects/final-project-ash-maheriya/include/core/model.bin"; //network.LoadNetwork(load_file); std::cout << "Finished training!" << std::endl; network.ValidateNetwork(); std::cout << "Finished validating!" << std::endl; return 0; }
true
ce1410063c149e62c748f9dfea053be99a6c5a30
C++
gs0622/leetcode
/missingNumbers.2.cc
UTF-8
477
3.390625
3
[]
no_license
/*https://leetcode.com/problems/missing-number/description/*/ #include <bits/stdc++.h> using namespace std; class Solution { public: int missingNumber(vector<int>& nums) { int sum1 = accumulate(nums.begin(), nums.end(), 0); int sum2 = (nums.size()+0)*(nums.size()+1)/2; return sum2-sum1; } }; int main(){ Solution s; vector<int> nums1{3,0,1}; cout << s.missingNumber(nums1) << endl; vector<int> nums2{9,6,4,2,3,5,7,0,1}; cout << s.missingNumber(nums2) << endl; }
true
22ddd339fac2a6b63793a678156f64699f665a16
C++
yusufRahmatullah/apaan
/m3dmap.cpp
UTF-8
3,993
2.703125
3
[]
no_license
#include "FrameBuffer.h" #include "Polygon.h" #include "header.h" #include "Keyboard.h" Polygon vsumatra, vjawa, vkalimantan, vsulawesi, vpapua; Polygon vsumatra2, vjawa2, vkalimantan2, vsulawesi2, vpapua2; void handleInput(){ if(Keyboard::isKeyPressed()){ int move = 20; if(Keyboard::getKeyCode() == 'w'){ vsumatra.moveMe(0,move); vsumatra2.moveMe(0,move); vjawa.moveMe(0,move); vjawa2.moveMe(0,move); vkalimantan.moveMe(0,move); vkalimantan2.moveMe(0,move); vsulawesi.moveMe(0,move); vsulawesi2.moveMe(0,move); vpapua.moveMe(0,move); vpapua2.moveMe(0,move); }else if(Keyboard::getKeyCode() == 'a'){ vsumatra.moveMe(move,0); vsumatra2.moveMe(move,0); vjawa.moveMe(move,0); vjawa2.moveMe(move,0); vkalimantan.moveMe(move,0); vkalimantan2.moveMe(move,0); vsulawesi.moveMe(move,0); vsulawesi2.moveMe(move,0); vpapua.moveMe(move,0); vpapua2.moveMe(move,0); }else if(Keyboard::getKeyCode() == 's'){ vsumatra.moveMe(0,-move); vsumatra2.moveMe(0,-move); vjawa.moveMe(0,-move); vjawa2.moveMe(0,-move); vkalimantan.moveMe(0,-move); vkalimantan2.moveMe(0,-move); vsulawesi.moveMe(0,-move); vsulawesi2.moveMe(0,-move); vpapua.moveMe(0,-move); vpapua2.moveMe(0,-move); }else if(Keyboard::getKeyCode() == 'd'){ vsumatra.moveMe(-move,0); vsumatra2.moveMe(-move,0); vjawa.moveMe(-move,0); vjawa2.moveMe(-move,0); vkalimantan.moveMe(-move,0); vkalimantan2.moveMe(-move,0); vsulawesi.moveMe(-move,0); vsulawesi2.moveMe(-move,0); vpapua.moveMe(-move,0); vpapua2.moveMe(-move,0); }else if(Keyboard::getKeyCode() == 'p' || Keyboard::getKeyCode() == 27){ exit(0); } } } void loadMap(string mapname, Polygon &poly, double scale) { FILE * filemap = fopen(mapname.c_str(), "r"); int x,y; vector<Point> v; while(fscanf(filemap, "%d %d", &x, &y) != EOF) { Point p(x*scale,y*scale); v.push_back(p); } poly.setVertex(v); fclose(filemap); } int main(){ double scale = 0.5; FrameBuffer fb; loadMap("sumatra.txt", vsumatra, scale); loadMap("jawa.txt", vjawa, scale); loadMap("kalimantan.txt", vkalimantan, scale); loadMap("sulawesi.txt", vsulawesi, scale); loadMap("papua.txt", vpapua, scale); loadMap("sumatra.txt", vsumatra2, scale); loadMap("jawa.txt", vjawa2, scale); loadMap("kalimantan.txt", vkalimantan2, scale); loadMap("sulawesi.txt", vsulawesi2, scale); loadMap("papua.txt", vpapua2, scale); int moveY = 20; vsumatra2.moveMe(0,moveY); vjawa2.moveMe(0,moveY); vkalimantan2.moveMe(0,moveY); vsulawesi2.moveMe(0,moveY); vpapua2.moveMe(0,moveY); Keyboard::initKeyboard(); while(true){ handleInput(); fb.initScreen(); fb.drawPolygon(vsumatra, 0xFF00); fb.drawPolygon(vjawa, 0xFF00); fb.drawPolygon(vkalimantan, 0xFF00); fb.drawPolygon(vsulawesi, 0xFF00); fb.drawPolygon(vpapua, 0xFF00); fb.drawPolygon(vsumatra2, 0xFF); fb.drawPolygon(vjawa2, 0xFF); fb.drawPolygon(vkalimantan2, 0xFF); fb.drawPolygon(vsulawesi2, 0xFF); fb.drawPolygon(vpapua2, 0xFF); vector<Point> temp, temp1; temp.clear(); temp = vsumatra2.getVertex(); temp1 = vsumatra.getVertex(); for(int i=0; i<temp.size(); i++){ fb.drawLine(temp[i], temp1[i], 0xFF0000); } temp.clear(); temp1.clear(); temp = vjawa2.getVertex(); temp1 = vjawa.getVertex(); for(int i=0; i<temp.size(); i++){ fb.drawLine(temp[i], temp1[i], 0xFF0000); } temp.clear(); temp1.clear(); temp = vkalimantan2.getVertex(); temp1 = vkalimantan.getVertex(); for(int i=0; i<temp.size(); i++){ fb.drawLine(temp[i], temp1[i], 0xFF0000); } temp.clear(); temp1.clear(); temp = vsulawesi2.getVertex(); temp1 = vsulawesi.getVertex(); for(int i=0; i<temp.size(); i++){ fb.drawLine(temp[i], temp1[i], 0xFF0000); } temp.clear(); temp1.clear(); temp = vpapua2.getVertex(); temp1 = vpapua.getVertex(); for(int i=0; i<temp.size(); i++){ fb.drawLine(temp[i], temp1[i], 0xFF0000); } fb.drawScreen(); } return 0; }
true
8e16213c0e1dc7a4b9381542b7ea18653c2d3f4f
C++
jyk2244/project1
/project1/resource.cpp
UTF-8
1,260
2.953125
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <cstdlib> //#include <boost/lexical_cast.hpp> #include "resource.h" #include "member.h" using namespace std; resource::resource(){ } resource::resource(string t, string n){ name = n; type = t; ret = 1; } string resource::show_name(){ return name; } int resource:: exist(){ return ret; } int resource:: exe(string name, int num, string type, string date){ if(ret == 0) cout<< "Other memver already borrowed this book. This book will be returned at"<< ret_date<< endl; else{ cout<<"Success"<<endl; who = num; ret = 0; } } void resource:: set(string t, string n){ type = t; name = n; } void resource:: set_borrow(string a, string b){ int d1, d2, d3; string s1, s2, s3; s1 = a.substr(0,2); s2 = a.substr(3,2); s3 = a.substr(6,2); d1 = atoi(s1.c_str()); d2 = atoi(s2.c_str()); d3 = atoi(s3.c_str()); //cout<< d1<<endl; d3+= 13; if(d3>30){ d2++; d3-=30; } if(d2>12){ d1++; d2-=12; } int result = d3+d2*100+d1*10000; s1 = to_string(d1); s2 = to_string(d2); s3 = to_string(d3); ret_date = to_string(result); ret_date.insert(4,"/"); ret_date.insert(2,"/"); who = b; } book::book(){ } book::book(string n, string t):resource(n,t){ }
true
8993ba3c63b39163c16bfa458ae64e0a1f2f2740
C++
CristianERAU/PSP
/component.hpp
UTF-8
1,824
2.78125
3
[]
no_license
/////////////////////////////// // CS225 Spring 2016 ////////// // Cristian Garcia //////////// /////////////////////////////// /////////////////////////////// #ifndef PA3COMPONENT_HPP_ #define PA3COMPONENT_HPP_ // Include Directives ///////// #include <iostream> #include <string> using std::ostream; // Decleration Section: ////////////////////////////////////////////////////////////// class Component { private: // Data Hiding ////////////////////////////////////////////////////////////////// static int num_alive; std::string name; /////std::string ip_address; /////int num_nodes; double power_rating; double price; //struct SizeInInches //{ // float height; // float width; // float depth; //} dimensions; public: // Constructor ////////////////////////////////////////////////////////////////// Component(); ///////////////////////////////////////////////////////////////////////////////// Component(std::string, double, double); // Destructor /////////////////////////////////////////////////////////////////// ~Component(); // Mutators //////////////////////////////////////////// int set_name(std::string); double set_power_rating(double); double set_price(double); int set_blank(); // Accessors /////////////////////////////////////////// static int get_num_alive(); std::string get_name()const{return name;} double get_power_rating()const{return power_rating;} double get_price()const{return price;} // Helpers ////////////////////////////////////////////////////////////////////// int isempty()const; //int display_mem_usage(); int toCout(); friend ostream& operator<< (ostream &output, const Component& Cp); }; #endif
true
125ab9d5e3feb529d7d9cfc60c75315d1880bf40
C++
jye210/OSS-1
/99dan.cpp
UTF-8
246
2.96875
3
[]
no_license
#include <iostream> using namespace std; int main() { int dan; for(int dan = 2; dan < 10; dan++) for (int i = 1; i < 10; i++) { cout << dan << " * " << i << " = " << dan * i << endl; } return 0; }
true
73af4a69ffec0ceaf4ef3a1b5e8d8d5ad0c1a00c
C++
ssw1991/FE-Applications
/FELibraries/Roots/NewtonMethodMod.cpp
UTF-8
930
3.4375
3
[]
no_license
/* Author Shilo Wilson Implementation of Newtons Method without directly passing derivative */ #include <functional> #include "NewtonMod.hpp" NewtonMethodMod::NewtonMethodMod(std::function<double(double)> &f, double tol) : m_function(f), m_tol(tol) {}; NewtonMethodMod::NewtonMethodMod(const NewtonMethodMod &p): m_function(p.m_function), m_tol(p.m_tol) { }; NewtonMethodMod::~NewtonMethodMod() {}; NewtonMethodMod &NewtonMethodMod::operator = (const NewtonMethodMod &p) { if (this != &p) { m_function = p.m_function; m_tol = p.m_tol; } return *this; } double NewtonMethodMod::operator ()(double initval) { double x1 = initval; do { initval = x1; double d = derivative(initval); double y = m_function(initval); x1 = initval - y / d; } while (std::abs(initval - x1) > m_tol); return x1; } double NewtonMethodMod::derivative(double val) { return (m_function(val + .0001) - m_function(val)) / .0001; }
true
d26615f784ac1222fefadec1df214118a64c9a87
C++
familymrfan/fanfei
/dp/Mediator/mediator.cpp
UTF-8
1,645
3.375
3
[]
no_license
#include "stdio.h" class Colleage; class Mediator { public: virtual void Send(char* msg, Colleage* colleage) = 0; }; class Colleage { public: Colleage(Mediator* mediator):mediator_(mediator) { } virtual void Send(char* msg) = 0; protected: Mediator* mediator_; }; class ConcreteColleageA : public Colleage { public: ConcreteColleageA(Mediator* mediator):Colleage(mediator) { } void Send(char* msg) { mediator_->Send(msg, this); } void Get(char* msg) { printf("A Get Msg:%s\n", msg); } }; class ConcreteColleageB : public Colleage { public: ConcreteColleageB(Mediator* mediator):Colleage(mediator) { } void Send(char* msg) { mediator_->Send(msg, this); } void Get(char* msg) { printf("B Get Msg:%s\n", msg); } }; class ConcretMediator : public Mediator { public: void SetConcreteColleageA(ConcreteColleageA* colleagea) { colleagea_ = colleagea; } void SetConcreteColleageB(ConcreteColleageB* colleageb) { colleageb_ = colleageb; } void Send(char* msg, Colleage* colleage) { if(reinterpret_cast<Colleage*>(colleagea_) == colleage) { colleageb_->Get(msg); } else { colleagea_->Get(msg); } } private: ConcreteColleageA* colleagea_; ConcreteColleageB* colleageb_; }; int main() { ConcretMediator mediator; ConcreteColleageA a(&mediator); ConcreteColleageB b(&mediator); mediator.SetConcreteColleageA(&a); mediator.SetConcreteColleageB(&b); a.Send("123"); b.Send("456"); return 0; }
true
e12e46879c0cb1fdf4bb482ce7e714fb23ad70eb
C++
PhamKhoa96/DataStructure_Algorithm
/OOP/C-Tutorial-master/Bai11.cpp
UTF-8
759
3.84375
4
[]
no_license
/* Cấu trúc rẽ nhánh trong C++ if(điều kiện){ // Nội dung thực hiện nếu đk đúng } else { // Nội dung thực hiện nếu điều kiện sai } Sinh viên A có điểm trung bình môn là t, điểm để qua môn đó là 4.0 Viết chương trình kiểm tra xem anh A có qua môn hay không. */ #include <iostream> using namespace std; #define PASS 4.0 #define GOOD 8.0 #define MEDIUM 6.5 int main() { float t = 5.5f; if (t >= GOOD) { cout << "A is Good student!" << endl; } else if(t >= MEDIUM && t < GOOD ) { cout << "A is a medium student!" << endl; } else if(t >= PASS && t < MEDIUM) { cout << "A passed this subject!" << endl; } else { cout << "A failed this subject!" << endl; } return 0; }
true
f624cd64d644fa73f86c026b1be28ed40356f448
C++
evenleo/leo
/test/HttpServer_test.cpp
UTF-8
845
2.53125
3
[ "MIT" ]
permissive
#include "http/HttpConnection.h" #include "TcpServer.h" #include "Scheduler.h" #include "Log.h" #include <stdio.h> using namespace leo; using namespace leo::http; int main() { Singleton<Logger>::getInstance()->addAppender("console", LogAppender::ptr(new ConsoleAppender())); Scheduler scheduler; scheduler.startAsync(); IpAddress addr(80); TcpServer server(addr, &scheduler); server.setConnectionHandler([](TcpConnection::ptr conn) { HttpConnection::ptr http_conn = std::make_shared<HttpConnection>(conn); HttpRequest::ptr request = http_conn->recvRequest(); HttpResponse::ptr rsp = std::make_shared<HttpResponse>(); rsp->setHttpStatus(HttpStatus::OK); rsp->setHeader("Content-Length", "5"); rsp->setContent("hello"); http_conn->sendResponse(rsp); }); server.start(); getchar(); return 0; }
true
e2241d1ed3b86e6dda2577cb0ead34931aff376b
C++
zouxiaoliang/redox
/src/cluster.cpp
UTF-8
12,492
2.546875
3
[ "Apache-2.0" ]
permissive
#include "cluster.hpp" #include <string.h> redox::cluster::Cluster::Cluster(std::ostream &log_stream, redox::log::Level log_level): m_logger(log_stream, log_level), m_log_stream(log_stream), m_log_level(log_level), m_connection_callback(nullptr) { // do nothing } redox::cluster::Cluster::~Cluster() { disconnect(); } bool redox::cluster::Cluster::connect(const char *host, uint32_t port, std::function<void (int)> connection_callback) { // store the connection callback m_connection_callback = connection_callback; // connect to redis cluster node, use tcp port; Redox rdx(m_log_stream, m_log_level); if (!rdx.connect(host, port)) { m_logger.error() << "connect to redis node failed, redis node:(" << host << ":" << port << ")"; return false; } // check redis mode is cluster if (!isCluster(rdx)) { m_logger.error() << "redis node is not cluster, redis node:(" << host << ":" << port << ")"; rdx.disconnect(); return false; } // check redis cluster status is ok? if (!isClusterOk(rdx)) { m_logger.error() << "redis cluster node is not OK, redis node:(" << host << ":" << port << ")"; rdx.disconnect(); return false; } // slot range return reflashRoute(rdx, m_connection_callback); } bool redox::cluster::Cluster::connect(const char *nodes[], uint32_t node_count, std::function<void (int)> connection_callback) { for (uint32_t i = 0; i < node_count; ++i) { std::vector<std::string> host_port; util::split(nodes[i], host_port, ":"); if (this->connect(host_port[0].c_str(), atoi(host_port[1].c_str()), connection_callback)) { return true; } } return false; } bool redox::cluster::Cluster::connect(const std::vector<std::string> &nodes, std::function<void (int)> connection_callback) { for (std::vector<std::string>::const_iterator iter = nodes.cbegin(); iter != nodes.cend(); ++iter) { std::vector<std::string> host_port; util::split(*iter, host_port, ":"); if (this->connect(host_port[0].c_str(), atoi(host_port[1].c_str()), connection_callback)) { return true; } } return false; } void redox::cluster::Cluster::disconnect() { for (auto node: m_nodes) { if (nullptr == node) { continue; } node->m_handle.disconnect(); } m_nodes.clear(); } bool redox::cluster::Cluster::reflashRouteSelf(std::function<void (int)> connection_callback) { for (auto node : m_nodes) { if (reflashRoute(node->m_handle, connection_callback)) { return true; } } return false; } bool redox::cluster::Cluster::reflashRoute(redox::Redox &rdx, std::function<void (int)> connection_callback) { if (nullptr == connection_callback) connection_callback = m_connection_callback; auto &r = rdx.commandSync<std::string>({"cluster", "nodes"}); if (!r.ok()) { m_logger.debug() << "get redis cluster nodes failed, redis node:(" << rdx.host_ << ":" << rdx.port_ << ")"; rdx.disconnect(); return false; } std::vector<std::string> nodes; util::split(r.reply(), nodes, "\r\n"); TClusterNodes cluster_node; for (std::string node: nodes) { std::vector<std::string> infos; util::split(node, infos, " "); std::shared_ptr<ClusterNode> n = std::make_shared<ClusterNode>(); if (nullptr == n) { m_logger.warning() << "create cluster node connector failed, make_shared<ClusterNode> => nullptr, node info '"<< node << "'"; continue; } n->init(infos, connection_callback); cluster_node.push_back(n); } m_nodes.swap(cluster_node); for (auto node: cluster_node) { if (nullptr != node) { node->m_handle.disconnect(); } } cluster_node.clear(); rdx.disconnect(); return true; } bool redox::cluster::Cluster::isCluster(redox::Redox &rdx) { auto &r1 = rdx.commandSync<std::string>({"info"}); if (!r1.ok()) { return false; } // std::cout << r1.reply() << std::endl; std::vector<std::string> lines; util::split(r1.reply(), lines, "\r\n"); for (std::vector<std::string>::iterator iter = lines.begin(); iter != lines.end(); ++iter) { std::string &line = *iter; // std::cout << "->" << line << "<-" << std::endl; if (line[0] == '#') continue; if (line.empty() || line[0] == '\n') continue; std::vector<std::string> kv; util::split(line, kv, ":"); if (kv[0] == "cluster_enabled" && atoi(kv[1].c_str()) == 1) return true; } return false; } bool redox::cluster::Cluster::isClusterOk(redox::Redox &rdx) { auto &r2 = rdx.commandSync<std::string>({"cluster", "info"}); if (!r2.ok()) { rdx.logger_.debug() << "exec command: 'cluster info' failed"; return false; } std::vector<std::string> lines; util::split(r2.reply(), lines, "\r\n"); for (std::vector<std::string>::iterator iter = lines.begin(); iter != lines.end(); ++iter) { std::string &line = *iter; if (line[0] == '#') continue; if (line.empty() || line[0] == '\n') continue; std::vector<std::string> kv; util::split(line, kv, ":"); if (kv.size() < 2) continue; if (kv[0] == "cluster_state" && kv[1] == "ok") return true; } return false; } void redox::cluster::Cluster::command(const std::vector<std::string> &cmdline) { std::string key = cmdline[1]; uint32_t slot = util::hash_slot(key.c_str(), key.length()); uint32_t node_index = this->findNodeBySlot(slot); if (node_index >= m_nodes.size()) { m_logger.error() << "key: " << key << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return ; } std::shared_ptr<ClusterNode> rdx = m_nodes[node_index]; if (rdx == nullptr) { m_logger.error() << "node ptr is null" << ", " << "key: " << key << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return; } rdx->m_handle.command(cmdline); } bool redox::cluster::Cluster::commandSync(const std::vector<std::string> &cmdline) { std::string key = cmdline[1]; uint32_t slot = util::hash_slot(key.c_str(), key.length()); uint32_t node_index = this->findNodeBySlot(slot); if (node_index >= m_nodes.size()) { m_logger.error() << "key: " << key << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return false; } std::shared_ptr<ClusterNode> rdx = m_nodes[node_index]; if (rdx == nullptr) { return false; } return rdx->m_handle.commandSync(cmdline); } std::string redox::cluster::Cluster::get(const std::string &key) { uint32_t slot = util::hash_slot(key.c_str(), key.length()); uint32_t node_index = this->findNodeBySlot(slot); if (node_index >= m_nodes.size()) { m_logger.error() << "key: " << key << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return ""; } std::shared_ptr<ClusterNode> rdx = m_nodes[node_index]; if (rdx == nullptr) { return ""; } return rdx->m_handle.get(key); } bool redox::cluster::Cluster::set(const std::string &key, const std::string &value) { uint32_t slot = util::hash_slot(key.c_str(), key.length()); uint32_t node_index = this->findNodeBySlot(slot); if (node_index >= m_nodes.size()) { m_logger.error() << "key: " << key << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return false; } std::shared_ptr<ClusterNode> rdx = m_nodes[node_index]; if (rdx == nullptr) { return false; } return rdx->m_handle.set(key, value); } bool redox::cluster::Cluster::del(const std::string &key) { uint32_t slot = util::hash_slot(key.c_str(), key.length()); uint32_t node_index = this->findNodeBySlot(slot); if (node_index >= m_nodes.size()) { m_logger.error() << "key: " << key << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return false; } std::shared_ptr<ClusterNode> rdx = m_nodes[node_index]; if (rdx == nullptr) { return false; } return rdx->m_handle.del(key); } void redox::cluster::Cluster::publish(const std::string &topic, const std::string &msg) { uint32_t slot = util::hash_slot(topic.c_str(), topic.length()); uint32_t node_index = this->findNodeBySlot(slot); if (node_index >= m_nodes.size()) { m_logger.error() << "key: " << topic << ", " << "slot:" << slot << ", " << "node index:" << node_index << ", " << "node size:" << m_nodes.size(); return; } std::shared_ptr<ClusterNode> rdx = m_nodes[node_index]; if (rdx == nullptr) { return; } rdx->m_handle.publish(topic, msg); } uint32_t redox::cluster::Cluster::findNodeBySlot(uint32_t slot) { uint32_t node_id = 0; for (TClusterNodes::iterator iter = m_nodes.begin(); iter != m_nodes.end(); ++iter) { const TClusterNodes::value_type &client = *iter; if (slot >= client->m_slots.first && slot <= client->m_slots.second) { break; } ++node_id; } return node_id; } bool redox::cluster::ClusterNode::init(std::vector<std::string> &items, std::function<void (int)> connection_callback) { // [0] Node ID m_id = items[0]; // [1] ip:port { std::string::size_type pos = items[1].find(':'); if (pos != std::string::npos) { const std::string port_str = items[1].substr(pos + 1); m_client_port = atoi(port_str.c_str()); m_client_host = items[1].substr(0, pos); } } // [2] flags: master, slave, myself, fail, ... std::vector<std::string> flags; util::split(items[2], flags, ","); for (auto f: flags) { if (f == "myself") { m_flag |= myself; } else if (f == "master") { m_flag |= master; } else if (f == "slave") { m_flag |= slave; } else if (f == "fail") { m_flag |= fail; } else if (f == "fail?") { m_flag |= fail_maybe; } else if (f == "handshake") { m_flag |= handshake; } else if (f == "noaddr") { m_flag |= noaddr; } else if (f == "noflags") { m_flag |= noflags; } } // [3] if it is a slave, the Node ID of the master m_master_id = items[3]; // [4] Time of the last pending PING still waiting for a reply. // [5] Time of the last PONG received. // [6] Configuration epoch for this node (see the Cluster specification). // [7] Status of the link to this node. m_link_state = items[7]; // [8] Slots served... if (master == (m_flag & master)) { std::string::size_type pos = items[8].find('-'); if (pos == std::string::npos) { m_slots.first = atoi(items[8].c_str()); m_slots.second = m_slots.first; } else { m_slots.first = atoi(items[8].substr(0, pos).c_str()); m_slots.second = atoi(items[8].substr(pos + 1).c_str()); } } return m_handle.connect(m_client_host, m_client_port, connection_callback); } void redox::cluster::ClusterNode::fini() { }
true
54ddf14cc80b26811ea8b6293cb88b69bf1b2a5d
C++
alexandraback/datacollection
/solutions_5631572862566400_1/C++/Sharph/codejam_2016_1a_c.cpp
UTF-8
1,059
2.515625
3
[]
no_license
#include <iostream> #include <deque> #include <cassert> #include <vector> #include <map> #include <tuple> using namespace std; int F[1024]; int idx[1024]; tuple<int, int, int, int> xd(int v) { fill(idx, idx + 1024, -1); int i = 0; while(idx[v] == -1) { idx[v] = i++; v = F[v]; } int m = 1024; int s = v; do { m = min(m, v); v = F[v]; } while(v != s); return make_tuple(idx[v], i - idx[v], m, v); } int main() { int T; cin >> T; for(int Te = 0; Te < T; ++Te) { int N; cin >> N; for(int i = 0; i < N; ++i) { cin >> F[i]; --F[i]; } int ret = 3; map<int, map<int, int>> asd; for(int i = 0; i < N; ++i) { int p, c, m, v; tie(p, c, m, v) = xd(i); if(c == 2) { asd[m][v] = max(asd[m][v], p); } else { assert(c > 2); ret = max(ret, c); } } int asdsum = 0; for(pair<int, map<int, int>> p : asd) { for(pair<int, int> p2 : p.second) { asdsum += p2.second; } asdsum += 2; } ret = max(ret, asdsum); cout << "Case #" << Te + 1 << ": " << ret << "\n"; } return 0; }
true
1f67055f794640391ad901b455ac1c0e578a5498
C++
Goodii/Graphics
/aieBootstrap-master/Graphics/MyApplication.h
UTF-8
606
2.5625
3
[ "MIT" ]
permissive
#pragma once #include <glm/glm.hpp> #include <glm/ext.hpp> struct GLFWindow; class MyApplication { public: MyApplication(); virtual ~MyApplication(); void run(const char* title, int width, int height, bool fullscreen); virtual bool startup() = 0; virtual void update(float deltaTime) = 0; virtual void draw() = 0; virtual void shutdown() = 0; void setBackgroundColour(float r, float g, float b, float a = 1.f); void quit(); protected: bool m_gameRunning; struct GLFWwindow* m_window; bool createWindow(const char* title, int width, int height, bool fullscreen); void destroyWindow(); };
true
0c9c8345a10a0df01b54414f4657053e5e7bbf51
C++
HaoLiSky/EON
/client/potentials/Water/potential_base.cpp
UTF-8
23,840
2.890625
3
[]
no_license
/** @file Basic tools to write potentials. @author Jean-Claude C. Berthet @date 2006-2008 University of Iceland */ #include <cmath> #include <iostream> #include <cassert> #include <cstdlib> #include "potential_base.hpp" /** @class forcefields::PotentialBase @brief Functions and tools commonly used by potentials. Contains functions for quadratic retrainst, Lennard-Jones, Coulomb, to manage the periodic boundaries and interface for cutoff. The system of units used is (eV, Angstrom, fs, e). Rules to combine different Lennard-Jones parameters were taken from:\n Unlike Lennard-Jones Parameters for Vapor-Liquid Equilibria, Thorsten Schnabel, Jadran Vrabec , Hans Hasse, Institut fur Technische Thermodynamik und Thermische Verfahrenstechnik, Universitat Stuttgart, D-70550 Stuttgart, Germany, http://www.itt.uni-stuttgart.de/~schnabel/CR.pdf. */ using namespace std; using namespace forcefields; /** Non bond interaction cutoff. When the distance between two molecules is over getCutoff(), van der Waals and Coulomb interactions between the two molecules are ignored. @see getSwitchingWidth().*/ PotentialBase::PotentialBase() : cutoff_(6.5), switchingWidth_(2.0) { periods_[0]=0.0; periods_[1]=0.0; periods_[2]=0.0; } PotentialBase::PotentialBase(double cutoff, double switchingWidth) : cutoff_(cutoff), switchingWidth_(switchingWidth) { if (switchingWidth_ > cutoff_) { cerr << "Error: getSwitchingWidth() > getCutoff()" << endl; exit(EXIT_FAILURE); }; periods_[0]=0.0; periods_[1]=0.0; periods_[2]=0.0; } double PotentialBase::getCutoff() const { return cutoff_; } void PotentialBase::setCutoff(double cutoff) { cutoff_=cutoff; } /** Width of the switching zone. In the switching zone the potential is replaced by @f$ V=U\times S(x) @f$ where @em U is the real potential @em V the switching potential and @em S the switching function. Variable x=0 at the beginning of the switching zone and x=1 at the end the function S is @f$ S=2x^3-3x^2+1 @f$ which has the following properties: S(0)=1, S(1)=0, S'(0)=0 and S'(1)=0. The switching when the distance between the two molecules is getCutoff()-getSwitchingWidth() and ends when the distance is getCutoff(); @see getCutoff(). @{ */ double PotentialBase::getSwitchingWidth() const { return switchingWidth_; } void PotentialBase::setSwitchingWidth(double width) { switchingWidth_=width; } // @} /** Minimum image representation. @return Minimum image representation of @a r. The value returned is @f$ \frac{-period}{2} \le r \le \frac{period}{2} @f$ @param[in] r Cyclic coordinate. @param[in] period Period of the coordinates. */ double PotentialBase::applyPeriodicity0(double r, double const period) { if (not isinf(period)) { double n=r/period+0.5; // This is slightly more efficient than using function floor(). int m=(int)n; if (n < 0) -- m; r-=m*period; }; return r; } /** Minimum image representation. @return Minimum image representation of @a r. The value returned is @f$ \frac{-period}{2} \le r \le \frac{period}{2} @f$. @param[in] r Three-dimension vector. @param[in] periods Three-dimension vector containing periods along each of the axes. */ void PotentialBase::applyPeriodicity0(double r[], double const periods[]) { for (int i=0; i < 3; ++i) r[i]=applyPeriodicity0(r[i], periods[i]); } /** Calculate the base of an isosceles triangle. An isosceles triangle is a triangle with two sides of equal length. If you know the length of the two equal sides and the angle between the two, the function can calculate the length of the third side. @param[in] length Length of the two equal sides of the triangle. @param[in] angle Angle between the two equal side in radiant. */ double PotentialBase::isoscelesBase(double length, double angle) { return 2.0*length*sin(angle/2.0); } /** Compute quadratic restraints between two atoms. @f$ U=k(r-r_0)^2 @f$ @param[in] R1[] Positions of atom 1. @param[in] R2[] Positions of atom 2. @param[in,out] F1[] Incremented by force on atom 1. @param[in,out] F2[] Incremented by force on atom 2. @param[in,out] u Incremented by energy. @param[in] k Potential curvature @param[in] req Distance of the two atoms at equilibrium. @warning @a F1, @a F2 and @a u are incremented.*/ void PotentialBase::restrainLength(const double R1[], const double R2[], double F1[], double F2[], double & u, const double k, const double req) { double f, fx; double r[3], r1, r2; distance(R2, R1, r, r1, r2); double d=r1-req; f = -2.0*k*d; u+=k*d*d; fx=f*r[0]/r1; F1[0]-=fx; F2[0]+=fx; fx=f*r[1]/r1; F1[1]-=fx; F2[1]+=fx; fx=f*r[2]/r1; F1[2]-=fx; F2[2]+=fx; } /** Angular quadratic restraints. @f$ U=k(a-a_0)^2 @f$ @param[in] "r1[], r2[], r3[]" Positions of atoms. @param[in,out] "f1[], f2[], f3[]" Force on atoms. The forces are incremeneted by the function. @param[in,out] u Incremented by energy. @param[in] k Potential curvature @param[in] aeq Angle made by the three atoms 1,2,3 at equilibrium. */ void PotentialBase::restrainAngle(double const r1[], double const r2[], double const r3[], double f1[], double f2[], double f3[], double & u, const double k, const double aeq) { double r12[3], r12_1, r12_2, r23[3], r23_1, r23_2, cosa, a, m, d12, d23; distance(r2, r1, r12, r12_1, r12_2); distance(r3, r2, r23, r23_1, r23_2); cosa=-dotProduct(r12, r23)/r12_1/r23_1; a=acos(cosa); u+=k*(a-aeq)*(a-aeq); m=-2*k*(a-aeq);// moment m/= -1*sqrt(1 - cosa*cosa);//*d(a)/d(cos a) for (int i=0; i<3; ++i) { d12= - cosa*r12[i]/r12_2 - r23[i]/r12_1/r23_1;//d(cos a)/d(r12) d23= - cosa*r23[i]/r23_2 - r12[i]/r12_1/r23_1;//d(cos a)/d(r23) f1[i]-=m*d12; f2[i]+=m*(d12-d23); f3[i]+=m*d23; }; } const double PotentialBase::ONE_OVER_4_PI_EPSILON0 = 14.399644532010862; // eV e^2 / Angstrom /** Calculate centre of two points. Calculate the centre of @a r1 and @a r2 and store the result in @a rc. @note The centre is calculated for the image or @a r2 the closed to @a r1. */ void PotentialBase::calculateCentre(double const r1[], double const r2[], double rc[]) { for (int i=0; i < 3; ++i) { rc[i]=(r1[i]+unBreak1(r2[i], r1[i], i))*0.5; }; } /// Calculate centre of three points. @see calculateCentre(). void PotentialBase::calculateCentre(double const r1[], double const r2[], double const r3[], double rc[]) { for (int i=0; i < 3; ++i) { rc[i]=(r1[i]+unBreak1(r2[i], r1[i], i)+unBreak1(r3[i], r1[i], i))/3.0; }; } /** Calculate barycentre. The inverse of this functions the forces is spreadWeightedForce() @pre Sum of weigths <em> w1, w2, w3 </em> must be 1. */ void PotentialBase::calculateWeightedCentre(double const w1, double const w2, double const w3, double const r1[], double const r2[], double const r3[], double rc[]) { assert(fabs(w1+w2+w3-1.0) < 1e-9); for (int i=0; i < 3; ++i) { rc[i]=w1*r1[i]+w2*unBreak1(r2[i], r1[i], i)+w3*unBreak1(r3[i], r1[i], i); }; } /** Coulomb interaction with single charge based cutoff. @f$ U = \frac{q_1q_2}{|\mathbf r_1- \mathbf r_2|} @f$ @param[in] r1 Positions of atom 1. @param[in] r2 Positions of atom 2. @param[in,out] f1 Incremented by force on atom 1. @param[in,out] f2 Incremented by force on atom 2. @param[in,out] energy Incremented by energy. @param[in] qq Product of the charges. @warning @a f1, @a f2 and @a u are incremented. @see getCutoff() and getSwitchingWidth().*/ void PotentialBase::coulombWithCutoff(const double r1[], const double r2[], double f1[], double f2[], double & energy, double qq) { double d1, d[3]; // d: vector distance (r1-r2), d1 distance and d2 squared distance distance(r1, r2, d, d1); if (d1 < cutoff_) { double f, en; coulomb(d1, f, en, qq); switching(d1, f, en); for (int l=0; l < 3; ++l) { f1[l]+=f*d[l]/d1; f2[l]-=f*d[l]/d1; }; energy+=en; } } /** Compute Coulomb interaction between two charges. @f$ U = \frac{q_1q_2}{|\mathbf r_1- \mathbf r_2|} @f$ @param[in] r1 Positions of atom 1. @param[in] r2 Positions of atom 2. @param[in,out] f1 Incremented by force on atom 1. @param[in,out] f2 Incremented by force on atom 2. @param[in,out] energy Incremented by energy. @param[in] qq Product of the charges. @warning @a f1, @a f2 and @a u are incremented.*/ void PotentialBase::coulomb(const double r1[], const double r2[], double f1[], double f2[], double & energy, double qq) { double d1, d[3], f, en; // d: vector distance (r1-r2), d1 distance and d2 squared distance distance(r1, r2, d, d1); coulomb(d1, f, en, qq); for (int l=0; l < 3; ++l) { f1[l]+=f*d[l]/d1; f2[l]-=f*d[l]/d1; }; energy+=en; } /** Compute Coulomb interaction between two charges. @f$ U = \frac{q_1q_2}{|\mathbf r_1- \mathbf r_2|} @f$ @param[in] distance between two charges @param[out] force Force Resulting from the coulom interaction. @param[out] energy Potential energy. @param[in] qq Product of the charges.*/ void PotentialBase::coulomb(double distance, double & force, double & energy, double const qq) { energy=ONE_OVER_4_PI_EPSILON0*qq/distance; force=energy/distance; } /** Spread force on centre to other points. Spread force @a fc to @a f1, @a f2. Each receives a half of the force. */ void PotentialBase::spreadForce(double f1[], double f2[], double const fc[]) { for (int i=0; i < 3; ++i) { double const f=fc[i]/2; f1[i]+=f; f2[i]+=f; }; } /** Spread force on centre to other points. Spread force @a fc to @a f1, @a f2, @a f3. Each receives 1/3 of the force. */ void PotentialBase::spreadForce(double f1[], double f2[], double f3[], double const fc[]) { for (int i=0; i < 3; ++i) { double const f=fc[i]/3; f1[i]+=f; f2[i]+=f; f3[i]+=f; }; } /** Spread force on barycentre to atoms. This is the inverse functions calculateWeightedCentre() @pre Sum of weigths <em> w1, w2, w3 </em> must be 1. @param[in] "w1, w2, w3" weights. @param[in,out] "f1, f2, f3" vector to spread @a fc to. @param[in,out] fc force to spread. */ void PotentialBase::spreadWeightedForce(double const w1, double const w2, double const w3, double f1[], double f2[], double f3[], double const fc[]) { for (int i=0; i < 3; ++i) { double const f=fc[i]; f1[i]+=f*w1; f2[i]+=f*w2; f3[i]+=f*w3; }; } /** Conversion for Lennard-Jones. The Lennard-Jones is sometimes expressed as: @f[ \frac{A}{r^{12}}-\frac{B}{r^6} @f] whereas the functions lennardJones() use the expression: @f[ 4\epsilon\left[\left(\frac{\sigma}{r}\right)^{12}-\left(\frac{\sigma}{r}\right)^6\right] @f] The function calculates the parameter @a epsilon. */ double PotentialBase::epsilon(double const A, double const B) { return B*B/A/4.0; } /** Lennard-Jones 12-6 between two atoms. Return the @a energy and scalar @a force resulting from a Lennard-Jones potential. @f$ E=4*\epsilon*(x^{12}-x^6) @f$ with @f$ x=\frac{\sigma}{r} @f$ and @f$ F=-\frac{dE}{dr} @f$ . @param[in] distance Distance between two atoms. @param[out] force Force. @param[out] energy Potential energy. @param[in] "epsilon, sigma" Lennard-Jones parameters. @see sigma() and epsilon()*/ void PotentialBase::lennardJones(double distance, double & force , double & energy, double const epsilon, double const sigma) { double x=sigma*sigma/(distance*distance); x*=x*x; energy=4*epsilon*(x-1)*x; force=24*epsilon*(2*x-1)*x/distance; } /** Lennard-Jones 12-6 between two atoms. @param[in] "R1, R2" Positions of atom 1 and 2. @param[in,out] "F1, F2" Force on atom 1 and 2. @param[in,out] E Energy. @param[in] "epsilon, sigma" Parameters of the Lennard-Jones potential. @warning @a F1, @a F2 and @a u are incremented. @see @ref lennardJones(double const, double &, double &, double const, double const) "lennardJones(distance, ...)".*/ void PotentialBase::lennardJones(const double R1[], const double R2[], double F1[], double F2[], double & E, double const epsilon, double const sigma) { //WARNING: F1 and F2 are incremented. double F, Fx, en; double R12[3]; double L, L2; distance(R2, R1, R12, L, L2); lennardJones(L, F, en, epsilon, sigma); E+=en; Fx=F*R12[0]/L; F1[0]-=Fx; F2[0]+=Fx; Fx=F*R12[1]/L; F1[1]-=Fx; F2[1]+=Fx; Fx=F*R12[2]/L; F1[2]-=Fx; F2[2]+=Fx; } /** Lennard Jones 12-6 Potential with cutoff. Interaction between two atoms. Cutoff and switching width should be set with setCutoff() and setSwitchingWidth(). @param[in] "r1, r2" Positions of the two atoms. @param[in,out] "f1, f2" Forces on the two atoms. @param[in,out] energy Potential energy. @param[in] "epsilon, sigma" See @ref lennardJones(double const distance, double & force, double & energy, double const epsilon, double const sigma) "lennardJones()" for definition of @a sigma and @a esplion. @see @ref lennardJones(double const, double &, double &, double const, double const) "lennardJones()". */ void PotentialBase::lennardJonesWithCutoff(double const r1[], double const r2[], double f1[], double f2[], double & energy, double const epsilon, double const sigma) { double r12[3]={0}, d=0.0, f, en;// distance distance(r2, r1, r12, d); if (d < cutoff_) { lennardJones(d, f, en, epsilon, sigma); switching(d, f, en); for (int i=0; i < 3; ++i) { f1[i]-=f*r12[i]/d; f2[i]+=f*r12[i]/d; }; energy += en; }; } /** Conversion for Lennard-Jones. The Lennard-Jones is sometimes expressed as: @f[ \frac{A}{r^{12}}-\frac{B}{r^6} @f] whereas the functions lennardJones() use the expression: @f[ 4\epsilon\left[\left(\frac{\sigma}{r}\right)^{12}-\left(\frac{\sigma}{r}\right)^6\right] @f] The function calculates the parameter @a sigma. */ double PotentialBase::sigma(double const A, double const B) { return pow(A/B, 1.0/6.0); } /** Smith and Kong combination rules. @f[ \epsilon^{SK}_{12}= \frac{2^{13}\epsilon_1\sigma_1^6\epsilon_2\sigma_2^6}{\left[(\epsilon_1\sigma_1^{12})^\frac{1}{13}+(\epsilon_1\sigma_1^{12})^\frac{1}{13}\right]^{13}} @f] @see smithKongSigma()*/ double PotentialBase::smithKongEpsilon(double sigma1, double epsilon1, double sigma2, double epsilon2) { double sa6, sb6, n, d; sa6=pow(sigma1, 6.0); sb6=pow(sigma2, 6.0); n=pow(2.0, 13.0)*epsilon1*sa6*epsilon2*sb6; d=pow(epsilon1*sa6*sa6, 1.0/13.0)+pow(epsilon2*sb6*sb6, 1.0/13.0); d=pow(d, 13); return n/d; } /** Smith and Kong combination rules. Combination of unlike Lennard-Jones parameters @f[ \sigma^{SK}= \left[ \frac{(\epsilon_1\sigma_1^{12})^{\frac{1}{13}}+(\epsilon_2\sigma_2^{12})^{\frac{1}{13}}} {2^{13}\sqrt{\epsilon_1\sigma_1^6\epsilon_2\sigma_2^6}} \right]^\frac{1}{6} @f] */ double PotentialBase::smithKongSigma(double sigma1, double epsilon1, double sigma2, double epsilon2) { double const sa6=pow(sigma1, 6.0); double const sb6=pow(sigma2, 6.0); double n, d; n=pow(epsilon1*sa6*sa6, 1.0/13.0)+pow(epsilon2*sb6*sb6, 1.0/13); n=pow(n, 13.0); d=pow(2.0, 13.0)*sqrt(epsilon1*sa6*epsilon2*sb6); return pow(n/d, 1.0/6.0); } /** Smooth cutoff switch off. Should be called when the distance between the two atoms is in the switching zone (see getSwitchinWidth() for more explanation). @param[in] distance Distance between two atoms. @param[in,out] force On atoms. The input values should be the full force for the interaction between the two atoms. The function returns the corrected force. @param[in,out] energy Potential energy. The input should be the full energy for the interaction between the two atoms. The functions returns the corrected energy. @note The function is for atom based cutoff only. @see getSwitchinWidth(). */ void PotentialBase::switching(double const distance, double & force, double & energy) { double x=(distance - cutoff_+switchingWidth_)/switchingWidth_; if (x >= 1.0) {// if more: cutoff force=0.0; energy=0.0; } if (x > 0.0) {// if more: switching zone double S=(2*x-3)*x*x+1; double dS=6*x*(x-1); double const u=energy; force= force*S - u*dS/switchingWidth_; energy *= S; }; // else: full interaction, leave force and energy as the are. } /** Smooth cutoff switch off. Should be called when the distance between the two atoms is in the switching zone (see getSwitchinWidth() for more explanation). @param[in] "r1, r2" Positions of atoms. @param[in,out] "f1, f2" Forces on atoms. The input values should be the full forces for the interaction between the two atoms. The function returns the corrected forces. @param[in,out] energy Potential energy. The input should be the full energy for the interaction between the two atoms. The functions returns the corrected energy. @note The function is for atom based cutoff only. @see getSwitchinWidth(). */ void PotentialBase::switching(double const r1[], double const r2[], double f1[], double f2[], double & energy) { double z[3], z1; distance(r1, r2, z, z1); double x=(z1-cutoff_+switchingWidth_)/switchingWidth_; assert(x > 0.0); assert(x < 1.0); double S=(2*x-3)*x*x+1; double dS=6*x*(x-1); double const u=energy; for(int k=0; k<3; ++k) { f1[k] = f1[k]*S - u*dS/switchingWidth_*z[k]/z1; f2[k] = f2[k]*S + u*dS/switchingWidth_*z[k]/z1; }; energy *= S; } /** Minimum image representation. @return Minimum image representation of @a r. The value returned is @f$ \frac{-period}{2} \le r \le \frac{period}{2} @f$. The periods should be set with setPeriodicity(); @param[in] r Three-dimension vector. @see setPeriodicity().*/ void PotentialBase::applyPeriodicity1(double r[]) { applyPeriodicity0(r, periods_); } /** Minimum image representation. @return Minimum image representation of @a r. The value returned is @f$ \frac{-period}{2} \le r \le \frac{period}{2} @f$. The periods should be set with setPeriodicity(); @param[in] r Cyclic coordinate. @param[in] axis Either 0, 1 or 2. @see setPeriodicity().*/ double PotentialBase::applyPeriodicity1(double r, int const axis) { return applyPeriodicity0(r, periods_[axis]); } /** Distance vector, norm and norm square. @param[in] "x, y" Two three dimension vector. @param[out] z @f$ \mathbf x -\mathbf y @f$ with pbc applied. @param[out] z1 @f$ |\mathbf z | @f$ @param[out] z2 @f$ |\mathbf z |^2 @f$ @see setPeriodicity().*/ void PotentialBase::distance(const double x[], const double y[], double z[], double & z1, double & z2) { assert(x); assert(y); assert(z); for(int i=0; i<3; ++i) z[i]=x[i]-y[i]; applyPeriodicity1(z); z2=z[0]*z[0]+z[1]*z[1]+z[2]*z[2]; z1=sqrt(z2); } /** Distance. @param[in] "x, y" Two three dimension vector. @param[out] z[] @param[out] z1 @f$| \mathbf x -\mathbf y | @f$ with pbc applied. @see setPeriodicity().*/ void PotentialBase::distance(const double x[], const double y[], double z[], double & z1) { double z2; distance(x, y, z, z1, z2); } /** Distance vector, norm. @see distance(const double x[], const double y[], double z[], double & z1, double & z2) and setPeriodicity().*/ void PotentialBase::distance(const double x[], const double y[], double z[]) { double z1; distance(x, y, z, z1); } /// Distance. @see distance void PotentialBase::distance(const double x[], const double y[], double & z1) { double z[3]; distance(x, y, z, z1); } /** Distance vector, norm and norm square. @param[in] "x, y" Two three dimension vector. @param[out] z Return x-y, |x-y| and |x-y|^2. @see setPeriodicity().*/ void PotentialBase::distance(const double x[], const double y[], Vector3 & z) { distance(x, y, z.v, z._1, z._2); } /** Set periodicity. Must be used before calling certain functions: distance(), applyPeriodicity(), etc... */ void PotentialBase::setPeriodicity(const double periods[]) { periods_[0]=periods[0]; periods_[1]=periods[1]; periods_[2]=periods[2]; } /** Undo the separation of two atoms created by the periodic boundaries. Example: two atoms H and O are at respectively x = -9.5 and x = 9.5 and the period along @em x is 20. The real distance between the two atoms is 1. We use unBreak() on the coordinates of these two atoms: @code unBreak(rh, ro); @endcode The coordinates @em rh of H is now 10.5 thus making O and H appears at a distance of 1 of each other.\n Apply periodic boundaries condition to vector @f$ r - r_{ef} @f$. @param[in] r Returns @f$ \textrm{applyPeriodicity}(r - r_{ef}) +r_{ef} @f$ @param[in] ref @param[in] period */ double PotentialBase::unBreak0(double const r, double const ref, double const period) { return applyPeriodicity0(r - ref, period)+ref; } /// Undo the separation of two atoms created by the periodic boundaries. @see unBreak0() void PotentialBase::unBreak0(double r[], double const ref[], double const periods[]) { for (int a=0; a < 3; ++a) r[a]=unBreak0(r[a], ref[a], periods[a]); } /// Undo the separation of two atoms created by the periodic boundaries. @see unBreak0() void PotentialBase::unBreak1(double r[], double const ref[]) { unBreak0(r, ref, periods_); } /// Undo the separation of two atoms created by the periodic boundaries. @see unBreak0() double PotentialBase::unBreak1(double const r, double const ref, int const axis) { return unBreak0(r, ref, periods_[axis]); } /** Potential for Platinum. Simple 12-6 Lennard-Jones potential for Platinum.\n Parameters from: C. Kittel, Introduction to Solid State Physics, (Wiley, New York, 1986). @param[in] nAtoms Number of atoms. @param[in] positions Positions of atoms. @param[out] forces Forces on atoms. @param[out] energy Potential energy. @param[in] periods Periods for periodic boundary conditions. @param[in] fixed Array of boolean of length equal to @a nAtoms. The array shall contain @em true is the atom is fixed, @em false is movable. */ void PotentialBase::computePt(int const nAtoms, double positions[], double forces[], double & energy, double const periods[], bool const fixed[]) { int const nCoord=3*nAtoms; for (int i=0; i < nCoord; ++i) forces[i]=0.0; energy=0.0; double const (*r)[3]=reinterpret_cast<double const (*)[3]>(positions); double (*f)[3]=reinterpret_cast<double (*)[3]>(forces); setPeriodicity(periods);// Set Periodic boundaries. Essential in order for some functions to work. for (int i=nAtoms-1; i >0 ; --i) { for (int j=i-1; j >=0; --j) { if (not fixed[i] and not fixed[j]) { lennardJonesWithCutoff(r[i], r[j], f[i], f[j], energy, EPSILON_PT, SIGMA_PT); }; }; }; } /** Platinum Lennard-Jones. Lennard-Jones parameters for platinum. @see computePt(). @{ */ const double PotentialBase::EPSILON_PT=0.68165797577788501;// eV const double PotentialBase::SIGMA_PT=2.54;// Angstrom /// @} /* const double PotentialBase::ONE_OVER_4_PI_EPSILON0 = unit_system::ONE_OVER_4_PI_EPSILON0; const double PotentialBase::EPSILON_PT=65.77*KJ_PER_MOL; const double PotentialBase::SIGMA_PT=0.254*NM; */
true
2c2f951d331bffacb451b748626e1a2bd7c56a7f
C++
Aleksey-Devyataikin/libbitmap
/libbitmap.h
UTF-8
778
3.09375
3
[]
no_license
#ifndef ___LIB_BITMAP_H___ #define ___LIB_BITMAP_H___ #include <cstdint> #include <string> class Bitmap { public: uint8_t * m_buffer; size_t m_width, m_height; public: Bitmap(void) : m_buffer(nullptr), m_width(0), m_height(0) {} virtual ~Bitmap(void) { clear(); } public: bool load(const char * file_name); inline bool load(const std::string & file_name) { return load(file_name.c_str()); } bool save(const char * file_name) const; inline bool save(const std::string & file_name) const { return save(file_name.c_str()); } public: void clear(void) { m_width = m_height = 0; delete [] m_buffer; m_buffer = nullptr; } private: Bitmap(const Bitmap &) = delete; Bitmap & operator = (const Bitmap &) = delete; }; #endif // ___LIB_BITMAP_H___
true
874b3ae14f0a0fc72ce850d2b38d28a0c365dfaa
C++
tg9963/CPP_files
/C and C++/SORTING/matrix_chain_multi.cpp
UTF-8
563
2.84375
3
[]
no_license
#include<iostream> #include<stdlib.h> using namespace std; void MCM(int p[],int n) { int c[n][n],s[n][n]; for(int i=1;i<n;i++) { c[i][i]=0; } for(int l=2;l<n;l++) { for(int i=1;i<n-l;i++) { int j=i+l; for(int k=i;k<j-1;k++) { int q=c[i][k]+c[k+1][j]+p[i-1]*p[k]*p[j]; if(q<c[i][j]) { c[i][j]=q; s[i][j]=k; } } } } cout<<c[n][n]; /* for(int i=1;i<n;i++) { for(int j=1;j<n;j++) { cout<<c[i][j]<<" "; } cout<<endl; } */ } int main() { int p[]={1,2,3,4,5}; int n=4; MCM(p,n); return 0; }
true
8291c836553236207b92d99bc77f6057d94eaba9
C++
sguzmanm/sshpc
/code_handson/exercise_2/write_to_file.cpp
UTF-8
491
3.84375
4
[ "MIT" ]
permissive
/* * Write a function "prime" that recieves an integer "n" and * writes all the prime numbers which are < n to a file * called "prime_numbers.txt" */ #include <stdio.h> using namespace std; /* * Write the prototype of the function */ int main(){ int n = 1000; prime(n); return 0; } /* * Write the implementation of the function "prime". * The function opens "prime_numbers.txt" for writing * and prints the prime numbers in it. * Don't forget to close the file! */
true
24d1bfddda3dc9b47b84406eed60ee09668798d8
C++
devlipe/INF110
/5Aula/zica.cpp
UTF-8
413
3.390625
3
[]
no_license
/* Programa para calcular o tempo ate a populacao de mosquitos chegar a 1 000 000 Felipe P Ferreira 02/10/2020 */ #include <iostream> using namespace std; int main(void) { long long int P = 0, G = 0, pop = 0, tempo = 0; cin >> P >> G; while (pop < 1000000000) { pop = (P * G) + P; P = pop; tempo++; } cout << tempo << endl; return 0; }
true
321f168d2d4b25765fe066b731aae5d84813f318
C++
Legend-sky/vscode
/Tempter_of_the_Bone.cpp
UTF-8
1,716
2.75
3
[]
no_license
/* * @Author: Whx * @Date: 2020-11-25 16:01:20 * @LastEditTime: 2020-11-25 16:35:39 */ #include <iostream> #include <algorithm> #include <cstring> using namespace std; int n, m, t, sx, sy, ex, ey; bool f; int dir[4][2] = {0, -1, -1, 0, 0, 1, 1, 0}; int vis[10][10]; char maze[10][10]; void dfs(int x, int y, int time) { if (f) return; if (time > t || (time == t && (x != ex || y != ey))) return; if (x < 0 || x >= n || y < 0 || y >= m) return; if (t - time < (abs(ex - x) + abs(ey - y))) return; if ((t - time) % 2 != (abs(ex - x) + abs(ey - y)) % 2) return; if (x == ex && y == ey && time == t) { f = true; return; } for (int i = 0; i < 4; i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if (!vis[nx][ny]) { vis[x][y] = 1; dfs(nx, ny, time + 1); vis[nx][ny] = 0; } } return; } int main() { while (cin >> n >> m >> t) { if (n == 0 && m == 0 && t == 0) break; f = false; memset(vis, 0, sizeof(vis)); memset(maze, '\0', sizeof(maze)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> maze[i][j]; if (maze[i][j] == 'S') sx = i, sy = j, vis[i][j] = 1; if (maze[i][j] == 'D') ex = i, ey = j; if (maze[i][j] == 'X') vis[i][j] = 1; } } dfs(sx, sy, 0); if (f) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
true
5160e11b75a275b0891507f95b818bf690a9300c
C++
WhiZTiM/coliru
/Archive/017395f447e2650549f16fdc5219e234-f674c1a6d04c632b71a62362c0ccfc51/main.cpp
UTF-8
1,911
3.40625
3
[]
no_license
#include <array> #include <iostream> #include <stdexcept> #include <string> #include <memory> #include <type_traits> // // Get index of T in Args // template<typename T, typename ...Args> struct GetIndex; template<typename T, typename ...Args> struct GetIndex<T, T, Args...> { enum { value = 0 }; }; template<typename T, typename U, typename ...Args> struct GetIndex<T, U, Args...> { enum { value = 1 + GetIndex<T, Args...>::value }; }; // // Union helper class // template<typename ...Args> struct Union; template<typename T> struct Union<T> { T t; const T& get(std::common_type<T>) const { return t; } }; template<typename T, typename ...Args> struct Union<T, Args...> { const T& get(std::common_type<T>) const { return t; } template<typename U> const U& get(std::common_type<U> u) const { return args.get(u); } union { T t; Union<Args...> args; }; }; // // Variant class // template<typename ...Args> struct Variant { template<typename T> Variant(T&& t) : type_index(GetIndex<T, Args...>::value) { new (&data) T(std::forward<T>(t)); } Union<Args...> data; unsigned type_index; }; template<typename T, typename ...Args> const T& get(const Variant<Args...>& v) { return v.data.get(std::common_type<T>{}); } template<typename T> std::ostream& operator<<(std::ostream& os, const Variant<T>& v) { return os << get<T>(v); } template<typename T, typename U> std::ostream& operator<<(std::ostream& os, const Variant<T, U>& v) { if (v.type_index == 0) { return os << get<T>(v); } else { return os << get<U>(v); } } int main() { std::cout << Variant<char, int>('c') << std::endl; std::cout << Variant<char, int>(42) << std::endl; // TODO: Fix this one //std::cout << Variant<char, int, std::string>(42) << std::endl; }
true
c87619844478d820781ff04b75c76ee4cabc9159
C++
AntisocialButterfly/algo-cpp
/flapjacks-120/main.cpp
UTF-8
1,036
3.203125
3
[]
no_license
#include <iostream> #include <sstream> #include <vector> #include <algorithm> using namespace std; void flip(vector<int>& v, size_t n, bool& first) { reverse(v.begin() + n, v.end()); if (!first) cout << " "; cout << n; first = false; } int main(int argc, const char * argv[]) { string line; while (getline(cin, line)) { stringstream ss(line); vector<int> v; int val; while (ss >> val) { v.insert(v.begin(), val); } bool first = true; for (auto r = v.rbegin(); r != v.rend(); ++r) { if (!first) cout << " "; cout << *r; first = false; } cout << endl; v.insert(v.begin(), 0); size_t sorted = 1; first = true; while (sorted < v.size()) { size_t max_index = max_element(v.begin() + sorted, v.end()) - v.begin(); if (max_index != sorted) { if (max_index != v.size() - 1) { flip(v, max_index, first); } flip(v, sorted, first); } sorted++; } flip(v, 0, first); cout << endl; } }
true
2855307dfe22719d25c6929800304ad7a8e46b2e
C++
idokka/ukrnet-test
/src/memcached/memcached.hpp
UTF-8
3,298
2.703125
3
[]
no_license
#pragma once #include <map> #include <deque> #include <mutex> #include <memory> #include "../include/server.hpp" #include "../include/client.hpp" #include "../include/factory.hpp" #include "../include/sighandler.hpp" namespace ukrnet { // test MemCached server class MemCached { public: // server command enum class Cmd { None, Get, Set, Del }; // one memcached record entity struct DataRec { // vector of char data typedef std::vector<char> vecData; // key hash int hash; // key data std::string key; // stored value vecData data; // expire in value, secs int expire; // expire at value, secs int exp_at; // default constructor, fills zeros DataRec(); // key constructor DataRec(std::string key); // returns size of record data size_t size() const; // shrd ptr lesser by expire at asc, and then by hash asc static bool PtrLessByExpireAt( const std::shared_ptr<DataRec> &lv, const std::shared_ptr<DataRec> &rv); // shrd ptr lesser by key hash asc, and then by key data asc struct PtrLessByHash { bool operator()( const std::shared_ptr<DataRec> &lv, const std::shared_ptr<DataRec> &rv); }; }; // string hash function typedef std::hash<std::string> strHash; // map data <data record as key> = <data record as value> typedef std::map< std::shared_ptr<DataRec>, std::shared_ptr<DataRec>, DataRec::PtrLessByHash> mapData; // deque of data records typedef std::deque<std::shared_ptr<DataRec>> deqData; // vector of data records typedef std::vector<std::shared_ptr<DataRec>> vecData; // lock guard for mutex typedef std::lock_guard<std::mutex> mLock; public: // default constructor // port: server socket port // use_thread: use thread connection execution model // use_fork: use fork connection execution model MemCached(int port, bool use_thread, bool use_fork); // do run server void Run(); // construct signal user handler function SigHandler::onSignal GetSigUsr1Handler(); // construct signal user handler function SigHandler::onSignal GetSigUsr2Handler(); private: // construct client func IFactory::funcClientExecute GetClientFunc(); // SIGUSR1 handler: save data to file void SignalUser1Handler(int signum); // SIGUSR2 handler: save data to file void SignalUser2Handler(int signum); // client func void ClientFunc(Client &client); // parse cmd from stream Cmd ParseCmd(std::istream &ss); // process set command void DoSet(Client &client, std::istream &ss); // process get command void DoGet(Client &client, std::istream &ss); // process delete command void DoDel(Client &client, std::istream &ss); // do process expire queue void ProcessExpireQueue(); // update data inf mmap file void UpdateMapFile(vecData &data); private: // server socket port int _port; // server socket Server _server; // data map mapData _data; // data expire deque deqData _expire_queue; // mutex for sync access to data map std::mutex _m_data; // mutex for sync access to data file std::mutex _m_data_file; // connection execute factory std::shared_ptr<IFactory> _factory; private: // path to data file static const std::string _data_file_path; }; }
true
18281f11939db1ebd57d0d60e86501d767874ee1
C++
ma1371sao/Leetcode-CPP
/LC581.cpp
UTF-8
385
3
3
[]
no_license
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { vector<int> sorted = nums; sort(sorted.begin(), sorted.end()); int start = 0; for (; start < nums.size() && sorted[start] == nums[start]; start++); int end = nums.size() - 1; for (; end >= 0 && nums[end] == sorted[end]; end--); if (end <= start) return 0; return end - start + 1; } };
true
752a94304533e60acbd26fafa9991b805ca95f19
C++
programmerQI/CSCI2270
/hw7/main.cpp
UTF-8
1,262
3.65625
4
[]
no_license
#include "MovieTree.cpp" #include <iostream> using namespace std; void printMenu() { cout << "======Main Menu======" << endl; cout << "1. Print the inventory" << endl; cout << "2. Delete a movie" << endl; cout << "3. Quit" << endl; } int readFile(std::string filename, MovieTree& t) { std::ifstream in(filename); if(!in.is_open()){ return -1; } std::string line; while(getline(in, line)){ std::string strs[5]; split(line, ',', strs, 5); t.addMovie(std::stoi(strs[0]), strs[1], std::stoi(strs[2]), std::stof(strs[3])); } in.close(); return 0; } int main(int argc, char *argv[]) { if(argc != 2){ std::cout << "Not enough argument!" << std::endl; return 0; } MovieTree mt; std::string file(args[1]); readFile(file, mt); std::string in; while(true){ showMenu(); std::getline(std::cin, in); if(in == "1") { mt.printMovieInventory(); } else if (in == "2") { std::cout << "Enter a movie title:" << std::endl; std::string r; std::getline(std::cin, r); mt.deleteMovie(r); } else if (in == "3") { std::cout << "Goodbye!" << std::endl; break; } } return 0; }
true
f73c615d81fce085017f6320f7f28effa87ba22f
C++
sunmike2002/MCF
/Unconverted/EventHandlerClass.cpp
GB18030
2,981
2.546875
3
[]
no_license
// ļ MCF һ֡ // йؾȨ˵ MCFLicense.txt // Copyleft 2012 - 2013. LH_Mouse. All wrongs reserved. #include "StdMCF.hpp" #include "EventHandlerClass.hpp" #include "Memory.hpp" using namespace MCF; // 캯 EventHandlerClass::EventHandlerClass(ReadWriteLock *prwlExternalLock) : xm_prwlExternalLock(prwlExternalLock) { } EventHandlerClass::~EventHandlerClass(){ } // Ǿ̬Ա void EventHandlerClass::xUnregisterHandler(DWORD dwEventID, std::list<EventHandlerClass::HANDLER>::const_iterator iterPos){ if(xm_prwlExternalLock != nullptr){ xm_prwlExternalLock->AcquireWriteLock(); } const auto iterList = xm_mapHandlers.find(dwEventID); if(iterList != xm_mapHandlers.end()){ iterList->second.erase(iterPos); } if(xm_prwlExternalLock != nullptr){ xm_prwlExternalLock->ReleaseWriteLock(); } } EventHandlerClass::Delegate EventHandlerClass::RegisterHandler(DWORD dwEventID, EventHandlerClass::HANDLER &&Handler){ if(xm_prwlExternalLock != nullptr){ xm_prwlExternalLock->AcquireWriteLock(); } auto &HandlerList = xm_mapHandlers[dwEventID]; HandlerList.emplace_front(std::move(Handler)); Delegate ret(this, dwEventID, HandlerList.cbegin()); if(xm_prwlExternalLock != nullptr){ xm_prwlExternalLock->ReleaseWriteLock(); } return std::move(ret); } void EventHandlerClass::Raise(DWORD dwEventID, std::intptr_t nArg1, std::intptr_t nArg2, std::intptr_t nArg3) const { if(xm_prwlExternalLock != nullptr){ xm_prwlExternalLock->AcquireReadLock(); } const auto iterList = xm_mapHandlers.find(dwEventID); if(iterList != xm_mapHandlers.end()){ for(auto cur = iterList->second.cbegin(); cur != iterList->second.cend(); ++cur){ if((*cur)(nArg1, nArg2, nArg3)){ break; } } } if(xm_prwlExternalLock != nullptr){ xm_prwlExternalLock->ReleaseReadLock(); } } namespace MCF { // ȫ¼Ӧ namespace { ReadWriteLock GlobalHandlerLock __attribute__((init_priority(2000))); EventHandlerClass GlobalEventHandler(&GlobalHandlerLock) __attribute__((init_priority(2000))); } extern EventHandlerDelegate RegisterGlobalEventHandler(DWORD dwEventID, EVENT_HANDLER &&EventHandler){ return GlobalEventHandler.RegisterHandler(dwEventID, std::move(EventHandler)); } extern void RaiseGlobalEvent(DWORD dwEventID, std::intptr_t nArg1, std::intptr_t nArg2, std::intptr_t nArg3){ GlobalEventHandler.Raise(dwEventID, nArg1, nArg2, nArg3); } // ߳¼Ӧ namespace { TLSManagerTemplate<EventHandlerClass> ThreadEventHandler; } extern EventHandlerDelegate RegisterThreadEventHandler(DWORD dwEventID, EVENT_HANDLER &&EventHandler){ return ThreadEventHandler->RegisterHandler(dwEventID, std::move(EventHandler)); } extern void RaiseThreadEvent(DWORD dwEventID, std::intptr_t nArg1, std::intptr_t nArg2, std::intptr_t nArg3){ ThreadEventHandler->Raise(dwEventID, nArg1, nArg2, nArg3); } }
true
484de374f12347042bf78566420f6e9c0f2e5f32
C++
westerly/fps
/jeu/arme.cpp
ISO-8859-1
4,913
2.859375
3
[]
no_license
#include "arme.h" arme::arme(std::string fichierTexture) { this->fichierTextureCouranteDisplayed = fichierTexture; this->ajouterTexture(this->fichierTextureCouranteDisplayed); } // Constructeur qui charge la fois le fichier de texture reprsentant l'arme mais aussi les textures // permettant d'afficher l'animation de cette arme arme::arme(std::string fichierTexture, std::vector<std::string> & texturesAnimation) { this->fichierTextureCouranteDisplayed = fichierTexture; this->ajouterTexture(this->fichierTextureCouranteDisplayed); for(std::vector<std::string>::iterator texture = texturesAnimation.begin(); texture != texturesAnimation.end(); texture++) { this->ajouterTexture(*texture); } } arme::~arme(void) { // Libration des textures for (Textures::iterator element = this->textures.begin(); element != textures.end(); element++) { this->conteneurTextures.supprimer(*element); } } // Ajoute et charge une texture partir d'un fichier // La texture est aussi ajout aux textures de l'objet void arme::ajouterTexture(std::string nomFichierTexture) { // Si la texture n'est pas deja creee if(this->textures.find(nomFichierTexture) == this->textures.end()) { this->conteneurTextures.ajouter(nomFichierTexture); this->textures.insert(nomFichierTexture); } } void arme::dessiner(float16 positionX,float16 positionY, float16 positionZ, float16 angleHorizontal, float16 angleVertical) { // on ajoute la texture de l'arme que l'on va dessiner // elle ne sera charg que si elle ne l'est pas dj this->ajouterTexture(this->fichierTextureCouranteDisplayed); // On mmorise le repre courant avant d'effectuer la RST glPushMatrix(); glTranslatef(positionX, positionY, positionZ); glRotatef(angleHorizontal, 0.0, 0.0, 1.0); glRotatef(angleVertical, 0.0, 1.0, 0.0); sint32 hauteurTextureCourante; sint32 largeurTextureCourante; // Permet d'afficher le gun et le viseur dans tous les cas et mme si une texture est dessin devant glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); // Permet d'afficher les textures transparentes glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); hauteurTextureCourante = this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).hauteur; largeurTextureCourante = this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).largeur; glBindTexture(GL_TEXTURE_2D, this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).texture); glBegin(GL_POLYGON); // 0.4f correspond au rayon du personnage... glTexCoord2f((float16)largeurTextureCourante / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).largeur, (float16)0.0 / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).hauteur); glVertex3d(-(0.4f-0.1), 0.25, 0.21); glTexCoord2f((float16)largeurTextureCourante / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).largeur, (float16)hauteurTextureCourante / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).hauteur); glVertex3d(-(0.4f-0.1), 0.25, -0.21); glTexCoord2f((float16)0.0 / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).largeur, (float16)hauteurTextureCourante / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).hauteur); glVertex3d(-(0.4f-0.1), -0.25, -0.21); glTexCoord2f((float16)0.0 / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).largeur, (float16)0.0 / this->conteneurTextures.texture(this->fichierTextureCouranteDisplayed).hauteur); glVertex3d(-(0.4f-0.1), -0.25, 0.21); glEnd(); glDisable(GL_BLEND); // Restoration du repre d'origine glPopMatrix(); // On mmorise le repre courant avant d'effectuer la RST glPushMatrix(); glTranslatef(positionX, positionY, positionZ); glRotatef(angleHorizontal, 0.0, 0.0, 1.0); glRotatef(angleVertical, 0.0, 1.0, 0.0); glEnable(GL_TEXTURE_2D); // Permet d'afficher les textures transparentes glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); hauteurTextureCourante = this->conteneurTextures.texture("personnage\\viseur.png").hauteur; largeurTextureCourante = this->conteneurTextures.texture("personnage\\viseur.png").largeur; GLuint textureViseur = this->conteneurTextures.texture("personnage\\viseur.png").texture; glBindTexture(GL_TEXTURE_2D, textureViseur); glBegin(GL_POLYGON); // 0.4f correspond au rayon du personnage... glTexCoord2f(1,0); glVertex3d(-2, 0.25, 0.21); glTexCoord2f(1, 1); glVertex3d(-2, 0.25, -0.21); glTexCoord2f(0, 1); glVertex3d(-2, -0.25, -0.21); glTexCoord2f(0, 0); glVertex3d(-2, -0.25, 0.21); glEnd(); glDisable(GL_BLEND); // Restoration du repre d'origine glPopMatrix(); glEnable(GL_DEPTH_TEST); }
true
aad05e980e50d8d5488d15b87cf2248085134fc5
C++
Ionsto/Hunt
/NeuralBrain.h
UTF-8
3,780
2.828125
3
[]
no_license
#pragma once #include <iostream> #include <fstream> #include <string> #include "math.h" #include <functional> #include "NeuralNet.h" #include <vector> template <int Inputs, int Nodes> class NeuralBrain : public NeuralNet { public: std::vector<float> Outputs; int ActivationFunction = 0; static constexpr int Stride = (Inputs + 1 + Nodes); static constexpr int Convergance = 4; /* Bulk allocate ourselves some of that memory bois Layout Inputs,Bias,Outputs* Weights.0 ... Weights.n */ std::array<float, Stride * (Nodes + 1)> WorkingMemory = {}; std::vector<float> RandomParam; NeuralBrain(); virtual ~NeuralBrain(); NeuralBrain(NeuralBrain const& ner); virtual std::vector<float> Update(std::vector<float> const & input); inline float Tanh(float x) { return x / (1.0 + fabs(x)); }; inline float Relu(float x) { return x > 0 ? x : 0; }; inline float ClippedIdentity(float x) { return x > -1 ? (x < 1 ? x :1) : -1; }; virtual void Randomise(float delta = 0.5); friend std::ostream& operator<<(std::ostream & is, const NeuralBrain<Inputs, Nodes> & ner) { //Bias is << 1; is << " "; //Input/output vector for (int i = 1; i < Stride; ++i) { is << 0; is << " "; } //Weight matrix for (int i = Stride; i < ner.WorkingMemory.size(); ++i) { is << (ner.WorkingMemory[i]) << " "; } for (int i = 0; i < ner.RandomParam.size(); ++i) { is << ner.RandomParam[i] << " "; } return is; }; friend std::istream& operator>>(std::istream & is, NeuralBrain<Inputs, Nodes> & ner) { for (int i = 0; i < ner.WorkingMemory.size(); ++i) { is >> (ner.WorkingMemory[i]); } for (int i = 0; i < ner.RandomParam.size(); ++i) { is >> ner.RandomParam[i]; } return is; }; }; template<int Inputs, int Nodes> NeuralBrain<Inputs, Nodes>::~NeuralBrain() { } template<int Inputs, int Nodes> NeuralBrain<Inputs, Nodes>::NeuralBrain() : NeuralNet(), RandomParam(Nodes) { WorkingMemory[0] = 1; for (int i = 0; i < RandomParam.size(); ++i) { RandomParam[i] = 1; } Outputs = std::vector<float>(); Outputs.resize(Nodes, 0); } template<int Inputs, int Nodes> NeuralBrain<Inputs, Nodes>::NeuralBrain(NeuralBrain<Inputs, Nodes> const& ner) : NeuralBrain<Inputs, Nodes>() { WorkingMemory = ner.WorkingMemory; for (int i = 1; i < Stride; ++i) { //Sanatise our preset outputs WorkingMemory[i] = 0; } Outputs = std::vector<float>(); Outputs.resize(Nodes, 0); } /* template<int Inputs, int Nodes> NeuralBrain<Inputs, Nodes>::NeuralBrain(NeuralBrain<Inputs, Nodes> const& ner) { //std::cout<<"Nueron cpy construct"<<std::endl; WorkingMemory = ner.WorkingMemory; }*/ template<int Inputs, int Nodes> std::vector<float> NeuralBrain<Inputs, Nodes>::Update(std::vector<float> const & input) { for (int i = 0; i < Inputs; ++i) { WorkingMemory[i + 1] = input[i]; } //std::cout<<"Output"<<Output<<"\n"; //std::cout<<"Bias"<<Bias<<"\n"; for (int Conv = 0; Conv < Convergance; ++Conv) { int StartWeight = 0; for (int Node = 0; Node < Nodes; ++Node) { float sum = 0; StartWeight += Stride; #pragma omp simd reduction(+:sum) for (int i = 0; i < Stride; ++i) { sum += WorkingMemory[i] * WorkingMemory[StartWeight + i]; } //Output WorkingMemory[Inputs+1 + Node] = ClippedIdentity(sum); } } //Go backwards for (int Node = 0; Node < Nodes; ++Node) { Outputs[Node] = WorkingMemory[Stride - (Node + 1)]; } return Outputs; } template<int Inputs, int Nodes> void NeuralBrain<Inputs, Nodes>::Randomise(float random) { for (int i = 1; i <= Nodes; ++i) { //RandomParam[i] *= (((std::rand() / (float)RAND_MAX)-1)/2.0); for (int w = 0; w < Stride; ++w) { WorkingMemory[(i*Stride) + w] += ((std::rand() / ((float)RAND_MAX / 2.0)) - 1) * random;// *RandomParam[i]; } } }
true
01ea10dd8206dc4d30df9c69740e5f44a565f693
C++
hawkproject/hawkproject
/HawkUtil/HawkFolder.h
GB18030
2,247
2.859375
3
[]
no_license
#ifndef HAWK_FOLDER_H #define HAWK_FOLDER_H #include "HawkRefCounter.h" #include "HawkXmlFile.h" namespace Hawk { /************************************************************************/ /* ϵͳļв */ /************************************************************************/ class UTIL_API HawkFolder : public HawkRefCounter { public: //ݽṹ struct FileInfo { AString Name; AString Path; Int32 Size; UInt32 Attr; UInt32 Time; FileInfo(const AString& sName = "", Int32 iSize = 0) { Name = sName; Size = iSize; Path = ""; Attr = 0; Time = 0; } }; struct FolderInfo; typedef list<FileInfo> FileList; typedef list<FolderInfo> FolderList; struct FolderInfo { AString Name; AString Path; UInt32 Time; UInt32 Attr; FileList Files; FolderList Folders; FolderInfo(const AString& sName = "") { Name = sName; Path = ""; Time = 0; Attr = 0; Files.clear(); Folders.clear(); } void Reset() { Files.clear(); Folders.clear(); } FolderInfo& operator = (const FolderInfo& sInfo) { Name = sInfo.Name; Path = sInfo.Path; Time = sInfo.Time; Attr = sInfo.Attr; FileList::const_iterator it_file = sInfo.Files.begin(); for (;it_file!=sInfo.Files.end();it_file++) Files.push_back(*it_file); FolderList::const_iterator it_folder = sInfo.Folders.begin(); for (;it_folder!=sInfo.Folders.end();it_folder++) Folders.push_back(*it_folder); return *this; } }; public: // HawkFolder(); virtual ~HawkFolder(); public: //ļ,bRecuIntoʾǷݹ²Ŀ¼ virtual Bool Open(const AString& sFolder, Bool bRecursion = true, const AString& sFilter = "*.*", Bool bHideFile = false); //дXmlļ virtual Bool WriteXml(AXmlDocument* pDoc); //رļ virtual Bool Close(); //FolderInfoָ FolderInfo* GetFolderPtr(); protected: virtual void ParseFolder(AXmlElement* pElement, FolderInfo* pFolder); protected: AString m_sFolder; FolderInfo m_sInfo; }; } #endif
true
d2ade41fa60fd9697970fa784e0f682123f863eb
C++
qingshuidoufu/data_structure
/单链表/单链表_综合运用.cpp
GB18030
9,394
3.71875
4
[]
no_license
/* Ҫݣ 1> 2>ӷ 3>ԭ 4>鲢 5>ɾظԪ 6>ͷڵ㵥Ƿ ཻཻأ-12345 ƬΡ */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef int ElemType; typedef struct SingleNode { ElemType data; struct SingleNode* next; }SingleNodeList, * Linklist; void LinkedListInit(SingleNodeList** head) {//1ʼͷڵĵ Linklist p; if ((*head = (SingleNodeList*)malloc(sizeof(SingleNodeList))) == NULL) { exit(1); } (*head)->next = NULL; } int LinkedList_PushBack(SingleNodeList* head, ElemType x) {//2β SingleNodeList* p = head, * q; while (p->next != NULL) p = p->next; if ((q = (SingleNodeList*)malloc(sizeof(SingleNodeList))) == NULL) { exit(1); } q->data = x; q->next = NULL; //βڵֵָ p->next = q;//βڵ return 1; } int LinkedListShow(SingleNodeList* head) {//3ӡ SingleNodeList* p = head; if (p->next == NULL) { printf("There is no data in the Linkedlist to print.\n"); return 0; } while (p->next != NULL) { printf("%d ", p->next->data); p = p->next; } printf("\n"); return 1; } void LinkedListDestroy(SingleNodeList** head) {//4ͷ SingleNodeList* p = *head, * q; while (p != NULL) { q = p; p = p->next; free(q); } *head = NULL; } //˺¹ //1һݣ 1 3 5 7 9 8 6 4 2 Щ֯һͷڵĵAԪ //Ϊ1. A head(A)->1->3->5->7->9->8->6->4->2 //2һXX=5.5AֳBC֣BнڵֵXСCнڵ㶼X //磺AֽBChead(B)->1->3->5->4->2 head(C)->6->8->9->7 //עBCԪԭAеĴ //3BCϲAͷָ֮ head(A)->1->3->5->4->2->6->8->9->7 int LinkedList_Divide(SingleNodeList* head, ElemType x) {//5Ļ SingleNodeList* headA, * headB; LinkedListInit(&headA); LinkedListInit(&headB); SingleNodeList* A, * B; A = headA; B = headB; SingleNodeList* p; p = head->next; while (p) { if (p->data < x) { A->next = p; A = A->next; } else if (p->data > x) { SingleNodeList* tem; if ((tem = (SingleNodeList*)(malloc(sizeof(SingleNodeList)))) == NULL) { exit(0); } tem->data = p->data; tem->next = NULL; tem->next = headB->next; headB->next = tem; } p = p->next; } A->next = headB->next; head->next = headA->next; return 1; //д } int LinkedList_Add(SingleNodeList* head, ElemType x1, ElemType x2) { SingleNodeList* p; int tem1 = x1, tem2 = x2; while (tem1 != 0) { printf("%d ", tem1 % 10); tem1 = tem1 / 10; } printf("\n"); while (tem2 != 0) { printf("%d ", tem2 % 10); tem2 = tem2 / 10; } printf("\n"); int max = x1, min = x1; if (x2 > max) { max = x2; } if (x2 < min) { min = x2; } while (max != 0) { LinkedList_PushBack(head, max % 10); max = max / 10; } p = head->next; SingleNodeList* p1; p1 = p->next; while (min != 0) { p->data = min % 10 + p->data; if (p->data >= 10) { p->data = p->data % 10; p1->data++; } min = min / 10; p = p->next; p1 = p->next; } return 0; //6תṹ //д } int LinkedList_Rever(SingleNodeList* head) {//7ԭ Linklist pre = NULL, next = NULL, p; p = head->next; //pǵǰڵ㣬prepֱǰnextpĺ while (p != NULL) { next = p->next; p->next = pre; pre = p; p = next; } //д head->next = pre; return 0; } //P111->23->35->47->59 //P18->36->44->52 //ϲP18->11->23->35->35->44->47->52->59 int LinkedList_MergingSort(Linklist p1, Linklist p2) {//8p1p2鲢򣬲p1ͷڵ SingleNodeList* q1, * q2, * q1pre, * tem; q1 = p1->next; q1pre = p1; q2 = p2->next; while (q2 != NULL) { q1 = p1->next; q1pre = p1; while (q1->data < q2->data && q1 != NULL) { q1pre = q1; q1 = q1->next; } if ((tem = (SingleNodeList*)malloc(sizeof(SingleNodeList))) == NULL) { exit(0); } tem->data = q2->data; tem->next = NULL; q1pre->next = tem; tem->next = q1; q2 = q2->next; } return 0; //д } //һΪ 36 -> 37 -> 65 -> 76 -> 97 -> 98 -> 98 -> 98 -> 98 -> 98 //ɾظԪغΪ: 36 -> 37 -> 65 -> 76 -> 97 -> 98 int LinkedList_Sorted_Delete(Linklist head) {//9ɾظԪ Linklist curr = head->next, temp; while (curr->next != NULL) { temp = curr->next; if (temp->data == curr->data) { curr->next = temp->next; } else { curr = curr->next; } } return 0; //д } //10жͷڵ㵥Ƿཻཻأ-12345 int LinkedList_Is_Intersect(Linklist p1, Linklist p2, ElemType* x) { SingleNodeList* q1, * q2, * temp; temp = p1->next; q1 = p1->next; q2 = p2->next; int flag = -1; while (q2 != NULL) { q1 = p1->next; while (q1 != NULL) { if (q1->data == q2->data) { temp = q1; SingleNodeList* q1x, * q2x; q1x = q1; q2x = q2; while (q1x->next != NULL) { q1x = q1x->next; q2x = q2x->next; if (q1x->data == q2x->data) { flag = 1; } else { flag = -1; } } } q1 = q1->next; if (flag == 1) { break; } } q2 = q2->next; if (flag == 1) { break; } } if (flag == 1) { *x = temp->data; } return 0; //д } int main() { SingleNodeList* head, * p, * q; Linklist p1, p2; ElemType i, x, x1, x2; int switch_num; scanf("%d", &switch_num); switch (switch_num) { case 1: LinkedListInit(&head); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 3); LinkedList_PushBack(head, 5); LinkedList_PushBack(head, 7); LinkedList_PushBack(head, 9); LinkedList_PushBack(head, 8); LinkedList_PushBack(head, 6); LinkedList_PushBack(head, 4); LinkedList_PushBack(head, 2); LinkedListShow(head); LinkedList_Divide(head, 5); LinkedListShow(head); break; case 2: LinkedListInit(&head); LinkedList_Add(head, 12345, 5678999); LinkedListShow(head); LinkedList_Rever(head); LinkedListShow(head); break; case 3: LinkedListInit(&head); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 3); LinkedList_PushBack(head, 5); LinkedList_PushBack(head, 7); LinkedList_PushBack(head, 9); LinkedList_PushBack(head, 8); LinkedList_PushBack(head, 6); LinkedList_PushBack(head, 4); LinkedList_PushBack(head, 2); LinkedListShow(head); LinkedList_Rever(head); LinkedListShow(head); break; case 4: LinkedListInit(&p1); LinkedListInit(&p2); LinkedList_PushBack(p1, 11); LinkedList_PushBack(p1, 23); LinkedList_PushBack(p1, 35); LinkedList_PushBack(p1, 47); LinkedList_PushBack(p1, 59); LinkedListShow(p1); LinkedList_PushBack(p2, 8); LinkedList_PushBack(p2, 36); LinkedList_PushBack(p2, 44); LinkedList_PushBack(p2, 52); LinkedListShow(p2); LinkedList_MergingSort(p1, p2); LinkedListShow(p1); break; case 5: LinkedListInit(&head); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 3); LinkedList_PushBack(head, 3); LinkedList_PushBack(head, 3); LinkedList_PushBack(head, 19); LinkedList_PushBack(head, 19); LinkedList_PushBack(head, 26); LinkedList_PushBack(head, 34); LinkedList_PushBack(head, 34); LinkedList_PushBack(head, 34); LinkedList_PushBack(head, 54); LinkedListShow(head); LinkedList_Sorted_Delete(head); LinkedListShow(head); break; case 6: LinkedListInit(&head); LinkedList_PushBack(head, 1); LinkedList_PushBack(head, 3); LinkedList_PushBack(head, 5); LinkedList_PushBack(head, 7); LinkedList_PushBack(head, 9); LinkedList_PushBack(head, 8); LinkedList_PushBack(head, 6); LinkedList_PushBack(head, 4); LinkedList_PushBack(head, 2); LinkedListShow(head); LinkedListInit(&p1); LinkedListInit(&p2); LinkedList_PushBack(p1, 11); LinkedList_PushBack(p1, 23); LinkedList_PushBack(p1, 35); LinkedList_PushBack(p1, 47); LinkedList_PushBack(p1, 59); p = p1; while (p->next != NULL) p = p->next; p->next = head->next; LinkedListShow(p1); LinkedList_PushBack(p2, 8); LinkedList_PushBack(p2, 36); LinkedList_PushBack(p2, 44); LinkedList_PushBack(p2, 52); p = p2; while (p->next != NULL) p = p->next; p->next = head->next; LinkedListShow(p2); LinkedList_Is_Intersect(p1, p2, &x); printf("The intersect node num = %d\n", x); } //LinkedListDestroy(&head); return 0; } /* 1 1 3 5 7 9 8 6 4 2 1 3 4 2 6 8 9 7 2 5 4 3 2 1 9 9 9 8 7 6 5 4 4 3 1 9 6 5 5 6 9 1 3 4 4 3 1 3 5 7 9 8 6 4 2 2 4 6 8 9 7 5 3 1 4 11 23 35 47 59 8 36 44 52 8 11 23 35 36 44 47 52 59 5 1 1 1 1 1 3 3 3 19 19 26 34 34 34 54 1 3 19 26 34 54 6 1 3 5 7 9 8 6 4 2 11 23 35 47 59 1 3 5 7 9 8 6 4 2 8 36 44 52 1 3 5 7 9 8 6 4 2 The intersect node num = 1 */
true
d60109c8130164dc9931c30b949a3ebfb2d7584f
C++
tf2keras/image-computer-processing
/icpl/brightness_mapings.cpp
UTF-8
7,097
2.78125
3
[ "MIT" ]
permissive
#include <vector> #include <opencv2/opencv.hpp> #include <icpl/brightness_mapings.h> #include <icpl/utils.h> namespace icpl { std::vector<uchar> build_LUT(const std::function<uchar(uchar)> &func) { std::vector<uchar> LUT(256); for (auto i = 0; i < 256; i++) { LUT[i] = func(i); } return LUT; } cv::Mat apply_LUTs(const cv::Mat &source, const std::vector<std::vector<uchar>> &LUTs) { cv::Mat result = source.clone(); int rows = result.rows; int cols = result.cols; int channels = result.channels(); if (result.isContinuous()) { cols = rows * cols; rows = 1; } #pragma omp parallel for if(rows > 1) for (int i = 0; i < rows; i++) { uchar *cur_line = result.ptr(i); #pragma omp parallel for if(rows == 1) for (int j = 0; j < cols; j++) { for (int ch = 0; ch < channels; ch++) { int cur_index = j * channels + ch; uchar cur_value = cur_line[cur_index]; cur_line[cur_index] = LUTs[ch][cur_value]; } } } return result; } cv::Mat correct_with_reference_colors(const cv::Mat &source, const cv::Scalar &src_color, const cv::Scalar &dst_color) { if (source.channels() > 4) { throw std::logic_error("correct_with_reference_colors: too much channels!"); } std::vector<std::vector<uchar>> LUTs(source.channels()); #pragma omp parallel for for (int i = 0; i < source.channels(); i++) { float cur_ch_koef = dst_color[i] / (float)src_color[i]; LUTs[i] = build_LUT([&cur_ch_koef](uchar bright) { return cv::saturate_cast<uchar>(bright * cur_ch_koef); }); } cv::Mat result = apply_LUTs(source, LUTs); return result; } cv::Mat apply_gray_world_effect(const cv::Mat &source) { int rows = source.rows; int cols = source.cols; int channels = source.channels(); if (source.isContinuous()) { cols = rows * cols; rows = 1; } std::vector<float> channels_avg(channels); float image_bright_avg = 0.0; #pragma omp parallel for if(rows > 1) for (int i = 0; i < rows; i++) { const uchar *cur_line = source.ptr(i); #pragma omp parallel for if(rows == 1) for (int j = 0; j < cols; j++) { for (int ch = 0; ch < channels; ch++) { channels_avg[ch] += cur_line[j * channels + ch]; } } } for (size_t i = 0; i < channels_avg.size(); i++) { channels_avg[i] /= rows * cols; image_bright_avg += channels_avg[i]; } image_bright_avg /= channels; std::vector<std::vector<uchar>> LUTs(source.channels()); #pragma omp parallel for for (int i = 0; i < source.channels(); i++) { float cur_ch_avg = channels_avg[i]; LUTs[i] = build_LUT([image_bright_avg, &cur_ch_avg](uchar bright) { return cv::saturate_cast<uchar>(bright * image_bright_avg / cur_ch_avg); }); } cv::Mat result = apply_LUTs(source, LUTs); return result; } cv::Mat apply_gamma_correction(const cv::Mat &source, const int power) { if (power < 0 || power > 100) { throw std::out_of_range("apply_gamma_correction: range should be " "in [0..100]"); } int new_power = power - 50; std::vector<std::vector<uchar>> LUTs(source.channels()); #pragma omp parallel for for (int i = 0; i < source.channels(); i++) { LUTs[i] = build_LUT([new_power](uchar bright) { float koef = std::pow(0.9, new_power); float real_val = 255 * std::pow((float)bright / 255.0, koef); return cv::saturate_cast<uchar>(real_val); }); } cv::Mat result = apply_LUTs(source, LUTs); return result; } cv::Mat apply_contrast_correction(const cv::Mat &source, const int power) { if (power < 0 || power > 100) { throw std::out_of_range("apply_gamma_correction: range should be " "in [0..100]"); } int new_power = power - 50; std::vector<std::vector<uchar>> LUTs(source.channels()); #pragma omp parallel for for (int i = 0; i < source.channels(); i++) { LUTs[i] = build_LUT([new_power](uchar bright) { int s1 = 50 - new_power; int r1 = 50 + 87.5 * new_power / 50.0; int s2 = 205 + new_power; int r2 = 205 - 87.5 * new_power / 50.0; if (bright <= r1) { return cv::saturate_cast<uchar>(s1 * bright / (r1 + 1)); } if (bright <= r2) { return cv::saturate_cast<uchar>((bright - r1) * (s2 - s1) / (r2 - r1 + 1) + s1); } return cv::saturate_cast<uchar>((bright - r2) * (255 - s2) / (255 - r2 + 1) + s2); }); } cv::Mat result = apply_LUTs(source, LUTs); return result; } cv::Mat apply_hist_normalization(const cv::Mat &source, const int k, const int b) { std::vector<std::vector<uchar>> LUTs(source.channels()); #pragma omp parallel for for (int i = 0; i < source.channels(); i++) { LUTs[i] = build_LUT([k, b](uchar bright) { return cv::saturate_cast<uchar>(bright * k + b); }); } cv::Mat result = apply_LUTs(source, LUTs); return result; } cv::Mat apply_hist_equalization(const cv::Mat &source) { auto histograms = build_histograms(source); std::vector<std::vector<uchar>> LUTs(source.channels()); #pragma omp parallel for for (int i = 0; i < source.channels(); i++) { auto cur_ch_hist = histograms[i]; float sum = std::accumulate(cur_ch_hist.begin(), cur_ch_hist.end(), 0.0); LUTs[i] = build_LUT([&cur_ch_hist, &sum](uchar bright) { float sub_sum = std::accumulate(cur_ch_hist.begin(), cur_ch_hist.begin() + bright, 0.0); return cv::saturate_cast<uchar>(255.0 * sub_sum / sum); }); } cv::Mat result = apply_LUTs(source, LUTs); return result; } } //namespace icpl
true
ef2a3552ada24b6417f525300c692c474114d6ba
C++
Kiritow/OJ-Problems-Source
/POJ/3040_hankcs.cpp
UTF-8
2,201
2.578125
3
[]
no_license
#include <iostream> #include <functional> #include <algorithm> #include <limits> using namespace std; typedef pair<int, int> Coin; // 硬币 面值和数量 Coin coin[20]; int need[20]; ///////////////////////////SubMain////////////////////////////////// int main(int argc, char *argv[]) { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif int N, C; cin >> N >> C; for (int i = 0; i < N; ++i) { cin >> coin[i].first >> coin[i].second; } int week = 0; // 面额不小于C的一定可以支付一周 for (int i = 0; i < N; ++i) { if (coin[i].first >= C) { week += coin[i].second; coin[i].second = 0; } } sort(coin, coin + N, greater<Coin>()); while(true) { int sum = C; // 等待凑足的sum memset(need, 0, sizeof(need)); // 从大到小 for (int i = 0; i < N; ++i) { if (sum > 0 && coin[i].second > 0) { int can_use = min(coin[i].second, sum / coin[i].first); if (can_use > 0) { sum -= can_use * coin[i].first; need[i] = can_use; } } } // 从小到大 for (int i = N - 1; i >= 0; --i) { if (sum > 0 && coin[i].second > 0) { int can_use = min(coin[i].second - need[i], // 上个loop用掉了一些 (sum + coin[i].first - 1) / coin[i].first); // 允许多出不超过一个面值的金额 if (can_use > 0) { sum -= can_use * coin[i].first; need[i] += can_use; } } } if(sum > 0) { break; } int add_up = numeric_limits<int>::max(); // 凑起来的week数 // add_up多少个最优的week 受限于 每种面值能满足最优解下的需求个数多少次 for (int i = 0; i < N; ++i) { if (need[i] == 0) { continue; } add_up = min(add_up, coin[i].second / need[i]); } week += add_up; // 最优解生效,更新剩余硬币数量 for (int i = 0; i < N; ++i) { if (need[i] == 0) { continue; } coin[i].second -= add_up * need[i]; } } cout << week << endl; #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); system("out.txt"); #endif return 0; } ///////////////////////////End Sub//////////////////////////////////
true
33d0b1359cbb149f8397ab68fa281c493714ff1a
C++
Kodiey/CS2A
/assignment_9/fraction.cpp
UTF-8
4,695
3.890625
4
[]
no_license
/* CS 2A Professor Harden 7/30/2018 fraction.cpp This is an implementation file of the Fraction class. All the methods and members of this class are in fraction.h. The purpose of this program is to compute fractions (+, -, *, /). */ #include <iostream> #include "fraction.h" using namespace std; // This is the Fraction class. This class takes in 0 or 2 parameters. Namely, // numerator and denominator. class Fraction; // This is the default constructor. Fraction::Fraction(){ numerator = 0; denominator = 1; } // Fraction // This is the constructor (and overloading function) when given two inputs: // numerator and denominator. I wrote this->simplify() (simplify()) would have // sufficed but I just wanted Fraction::Fraction(int inNum, int inDenom) { numerator = inNum; denominator = inDenom; this->simplify(); } // Fraction Constructor // This function prints out the Fraction object (numerator/denominator). void Fraction::print() const { cout << numerator << "/" << denominator; } // Fraction::print() // This function takes in a Fraction object and multiplies the two Fractions. // It returns the resulting (product) of two Fractions. Fraction Fraction::multipliedBy(const Fraction &inFrac) const { int newNum, newDenom; newNum = numerator * inFrac.numerator; newDenom = denominator * inFrac.denominator; Fraction newFrac(newNum, newDenom); newFrac.simplify(); return newFrac; } // Fraction::multipledBy // This function takes in a Fraction object and divides the two Fractions. // It returns the quotient of two fractions. Fraction Fraction::dividedBy(const Fraction &inFrac) const { int newNum, newDenom; newNum = numerator * inFrac.denominator; newDenom = denominator * inFrac.numerator; Fraction newFrac(newNum, newDenom); newFrac.simplify(); return newFrac; } // dividedBy() // This function takes in a Fraction object and divides the two Fractions. // It returns the sum of two fractions. Fraction Fraction::addedTo(const Fraction &inFrac) const { int leftNum, rightNum; int newNum, newDenom; leftNum = numerator * inFrac.denominator; rightNum = inFrac.numerator * denominator; newNum = leftNum + rightNum; newDenom = denominator * inFrac.denominator; Fraction newFrac(newNum, newDenom); newFrac.simplify(); return newFrac; } // Fraction::addedTo // This function takes in a fraction object and subtracts the two Fractions. // It returns the difference of two fractions. Fraction Fraction::subtract(const Fraction &inFrac) const { int leftNum, rightNum; int newNum, newDenom; leftNum = numerator * inFrac.denominator; rightNum = denominator * inFrac.numerator; newNum = leftNum - rightNum; newDenom = denominator * inFrac.denominator; Fraction newFrac(newNum, newDenom); newFrac.simplify(); return newFrac; } // Fraction::subtract // This function accesses the data members and changes (or simplify) the // fraction. The two base cases is when the numerator/denomintor is a divisor // of one another. (E.g. 9/3 --> 3/1, and 3/9 --> 1/3) The last condition (else) // naively looks for the greatest common factor between numerator and // denominator. void Fraction::simplify(){ if (numerator % denominator == 0){ numerator = (numerator / denominator); denominator = 1; } else if (denominator % numerator == 0){ numerator = 1; denominator = (denominator / numerator); } else this->reduce(); } // Fraction::simplify // This function uses a crude method O(n) to find the greatest common factor // of the numerator and denomoinator. If the numerator and denominator are both // prime numbers -- this program will not do anything (gcf = 1). void Fraction::reduce(){ int numIterations; if (numerator > denominator) numIterations = denominator; else numIterations = numerator; // Find Greatest Commmon Factor (Naive Approach) int gcf = 1; for (int i = 2; i < numIterations; i++){ if (numerator % i == 0 && denominator % i == 0) gcf = i; } numerator /= gcf; denominator /= gcf; } // Fraction::reduce // Checks if the two Fractions are equivalent. bool Fraction::isEqualTo(const Fraction &inFrac) const { return numerator * inFrac.denominator == denominator * inFrac.numerator; // return (numerator == inFrac.numerator) && (denomintor == inFrac.denomintor); } // Fraction::isEqualTo // Output: // The result starts off at 0/1 // The product of 9/8 and 2/3 is 3/4 // The quotient of 9/8 and 2/3 is 27/16 // The sum of 9/8 and 2/3 is 43/24 // The difference of 9/8 and 2/3 is 11/24 // The two Fractions are not equal. // The product of 3/2 and 2/3 is 1/1
true
86fc56eddb3aa166ec981cc7726825cce0473e36
C++
dariusjlukas/ENES100
/NavSimSimple/Enes100Libraryexamples/Debris.ino
UTF-8
990
2.75
3
[ "MIT" ]
permissive
#include "Enes100.h" void setup() { // Initialize Enes100 library // Team Name, Mission Type, Marker ID, RX Pin, TX Pin Enes100.begin("Duhbree", DEBRIS, 3, 8, 9); Enes100.print("Destination is at ("); Enes100.print(Enes100.destination.x); Enes100.print(", "); Enes100.print(Enes100.destination.y); Enes100.println(")"); // Any other setup code... } void loop() { // Update the OSV's current location if (Enes100.updateLocation()) { Enes100.print("OSV is at ("); Enes100.print(Enes100.location.x); Enes100.print(", "); Enes100.print(Enes100.location.y); Enes100.print(", "); Enes100.print(Enes100.location.theta); Enes100.println(")"); } else { // OSV's location was not found Enes100.println("404 Not Found"); } // Transmit the material of the debris Enes100.mission(STEEL); // Transmit the mass of the debris in grams Enes100.mission(2.43); }
true
5be549972f424997a4652c9b1e036fe7024f116b
C++
wtrnash/LeetCode
/cpp/210课程表 II/210课程表 II.cpp
UTF-8
3,023
3.8125
4
[]
no_license
/* 现在你总共有 n 门课需要选,记为 0 到 n-1。 在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1] 给定课程总量以及它们的先决条件,返回你为了学完所有课程所安排的学习顺序。 可能会有多个正确的顺序,你只要返回一种就可以了。如果不可能完成所有课程,返回一个空数组。 示例 1: 输入: 2, [[1,0]] 输出: [0,1] 解释: 总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。 示例 2: 输入: 4, [[1,0],[2,0],[3,1],[3,2]] 输出: [0,1,2,3] or [0,2,1,3] 解释: 总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。 因此,一个正确的课程顺序是 [0,1,2,3] 。另一个正确的排序是 [0,2,1,3] 。 说明: 输入的先决条件是由边缘列表表示的图形,而不是邻接矩阵。详情请参见图的表示法。 你可以假定输入的先决条件中没有重复的边。 提示: 这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。 通过 DFS 进行拓扑排序 - 一个关于Coursera的精彩视频教程(21分钟),介绍拓扑排序的基本概念。 拓扑排序也可以通过 BFS 完成。 */ //解答:类似题207,用拓扑序列做 #include <vector> #include <set> #include <queue> using namespace std; class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<int> result; if(prerequisites.size() == 0) { for(int i = 0; i < numCourses; i++) { result.push_back(i); } return result; } vector<int> inDegree(numCourses, 0); vector<set<int>> successors(numCourses, set<int>()); for(int i = 0; i < prerequisites.size(); i++) { inDegree[prerequisites[i][0]]++; successors[prerequisites[i][1]].insert(prerequisites[i][0]); } queue<int> q; for(int i = 0; i < inDegree.size(); i++) { if(inDegree[i] == 0) q.push(i); } int count = 0; int index; while(!q.empty()) { index = q.front(); result.push_back(index); q.pop(); count++; for(auto it = successors[index].begin(); it != successors[index].end(); it++) { inDegree[*it]--; if(inDegree[*it] == 0) { q.push(*it); } } } if(count == numCourses) return result; else return vector<int>(); } };
true