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
ae00007e70820a787eb32fc8cbfd7e01bb43f430
C++
zeroch/Planning
/src/main/mainwindow.cpp
UTF-8
4,385
2.609375
3
[]
no_license
#include "mainwindow.h" #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWidget *widget = new QWidget(); QVBoxLayout *m_mainLayout = new QVBoxLayout; setWindowTitle(tr("GTRI")); creatList(); creatDisplay(); creatButtonGroup(); creatLog(); // for layout purpose need top and bot place in diff widget creatTopGroup(); m_mainLayout->addWidget(m_topGroup); creatBotGroup(); m_mainLayout->addWidget(m_botGroup); // work around to place our layout instead of default. widget->setLayout(m_mainLayout); setCentralWidget(widget); } MainWindow::~MainWindow() { } void MainWindow::creatList(){ m_listView = new QListView(this); setCentralWidget(m_listView); QStringListModel *m_model = new QStringListModel(); QStringList m_list; m_list << "RRT* search" << "A*" << "D*"; m_model ->setStringList(m_list); m_listView->setModel(m_model); m_listView->show(); } void MainWindow::creatButtonGroup(){ m_buttonGroup = new QGroupBox(tr("Button Group")); QHBoxLayout *layout =new QHBoxLayout; buttons[0] = new QPushButton(tr("Run")); layout->addWidget(buttons[0]); buttons[1] = new QPushButton(tr("Pause")); layout->addWidget(buttons[1]); buttons[2] = new QPushButton(tr("Stop")); layout->addWidget(buttons[2]); m_buttonGroup->setLayout(layout); //TODO } void MainWindow::creatTopGroup(){ m_topGroup = new QGroupBox(tr("Top Group")); QHBoxLayout *topLayout =new QHBoxLayout; topLayout->addWidget(m_listView); topLayout->addWidget(m_buttonGroup); m_topGroup->setLayout(topLayout); } void MainWindow::creatBotGroup(){ m_botGroup = new QGroupBox(tr("Botton Group")); QHBoxLayout *botLayout =new QHBoxLayout; botLayout->addWidget(m_log); botLayout->addWidget(m_testLog); botLayout->addWidget(m_browseFile); botLayout->addWidget(m_view); m_botGroup->setLayout(botLayout); } void MainWindow::creatDisplay(){ m_image = new QImage(); bool insp = m_image->load(""); if(!insp){ qDebug() << "[DEBUG] image loading error"; } m_scene = new QGraphicsScene(); m_pixItem = new QGraphicsPixmapItem(QPixmap::fromImage(*m_image)); m_scene->addItem(m_pixItem); m_view = new QGraphicsView(m_scene); m_view->show(); m_browseFile = new QPushButton(); m_browseFile->setText("Browse"); connect(m_browseFile,SIGNAL(clicked()),this,SLOT(selectImage())); } void MainWindow::reloadDisplay(){ m_scene->clear(); m_pixItem = new QGraphicsPixmapItem(QPixmap::fromImage(*m_image)); m_scene->addItem(m_pixItem); m_log->append(QString("loading map: %1").arg(fileName)); } void MainWindow::creatLog(){ m_log = new QTextEdit(); m_log->setText("Hello World!\n"); m_log->append("appending some text.."); m_log->setReadOnly(true); m_log->show(); m_testLog = new QPushButton(); m_testLog->setText("Test"); _numTestLog = 0; connect(m_testLog,SIGNAL(released()),this,SLOT(appLog())); } void MainWindow::appLog(){ ++_numTestLog; m_log->append(QString("Updating string by pushbutton: %1 ").arg(_numTestLog)); } void MainWindow::selectImage(){ fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "/home/ze", tr("Image Files (*.png *.jpg *.bmp *.pgm)")); qDebug()<< fileName; // space type should be able determinated. Space *m_space = new Space2D(); m_space->initFromImage(fileName.toStdString().c_str()); //TODO for demo the start and end point on image. int start_arr [] = {170,15}; int end_arr [] = {310,15}; m_log->append(QString("this size of map is %1 and %2").arg(m_space->get_maxDimension(0),m_space->get_maxDimension(1) )); m_space->set_start(start_arr); m_space->set_end(end_arr); qDebug() << m_space->get_start(); qDebug() << m_space->get_image(); m_search = new Astar(m_space); connect(buttons[0], SIGNAL(clicked()),m_search,SLOT(run())); connect(buttons[1], SIGNAL(clicked()),m_search,SLOT(pause())); connect(buttons[2], SIGNAL(clicked()),m_search,SLOT(stop())); // QImage temp_image = QImage(m_space->get_image()); *m_image = temp_image; reloadDisplay(); }
true
b979b2b7c53d12212653c1d3e94df50290bf40b7
C++
dborysen/pool_c-
/day04/ex02/TacticalMarine.cpp
UTF-8
1,848
2.71875
3
[]
no_license
// ************************************************************************** // // // // ::: :::::::: // // TacticalMarine.cpp :+: :+: :+: // // +:+ +:+ +:+ // // By: dborysen <marvin@42.fr> +#+ +:+ +#+ // // +#+#+#+#+#+ +#+ // // Created: 2018/05/31 15:30:20 by dborysen #+# #+# // // Updated: 2018/05/31 15:30:20 by dborysen ### ########.fr // // // // ************************************************************************** // #include "TacticalMarine.hpp" TacticalMarine::TacticalMarine(void) { std::cout << "Tactical Marine ready for battle" << std::endl; return ; } TacticalMarine::TacticalMarine(TacticalMarine &other) { std::cout << "Tactical Marine ready for battle" << std::endl; *this = other; return ; } TacticalMarine::~TacticalMarine() { std::cout << "Aaargh ..." << std::endl; return ; } void TacticalMarine::battleCry(void) const { std::cout << "For the holy PLOT !" << std::endl; return ; } void TacticalMarine::rangedAttack(void) const { std::cout << "* attacks with bolter *" << std::endl; return ; } void TacticalMarine::meleeAttack(void) const { std::cout << "* attacks with chainsword *" << std::endl; return ; } ISpaceMarine *TacticalMarine::clone(void) const { TacticalMarine *clone = new TacticalMarine; return (clone); } TacticalMarine &TacticalMarine::operator = (const TacticalMarine &other) { static_cast<void>(other); return (*this); }
true
c7441d9d45f3bbe87a8a7527588c1d8576be7f92
C++
silky/repobuild
/repobuild/env/resource.h
UTF-8
2,158
2.875
3
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
// Copyright 2013 // Author: Christopher Van Arsdale #ifndef _REPOBUILD_ENV_RESOURCE_H__ #define _REPOBUILD_ENV_RESOURCE_H__ #include <iosfwd> #include <vector> #include <set> #include <string> namespace repobuild { class Resource { public: static Resource FromRootPath(const std::string& root_path); static Resource FromRaw(const std::string& raw_name); // no dirname/basename static Resource FromLocalPath(const std::string& path, const std::string& local); Resource() {} ~Resource() {} // accessors const std::string& path() const { return root_path_; } const std::string& basename() const { return basename_; } const std::string& dirname() const { return dirname_; } bool has_tag(const std::string& tag) const { return tags_.find(tag) != tags_.end(); } const std::set<std::string>& tags() const { return tags_; } // mutators void CopyTags(const Resource& other) { tags_ = other.tags_; } std::set<std::string>* mutable_tags() { return &tags_; } void add_tag(const std::string& tag) { tags_.insert(tag); } // STL stuff (for set<>, etc) ---- bool operator<(const Resource& other) const { return root_path_ < other.root_path_; } bool operator==(const Resource& other) const { return root_path_ == other.root_path_; } private: std::string root_path_, basename_, dirname_; std::set<std::string> tags_; }; extern std::ostream& operator<<(std::ostream& o, const Resource& r); class ResourceFileSet { public: ResourceFileSet() {} ~ResourceFileSet() {} // Files. const std::vector<Resource>& files() const { return files_; } void Add(const Resource& resource) { if (fileset_.insert(resource).second) { files_.push_back(resource); } } template <class T> void AddRange(const T& t) { for (const Resource& it : t) { Add(it); } } std::vector<Resource>::const_iterator begin() const { return files_.begin(); } std::vector<Resource>::const_iterator end() const { return files_.end(); } private: std::set<Resource> fileset_; std::vector<Resource> files_; }; } // namespace repobuild #endif // _REPOBUILD_ENV_RESOURCE_H__
true
3910ad1d792f189083878cd2aea1466cfccf6018
C++
Soogyung1106/Algorithm-Study
/백준/그리디/[1541]잃어버린 괄호/길형.cpp
UTF-8
891
3.375
3
[]
no_license
#include <vector> #include <iostream> #include <string> #include <algorithm> #include <cstdio> #include <cmath> #pragma warning(disable:4996) using namespace std; int main(void) { freopen("input.txt", "r", stdin); string str; cin >> str; int sum = 0; int temp = 0; bool flag = false; for (int i = 0; i < str.size(); i++) { if (str[i] == '-' || str[i] == '+') { if (flag)sum -= temp; // '-' 가 한번이라도 나온 후에는 전부 빼주기 else sum += temp; // '-' 가 나오기 전까지는 더해주기 temp = 0; // temp수를 다시 리셋 if (str[i] == '-')flag = true; // '-'가 나오면 flag를 true } else //숫자가 연속해서 나오는동안은 한 수로 붙이기 { temp *= 10; temp += str[i] - '0'; } } //마지막 남은 숫자 if (flag)sum -= temp; else sum += temp; cout << sum << endl; return 0; }
true
c84b9aab620c49f84e851ba8163329e24ee06e31
C++
lilla021/GraphicsProject
/Plane.cpp
UTF-8
824
2.953125
3
[]
no_license
#include "Plane.h" Plane::Plane() { } Plane::~Plane() { } void Plane::setNormal(glm::vec3 norm) { normal = norm; } void Plane::setPosition(glm::vec3 pos) { position = pos; } void Plane::setAmbient(glm::vec3 amb) { ambient = amb; } void Plane::setDiffuse(glm::vec3 diff) { diffuse = diff; } void Plane::setSpecular(glm::vec3 spec) { specular = spec; } void Plane::setShininess(float shine) { shininess = shine; } glm::vec3 Plane::getNormal() { return normal; } glm::vec3 Plane::getPosition() { return position; } glm::vec3 Plane::getAmbient() { return ambient; } glm::vec3 Plane::getDiffuse() { return diffuse; } glm::vec3 Plane::getSpecular() { return specular; } float Plane::getShininess() { return shininess; }
true
80b827f9a32edf092d41193da97650bce335d59e
C++
hiroki252/BT_1000
/BT_64.cpp
UTF-8
1,702
2.84375
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<math.h> int main() { float a, b, c,X; int k; printf("\nNHAP SO THICH HOP"); printf("\n1. GAI PHUONG TRINH BAC 1"); printf("\n2.GIAI PHUONG TRINH BAC 2"); scanf("%d", &k); switch (k) { case 1: { printf("\nCHUONG TRINH GIAI PHUONG TRINH BAC 1 "); printf("\nA + BX = C"); printf("\nNHAP GIA TRI CUA A = "); scanf("%f",&a); printf("\nNHAP GIA TRI CUA B = "); scanf("%f", &b); printf("\nNHAP GIA TRI CUA C = "); scanf("%f", &c); if (b==0) printf("\nPHUONG TRINH VO NGHIEM"); else X= (c-a)/b; } case 2: { printf("\nPHUONG TRINH GIAI PHUONG TRINH BAC 2"); printf("\NNHAP GIA TRI CUA A = "); printf("\nNHAP GIA TRI CUA B = "); printf("\nNHAP GIA TRI CUA C = "); int delta = b*b-4*a*c; if(delta < 0) printf("\nPHUONG TRINH VO NGHIEM"); else if ( delta = 0 ) { printf("\nPHUONG TRINH CO NGIEM KEP "); X = -b/2*a; printf("\n X = %d", X); } else { printf("\nPHUONG TRINH CO HAI NGHIEM PHAN BIET "); float X1 = (-b+sqrt(delta))/2*a; printf("\nX1 = %f", X1); float X2 = (b+sqrt(delta))/2*a; printf("\nX2 = %f", X2); } } } }
true
76b0c8fa72ba5e782a154554dd6d469518ab5f99
C++
oneapi-src/oneAPI-samples
/DirectProgramming/C++SYCL_FPGA/include/streaming_qri.hpp
UTF-8
11,589
2.96875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef __STREAMING_QRI_HPP__ #define __STREAMING_QRI_HPP__ #include "constexpr_math.hpp" #include "tuple.hpp" #include "unrolled_loop.hpp" namespace fpga_linalg { /* QRI (QR inversion) - Given two matrices Q and R from the QR decomposition of a matrix A such that A=QR, this function computes the inverse of A. - Input matrix Q (unitary/orthogonal) - Input matrix R (upper triangular) - Output matrix I, the inverse of A such that A=QR Then input and output matrices are consumed/produced from/to pipes. */ template <typename T, // The datatype for the computation bool is_complex, // True if T is ac_complex<T> int rows, // Number of rows in the input matrices int columns, // Number of columns in the input matrices int raw_latency, // Read after write latency (in iterations) of // the triangular loop of this function. // This value depends on the FPGA target, the // datatype, the target frequency, etc. // This value will have to be tuned for optimal // performance. Refer to the Triangular Loop // design pattern tutorial. // In general, find a high value for which the // compiler is able to achieve an II of 1 and // go down from there. int pipe_size, // Number of elements read/write per pipe // operation typename QIn, // Q input pipe, receive a full column with each // read. typename RIn, // R input pipe. Receive one element per read. // Only upper-right elements of R are sent. // Sent in row order, starting with row 0. typename IOut // Inverse matrix output pipe. // The output is written column by column > struct StreamingQRI { void operator()() const { // Functional limitations static_assert(rows == columns, "only square matrices with rows==columns are supported"); static_assert(columns >= 4, "only matrices of size 4x4 and upper are supported"); // Set the computation type to T or ac_complex<T> depending on the value // of is_complex using TT = std::conditional_t<is_complex, ac_complex<T>, T>; // Continue to compute as long as matrices are given as inputs while (1) { // Q matrix read from pipe [[intel::private_copies(4)]] // NO-FORMAT: Attribute [[intel::max_replicates(1)]] // NO-FORMAT: Attribute TT q_matrix[rows][columns]; // Transpose of Q matrix [[intel::private_copies(4)]] // NO-FORMAT: Attribute [[intel::max_replicates(1)]] // NO-FORMAT: Attribute TT qt_matrix[rows][columns]; // Transpose of R matrix [[intel::private_copies(4)]] // NO-FORMAT: Attribute [[intel::max_replicates(1)]] // NO-FORMAT: Attribute TT rt_matrix[rows][columns]; // Inverse of R matrix [[intel::private_copies(4)]] // NO-FORMAT: Attribute [[intel::max_replicates(1)]] // NO-FORMAT: Attribute TT ri_matrix[rows][columns]; [[intel::private_copies(2)]] // NO-FORMAT: Attribute [[intel::max_replicates(1)]] // NO-FORMAT: Attribute TT ri_matrix_compute[rows][columns]; // Inverse matrix of A=QR [[intel::private_copies(4)]] // NO-FORMAT: Attribute [[intel::max_replicates(1)]] // NO-FORMAT: Attribute TT i_matrix[rows][columns]; // Transpose the R matrix [[intel::loop_coalesce(2)]] // NO-FORMAT: Attribute for (int row = 0; row < rows; row++) { for (int col = 0; col < columns; col++) { rt_matrix[col][row] = col < row ? TT{0} : RIn::read(); } } // Copy a Q matrix from the pipe to a local memory // Number of pipe reads of pipe_size required to read a full // column constexpr int kExtraIteration = (rows % pipe_size) != 0 ? 1 : 0; constexpr int kLoopIterPerColumn = rows / pipe_size + kExtraIteration; // Number of pipe reads of pipe_size to read all the matrices constexpr int kLoopIter = kLoopIterPerColumn * columns; // Size in bits of the loop iterator over kLoopIter iterations constexpr int kLoopIterBitSize = fpga_tools::BitsForMaxValue<kLoopIter + 1>(); [[intel::initiation_interval(1)]] // NO-FORMAT: Attribute for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) { fpga_tools::NTuple<TT, pipe_size> pipe_read = QIn::read(); int write_idx = li % kLoopIterPerColumn; fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) { fpga_tools::UnrolledLoop<pipe_size>([&](auto t) { if (write_idx == k) { if constexpr (k * pipe_size + t < rows) { q_matrix[li / kLoopIterPerColumn][k * pipe_size + t] = pipe_read.template get<t>(); } } // Delay data signals to create a vine-based data distribution // to lower signal fanout. pipe_read.template get<t>() = sycl::ext::intel::fpga_reg(pipe_read.template get<t>()); }); write_idx = sycl::ext::intel::fpga_reg(write_idx); }); } /* Compute the inverse of R The inverse of R is computed using the following algorithm: RInverse = 0 // matrix initialized to 0 for col=1:n for row=1:col-n // Because Id[row][col] = R[row:] * RInverse[:col], we have: // RInverse[row][col] = (Id[row][col] - R[row:] * RInverse[:col]) /R[col][col] for k=1:n dp = R[col][k] * ri_matrix[row][k] RInverse[row][col] = (Id[row][col] - dp)/R[col][col] */ // Count the total number of loop iterations, using the triangular loop // optimization (refer to the triangular loop optimization tutorial) constexpr int kNormalIterations = columns * (columns + 1) / 2; constexpr int kExtraIterations = raw_latency > rows ? (rows - 1) * (raw_latency - rows) + (rows - 2) * (rows - 1) / 2 : (raw_latency - 2) * (raw_latency - 2 + 1) / 2; constexpr int kTotalIterations = kNormalIterations + kExtraIterations; constexpr bool kThereAreExtraInitIterations = rows - 1 < raw_latency - 1; constexpr int kInitExtraIterations = kThereAreExtraInitIterations ? raw_latency - 1 : rows - 1; constexpr int kInitIterations = (rows - 2) * (rows - 1) / 2 + kInitExtraIterations; // All the loop control variables with all the requirements to apply // some shannonization (refer to the shannonization tutorial) int row = rows - 1; int row_plus_1 = rows; int col = 0; int col_plus_1 = 1; int row_limit = rows - 1; int diag_size = 1; int next_diag_size = 2; int diag_iteration = 0; int diag_iteration_plus_1 = 1; int start_row = rows - 2; int start_row_plus_1 = rows - 1; int start_col = 0; int start_col_plus_1 = 1; int next_row_limit = rows - 1; [[intel::ivdep(raw_latency)]] // NO-FORMAT: Attribute for (int it = 0; it < kTotalIterations + kInitIterations; it++) { // Only perform work when in not dummy iterations if (row < rows & col < columns) { qt_matrix[row][col] = q_matrix[col][row]; TT current_sum = row == col ? TT{1} : TT{0}; TT div_val; fpga_tools::UnrolledLoop<columns>([&](auto k) { auto lhs = rt_matrix[col][k]; auto rhs = (k >= col) || (col < row) ? TT{0} : ri_matrix_compute[row][k]; if (k == col) { div_val = lhs; } current_sum -= lhs * rhs; }); TT result = current_sum / div_val; // Write the result to both the working copy and the final matrix // This is done to only have matrices with a single read and a // single write. ri_matrix_compute[row][col] = result; ri_matrix[row][col] = result; } // Update loop indexes if (row == row_limit) { row_limit = next_row_limit; if constexpr (kThereAreExtraInitIterations) { next_row_limit = (diag_iteration + 2) >= (rows - 2) ? sycl::max(next_diag_size, raw_latency - 1) : rows - 1; } else { next_row_limit = (diag_iteration + 2) >= rows ? sycl::max(next_diag_size - 2, raw_latency - 1) : rows - 1; } diag_size = next_diag_size; int to_sum = diag_iteration >= rows - 2 ? -1 : 1; next_diag_size = diag_size + to_sum; row = start_row; row_plus_1 = start_row_plus_1; col = start_col; col_plus_1 = start_col_plus_1; int start = diag_iteration + 1 - rows + 2; start_col = start < 0 ? 0 : start; start_col_plus_1 = start_col + 1; start_row = start >= 0 ? 0 : -start; start_row_plus_1 = start_row + 1; diag_iteration = diag_iteration_plus_1; diag_iteration_plus_1 = diag_iteration_plus_1 + 1; } else { row = row_plus_1; row_plus_1++; col = col_plus_1; col_plus_1++; } } // Multiply the inverse of R by the transposition of Q [[intel::loop_coalesce(2)]] // NO-FORMAT: Attribute for (int row = 0; row < rows; row++) { for (int col = 0; col < columns; col++) { TT dot_product = {0.0}; fpga_tools::UnrolledLoop<rows>([&](auto k) { if constexpr (is_complex) { dot_product += ri_matrix[row][k] * qt_matrix[col][k].conj(); } else { dot_product += ri_matrix[row][k] * qt_matrix[col][k]; } }); i_matrix[row][col] = dot_product; } // end of col } // end of row // Copy the inverse matrix result to the output pipe [[intel::initiation_interval(1)]] // NO-FORMAT: Attribute for (ac_int<kLoopIterBitSize, false> li = 0; li < kLoopIter; li++) { int column_iter = li % kLoopIterPerColumn; bool get[kLoopIterPerColumn]; fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto k) { get[k] = column_iter == k; column_iter = sycl::ext::intel::fpga_reg(column_iter); }); fpga_tools::NTuple<TT, pipe_size> pipe_write; fpga_tools::UnrolledLoop<kLoopIterPerColumn>([&](auto t) { fpga_tools::UnrolledLoop<pipe_size>([&](auto k) { if constexpr (t * pipe_size + k < rows) { pipe_write.template get<k>() = get[t] ? i_matrix[li / kLoopIterPerColumn][(t * pipe_size) + k] : sycl::ext::intel::fpga_reg( pipe_write.template get<k>()); } }); }); IOut::write(pipe_write); } } // end of while (1) } // end of operator }; // end of struct } // namespace fpga_linalg #endif /* __STREAMING_QRI_HPP__ */
true
ae845b86ffb5988fe6fcf9b3501fd0592e1d28b5
C++
algoriddle/cp
/uva/11292.cc
UTF-8
645
2.890625
3
[ "MIT" ]
permissive
#include <algorithm> #include <iostream> using namespace std; int d[20000], k[20000]; int main() { ios::sync_with_stdio(false); for (int n, m; cin >> n >> m && n && m; ) { for (int i = 0; i < n; i++) { cin >> d[i]; } for (int i = 0; i < m; i++) { cin >> k[i]; } sort(d, d + n); sort(k, k + m); int t = 0; int i = 0; for (int j = 0; i < n && j < m; ) { if (d[i] <= k[j]) { t += k[j]; ++i; ++j; } else { ++j; } } if (i == n) { cout << t << endl; } else { cout << "Loowater is doomed!" << endl; } } return 0; }
true
f29e53b2cfa499d5806e2156e43cb18285efed74
C++
ggandycong/program
/cpp/eventtest/main.cpp
UTF-8
3,357
2.65625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <event.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #define SERVER_PORT 8000 #ifndef null #define null 0 #endif int debug = 0; struct client { int fd; struct bufferevent * buf_ev; }; int setnonblock(int fd) { int flags = fcntl(fd,F_GETFL); flags |= O_NONBLOCK; fcntl(fd,F_SETFL,flags); } void buf_read_callback(struct bufferevent *incoming,void *arg) { struct evbuffer *evreturn; char *req; req = evbuffer_readline(incoming->input); if (req == null) { return; } struct client *client = (struct client *)arg; if (strcmp(req,"bye") == 0) { } evreturn = evbuffer_new(); evbuffer_add_printf(evreturn,"You said %s\n",req); bufferevent_write_buffer(incoming,evreturn); evbuffer_free(evreturn); free(req); } void buf_write_callback(struct bufferevent * bev, void *arg) { } void buf_error_callback(struct bufferevent *bev,short what, void *arg) { struct client *client = (struct client *)arg; bufferevent_free(client->buf_ev); close(client->fd); printf("Error ,reason %d",what); free(client); } void accept_callback(int fd,short ev,void *arg) { int client_fd; struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); struct client *client; client_fd = accept(fd,(struct sockaddr *)&client_addr,&client_len); if (client_fd < 0) { printf("Client: accept() failed"); return; } setnonblock(client_fd); client = (struct client *)calloc(1,sizeof(struct client)); if (client == null) { printf("malloc failed"); return; } client->fd = client_fd; client->buf_ev = bufferevent_new(client_fd,buf_read_callback, buf_write_callback, buf_error_callback, client); bufferevent_enable(client->buf_ev,EV_READ); struct evbuffer *evreturn = evbuffer_new(); evbuffer_add_printf(evreturn,"Hello ,Welcome ! input bye to quit!\n"); bufferevent_write_buffer(client->buf_ev,evreturn); evbuffer_free(evreturn); } int main() { int socketlisten; struct sockaddr_in addresslisten; struct event accept_event; int reuse = 1; event_init(); socketlisten = socket(AF_INET,SOCK_STREAM,0); if (socketlisten < 0) { fprintf(stderr,"Fail to create listen socket!"); return 1; } memset(&addresslisten,0,sizeof(addresslisten)); addresslisten.sin_family = AF_INET; addresslisten.sin_addr.s_addr = INADDR_ANY; addresslisten.sin_port = htons(SERVER_PORT); if (bind(socketlisten,(struct sockaddr *)&addresslisten,sizeof(addresslisten)) < 0) { fprintf(stderr,"Failed to bind"); return 1; } if (listen(socketlisten,5)< 0) { fprintf(stderr,"Failed to listen to socket"); return 1; } setsockopt(socketlisten,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)); setnonblock(socketlisten); event_set(&accept_event,socketlisten,EV_READ|EV_PERSIST,accept_callback,NULL); event_add(&accept_event,NULL); event_dispatch(); close(socketlisten); printf("hello world!"); return 0; }
true
d9de46e62524ce134b3e272ddad47350a46c2bd0
C++
oraoto/pulsar-client-phpcpp
/src/MessageId.cpp
UTF-8
1,456
2.78125
3
[ "MIT" ]
permissive
#include "MessageId.h" #include <string> #define MESSAGE_ID_CLASS_NAME "Pulsar\\MessageId" MessageId::MessageId(pulsar::MessageId messageId) { this->messageId = messageId; } static Php::Value earliest() { auto messageId = new MessageId(pulsar::MessageId::earliest()); return Php::Object(MESSAGE_ID_CLASS_NAME, messageId); } static Php::Value latest() { auto messageId = new MessageId(pulsar::MessageId::latest()); return Php::Object(MESSAGE_ID_CLASS_NAME, messageId); } Php::Value MessageId::getTopicName() { return this->messageId.getTopicName(); } void MessageId::setTopicName(Php::Parameters &params) { return this->messageId.setTopicName(params[0]); } Php::Value MessageId::deserialize(Php::Parameters &params) { auto messageId = new MessageId(pulsar::MessageId::deserialize(params[0])); return Php::Object(MESSAGE_ID_CLASS_NAME, messageId); } Php::Value MessageId::serialize(Php::Parameters &params) { std::string *result = new std::string(); this->messageId.serialize(*result); return result; } void registerMessageId(Php::Namespace &pulsarNamespace) { Php::Class<MessageId> messageId("MessageId"); messageId.method<&MessageId::earliest>("earliest"); messageId.method<&MessageId::latest>("latest"); messageId.method<&MessageId::getTopicName>("getTopicName"); messageId.method<&MessageId::serialize>("serialize"); messageId.method<&MessageId::deserialize>("deserialize"); }
true
1d4fa0eb8c0f3e77a478bd1fa061108970ea9890
C++
TheKrzyko/SokobanSDL
/SDLProjekt/Vector2.h
UTF-8
1,465
3.375
3
[ "MIT" ]
permissive
#pragma once template <typename t> class Vector2 { public: static Vector2<t> lerp(Vector2<t> start, Vector2<t> end, double progress) { if (progress >= 1) return end; if (progress <= 0) return start; return (end - start)*progress + start; } Vector2() { } Vector2(t X, t Y) { x = X; y = Y; } Vector2<t>& operator=(const Vector2<t>& v) { x = v.x; y = v.y; return *this; } Vector2<t> operator+(const Vector2<t>& v2)const { return Vector2<t>(x + v2.x, y + v2.y); } Vector2<t> operator-(const Vector2<t>& v2)const { return Vector2<t>(x - v2.x, y - v2.y); } Vector2<t> operator*(const Vector2<t>& v2)const { return Vector2<t>(x*v2.x, y*v2.y); } Vector2<t> operator*(const t& val) { return Vector2<t>(x*val, y*val); } Vector2<t> operator/(const Vector2<t>& v2)const { return Vector2<t>(x / v2.x, y / v2.y); } Vector2<t>& operator+=(const Vector2<t>& v) { x += v.x; y += v.y; return (*this); } Vector2<t>& operator-=(const Vector2<t>& v) { x -= v.x; y -= v.y; return (*this); } Vector2<t>& operator*=(const Vector2<t>& v) { x *= v.x; y *= v.y; return (*this); } Vector2<t>& operator/=(const Vector2<t>& v) { x /= v.x; y /= v.y; return (*this); } bool operator==(const Vector2<t>& v) { return x == v.x && y == v.y; } bool operator!=(const Vector2<t>& v) { return x != v.x || y != v.y; } t x; t y; }; using Vector2f = Vector2<float>; using Vector2i = Vector2<int>;
true
e18e768fb83c5383df5d8c326d9e3498b98df219
C++
hleal18/libraries
/Press/Examples/Pressure with PCF8591/main.cpp
UTF-8
788
2.71875
3
[]
no_license
#include <Arduino.h> #include "Press.h" #include "PCF8591.h" // PCF configuration #define PCF_ADDRESS 0x48 #define PCF_SDA_PIN D2 #define PCF_SCL_PIN D1 PCF8591 pcf48(PCF_ADDRESS, PCF_SDA_PIN, PCF_SCL_PIN); // pressure sensor configuration // Pin number should correspond to an // available pin at PCF8591. #define PRESS_ANALOG_PIN 1 Press pressure_sensor(PRESS_ANALOG_PIN, pcf48, [](uint16_t kpa) { Serial.print("Pressure is: "); Serial.print(kpa); Serial.println(" kpa"); }); void setup() { Serial.begin(9600); pcf48.iniciar(); pressure_sensor.begin(); } void loop() { // Invokes the callback with the pressure // read as kpa units. // Reads from the PCF8591 pin configured // inside of it. pressure_sensor.handle(); delay(200); }
true
a49daf16cd204b277e6d461cbd779181f01391e7
C++
Linyxus/game-system
/game-system/manager.cc
UTF-8
8,964
2.53125
3
[]
no_license
#include "manager.h" #include <cmath> #include <fstream> #include <string> #include <sstream> #include <iostream> using namespace std; Random::Random() { generator = default_random_engine(time(NULL)); pointDis = uniform_int_distribution<int>(1,6); probDis = uniform_int_distribution<int>(1,100); } int Random::randPoint() { return pointDis(generator); } bool Random::hitted(int prob) { return (probDis(generator) <= prob); } int Random::randProb() { return probDis(generator); } Manager::Manager() { } Manager::~Manager() { for (int i = 0; i < m_ctls.size(); i++) delete (m_ctls[i]); } template<typename T> double _SUM(const T& vec) { double s = 0.0; for (auto it = vec.begin(); it != vec.end(); it++) { if (*it != -1) { s += (*it); } } return s; } template <typename T> double _GET_P(const T& vec, int index) { double sum = _SUM(vec); return double(vec[index]) / sum; } void Manager::run() { int r = 0; int arred = 0; while (true) { bool ended = true; vector<int> lens; vector<int> credits; vector<int> coins; //vector<double> diffics; vector<double> probs; for (int i = 0; i < m_cars.size(); i++) { lens.push_back(-1); credits.push_back(-1); coins.push_back(-1); //diffics.push_back(-1); probs.push_back(-1); } for (int i = 0; i < m_cars.size(); i++) { if (m_recorder.status(i) == Recorder::OUT || m_recorder.status(i) == Recorder::REACH) continue; ended = false; m_recorder.newTurn(i); Car& car = m_cars[i]; double sr = car.speedRate(); if (!car.turnable()) continue; int step = random->randPoint(); step = round(double(step) * sr); Path path = car.decidePath(step); car.pos = path.positions[path.positions.size() - 1]; for (int ip = 0; ip < m_places.size(); ip++) { Manager::PlaceStatus ps = getPlaceStatus(m_places[ip], path); if (ps == Manager::LEAVE) { m_places[i]->onLeave(car, path); } if (ps == Manager::VISIT) { m_places[i]->onVisit(car, path); } if (ps == Manager::STAY) { m_places[i]->onStay(car, path); } if (ps == Manager::PASS) { m_places[i]->onPass(car, path); } } if (car.outed()) { m_recorder.setStatus(i, Recorder::OUT); } if (m_map->posEqual(car.pos, car.dest)) { m_recorder.setStatus(i, Recorder::REACH); m_recorder.setRanking(i, arred++); } //caculate shortest path Path sp = m_map->caculatePath(car.pos, car.dest); int len = m_map->pathLen(sp); //double diffic = caculateDiffic(sp); lens[i] = len; //diffics[i] = diffic; coins[i] = car.coins(); credits[i] = car.credits(); probs[i] = car.controller->prob; } if (ended) { break; } else { for (int i = 0; i < m_cars.size(); i++) { if (probs[i] == -1) continue; Record rec; rec.coins = coins[i]; rec.pcoins = _GET_P(coins, i); rec.credits = credits[i]; rec.pcredits = _GET_P(credits, i); rec.length = lens[i]; rec.plength = _GET_P(lens, i); //rec.diffic = diffics[i]; //rec.pdiffic = _GET_P(diffics, i); rec.prob = probs[i]; rec.pprob = _GET_P(probs, i); m_recorder.addRecord(i, rec); } } } } void Manager::init(Map * map, int cars, vector<Position> poss, vector<Controller*> ctls, Car initialCar) { m_map = map; for (int i = 0; i < cars; i++) { m_recorder.addCar(); m_cars.push_back(initialCar); m_cars[i].pos = poss[i]; m_cars[i].controller = ctls[i]; m_cars[i].setManager(this); m_cars[i].dest = dest[i]; } for (int i = 0; i < cars; i++) { m_cars[i].controller->m_parent = &(m_cars[i]); } } void Manager::initFromFile(Map * map, string fn) { std::ifstream t(fn); std::stringstream buffer; buffer << t.rdbuf(); std::string contents(buffer.str()); stringstream ss(contents); int n; vector<Position> poses; ss >> n; for (int i = 0; i < n; i++) { int rid, rpos; ss >> rid >> rpos; Position pos; pos.rid = rid; pos.rpos = rpos; poses.push_back(pos); } for (int i = 0; i < n; i++) { Car tmp(this); double prob; ss >> prob; Controller *ctl = new AI(); ctl->prob = prob; m_ctls.push_back(ctl); } int iniCoins, iniCredits; ss >> iniCoins >> iniCredits; Car car(this); car.setCoins(iniCoins); car.setCredits(iniCredits); for (int i = 0; i < n; i++) { int rid, rpos; ss >> rid >> rpos; Position pos; pos.rid = rid; pos.rpos = rpos; dest.push_back(pos); } init(map, n, poses, m_ctls, car); } Manager::PlaceStatus Manager::getPlaceStatus(Place* place, Path path) const { return getPlaceStatus(place->range(), path); } Manager::PlaceStatus Manager::getPlaceStatus(Range place, Path path) const { if (path.positions.size() == 0) return Manager::PlaceStatus::NONE; else if (path.positions.size() == 1) { if (place.in(path.positions[0])) return Manager::PlaceStatus::STAY; else return Manager::PlaceStatus::NONE; } else if (path.positions.size() == 2) { bool begin = place.in(path.positions[0]); bool end = place.in(path.positions[1]); if (begin && end) { return Manager::PlaceStatus::STAY; } if ((!begin) && (!end)) { return Manager::PlaceStatus::NONE; } if ((!begin) && end) { return Manager::PlaceStatus::VISIT; } if (begin && (!end)) { return Manager::PlaceStatus::LEAVE; } } else { //path positions >= 3 bool begin = place.in(path.positions[0]); bool end = place.in(path.positions[path.positions.size() - 1]); bool mid = false; for (int i = 1; i < path.positions.size() - 1; i++) { if (place.in(path.positions[i])) { mid = true; break; } } if (begin && end) return Manager::PlaceStatus::STAY; else if (begin && (!end)) return Manager::PlaceStatus::LEAVE; else if ((!begin) && end) return Manager::PlaceStatus::VISIT; else if ((!begin) && (!end) && mid) return Manager::PlaceStatus::PASS; else return Manager::PlaceStatus::NONE; } return Manager::PlaceStatus::NONE; } double Manager::caculateDiffic(Path path) const { double d = 0.0; for (int i = 0; i < path.positions.size(); i++) { Position pos = path.positions[i]; for (int j = 0; j < m_places.size(); j++) { if (m_places[i]->in(pos)) d += m_places[i]->diffic(); } } return d; } void Manager::_DISPLAY_CARS() const { cout << "### Manager Car Data:" << endl; for (int i = 0; i < m_cars.size(); i++) { cout << "<<<< Car #" << i << endl; cout << "Probability: " << m_cars[i].controller->prob << endl; cout << "Coins: " << m_cars[i].coins() << endl; cout << "Credits: " << m_cars[i].credits() << endl; cout << "Position: " << m_cars[i].pos.rid << ", " << m_cars[i].pos.rpos << endl; cout << "Destnation: " << dest[i].rid << ", " << dest[i].rpos << endl; } cout << endl; } Recorder::Recorder() { } void Recorder::output(string fn) const { ofstream fout; fout.open(fn, ios_base::app); fout << "prob,pprob,len,plen,coins,pcoins,credits,pcredits,outcome,outed" << endl; for (int i = 0; i < m_records.size(); i++) { const Records &recs = m_records[i]; for (int j = 0; j < recs.size(); j++) { Record rec = recs[j]; fout << rec.prob << "," << rec.pprob << "," << rec.length << "," << rec.plength << "," //<< rec.diffic << "," //<< rec.pdiffic << "," << rec.coins << "," << rec.pcoins << "," << rec.credits << "," << rec.pcredits << "," << ranking(i) << "," << ((status(i) == Recorder::OUT) ? 1 : 0) << endl; } } fout.close(); } void Recorder::append(string fn) const { ofstream fout; fout.open(fn, ios_base::app); fout << "prob,pprob,len,plen,coins,pcoins,credits,pcredits,outcome,outed" << endl; for (int i = 0; i < m_records.size(); i++) { const Records &recs = m_records[i]; for (int j = 0; j < recs.size(); j++) { Record rec = recs[j]; if (rec.plength == 0) fout << rec.prob << "," << rec.pprob << "," << rec.length << "," << rec.plength << "," //<< rec.diffic << "," //<< rec.pdiffic << "," << rec.coins << "," << rec.pcoins << "," << rec.credits << "," << rec.pcredits << "," << ranking(i) << "," << ((status(i) == Recorder::OUT) ? 1 : 0) << endl; } } fout.close(); } void Recorder::addRecord(int index, Record record) { m_records[index].push_back(record); } int Recorder::addCar() { m_records.push_back(Recorder::Records()); m_status.push_back(Recorder::RUN); m_rankings.push_back(0); m_turns.push_back(0); return m_records.size() - 1; } void Recorder::setStatus(int index, CarStatus cs) { m_status[index] = cs; } void Recorder::setRanking(int index, int r) { m_rankings[index] = r; } Recorder::CarStatus Recorder::status(int index) const { return m_status[index]; } int Recorder::ranking(int index) const { return m_rankings[index]; } int Recorder::result(int index) const { if (m_status[index] == Recorder::OUT) return -1; else return m_rankings[index]; } int Recorder::turns(int index) const { return m_turns[index]; } void Recorder::newTurn(int index) { m_turns[index]++; }
true
069788d4bd3f83cc09630fd3549b9b916b508744
C++
benharri/cs201
/PG5/ArrayLL.h
UTF-8
1,669
3.453125
3
[]
no_license
//Ben Harris //Template for an linked list that can be used as a array. #ifndef _ARRAYLL_ #define _ARRAYLL_ #include <iostream> #include <string> #include <cstdlib> #include "ArrayLLN.h" using namespace std; template <class T> class ArrayLL{ private: ArrayLLN<T> * head; public: ArrayLL(){ head = nullptr; } ~ArrayLL(){ delete head; } void sethead(ArrayLLN<T>* t){ head = t; } int length(){ // returns length of the list int cnt = 0; for (ArrayLLN<T>*P = head; P != nullptr; cnt++, P = P->getnext()); return cnt; } T remove(int pos){ // removes the node at pos ArrayLLN<T> *P = head, *Q = nullptr; for (int cnt = 0; cnt < pos; cnt++, Q = P, P = P->getnext()); T tempcontents = P->getcontents(); P->removeself(P, Q, this); return tempcontents; } T& operator[] (const int pos){ // overloads [], which returns a reference to the node at pos ArrayLLN<T>* P = head; for (int cnt = 0; cnt < pos; cnt++, P = P->getnext()); return P->getcontents(); } void insert(int pos, T stuff){ // inserts a node at pos with stuff contents if (pos == 0) head = new ArrayLLN<T>(stuff, head); // insert at head, with head as next pointer else if (pos > 0 && pos < length()){ // if inserting not at the head or tail ArrayLLN<T> *P = head, *Q = nullptr; for (int i = 0; i < pos; i++, Q = P, P = P->getnext()); if (Q) Q->setnext(new ArrayLLN<T>(stuff, P)); else P->setnext(new ArrayLLN<T>(stuff, P->getnext())); } else if (pos == length()) // if inserting at the tail. if (head == NULL) head = new ArrayLLN<T>(stuff, NULL); else head->addback(stuff); else return; } }; #endif
true
7e86f2d69ca49b189da7ed6e4c750e377a99bd64
C++
Mustafiz48/Programming_Codes
/DSA/merge sort diye devide and coquer shikhi.cpp
UTF-8
1,364
3.484375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int arr[123456]; void mergeit(int arr[],int l,int m,int r) { int n1=m-l+1; //left array size int n2=r-m; //right array size int temp1[n1]; int temp2[n2]; for(int i=0;i<n1;i++) { temp1[i]=arr[l+i]; } for(int i=0;i<n2;i++) { temp2[i]=arr[m+i+1]; } int i=0; //index for temp1 int j=0; //index for temp2 int k=l; //index for main array while(i<n1 && j<n2) { if(temp1[i]<=temp2[j]) // comparing arrays { arr[k]=temp1[i]; i++; k++; } else { arr[k]=temp2[j]; j++; k++; } } while(i<n1) //copying what's left of array 1 { arr[k]=temp1[i]; k++; i++; } while(j<n2) // copying what's left of array2 { arr[k]=temp2[j]; k++; j++; } } void mergesort(int arr[],int l,int r) { if(l<r) { int m=(l+r)/2; mergesort(arr,l,m); mergesort(arr,m+1,r); mergeit(arr,l,m,r); // marging two copies of array } } int main() { int n; cin>>n; for(int i=0;i<n;i++) { cin>>arr[i]; } mergesort(arr,0,n-1); for(int i=0;i<n;i++) { cout<<arr[i]<<" "; } return 0; }
true
191b1f3ee06de198c8f3dd18969586b0a4d30640
C++
ahmamani/CCOMP-Verano
/12_estructura_de_datos/pila/main.cpp
UTF-8
262
2.953125
3
[]
no_license
#include <iostream> #include "MyStack.h" using namespace std; int main() { MyStack<int> s, r; s.push(1); s.push(2); s.push(3); r.push(4); r.push(5); r.push(6); MyStack<int> t = s + r; cout << t << endl; return 0; }
true
2f98be62fc5204791878c2004667581bb16d7e61
C++
iTXCode/Review
/cpp_base/day13_template_plus/test/template.cc
UTF-8
658
3.28125
3
[]
no_license
#include<iostream> #include<string.h> using namespace std; struct TrueType{ static bool Get(){ return false; } }; struct FalseType{ static bool Get(){ return false; } }; template <class T> struct TypeTraits{ typedef FalseType IsPODType; }; template<class T> void Copy(T* dst, const T* src, size_t size) { if(TypeTraits<T>::IsPODType::Get()) memcpy(dst, src, sizeof(T)*size); else {for(size_t i = 0; i < size; ++i) dst[i] = src[i]; } } int main() { int a1[] = {1,2,3,4,5,6,7,8,9,0}; int a2[10]; Copy(a2, a1, 10); string s1[] = {"1111", "2222", "3333", "4444"}; string s2[4]; Copy(s2, s1, 4); return 0; }
true
4ba3cbd6315b0699e06708e9161e21581449b574
C++
Ritesh-saini/NASSCOM-MHRD-IOT-Practical-Module_1-2
/Submissions/Radhika_Mishra/Practial 1/Fading.ino
UTF-8
352
2.90625
3
[ "CC0-1.0" ]
permissive
int brightness = 0; void setup() { pinMode(9, OUTPUT); } void loop() { for(brightness = 0; brightness <= 255; brightness += 5) { analogWrite(9, brightness); delay(50); // Wait for 50 millisecond(s) } for(brightness = 255; brightness >0; brightness -= 5) { analogWrite(9, brightness); delay(50); // Wait for 50 millisecond(s) } }
true
23e54c81337b26c1540cf2a21cde320ef1ef1022
C++
ahmadner/100Questions_cpp
/3.cpp
UTF-8
183
3.1875
3
[]
no_license
// 3. Write C++ Program to print your name 100 times. #include <iostream> using namespace std; int main (){ for (int count=1 ; count<=100;count++){ cout<<count<<". Ahmad\n"; } }
true
121708b232e5283eaf4221de140b6fdaf41677cd
C++
benahedron/scanahedron
/src/scanner/scanservice.cpp
UTF-8
2,794
2.765625
3
[ "MIT" ]
permissive
#include "scanservice.h" #include "iscannerinterface.h" #include <png.hpp> #include <iostream> ScanService::ScanService(IScannerInterfacePtr interface_) : interface(interface_) { if (!interface) { throw std::runtime_error("No scanner interface given!"); } if (!interface->init()) { throw std::runtime_error("Could not initialize scanner interface!"); } } ScanService::~ScanService() { if (interface) { interface->exit(); } } void ScanService::loadScanners() { availableScanners = interface->getDevices(); } const std::vector<ScannerDeviceDescriptorPtr> &ScanService::getAvailableScanners() { if (availableScanners.empty()) { loadScanners(); } return availableScanners; } ScannerDeviceDescriptorPtr ScanService::getActualDevice(ScannerDeviceDescriptorPtr device) { if (device == nullptr) { const auto &scanners = getAvailableScanners(); if (scanners.empty()) { throw std::runtime_error("No scanner found!"); } return scanners[0]; } return device; } ScannerCapabilities ScanService::getCapabilities(ScannerDeviceDescriptorPtr device) { ScannerDeviceDescriptorPtr actualDevice = getActualDevice(device); return interface->getCapabilities(actualDevice); } ScannerConfiguration ScanService::getConfiguration(ScannerDeviceDescriptorPtr device) { ScannerDeviceDescriptorPtr actualDevice = getActualDevice(device); return interface->getConfiguration(actualDevice); } void ScanService::setConfiguration(ScannerDeviceDescriptorPtr device, const ScannerConfiguration &configuration) { ScannerDeviceDescriptorPtr actualDevice = getActualDevice(device); interface->setConfiguration(actualDevice, configuration); } RawImagePtr ScanService::scanToBuffer(ScannerDeviceDescriptorPtr device) { ScannerDeviceDescriptorPtr actualDevice = getActualDevice(device); return interface->scanToBuffer(actualDevice); } bool ScanService::scanToFile(ScannerDeviceDescriptorPtr device, const std::string &destinationPath) { RawImagePtr buffer = scanToBuffer(device); if (buffer == nullptr) { return false; } png::image<png::rgb_pixel> image(buffer->width, buffer->height); unsigned char *pivot = buffer->pixels; for (int y = 0; y < buffer->height; ++y) { for (int x = 0; x < buffer->width; ++x) { if (buffer->bytesPerPixel == 3) { image[y][x] = png::rgb_pixel(*pivot++, *pivot++, *pivot++); } else if (buffer->bytesPerPixel == 1) { image[y][x] = png::rgb_pixel(*pivot, *pivot, *pivot++); } } } image.write(destinationPath); return true; }
true
7b91b2ebe3e1c843e10234c251545e94be09ecb1
C++
HWMooo/Black_Jack
/Game.cpp
UTF-8
7,953
2.984375
3
[]
no_license
// // Created by Harry Moore // #include <iostream> #include <vector> #include "Game.h" #include "Card.h" Game::Game(const std::vector<std::string>& names) { std::vector<std::string>::const_iterator ThePlayerNames; for (ThePlayerNames = names.begin(); ThePlayerNames != names.end(); ++ThePlayerNames) _Players.emplace_back(Player(*ThePlayerNames)); srand(time(NULL)); _DeckOnTheTable.FillTheDeck(); _DeckOnTheTable.Shuffle(); } //Actual game //user input required //deals with outcomes //clears hands and decks and re shuffles void Game::PlayBlackJack(){ // Shuffles multiple decks to avoid repetition. int random = rand() % 10000; for(int i = 0; i < random; i++){ _DeckOnTheTable.Shuffle(); } std::vector<Player>::iterator PeoplePlayers; float input = 0; std::string AddABot; int AddAnotherBot = 0; std::cout << "Would like to add a bot (y/n) ?"; std::cin >> AddABot; if(AddABot == "Y" || AddABot == "y") { std::cout << "How Many would you like to add? (1/2)"; std::cin >> AddAnotherBot; } while(!noBet) { if(AddAnotherBot == 1){ _SydneyOnTheTable.ShowBotOneBankRoll(); _SydneyOnTheTable.ShowBotOneBet(); } if(AddAnotherBot == 2){ _SydneyOnTheTable.ShowBotOneBankRoll(); _SydneyOnTheTable.ShowBotOneBet(); _AlexOnTheTable.ShowBotTwoBankRoll(); _AlexOnTheTable.ShowBotTwoBet(); } for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { PeoplePlayers->ShowBankRoll(); PeoplePlayers->Betup(); std::cin >> input; while(std::cin.fail()){ std::cout << "Error, please try again : £"; std::cin.clear(); std::cin.ignore(256, '\n'); std::cin >> input; } PeoplePlayers->Bet(input); if(PeoplePlayers->BetCorrect(input)) { noBet = true; } else if(!PeoplePlayers->BetCorrect(input)) {; noBet = false; } } } if(noBet == true) { for (int i = 0; i < 2; ++i) { for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { _DeckOnTheTable.Shuffle(); _DeckOnTheTable.DealACard(*PeoplePlayers); } _DeckOnTheTable.DealACard(_House); } _House.FlipFirstCard(); for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { std::cout << *PeoplePlayers << std::endl; } if (AddAnotherBot == 1) { for (int i = 0; i < 2; ++i) { _DeckOnTheTable.DealACard(_SydneyOnTheTable); } std::cout << _SydneyOnTheTable << std::endl; _DeckOnTheTable.ContinueToDeal(_SydneyOnTheTable); } if (AddAnotherBot == 2) { for (int i = 0; i < 2; ++i) { _DeckOnTheTable.DealACard(_SydneyOnTheTable); _DeckOnTheTable.DealACard(_AlexOnTheTable); } std::cout << _SydneyOnTheTable << std::endl; std::cout << _AlexOnTheTable << std::endl; _DeckOnTheTable.ContinueToDeal(_SydneyOnTheTable); _DeckOnTheTable.ContinueToDeal(_AlexOnTheTable); } std::cout << _House << std::endl; for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { _DeckOnTheTable.ContinueToDeal(*PeoplePlayers); } _House.FlipFirstCard(); std::cout << std::endl << _House; _DeckOnTheTable.ContinueToDeal(_House); if (_House.IsBust()) { if (!_SydneyOnTheTable.IsBust() || !_AlexOnTheTable.IsBust()) { if (AddAnotherBot == 1 || _SydneyOnTheTable.TotalValue() <= 20) { _SydneyOnTheTable.BotOneWins(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.TotalValue() <= 20) { _AlexOnTheTable.BotTwoWins(); } else if (AddAnotherBot == 1 || _SydneyOnTheTable.TotalValue() == 21) { _SydneyOnTheTable.BotOneBlackJack(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.TotalValue() == 21) { _AlexOnTheTable.BotTwoBlackJack(); } } for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { if (!PeoplePlayers->IsBust() && PeoplePlayers->TotalValue() <= 20) { PeoplePlayers->winsBet(); } if (PeoplePlayers->IsBlackJack()) { PeoplePlayers->BlackJackWin(); } } } else if (!_House.IsBust()) { if (AddAnotherBot == 1 || _SydneyOnTheTable.IsBlackJack() && _House.IsBlackJack()) { _SydneyOnTheTable.BotOneTies(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.IsBlackJack() && _House.IsBlackJack()) { _AlexOnTheTable.BotTwoTies(); } if (AddAnotherBot == 1 || _SydneyOnTheTable.IsBlackJack() && !_House.IsBlackJack()) { _SydneyOnTheTable.BotOneBlackJack(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.IsBlackJack() && !_House.IsBlackJack()) { _AlexOnTheTable.BotTwoBlackJack(); } if (AddAnotherBot == 1 || _SydneyOnTheTable.TotalValue() > _House.TotalValue() && !_SydneyOnTheTable.IsBust() && !_SydneyOnTheTable.IsBlackJack()) { _SydneyOnTheTable.BotOneWins(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.TotalValue() > _House.TotalValue() && !_AlexOnTheTable.IsBust() && !_AlexOnTheTable.IsBlackJack()) { _AlexOnTheTable.BotTwoWins(); } if (AddAnotherBot == 1 || _SydneyOnTheTable.TotalValue() < _House.TotalValue()) { _SydneyOnTheTable.BotOneLoses(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.TotalValue() < _House.TotalValue()) { _AlexOnTheTable.BotTwoLoses(); } if(AddAnotherBot == 1 || _SydneyOnTheTable.IsBust()){ _SydneyOnTheTable.BotOneLoses(); }else if(AddAnotherBot == 2 && _AlexOnTheTable.IsBust()){ _AlexOnTheTable.BotTwoLoses(); } if (AddAnotherBot == 1 || _SydneyOnTheTable.TotalValue() == _House.TotalValue()) { _SydneyOnTheTable.BotOneTies(); } else if (AddAnotherBot == 2 && _AlexOnTheTable.TotalValue() == _House.TotalValue()) { _AlexOnTheTable.BotTwoTies(); } for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { if (!PeoplePlayers->IsBust()) { if (PeoplePlayers->IsBlackJack()) { PeoplePlayers->BlackJackWin(); } else if (PeoplePlayers->IsBlackJack() && _House.IsBlackJack()) { PeoplePlayers->tieBet(); } else if (PeoplePlayers->TotalValue() > _House.TotalValue()) { PeoplePlayers->winsBet(); } else if (PeoplePlayers->TotalValue() < _House.TotalValue()) { PeoplePlayers->losesBet(); } else { PeoplePlayers->tieBet(); } } } } } for (PeoplePlayers = _Players.begin(); PeoplePlayers != _Players.end(); ++PeoplePlayers) { PeoplePlayers->ClearHand(); } AddAnotherBot = 0; _House.ClearHand(); _SydneyOnTheTable.ClearHand(); _AlexOnTheTable.ClearHand(); noBet = false; } Game::~Game() = default;
true
e1ce6415843648f8fcfb78b570a800d5d029d0e4
C++
FeronCompany/MyObject
/ObjectManager/tools/MemberFuncRegister.h
UTF-8
1,163
2.546875
3
[]
no_license
#pragma once #include <map> #include <string> #include "CommSingleton.h" #include "BaseObject.h" class RegFuncManager { friend CommSingleton<RegFuncManager>; public: void addFunc(const std::string& key, void* func); void* getFunc(const std::string& key); private: RegFuncManager() {} private: std::map<std::string, void*> mFuncMap; }; typedef CommSingleton<RegFuncManager> RegfuncManager; class RegObject { public: RegObject(const std::string& key, void* func); }; #define DECLARE_MEMBER_FUNC(class_name, func_name) \ void func_name(int num); \ static void st_##func_name(BaseObject* obj, int num) \ { \ static_cast<class_name*>(obj)->func_name(num);\ } #define REG_MEMBER_FUNC(class_name, func_name) \ RegObject regObj##class_name##func_name(#func_name, (void*)class_name::st_##func_name); #define REG_MEMBER_FUNC_LITE(class_name, member_name) \ RegfuncManager::instance().addFunc(std::string("mod") + #member_name, (void*)class_name::st_##mod##member_name) #define DECLARE_MOD_AND_GET(class_name, member_name, member_type) \ DECLARE_MEMBER_FUNC(class_name, mod##member_name) \ member_type get##member_name() { return member_name; }
true
157ca1f87271fba47b9bae9c5bd0dd925802c286
C++
DCurro/gtmiami
/src/ZombieMind.cpp
UTF-8
1,738
2.734375
3
[]
no_license
#include "ZombieMind.hpp" ZombieMind::ZombieMind() { } ZombieMind::~ZombieMind() { } void ZombieMind::setup(PlayContext* playContext, Animal* controllingAnimal) { Mind::setup(playContext, controllingAnimal); float animalDiameter = this->mAnimal->getBodyFixture()->GetShape()->m_radius*2; mRouteController.setup(playContext, controllingAnimal, animalDiameter); mRouteController.delegate = this; } void ZombieMind::update(float timeStep) { Mind::update(timeStep); mRouteController.update(timeStep); } void ZombieMind::draw(sf::RenderTarget& window) { Mind::draw(window); this->mRouteController.draw(window); } void ZombieMind::hearSoundAtLocation(b2Vec2 soundLocation) { mDesiredDestination = soundLocation; mRouteController.setDestination(soundLocation); } #pragma mark - <RouteControllerDelegate> void ZombieMind::routeController_noLongerOnRoute(RouteController* routeController) { routeController->setDestination(mDesiredDestination); std::cout << "zombie no longer on route" << std::endl; } void ZombieMind::routeController_routeBecameBlocked(RouteController* routeController) { routeController->setDestination(mDesiredDestination); std::cout << "zombie route became blocked" << std::endl; } void ZombieMind::routeController_directionVectorToNextDestination(b2Vec2 destinationVector) { this->mAnimal->applyMotion(destinationVector, 1.0f); this->mAnimal->applyLook(b2Atan2(destinationVector.y, destinationVector.x) * RADIANS_TO_DEGREES); ; } void ZombieMind::routeController_didReachDestination(RouteController* routeController) { UNUSED(routeController); std::cout << "zombie did reach destination" << std::endl; }
true
73667f9cea9f7940be1f7ff34e00a118670ace65
C++
harikulendran/AntSimulation
/AntSimulation/Cell.cpp
UTF-8
421
2.765625
3
[]
no_license
#include "Cell.h" #include <random> #include <time.h> Cell::Cell(int percent, int richness) { srand(time(NULL)); if (rand() % 100 < percent) source = richness; } void Cell::evaporate() { pLevel *= (1.0 - EVAPORATION_RATE); } void Cell::add(double amount) { pLevel += amount; } bool Cell::isFull() { return popSize >= MAX_POP_SIZE; } void Cell::moveHere() { popSize++; } void Cell::leaveHere() { popSize--; }
true
473bdce7e3577de5913f15c531bce3295cf6a537
C++
hstefan/Restaurant-Tycoon
/src/Parking.cpp
UTF-8
3,331
2.5625
3
[ "MIT" ]
permissive
/* * Copyright (c) 2010 * Hugo Stefan Kaus Puhlmann <hugopuhlmann@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "Parking.h" #include "htl/hlist.h" #include <utility> #include <iostream> namespace rty { Parking::Parking() { reset(); } void Parking::reset() { for(int i = 0; i < NUM_ROW; i++) for(int j = 0; j < NUM_SLOT + 1; j++) park_emp[i][j] = false; } bool Parking::isBusy(int row, int slot) { return park_emp[row][slot]; } std::pair<int, std::pair<int,int> > Parking::parkCar() { for(int i = 0; i < NUM_ROW; i++) //tenta achar vagas no ultimo slot de cada linha (assim o tempo de remocao fica menor) { if(!isBusy(i, NUM_SLOT - 1)) { park_emp[i][NUM_SLOT - 1] = true; return std::pair<int, std::pair<int, int>>(i + 1, std::pair<int,int>(i, NUM_SLOT - 1)); //numero de linhas percorridas + 1 da entrada no slot } } for(int i = 0; i < NUM_ROW; i++) { if(theresAnEmptySlot(i)) { int t_push = pushCars(i); park_emp[i][NUM_SLOT - 1] = true; return std::pair<int, std::pair<int, int>>(t_push + i + 1, std::pair<int,int>(i, NUM_SLOT - 1)); } } return std::pair<int, std::pair<int, int>>(0, std::pair<int,int>(0, 0)); } bool Parking::theresAnEmptySlot(int row) { for(int i = 0; i < NUM_SLOT; i++) { if(park_emp[row][i]) return true; } return false; } int Parking::pushCars(int row) { int temp_push = 0; for(int i = 1; i < NUM_SLOT; i++) { park_emp[row][i] = false; park_emp[row][i - 1] = true; temp_push++; } return temp_push; } int Parking::removeCar(int row, int slot) { if(!theresABehind(row,slot)) { park_emp[row][slot] = false; return row + slot; } int cars_moved = 0; std::pair<int, std::pair<int, int>> newpos; for(int i = slot - 1; i > 0; i--) { cars_moved++; park_emp[row][i] = false; newpos = parkCar(); std::cout << "O carro que estava na fileira " << row << " na posicao " << i << " foi movido para fileira " << newpos.second.first << " na posicao " << newpos.second.second << std::endl; } int total = 0; while(cars_moved > 0) { total += parkCar().first; cars_moved--; } return cars_moved + total + row + slot; } bool Parking::theresABehind(int row, int slot) { return park_emp[row][slot - 1]; } }
true
cfdd1584b9b7f879375e4ace8ba333d4b28de7c5
C++
GaigeKinsey/GAT350
/GAT350/core/ref_count.h
UTF-8
280
3.140625
3
[]
no_license
#pragma once class ref_count { public: ref_count() {} ref_count(const ref_count&) = delete; ref_count& operator = (const ref_count&) = delete; void add_ref() { m_count++; } void release() { m_count--; } size_t count() { return m_count; } private: size_t m_count = 0; };
true
0edf309c9bc0c8092eeb0b264df9a283c96731a5
C++
nachodz/tpdatos2do2012
/Ocurrencia/Ocurrencia.h
UTF-8
750
2.703125
3
[]
no_license
#ifndef OCURRENCIA_H_ #define OCURRENCIA_H_ #include <list> #include <string> using namespace std; class Ocurrencia{ private: string palabra; int idPalabra; string codigoGammaDocumento; int idDocumento; list <int> posiciones; public: Ocurrencia(); ~Ocurrencia(){} int getIdPalabra(); void setIdPalabra(int idPalabra); string getPalabra(); void setPalabra(string palabra); string getCodigoGammaDocumento(); void setCodigoGammaDocumento(string idDocumento); int getIdDocumento(); void setIdDocumento(int idDocumento); list<int> getPosiciones(); void setPosiciones(list<int> posiciones); void agregarPosicion(int posicion); void agregarPosiciones(list < int > & posiciones); }; #endif /* OCURRENCIA_H_ */
true
4911eb01d431f2048e8646e9d615b72df7b93bc9
C++
charto/nbind-examples
/2-classes.cc
UTF-8
411
2.984375
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#include <iostream> class ClassExample { public: ClassExample() { std::cout << "No arguments\n"; } ClassExample(int a, int b) { std::cout << "Ints: " << a << " " << b << "\n"; } ClassExample(const char *msg) { std::cout << "String: " << msg << "\n"; } }; #include "nbind/nbind.h" NBIND_CLASS(ClassExample) { construct<>(); construct<int, int>(); construct<const char *>(); }
true
c0d07abf9dd1361e1dd669fd68618296b679ca04
C++
mrBymax/simpleShipGame
/header/Bullet.h
UTF-8
612
2.515625
3
[]
no_license
// // Created by Federico Bertossi on 07/07/21. // #ifndef BULLET_H #define BULLET_H #include <SFML/Graphics.hpp> #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include <SFML/Audio.hpp> #include <SFML/Network.hpp> class Bullet { private: sf::Sprite shape; sf::Vector2f direction; float movementSpeed; public: Bullet(sf::Texture *texture, float posX, float posY, float dirX, float dirY, float movementSpeed); Bullet(); virtual ~Bullet(); // Accessories sf::FloatRect getBounds() const; void update(); void render(sf::RenderTarget *target); }; #endif // BULLET_H
true
ea07b138433e4476a9b6eff1f6c8d19185404f6d
C++
ruandaniel/R-LC
/459. Repeated Substring Pattern.cpp
UTF-8
502
2.625
3
[]
no_license
class Solution { public: bool repeatedSubstringPattern(string s) { int n = s.size(); for (int i = 1; i <= n/2; i++){ if (n % i) continue; bool isRpt = true; string rpt = s.substr(0, i); for (int j = 1; j < n/i; j++){ if (rpt != s.substr(i*j, i)) { isRpt = false; break; } } if (isRpt) return true; } return false; } };
true
0d9035492cff1f12f467908e0dd29f78c6f76012
C++
Mionger/LeetCode
/PASS2/containsDuplicate.cpp
UTF-8
755
3.421875
3
[]
no_license
#include<iostream> #include<vector> // #include<algorithm> using namespace std; class Solution { public: bool containsDuplicate(vector<int> &nums); }; bool Solution::containsDuplicate(vector<int> &nums) { if(nums.empty()) { return false; } sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 1;i++) { if(nums[i]==nums[i+1]) return true; } return false; } int main() { Solution s; vector<int> obj; int temp; for (int i = 0; i < 10; i++) { cin >> temp; obj.push_back(temp); } cout << s.containsDuplicate(obj) << endl; for (int i = 0; i < obj.size();i++) { cout << obj[i]<<" "; } cout << endl; return 0; }
true
3e0888fe0b7f0ba7cb62b4ff906b567b83366710
C++
dikdack009/Labs_2course
/Murov_labs_3sem/lab2/Chain_line.cpp
WINDOWS-1251
1,598
2.859375
3
[]
no_license
#include <strstream> #include <iostream> #include <Windows.h> #include <stdlib.h> #include <math.h> #define graphic(x,a) (a*cosh(x / a)) // #include "Chain_line.h" namespace Chain { // 0, - Chain::Chain(double x) { if (x == 0) throw std::exception("invalid param a"); a = x; } Chain& Chain::set_a(double x) { if (x == 0) throw std::exception("invalid param a"); a = x; return *this; } Point Chain::center(double x) const { double y = f(x); double y1 = sinh(x / a); double y2 = f(x) / (a * a); Point res; res.x = x - (y1 * (1 + y1 * y1) / y2); res.y = y + ((1 + y1 * y1) / y2); return res; } Point Chain::get_proj() const { Point res; double x1, x2; std::cout << "Enter x1 and x2 (suspension abscesses): "; std::cin >> x1; std::cin >> x2; if (x2 > x1){ res.x = x2; res.y = x1; } else { res.x = x1; res.y = x2; } return res; } void Chain::paint()const { float x; HDC hDC = GetDC(GetConsoleWindow()); HPEN Pen = CreatePen(PS_SOLID, 2, RGB(255, 255, 255)); SelectObject(hDC, Pen); MoveToEx(hDC, 0, 85, NULL); LineTo(hDC, 200, 85); MoveToEx(hDC, 100, 0, NULL); LineTo(hDC, 100, 170); for (x = -8.0f; x <= 8.0f; x += 0.01f) // O(100,85) - center { MoveToEx(hDC, 10 * x + 100, -15 * graphic(x, a) + 85, NULL);//10 - scale LineTo(hDC, 10 * x + 100, -15 * graphic(x, a) + 85); } } }
true
d95e470a8e7f7718455f9d961e7e3ddbe78af22e
C++
Aryanagarwala/CodeForces
/1269-C/1269-C-67346568.cpp
UTF-8
1,012
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> #include <cmath> #include <unordered_map> #include <fstream> #include <stack> #include <vector> #include <set> #include <queue> #include <cstdlib> #include <cstring> #include <map> #define int long long using namespace std; int n, k; bool big(string s, string s1){ bool big = false; for(int i = 0;i<n;i++){ if(s1[i]>s[i]) big = true; if(s1[i]<s[i] && !big) return false; } return true; } int32_t main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n>>k; string s; cin>>s; string s1 = s.substr(0, k); for(int i = k;i<n;i++){ s1+=s1[i-k]; } if(big(s, s1)){ cout<<n<<endl; cout<<s1<<endl; return 0; } int ind = k-1; while(ind>0 && s[ind]=='9'){ s[ind] = '0'; ind--; } s[ind] = s[ind]+1; for(int i = k;i<n;i++){ s[i] = s[i-k]; } cout<<n<<endl; cout<<s<<endl; } /* 1 3 2 11 4 8 5 7 6 10 9 12 */
true
954b96f7f7030d857ea2c036ffa55331c1571676
C++
liguomin9496/chuxuezhedechangshi
/AlgorithmCompetition/蓝桥杯赛题/第七届省赛/第七届蓝桥杯大赛个人赛省赛(软件类)真题/C语言B组源码/6.cpp
GB18030
914
3.125
3
[]
no_license
#include<iostream> #include<math.h> using namespace std; int Map[3][4]={0,1,1,1,1,1,1,1,1,1,1,0}; int vis[3][4]; int res=0; void Dfs(int step,int x,int y){ if(step==9){ res++; return; } for(int i=0;i<3;i++){//ﱾڱλãԲҵλãһıң for(int j=0;j<4;j++){ if(abs(j-y)<=1 && abs(i-x)<=1)//xƽߺyƽཻɵķ񶼲 continue; else{ if(Map[i][j]==1 && vis[i][j]==0){ vis[i][j]=1; Dfs(step+1,i,j); vis[i][j]=0; } } } } } int main(){ for(int i=0;i<3;i++){ for(int j=0;j<4;j++){ if(Map[i][j]==1){ vis[i][j]=1; Dfs(0,i,j); vis[i][j]=0; } } } cout<<res<<endl; }
true
08b3a89fb1e72fa9821fdd377b2ad102aca23f89
C++
drewag/Flurry
/core/inc/FL_ObjectList.h
UTF-8
2,132
3.15625
3
[]
no_license
#ifndef FL_ObjectList #define FL_ObjectList #include <set> namespace Flurry { class Object; class Category; class ObjectList { public: typedef std::set<Object>::iterator iterator; typedef std::set<Object>::const_iterator const_iterator; public: //! Constructor ObjectList(); //! Copy Constructor ObjectList ( const ObjectList &other //!< List to copy ); //! Destructor ~ObjectList(); //! Add Object to end list void add ( const Object &obj //!< Object to add ); //! Append a list onto this list void add ( const ObjectList &other //!< List to append onto this one ); //! Remove Object to end list void remove ( const Object &obj //!< Object to remove ); //! Remove a list of objects void remove ( const ObjectList &list //!< list of objects to remove ); //! @returns true if all objects are of the given category bool allObjectsAreOfCategory ( const Category& cat //!< Category to check for ); //! @return true if the given object is within this list bool containsObject ( Object obj //!< Object to test if it is within this list ); //! @returns the number of Objects in list unsigned int size() const; //! Delete all elements void clear(); //! @returns an iterator pointing at the beginning of the list iterator begin(); //! @returns an iterator pointing at the end of the list iterator end(); //! @returns an iterator pointing at the beginning of the list const_iterator begin() const; //! @returns an iterator pointing at the end of the list const_iterator end() const; private: std::set<Object>* mObjects; //!< internal list of objects }; } // namespace Flurry #endif
true
8dc48c4d6fea0c78e8949e5421a3be47247279aa
C++
r-o-b-o-t-o/podracer
/window/src/TextureLoader.cpp
UTF-8
1,042
2.890625
3
[ "MIT" ]
permissive
#include <vector> #include "TextureLoader.h" namespace Window { TextureLoader::TextureLoader() { std::vector<std::string> texturePaths = { }; for (int i = 1; i <= 3; ++i) { texturePaths.push_back("walls/brown" + std::to_string(i) + ".png"); texturePaths.push_back("walls/grey" + std::to_string(i) + ".png"); } for (int i = 1; i <= 12; ++i) { for (int j = 1; j <= 4; ++j) { texturePaths.push_back("pod_" + std::to_string(i) + "/" + std::to_string(j) + ".png"); } } for (const std::string &path : texturePaths) { std::string fileName = path.substr(0, path.find_last_of('.')); this->textures[fileName] = sf::Texture(); this->textures[fileName].setSmooth(true); this->textures[fileName].loadFromFile("assets/textures/" + path); } } const sf::Texture* TextureLoader::get(const std::string &name) const { return &this->textures.at(name); } }
true
ba28f2dc210ce4a71f960e901d9b73df1b62095f
C++
0xTaoL/COP3503
/Project 3/pa3.cpp
UTF-8
6,004
3.390625
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> #include <string> #include "pa3.h" #include <vector> using namespace std; int main() { cout << "Please enter the name of the input file: "; string input; cin >> input; ifstream file(input); if(!file){ cout << "Invalid File."; return 1; } stack depth; stack constants; stack identifiers; stack badSyntaxs; bool comma = false; bool semicolon = false; bool plusplus = false; bool minusminus = false; bool minus = false; bool plus = false; bool equals = false; bool equalsequals = false; bool mult = false; bool div = false; bool begin = false; bool end = false; bool forr = false; //goes line by line and checks what is there int count = 0; int parentError = 0; int numBegin = 0; int numEnd = 0; int numFor = 0; string line; while( getline(file, line) ) { cout << "Line " << count++ << ": " << line << std::endl; //figures out if there are unbalanced parenthesis for (unsigned i = 0; i < line.size(); i++) { if(line[i] == '('){ parentError++; } if(line[i] == ')'){ parentError--; } } //finds constants (numbers) for (unsigned i = 0; i < line.size(); i++) { if (isdigit(line.at(i))) { unsigned j = 0; while (i+j < line.size() && isdigit(line.at(i+j))) { j++; } string constant = line.substr(i,j); constants.push(constant); i += j; } } //same as above but finds identifiers for (unsigned i = 0; i < line.size(); i++) { if (islower(line.at(i))) { unsigned j = 0; while (i+j < line.size() && islower(line.at(i+j))) { j++; } string indentifier = line.substr(i,j); identifiers.push(indentifier); i += j; } } //same as above but finds misspelled syntax for (unsigned i = 0; i < line.size(); i++) { if (isupper(line.at(i))) { unsigned j = 0; while (i+j < line.size() && isupper(line.at(i+j))) { j++; } string badSyntax = line.substr(i,j); badSyntaxs.push(badSyntax); i += j; } } //finds delimiters and operators and keywords if(line.find("FOR") != string::npos){ forr = true; numFor++; } if(line.find("BEGIN") != string::npos){ begin = true; depth.push("BEGIN"); numBegin++; } if(line.find("END") != string::npos){ end = true; depth.pop(); numEnd++; } if(line.find(";") != string::npos){ semicolon = true; } if(line.find(",") != string::npos){ comma = true; } if(line.find("*") != string::npos){ mult = true; } if(line.find("/") != string::npos){ div = true; } if(line.find("+") != string::npos){ if(line.find("++") != string::npos){ plusplus = true; } else { plus = true; } } if(line.find("-") != string::npos){ if(line.find("--") != string::npos){ minusminus = true; } else { minus = true; } } if(line.find("=") != string::npos){ if(line.find("==") != string::npos){ equalsequals = true; } else { equals = true; } } } file.close(); cout << "The depth of the nested loop(s) is "; cout << depth.nestedLoopCount(); cout << "\n"; cout << "Keywords: "; if(begin){ cout << "BEGIN "; } if(end){ cout << "END "; } if(forr){ cout << "FOR "; } cout << "\n"; cout << "Identifier: "; identifiers.removeDuplicates(); while (identifiers.size()>0){ cout << identifiers.pop() + " "; } cout << "\n"; cout << "Constant: "; constants.removeDuplicates(); while (constants.size()>0){ cout << constants.pop() + " "; } cout << "\n"; cout << "Operators: "; if(plus){ cout << "+ "; } if(minus){ cout << "- "; } if(mult){ cout << "* "; } if(div){ cout << "/ "; } if(minusminus){ cout << "-- "; } if(plusplus){ cout << "++ "; } if(equals){ cout << "= "; } if(equalsequals){ cout << "== "; } cout << "\n"; cout << "Delimiter: "; if(semicolon){ cout << "; "; } if (comma){ cout << ", "; } cout << "\n\n"; cout << "Syntax Error(s): "; badSyntaxs.removeDuplicates(); while (badSyntaxs.size()>0){ string test = badSyntaxs.pop(); if(test == "BEGIN"){ continue; } if(test == "FOR"){ continue; } if(test == "END"){ continue; } cout << test + " "; } if(parentError>0){ cout << ") "; } if(parentError<0){ cout << "( "; } //this part will state the excess keywords //Scott Liu stated in discussion "it will be acceptable for your program to declare // either extra or missing keywords as syntax errors" if(numBegin<numEnd){ cout << "END "; } if(numBegin>numEnd){ cout << "BEGIN "; } if(numFor>numEnd){ cout << "FOR "; } if(numFor<numEnd){ cout << "END "; } return 0; }
true
893c1ecdc3861a9a44758633412184c5a23a6c0e
C++
jeffason/JrsCheckers
/src/Application.h
UTF-8
1,849
2.890625
3
[]
no_license
///////////////////////////////////////////////////////////////////////////////////////////////////// // // Application.h // // DESCRIPTION: // Our core application singleton which manages global access to our polymorphic Engine and our // global application configuration. // // jrs051413 - created // ///////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <string> #include <memory> #include <Windows.h> namespace jrs{ class Config; class Engine; class Application { public: // // Methods // // singleton accessor static Application& Instance() { static Application instance; return instance; } inline std::shared_ptr<Config> GetConfig() { return m_Config; } inline std::shared_ptr<Engine> GetEngine() { return m_Engine; } // // Application::ConsoleHandlerRoutine // // DESCRIPTION: // handles console events like exit // // RETURN: // true - application exit with no prompt // false - application exit error static BOOL WINAPI ConsoleHandlerRoutine(DWORD _type); // // Application::Initialize // // DESCRIPTION: // initializes the application based on config settings // // RETURN: // true - application initialized properly // false - application initialization failed bool Initialize(const std::wstring &_config_path); // // Application::Run // // DESCRIPTION: // runs application based on initialization configuration // // RETURN: // int - application error code int Run(); private: // // Methods // Application(); ~Application(void); Application(Application const&); void operator=(Application const&); // // Members // std::shared_ptr<Config> m_Config; std::shared_ptr<Engine> m_Engine; //signal when application should close static bool m_bCloseApplicationStateFlag; }; }
true
e732f9585b906defab2aaddeddde770c90938ed6
C++
A2andil/Algorithms
/Sorting/02- Insertion Sort.cpp
UTF-8
410
2.921875
3
[]
no_license
// in the name of God #include <iostream> #include <vector> using namespace std; vector<int> sort_by_insertion(vector<int> v) { for (int i = 1; i < (int)v.size(); i++) { for (int j = i; j > 0; j--) { if (v[j] < v[j - 1]) { swap(v[j], v[j - 1]); } else break; } } return v; } int main() { return 0; }
true
892efb8e92831ddd636a9d70d1f339fb1925e19b
C++
pirtwo/Arcade-Games
/Pong/src/Paddle.cpp
UTF-8
721
2.859375
3
[ "MIT" ]
permissive
#include "Paddle.h" #include <SFML/Graphics.hpp> Paddle::Paddle(float w, float h, sf::Color color) { _sp = sf::RectangleShape(sf::Vector2f(w, h)); _sp.setFillColor(color); } Paddle::~Paddle() { // } sf::FloatRect Paddle::getBody() { return sf::FloatRect( getPosition().x, getPosition().y, _sp.getGlobalBounds().width, _sp.getGlobalBounds().height); } void Paddle::moveUp() { velocity.y = -speed; } void Paddle::moveDown() { velocity.y = speed; } void Paddle::stop() { velocity.y = 0; } void Paddle::update() { move(0, velocity.y); } void Paddle::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(_sp, getTransform()); }
true
a047e5d39cd338201ab8dd01f1dab86fde48b261
C++
CCEP16Fa/3DEngineCpp
/src/freeLook.h
UTF-8
579
2.640625
3
[]
no_license
#ifndef FREELOOK_H #define FREELOOK_H #include "math3d.h" #include "gameComponent.h" class FreeLook : public GameComponent { public: FreeLook(const Vector2f& windowCenter, float sensitivity = 0.5f, int unlockMouseKey = Input::KEY_ESCAPE) : m_sensitivity(sensitivity), m_unlockMouseKey(unlockMouseKey), m_mouseLocked(false), m_windowCenter(windowCenter) {} virtual void ProcessInput(const Input& input, float delta); protected: private: float m_sensitivity; int m_unlockMouseKey; bool m_mouseLocked; Vector2f m_windowCenter; }; #endif // FREELOOK_H
true
bd86f271ced9aba0ffc58d2fb6d8ee5a42ab2bd7
C++
z-a-f/Fun-Codes
/primeChecks.cpp
UTF-8
2,516
3.8125
4
[]
no_license
/* Assumption: * Every prime number reversed in binary is either a * prime, or a square of a prime */ #include <cmath> #include <iostream> #include <vector> using namespace std; bool isPrime(unsigned num) { // return 0 if not prime // return 1 if prime // return 2 if square of a prime if (num == 2) return true; if (num < 2 || num % 2 == 0) return false; for (unsigned idx = 3, sq=sqrt(num); idx <= sq; idx+=2) { if (num % idx == 0) return false; } return true; } vector<bool> sieve(unsigned max) { vector<bool> visited = vector<bool>(max, false); visited[0] = true; visited[1] = true; vector<bool> primes = vector<bool>(max, false); unsigned step = 0; for (unsigned ii = 2, sq = sqrt(max); ii <= sq; ii++) { if (visited[ii]) continue; visited[ii] = true; primes[ii] = true; step = ii; // Strike out for (unsigned jj = 1; jj <= max/step; jj++) { visited[jj*step] = true; } } // Get the ones that are not striked out for (unsigned ii = sqrt(max); ii < max; ii++) { if (!visited[ii]) primes[ii] = true; } return primes; } bool isSquare(unsigned num) { unsigned temp = sqrt(num); if (temp*temp == num) return true; else return false; } bool isPrimeSquared(unsigned num) { unsigned temp = sqrt(num); if (temp*temp != num) return false; if (isPrime(temp)) return true; return false; } unsigned reverseBin(unsigned num) { unsigned temp = 0; while (num) { temp = (temp<<1) + (num%2); num = num >> 1; } return temp; } void printPrimeFactors(unsigned num) { cout << "[ "; cout << 1 << " "; unsigned counter = 2; while (num % counter == 0) { cout << counter << " "; num = num / counter; } unsigned sq; for (counter = 3, sq = sqrt(num); counter <= sq; counter += 2) { while (num % counter == 0) { cout << counter << " "; num = num / counter; } } cout << "]"; } int main() { // Create the list of all the prime numbers smaller than some big number: unsigned static MAX_NUMS = 10000; vector<bool> primes; primes = sieve(MAX_NUMS); // cout << primes.size() << endl; /* for (unsigned ii = 0; ii < MAX_NUMS; ii++){ if (primes[ii]) { cout << ii << ", "; } } cout << endl; */ unsigned temp = 0; for (unsigned ii = 3; ii < MAX_NUMS; ii++){ if (!primes[ii]) continue; temp = reverseBin(ii); cout << ii << " <-> " << temp; if (!isPrime(temp) && !isPrimeSquared(temp)) { cout << "\t"; printPrimeFactors(temp); cout << "\tWoops!"; // break; } cout << endl; } cout << endl; }
true
5827d92d7eab17c2a277405d59aa84665058ba7e
C++
9sheng/leetcode
/790.domino-and-tromino-tiling.cpp
UTF-8
2,157
3.59375
4
[]
no_license
/** * 790. Domino and Tromino Tiling * * We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated. * * XX <- domino * * XX <- "L" tromino * X * Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7. * * (In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.) * * Example: * Input: 3 * Output: 5 * Explanation: * The five different ways are listed below, different letters indicates different tiles: * XYZ XXZ XYY XXY XYY * XYZ YYZ XZZ XYY XXY */ #include "testharness.h" #include <iostream> #include <map> #include <vector> using namespace std; // 更高效的方法,将递归改为动态规划 // 按 0..n 计算 f、g 的值 class Solution { public: int numTilings(int n) { // return f(n); if (n < 3) return n; vector<long> fv(n+1), gv(n+1); fv[0] = 0; fv[1] = 1; fv[2] = 2; gv[0] = 0; gv[1] = 1; gv[2] = 2; for (int i = 3; i <= n; i++) { fv[i] = (fv[i-1] + fv[i-2] + 2*gv[i-2]) % MOD; gv[i] = (gv[i-1] + fv[i-1]) % MOD; } return fv[n]; } private: long f(int n) { if (n <= 2) return n; auto iter = f_cache_.find(n); if (iter != f_cache_.end()) return iter->second; long ret = f(n-1) + f(n-2) + 2*g(n-2); if (ret > MOD) ret %= MOD; f_cache_[n] = ret; return ret; } // n: short leg length long g(int n) { if (n <= 2) return n; auto iter = g_cache_.find(n); if (iter != g_cache_.end()) { return iter->second; } long ret = g(n-1) + f(n-1); if (ret > MOD) ret %= MOD; g_cache_[n] = ret; return ret; } private: const int MOD = 1e9 + 7; map<int, long> f_cache_; map<int, long> g_cache_; }; TEST(Solution, test) { ASSERT_EQ(01, numTilings(1)); ASSERT_EQ(02, numTilings(2)); ASSERT_EQ(05, numTilings(3)); ASSERT_EQ(11, numTilings(4)); ASSERT_EQ(24, numTilings(5)); ASSERT_EQ(979232805, numTilings(1000)); }
true
f58e443de8f52d5bdbecb90cba9f9eeeff6cc15d
C++
bedomarci/EasyLCDMenu
/src/menuitem/CommandMenuItem.hpp
UTF-8
1,708
2.828125
3
[]
no_license
// // Created by m4800 on 10/4/2019. // #ifndef EASYLCDMENU_COMMANDMENUITEM_HPP #define EASYLCDMENU_COMMANDMENUITEM_HPP #include "ValueMenuItemTemplate.hpp" class CommandMenuItem : public MenuItemTemplate<EasyLCDMenuFunction> { public: CommandMenuItem(EasyLCDMenuFunction value, const char *label, const char *description = nullptr); void navigate(EasyLCDMenuControl control) override; void render(uint8_t **display, uint8_t rows, uint8_t columns) override; void setDescription(const char *description); protected: EasyLCDMenuFunction _callback = nullptr; void toString(char *valueString); const char *_description; }; void CommandMenuItem::navigate(EasyLCDMenuControl control) { switch (control) { case GO: if (getValue()){ getValue()(); this->getMenu()->home(); } break; case BACK: this->leave(); break; case NEXT: case PREVIOUS: break; } } CommandMenuItem::CommandMenuItem(EasyLCDMenuFunction value, const char *label, const char *description) : MenuItemTemplate(&value, label) { setDescription(description); } void CommandMenuItem::render(uint8_t **display, uint8_t rows, uint8_t columns) { this->setCursor(0, 0); this->print(display, this->getLabel()); this->setCursor(this->getRows() - 1, 0); this->print(display, this->_description); this->setCursor(this->getRows() - 1, this->getColumns() - 1); this->print(display, EasyLCDMenuRight); } void CommandMenuItem::setDescription(const char *description) { _description = description; } #endif //EASYLCDMENU_COMMANDMENUITEM_HPP
true
3c1ccc91502864351e473732f7d1a0747a5cf532
C++
flameshimmer/leet2019.io
/Leet2019/WiggleSort.cpp
UTF-8
589
3.390625
3
[]
no_license
#include "stdafx.h" //Given an unsorted array nums, reorder it in-place such //that nums[0] <= nums[1] >= nums[2] <= nums[3].... // //Example: // //Input: nums = [3,5,2,1,6,4] //Output: One possible answer is [3,5,1,6,2,4] namespace Solution2019 { namespace WiggleSort { void wiggleSort(vector<int>& nums) { int len = nums.size(); for (int i = 1; i < len; i++) { if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { swap(nums[i], nums[i - 1]); } } } void Main() { string test = "tst test test"; print(test); } } }
true
5b31d819de5a6b80547d6e08f3994b9216516dcc
C++
OKullmann/oklibrary
/ComputerAlgebra/Matroids/Lisp/Greedoids/plans/general.hpp
UTF-8
1,564
2.59375
3
[]
no_license
// Oliver Kullmann, 1.8.2008 (Swansea) /* Copyright 2008, 2012 Oliver Kullmann This file is part of the OKlibrary. OKlibrary is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation and included in this library; either version 3 of the License, or any later version. */ /*! \file ComputerAlgebra/Matroids/Lisp/Greedoids/plans/general.hpp \brief General plans regarding greedoids \todo Fundamental notions <ul> <li> A "greedoid" can be considered, like a matroid, as a special type of hypergraph (the hereditarity-condition is replaced by the weaker condition of "accessibility", that is, for every non-empty hyperedge there exists an element which can be removed). </li> <li> These are the unordered versions. And then there is the notion of an "ordered greedoid", which is a pair [V,W], where V is a finite set while W is a set of repetition-free lists over V. </li> <li> The notion of "greedoid language" is used for these "ordered" versions". </li> <li> Perhaps by default the greedoid languages have implicitly given set of words, since these are just the permutations of the underlying greedoid. </li> <li> Let's use the abbreviations "grd" and "grdl". </li> </ul> \todo Branching greedoids <ul> <li> While the cycle matroids (see "Examples" in ComputerAlgebra/Matroids/Lisp/plans/general.hpp) cover Kruskal's algorithm for computing minimum spanning trees, now Prim's algorithm is covered. </li> </ul> */
true
2ce526d852687cba0447ebb1705f31bbe3d4a50f
C++
odilonafonso/IOT
/GenericBoards/testmacaddress/testmacaddress.ino
UTF-8
1,288
3.078125
3
[]
no_license
/* * Retrieve the MAC address from a Microchip 24AA125E48 I2C ROM, and report it * to the serial console at 57600bps. The I2C address of the ROM is set to 0x50, * which assumes both the address pins are tied to 0V. */ #define I2C_ADDRESS 0x50 #include <Wire.h> static uint8_t mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; void setup() { Wire.begin(); // Join i2c bus (I2C address is optional for the master) Serial.begin(9600); for(int i = 0; i < 30; i++) { Serial.println(" "); } Serial.println("Starting test for MAC address ROM"); Serial.print("Getting MAC: "); mac[0] = readRegister(0xFA); mac[1] = readRegister(0xFB); mac[2] = readRegister(0xFC); mac[3] = readRegister(0xFD); mac[4] = readRegister(0xFE); mac[5] = readRegister(0xFF); char tmpBuf[17]; sprintf(tmpBuf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); Serial.println(tmpBuf); Serial.println(" TEST OK"); } void loop() { // Do nothing } byte readRegister(byte r) { unsigned char v; Wire.beginTransmission(I2C_ADDRESS); Wire.write(r); // Register to read Wire.endTransmission(); Wire.requestFrom(I2C_ADDRESS, 1); // Read a byte while(!Wire.available()) { // Wait } v = Wire.read(); return v; }
true
e9ec3d0b9d9b232c9e3c636a4d1b97eff54acab9
C++
caogtaa/OJCategory
/ProjectEuler/1_100/0046.cpp
UTF-8
971
2.875
3
[]
no_license
#include <vector> #include <string> #include <algorithm> #include <utility> #include <functional> #include <iostream> #include <set> #include <stack> #include <unordered_map> #include <unordered_set> #include <numeric> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "helper.h" using namespace std; class Solution { public: int solve() { helper.init(1000000); auto primes = helper.getPrimes(3, 1000000); int n = 35; int k = 0; while (true) { if (primes[k+1] <= n) { // find the largest prime that <= n ++ k; continue; } if (primes[k] == n) { n += 2; continue; } bool establish = false; for (int i = k; i >= 0; --i) { if (SpecialNumber::isSquareNumber((n-primes[i]) / 2)) { establish = true; break; } } if (!establish) return n; n += 2; } return -1; } PrimeHelper helper; }; int main() { Solution s; cout << s.solve() << endl; return 0; } // brute force
true
ebd631720c6effd9ac903dadc8121da8f60e0670
C++
Nammur/projetoEDB1
/src/main.cpp
UTF-8
14,419
3
3
[]
no_license
#include "../include/includeGeral.h" int main(){ srand (time(NULL)); std::ofstream myfile; int vetorPos = 0; int selecaoVetor; std::cout << "Selecione como deseja o vetor inicialmente\n" "1) Ordem Crescente\n" "2) 50% ordenado\n" "3) 25% ordenado\n" "4) 75% ordenado\n" "5) Posições aleatórias\n" "6) Ordem decrescente \n"; std::cin >> selecaoVetor; if (selecaoVetor <= 0 || selecaoVetor > 6){ while(selecaoVetor <= 0 || selecaoVetor > 6){ std::cout << "Opcao invalida.\n" "Selecione como deseja o vetor inicialmente\n" "1) Ordem Crescente\n" "2) 50% ordenado\n" "3) 25% ordenado\n" "4) 75% ordenado\n" "5) Posições aleatórias\n" "6) Ordem decrescente \n"; std::cin >> selecaoVetor; } } int selecao; std::cout << "Selecione qual algoritmo deseja testar\n" "0) todos\n" "1) insertion\n" "2) selection\n" "3) bubble\n" "4) quick\n" "5) merge\n" "6) shell\n" "7) radix\n" "8) quick com insertion\n"; std::cin >> selecao; if (selecao < 0 || selecao > 8){ while(selecao < 0 || selecao > 8){ std::cout << "Opcao invalida.\nSelecione qual algoritmo deseja testar\n" "0) todos\n" "1) insertion\n" "2) selection\n" "3) bubble\n" "4) quick\n" "5) merge\n" "6) shell\n" "7) radix\n" "8) quick com insertion\n"; std::cin >> selecao; } } int quantidadeTamanhos; int valoresVetor; int indice; std::cout << "Escreva a quantidade de tamanhos para o vetor que deseja testar:"; std::cin >> quantidadeTamanhos; int arrayTamanhos[quantidadeTamanhos]; std::cout << "Escreva quais os valores de tamanhos para o vetor que deseja testar:"; for (indice = 0 ; indice <= quantidadeTamanhos -1 ; indice++){ std::cin >> valoresVetor; arrayTamanhos[indice] = valoresVetor; std::cout << " "; } std::cout << "\n"; std::string nomeArq; int vezes = 0; int vezesTotal; std::cout << "Escreva a quantidade de vezes que quer testar o tamanho para cada algoritmo selecionado:"; std::cin >> vezesTotal; if (selecaoVetor == 1){ nomeArq = "100ordenado"; } if (selecaoVetor == 2){ nomeArq = "50ordenado"; } if (selecaoVetor == 3){ nomeArq = "25ordenado"; } if (selecaoVetor == 4){ nomeArq = "75ordenado"; } if (selecaoVetor == 5){ nomeArq = "0ordenado"; } if (selecaoVetor == 6){ nomeArq = "inverso"; } while(vetorPos <= quantidadeTamanhos - 1){ //Variavel para armazenar o valor máximo de valores a ser armazenado //de forma aleatória. //Variaveis aleatórias até limiteAleatorio int valor = 0; int begin = 0; int tamanhoVetor, i; tamanhoVetor = arrayTamanhos[vetorPos]; //Auxiliares na ordenacao do insertion sort //i = indice //int i; //Alocacao dinamica de um ponteiro que aponta para um array de x posições int *Array = new int [tamanhoVetor]; int *ArrayIndex = new int [tamanhoVetor]; int *copia = new int [tamanhoVetor]; for(i = 0 ; i<= tamanhoVetor; i++){ Array[i] = valor; ArrayIndex[i] = valor; valor ++; } menu(Array, ArrayIndex, tamanhoVetor,selecaoVetor); copiar(Array, copia, tamanhoVetor); if(selecao == 1 || selecao == 0){ while (vezes<vezesTotal){ std::cout << "Ordenando com Insertion sort" << std::endl; auto inicio = std::chrono::high_resolution_clock::now(); insertionSort(Array, tamanhoVetor); std::cout << "O arranjo foi ordenado com sucesso atraves do Insertion Sort" << std::endl; auto resultado = std::chrono::high_resolution_clock::now() - inicio; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(resultado).count(); std::cout << "tempo de execução do insertion " << microseconds << " microsegundos \n\n"; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/insertion/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/insertion/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds << std::endl; myfile.close(); vezes++; } } vezes = 0; if(selecao == 2 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); auto inicio3 = std::chrono::high_resolution_clock::now(); SelectionSort(Array, tamanhoVetor); std::cout << "O arranjo foi ordenado com sucesso atraves do Selection Sort" << std::endl; auto resultado3 = std::chrono::high_resolution_clock::now() - inicio3; long long microseconds3 = std::chrono::duration_cast<std::chrono::microseconds>(resultado3).count(); std::cout << "tempo de execução do Selection " << microseconds3 << " microsegundos \n\n"; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/selection/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/selection/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds3 << std::endl; myfile.close(); vezes++; } vezes = 0; } if(selecao == 3 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); auto inicio4 = std::chrono::high_resolution_clock::now(); bubbleSort(Array, tamanhoVetor); auto resultado4 = std::chrono::high_resolution_clock::now() - inicio4; long long microseconds4 = std::chrono::duration_cast<std::chrono::microseconds>(resultado4).count(); std::cout << "tempo de execução do bubble " << microseconds4 << " microsegundos \n"; std::cout << "O arranjo foi ordenado com sucesso atraves do Bubble Sort\n" << std::endl; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/bubble/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/bubble/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds4 << std::endl; myfile.close(); vezes++; } vezes = 0; } if(selecao == 4 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); std::cout << "Ordenando com Quick sort" << std::endl; auto inicio5 = std::chrono::high_resolution_clock::now(); quickSort(Array,begin, tamanhoVetor); auto resultado5 = std::chrono::high_resolution_clock::now() - inicio5; long long microseconds5 = std::chrono::duration_cast<std::chrono::microseconds>(resultado5).count(); std::cout << "tempo de execução do Quick " << microseconds5 << " microsegundos \n"; std::cout << "O arranjo foi ordenado com sucesso atraves do Quick\n" << std::endl; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/quick/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/quick/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds5 << std::endl; myfile.close(); vezes++; } vezes = 0; } if(selecao == 5 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); std::cout << "Ordenando com Merge sort" << std::endl; auto inicio2= std::chrono::high_resolution_clock::now(); mergeSort(Array, begin, tamanhoVetor); auto resultado2 = std::chrono::high_resolution_clock::now() - inicio2; long long microseconds2 = std::chrono::duration_cast<std::chrono::microseconds>(resultado2).count(); std::cout << "tempo de execução do merge " << microseconds2 << " microsegundos \n"; std::cout << "O arranjo foi ordenado com sucesso atraves do merge\n" << std::endl; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/merge/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/merge/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds2 << std::endl; myfile.close(); vezes++; } vezes = 0; } if(selecao == 6 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); std::cout << "Ordenando com Shell sort" << std::endl; auto inicio6= std::chrono::high_resolution_clock::now(); shellSort(Array, tamanhoVetor); auto resultado6 = std::chrono::high_resolution_clock::now() - inicio6; long long microseconds6 = std::chrono::duration_cast<std::chrono::microseconds>(resultado6).count(); std::cout << "tempo de execução do Shell " << microseconds6 << " microsegundos \n"; std::cout << "O arranjo foi ordenado com sucesso atraves do Shell\n" << std::endl; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/shell/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/shell/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds6 << std::endl; myfile.close(); vezes++; } vezes = 0; } if(selecao == 7 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); std::cout << "Ordenando com Radix sort" << std::endl; auto inicio7= std::chrono::high_resolution_clock::now(); radixSort(Array, tamanhoVetor); auto resultado7 = std::chrono::high_resolution_clock::now() - inicio7; long long microseconds7 = std::chrono::duration_cast<std::chrono::microseconds>(resultado7).count(); std::cout << "tempo de execução do Radix " << microseconds7 << " microsegundos \n"; std::cout << "O arranjo foi ordenado com sucesso atraves do Radix\n" << std::endl; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/radix/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/radix/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds7 << std::endl; myfile.close(); vezes++; } vezes = 0; } if(selecao == 8 || selecao == 0){ while (vezes<vezesTotal){ copiarReverso(Array, copia, tamanhoVetor); std::cout << "Ordenando com quickInsertion sort" << std::endl; auto inicio8= std::chrono::high_resolution_clock::now(); quickInsertion2(Array,begin, tamanhoVetor); auto resultado8 = std::chrono::high_resolution_clock::now() - inicio8; long long microseconds8 = std::chrono::duration_cast<std::chrono::microseconds>(resultado8).count(); std::cout << "tempo de execução do quick com insertion " << microseconds8 << " microsegundos \n"; std::cout << "O arranjo foi ordenado com sucesso atraves do quick com insertion\n" << std::endl; if(vezes == 0){ myfile.open (std::string("../output/" + nomeArq + "/quickInsertion/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::trunc); } else{ myfile.open (std::string("../output/" + nomeArq + "/quickInsertion/" + std::to_string(tamanhoVetor) + ".txt"), std::ios::app); } myfile << microseconds8 << std::endl; myfile.close(); vezes++; } vezes = 0; } vetorPos++; } return 0; }
true
239091a6504a2c06f66eb6c151a0c894380a475b
C++
BENIMALS9/Fifth_GIS
/工程/FIfth_Gis/FIfth_Gis/Geometry.h
GB18030
12,552
2.671875
3
[]
no_license
#pragma once #include "framework.h" #include "FIfth_Gis.h" #include <json/json.h> #include <iostream> #include <fstream> #include <sstream> #include <cassert> #include <errno.h> #include <string.h> #include <vector> #include <cmath> using namespace std; // Ҫ࣬ͬID class Geometry { protected: string ID; public: Geometry(string id) { ID = id; } string GetID() { return ID; } }; // Ҫ(Point) class Point : public Geometry { protected: float x; float y; public: // 캯ʼ Point(float px = (rand() % 800), float py = (rand() % 500), string id = std::to_string(rand() % 100)) :Geometry(id) { x = px; y = py; } // ȡX float GetX() { return x; } // ȡY float GetY() { return y; } // GeoJson void InitialFromJSON(Json::Value root) { Json::Value properties, geometry, coordinates, xy; // ȡJsonҪ properties = root["properties"]; // ȡҪID string pID = properties["id"].asString(); // ȡҪصĵϢ geometry = root["geometry"]; coordinates = geometry["coordinates"]; float px = 0; float py = 0; xy = coordinates[0]; x = xy[0].asFloat(); y = xy[1].asFloat(); ID = pID; } // ƺ void Draw(HDC hdc) { Ellipse(hdc, x * 10 - 1, y * 10 - 1, x * 10 + 1, y * 10 + 1); } }; // ҪࣨLineString class PolyLine : public Geometry { public: std::vector<Point> pts; // 캯ʼ PolyLine(string id = std::to_string(rand() % 100)) :Geometry(id) { ID = id; } // GeoJsonɣҪظGeoJsonʽصвͬJsonҪɣCoordinates֯ṹͬ΢죬ͬ void InitialFromGeoJson(Json::Value root) { Json::Value properties, geometry, coordinates, xy; properties = root["properties"]; string pID = properties["id"].asString(); geometry = root["geometry"]; coordinates = geometry["coordinates"]; float px = 0; float py = 0; ID = pID; for (int i = 0; i < coordinates.size(); ++i) { xy = coordinates[i]; px = xy[0].asFloat(); py = xy[1].asFloat(); Point pt(px, py, ID); pts.push_back(pt); } } // GeoJsonʼ//Ҫص void AddCoorFromGeoJson(Json::Value coordinates) { Json::Value p_xy, xy; float px = 0; float py = 0; for (int i = 0; i < coordinates.size(); ++i) { xy = coordinates[i]; px = xy[0].asFloat(); py = xy[1].asFloat(); Point pt(px, py, ID); pts.push_back(pt); } } // ƺ void Draw(HDC hdc) { POINT* point = new POINT[pts.size()]; for (int i = 0; i < pts.size(); ++i) { point[i].x = (pts[i].GetX() * 10); point[i].y = (pts[i].GetY() * 10); } Polyline(hdc, point, pts.size()); delete[] point; } static PolyLine CreateRandomPolyLine() { PolyLine polyline(std::to_string(rand() % 100)); int ptn = rand() % 500 + 2; for (int i = 0; i < ptn; ++i) { polyline.pts.push_back(Point::Point()); } return polyline; } }; // ҪࣨPolygon class PolyGon : public Geometry { public: std::vector<Point> pts; // 캯ʼ PolyGon(string id = std::to_string(rand() % 100)) :Geometry(id) { ID = id; } // GeoJson void InitialFromGeoJson(Json::Value root) { Json::Value properties, geometry, coordinates, p_xy, xy; properties = root["properties"]; string pID = properties["id"].asString(); geometry = root["geometry"]; coordinates = geometry["coordinates"]; float px = 0; float py = 0; ID = pID; // // JsonݸʽΪ // [ // [ // [122.12345, 23.234212], // [122.83571, 24.342112], // [113.42612, 22.738014], // [113.447808, 22.735836], // [113.467964, 22.728504], // ] // ] // for (int i = 0; i < coordinates.size(); ++i) { p_xy = coordinates[i]; for (int j = 0; j < p_xy.size(); ++j) { xy = p_xy[j]; px = xy[0].asFloat(); py = xy[1].asFloat(); Point pt(px, py, ID); pts.push_back(pt); } } } // GeoJsonʼ//Ҫص void AddCoorFromGeoJson(Json::Value coordinates) { Json::Value p_xy, xy; float px = 0; float py = 0; for (int i = 0; i < coordinates.size(); ++i) { p_xy = coordinates[i]; for (int j = 0; j < p_xy.size(); ++j) { xy = p_xy[j]; px = xy[0].asFloat(); py = xy[1].asFloat(); Point pt(px, py, ID); pts.push_back(pt); } } } // ƺ void Draw(HDC hdc) { POINT* point = new POINT[pts.size() + 1]; for (int i = 0; i < pts.size(); ++i) { /*point[i].x = (fabs(pts[i].GetX() - int(pts[i].GetX() / 10 * 10) + int(pts[i].GetX()) % 100) * 20); point[i].y = (fabs(pts[i].GetY() - int(pts[i].GetY() / 10 * 10) + int(pts[i].GetY()) % 100) * 20);*/ point[i].x = (pts[i].GetX() * 10); point[i].y = ((90.0 - pts[i].GetY()) * 10); } /*point[pts.size()].x = (fabs(pts[0].GetX() - int(pts[0].GetX() / 10 * 10) + int(pts[0].GetX()) % 100) * 20); point[pts.size()].y = (fabs(pts[0].GetY() - int(pts[0].GetY() / 10 * 10) + int(pts[0].GetY()) % 100) * 20);*/ point[pts.size()].x = (pts[0].GetX() * 10); point[pts.size()].y = ((90.0 - pts[0].GetY()) * 10); Polygon(hdc, point, pts.size()); delete[] point; } static PolyGon CreateRandomPolyGon() { PolyGon polygon(std::to_string(rand() % 100)); int ptn = rand() % 10 + 3; for (int i = 0; i < ptn; ++i) { polygon.pts.push_back(Point::Point()); } return polygon; } }; // ҪͼࣨMultiPoint class PointLayer { public: string layer_id; // ͼĵҪ std::vector<Point> element; // 캯ʼ PointLayer(string layer_id = "PointLayer_1") { int elementCount = rand() % 5 + 1; for (int i = 0; i < elementCount; ++i) { element.push_back(Point::Point(0, 0, "id")); } } // GeoJson void InitialFromGeoJson(Json::Value root) { Json::Value properties, geometry, coordinates, xy; properties = root["properties"]; string pID = properties["id"].asString(); geometry = root["geometry"]; coordinates = geometry["coordinates"]; float px = 0; float py = 0; layer_id = pID; for (int i = 0; i < coordinates.size(); ++i) { xy = coordinates[i]; px = xy[0].asFloat(); py = xy[1].asFloat(); Point pt(px, py, std::to_string(i)); element.push_back(pt); } } // ƺ void Draw(HDC hdc) { for (int i = 0; i < element.size(); ++i) { element[i].Draw(hdc); } } }; // ҪͼࣨMultiLineString class PolyLineLayer { public: std::string layer_id; // ͼҪ std::vector<PolyLine> element; int LineWidth; COLORREF color; int style; // 캯ʼ PolyLineLayer(string layer_id = "PolylineLayer_1") { style = PS_SOLID; LineWidth = 1.0; color = RGB(0, 255, 0); } // GeoJson void InitialFromGeoJson(Json::Value root) { style = PS_SOLID; LineWidth = 1.0; color = RGB(rand() % 256, rand() % 256, rand() % 256); Json::Value properties, geometry, coordinates, p_xy, xy; properties = root["properties"]; string pID = properties["id"].asString(); geometry = root["geometry"]; coordinates = geometry["coordinates"]; float px = 0; float py = 0; layer_id = pID; // // Jsonе֯ʽ //[ // [ // [105.6005859375, 30.65681556429287], // [107.95166015624999, 31.98944183792288], // [109.3798828125, 30.031055426540206], // [107.7978515625, 29.935895213372444] // ] , // [ // [109.3798828125, 30.031055426540206], // [107.1978515625, 31.235895213372444] // ] //] // for (int i = 0; i < coordinates.size(); ++i) { p_xy = coordinates[i]; string line_name = "Line_"; string line_no = std::to_string(i); string line_id = line_name + line_no; PolyLine polyline(line_id); polyline.AddCoorFromGeoJson(p_xy); element.push_back(polyline); } } // ƺ void Draw(HDC hdc) { HPEN hPen1 = CreatePen(style, LineWidth, color); HPEN hOld = (HPEN)SelectObject(hdc, hPen1); for (int i = 0; i < element.size(); ++i) { element[i].Draw(hdc); } SelectObject(hdc, hOld); } }; // ҪͼࣨMultiPolygon class PolyGonLayer { public: std::string layer_id; // ͼҪ std::vector<PolyGon> element; int style; int LineWidth; COLORREF LineColor; COLORREF FillColor; // 캯ʼ PolyGonLayer(string layer_id = "PolygonLayer") { style = PS_SOLID; LineWidth = 1.0; LineColor = RGB(255, 0, 0); FillColor = RGB(0, 0, 255); } // GeoJson void InitialFromGeoJson(Json::Value root) { style = PS_SOLID; LineWidth = 1.0; LineColor = RGB(255, 0, 0); FillColor = RGB(0, 0, 255); Json::Value properties, geometry, coordinates, p_xy, xy; properties = root["properties"]; string pID = properties["id"].asString(); geometry = root["geometry"]; coordinates = geometry["coordinates"]; float px = 0; float py = 0; layer_id = pID; // // Jsonе֯ʽ /*[ [ [ [109.2041015625, 30.088107753367257], [115.02685546875, 30.088107753367257], [115.02685546875, 32.7872745269555], [109.2041015625, 32.7872745269555], [109.2041015625, 30.088107753367257] ] ] , [ [ [112.9833984375, 26.82407078047018], [116.69677734375, 26.82407078047018], [116.69677734375, 29.036960648558267], [112.9833984375, 29.036960648558267], [112.9833984375, 26.82407078047018] ] ] ]*/ // for (int i = 0; i < coordinates.size(); ++i) { p_xy = coordinates[i]; string poly_name = "Polygon_"; string poly_no = std::to_string(i); string poly_id = poly_name + poly_no; PolyGon polyGon(poly_id); polyGon.AddCoorFromGeoJson(p_xy); element.push_back(polyGon); } } // ƺ void Draw(HDC hdc) { HPEN hPen1 = CreatePen(style, LineWidth, LineColor); HBRUSH hBrush = CreateSolidBrush(FillColor); HPEN hOldPen = (HPEN)SelectObject(hdc, hPen1); HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, hBrush); for (int i = 0; i < element.size(); ++i) { element[i].Draw(hdc); } SelectObject(hdc, hOldPen); SelectObject(hdc, hOldBrush); } }; // ࣨӣҪؼͼ/ͼ(FeatureCollectionΪFeature) class FeatureCollection { public: std::string layer_id; // ͼ/ͼĵҪؼ/ͼ std::vector<PolyGonLayer> Poly_element; // ͼ/ͼҪؼ/ͼ std::vector<PolyLineLayer> Line_element; // ͼ/ͼҪؼ/ͼ std::vector<PointLayer> Point_element; int style; int LineWidth; COLORREF LineColor; COLORREF FillColor; // 캯ʼ FeatureCollection() { layer_id = "Map"; style = PS_SOLID; LineWidth = 1.0; LineColor = RGB(255, 0, 0); FillColor = RGB(0, 0, 255); } // GeoJson void InitialFromGeoJson(Json::Value root) { style = PS_SOLID; LineWidth = 1.0; LineColor = RGB(255, 0, 0); FillColor = RGB(0, 0, 255); Json::Value features, feature, properties, geometry, coordinates, p_xy, xy; features = root["features"]; for (int i = 0; i < features.size(); ++i) { feature = features[i]; properties = feature["properties"]; geometry = feature["geometry"]; string pID = properties["name"].asString(); string l_type = geometry["type"].asString(); // жҪͣ㡢ߡ棬ɶӦҪأ if (l_type == "MultiPolygon") { PolyGonLayer pgl(pID); pgl.InitialFromGeoJson(feature); Poly_element.push_back(pgl); } else if (l_type == "MultiLineString") { PolyLineLayer pll(pID); pll.InitialFromGeoJson(feature); Line_element.push_back(pll); } else if (l_type == "MultiPoint") { PointLayer pl(pID); pl.InitialFromGeoJson(feature); Point_element.push_back(pl); } } } // ƺ void Draw(HDC hdc) { HPEN hPen1 = CreatePen(style, LineWidth, LineColor); HBRUSH hBrush = CreateSolidBrush(FillColor); HPEN hOldPen = (HPEN)SelectObject(hdc, hPen1); HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, hBrush); for (int i = 0; i < Poly_element.size(); ++i) { Poly_element[i].Draw(hdc); } for (int i = 0; i < Line_element.size(); ++i) { Line_element[i].Draw(hdc); } for (int i = 0; i < Point_element.size(); ++i) { Point_element[i].Draw(hdc); } SelectObject(hdc, hOldPen); SelectObject(hdc, hOldBrush); } };
true
595c81486dbe7c52f553d38e72f97cc643987b6e
C++
vjkholiya123/Library-Management-System
/Library Management System.cpp
UTF-8
3,478
2.71875
3
[]
no_license
#include<iostream> #include<string.h> #include<string> #include<conio.h> #include<fstream> #include<stdio.h> #include<bits/stdc++.h> using namespace std; bool checkiflogin=false; int choice=0; class check { public: string a; int b; void add1() { cout<<"\n\t\tenter the book name you want to enter in our record = "; cin>>a; add(); } void add() { cout<<" \n\t\tEnter the price of the book ="; cin>>b; ofstream f1; f1.open("books.txt",ios::app); f1<<a<<" RS."<<b<<" "; cout<<"\n\n\t\tRecords sucessfully saved in file"; f1.close(); } }c1; class books { char a[30],b[20]; public: void show() { char ch; ifstream ii("books.txt"); cout<<"\n\n\t\t "; while(!ii.eof()) { ii.get(ch); if(ch==' ') { cout<<"\n\n\t"; } cout<<ch; } ii.close(); } void check() { char c[20],w[20]; int k=0; fstream iff; books b1; iff.open("books.txt"); cout<<"\n\t\tEnter the name of the book you want to check if present in our \t\t\tlibrary :"; cin>>c; while(iff) { iff>>w; if(strcmp(w,c)==0) k++; } if(k>0) cout<<"\n\n\t\tBook present"; else cout<<"\n\n\t\tNo such book"; } void deletee() { if(checkiflogin) { char ch; cout<<"\n\t\tAre you sure you want to delete the book record.\n\t\tUndo is not possible"; cout<<"\n\t\tPress y to confirm or other key to cancel = "; cin>>ch; if(ch=='y'||ch=='Y') { ofstream xyz("books.txt",ios::out|ios::trunc); xyz.close(); cout<<"\n\t\tFile contents deleted succesfully"; } else { cout<<"\n\n\t\tCancelled by user"; } } else { login(); } } void login() { bool checking_if_login_done=false; string s1; char s3[]="vijay"; string s2="vjkholiya"; int c=0; char pass[25]; int p; d: cout<<"\n\n\t\tEnter Login ID:"; cin>>s1; if (s1==s2) { cout<<"\n\t\tEnter Password:"; for (int i=0;i<strlen(s3);i++) { pass[i] = getch(); cout<<"*"; } for (int j=0;j<strlen(s3);j++) { if (pass[j] == s3[j]) c = c+1; } if (c == strlen(s3)) { cout<<"\n\n\t\tCorrect Password"; cout<<"\n\n\t\tYou have succesfully logged in as vjkholiya"; checking_if_login_done=true; checkiflogin=true; } else cout<<"\n\n\t\tInvalid Password"; } else { cout<<"\n\n\t\tWrong username please retry"; goto d; } if(checking_if_login_done && choice==4) deletee(); else exit; } }b1; main() { int ch,i; char a; cout<<"\n\n\t\t"; for(i=0;i<33;i++) {cout<<"*"; } cout<<"\n\t\t*\t\t\t\t*"; cout<<"\n\t\t* BOOK SHOP MANAGEMENT SYSTEM * "; cout<<"\n\t\t*\t\t\t\t*\n\t\t"; for(i=0;i<33;i++) {cout<<"*"; } xyz: cout<<"\n\n\n\t\tEnter your choices(1-5)\n\n"; cout<<"\n\n\t\t1.Add book records\n"; cout<<"\n\t\t2.Show book records\n"; cout<<"\n\t\t3.Check availability\n"; cout<<"\n\t\t4.Delete book records\n"; cout<<"\n\t\t5.Login\n"; cout<<"\n\t\t6.Exit\n\t\t"; cin>>ch; choice=ch; switch(ch) { case 1: c1.add1(); break; case 2: b1.show(); break; case 3: b1.check(); break; case 4: b1.deletee(); break; case 5: b1.login(); break; case 6: return 0; default: exit; } cout<<"\n\n\t\tWant to do more(Y or N)"; cin>>a; if(a=='y'||a=='Y') goto xyz; else exit; }
true
285bb7006b34fe715313f2b9e91080b112747d3a
C++
wlmwang/hnet-src
/core/wMisc.cpp
UTF-8
16,120
2.671875
3
[]
no_license
/** * Copyright (C) Anny Wang. * Copyright (C) Hupu, Inc. */ #include <algorithm> #include "wMisc.h" #include "wAtomic.h" #include "wLogger.h" namespace hnet { namespace coding { void EncodeFixed8(char* buf, uint8_t value) { if (kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; } } void EncodeFixed16(char* buf, uint16_t value) { if (kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; } } void EncodeFixed32(char* buf, uint32_t value) { if (kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; buf[2] = (value >> 16) & 0xff; buf[3] = (value >> 24) & 0xff; } } void EncodeFixed64(char* buf, uint64_t value) { if (kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; buf[2] = (value >> 16) & 0xff; buf[3] = (value >> 24) & 0xff; buf[4] = (value >> 32) & 0xff; buf[5] = (value >> 40) & 0xff; buf[6] = (value >> 48) & 0xff; buf[7] = (value >> 56) & 0xff; } } void PutFixed32(std::string* dst, uint32_t value) { char buf[sizeof(value)]; EncodeFixed32(buf, value); dst->append(buf, sizeof(buf)); } void PutFixed64(std::string* dst, uint64_t value) { char buf[sizeof(value)]; EncodeFixed64(buf, value); dst->append(buf, sizeof(buf)); } } // namespace coding namespace logging { void AppendNumberTo(std::string* str, uint64_t num) { char buf[30]; snprintf(buf, sizeof(buf), "%llu", (unsigned long long) num); str->append(buf); } void AppendEscapedStringTo(std::string* str, const wSlice& value) { for (size_t i = 0; i < value.size(); i++) { char c = value[i]; if (c >= ' ' && c <= '~') { // 可见字符范围 str->push_back(c); } else { char buf[10]; // 转成\x[0-9]{2} 16进制输出,前缀补0 snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned int>(c) & 0xff); str->append(buf); } } } std::string NumberToString(uint64_t num) { std::string r; AppendNumberTo(&r, num); return r; } std::string EscapeString(const wSlice& value) { std::string r; AppendEscapedStringTo(&r, value); return r; } bool DecimalStringToNumber(const std::string& in, uint64_t* val, uint8_t *width) { uint64_t v = 0; uint8_t digits = 0; while (!in.empty()) { char c = in[digits]; if (c >= '0' && c <= '9') { ++digits; const int delta = (c - '0'); static const uint64_t kMaxUint64 = ~static_cast<uint64_t>(0); if (v > kMaxUint64/10 || (v == kMaxUint64/10 && static_cast<uint64_t>(delta) > kMaxUint64%10)) { // 转化uint64溢出 return false; } v = (v * 10) + delta; } else { break; } } *val = v; (width != NULL) && (*width = digits); return (digits > 0); } } // namespace logging namespace misc { static inline void FallThroughIntended() { } uint32_t Hash(const char* data, size_t n, uint32_t seed) { const uint32_t m = 0xc6a4a793; const uint32_t r = 24; const char* limit = data + n; uint32_t h = seed ^ (n * m); // Pick up four bytes at a time while (data + 4 <= limit) { uint32_t w = coding::DecodeFixed32(data); data += 4; h += w; h *= m; h ^= (h >> 16); } switch (limit - data) { case 3: h += static_cast<unsigned char>(data[2]) << 16; FallThroughIntended(); case 2: h += static_cast<unsigned char>(data[1]) << 8; FallThroughIntended(); case 1: h += static_cast<unsigned char>(data[0]); h *= m; h ^= (h >> r); break; } return h; } char *Cpystrn(char *dst, const char *src, size_t n) { if (n == 0) return dst; while (--n) { *dst = *src; if (*dst == '\0') { return dst; } dst++; src++; } *dst = '\0'; return dst; } void Strlow(char *dst, const char *src, size_t n) { do { *dst = tolower(*src); dst++; src++; } while (--n); } void Strupper(char *dst, const char *src, size_t n) { do { *dst = toupper(*src); dst++; src++; } while (--n); } int32_t Strcmp(const std::string& str1, const std::string& str2, size_t n) { return str1.compare(0, n, str2, 0, n); } int32_t Strpos(const std::string& haystack, const std::string& needle) { std::string::size_type pos = haystack.find(needle); if (pos != std::string::npos) { return pos; } return -1; } std::vector<std::string> SplitString(const std::string& src, const std::string& delim) { std::vector<std::string> dst; std::string::size_type pos1 = 0, pos2 = src.find(delim); while (std::string::npos != pos2) { dst.push_back(src.substr(pos1, pos2-pos1)); pos1 = pos2 + delim.size(); pos2 = src.find(delim, pos1); } if (pos1 != src.length()) { dst.push_back(src.substr(pos1)); } return dst; } static uint64_t Gcd(uint64_t a, uint64_t b) { if (a < b) std::swap(a, b); if (b == 0) return a; return Gcd(b, a % b); } uint64_t Ngcd(uint64_t *arr, size_t n) { if (n <= 1) return arr[n-1]; return Gcd(arr[n-1], Ngcd(arr, n-1)); } int GetIpList(std::vector<unsigned int>& iplist) { unsigned int ip = 0; ssize_t fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd >= 0) { struct ifconf ifc = {0, {0}}; struct ifreq buf[64]; memset(buf, 0, sizeof(buf)); ifc.ifc_len = sizeof(buf); ifc.ifc_buf = reinterpret_cast<caddr_t>(buf); if (!ioctl(fd, SIOCGIFCONF, (char*)&ifc)) { size_t interface = ifc.ifc_len / sizeof(struct ifreq); while (interface-- > 0) { if (!ioctl(fd, SIOCGIFADDR, reinterpret_cast<char*>(&buf[interface]))) { ip = reinterpret_cast<unsigned>((reinterpret_cast<struct sockaddr_in*>(&buf[interface].ifr_addr))->sin_addr.s_addr); iplist.push_back(ip); } } } close(fd); return 0; } return -1; } unsigned int GetIpByIF(const char* ifname) { unsigned int ip = 0; ssize_t fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd >= 0) { struct ifconf ifc = {0, {0}}; struct ifreq buf[64]; memset(buf, 0, sizeof(buf)); ifc.ifc_len = sizeof(buf); ifc.ifc_buf = reinterpret_cast<caddr_t>(buf); if (!ioctl(fd, SIOCGIFCONF, (char*)&ifc)) { size_t interface = ifc.ifc_len / sizeof(struct ifreq); while (interface-- > 0) { if (strcmp(buf[interface].ifr_name, ifname) == 0) { if (!ioctl(fd, SIOCGIFADDR, reinterpret_cast<char*>(&buf[interface]))) { ip = reinterpret_cast<unsigned>((reinterpret_cast<struct sockaddr_in*>(&buf[interface].ifr_addr))->sin_addr.s_addr); } break; } } } close(fd); } return ip; } int FastUnixSec2Tm(time_t unix_sec, struct tm* tm, int time_zone) { static const int kHoursInDay = 24; static const int kMinutesInHour = 60; static const int kDaysFromUnixTime = 2472632; static const int kDaysFromYear = 153; static const int kMagicUnkonwnFirst = 146097; static const int kMagicUnkonwnSec = 1461; tm->tm_sec = unix_sec % kMinutesInHour; int i = (unix_sec/kMinutesInHour); tm->tm_min = i % kMinutesInHour; i /= kMinutesInHour; tm->tm_hour = (i + time_zone) % kHoursInDay; tm->tm_mday = (i + time_zone) / kHoursInDay; int a = tm->tm_mday + kDaysFromUnixTime; int b = (a*4 + 3) / kMagicUnkonwnFirst; int c = (-b*kMagicUnkonwnFirst)/4 + a; int d =((c*4 + 3) / kMagicUnkonwnSec); int e = -d * kMagicUnkonwnSec; e = e/4 + c; int m = (5*e + 2)/kDaysFromYear; tm->tm_mday = -(kDaysFromYear * m + 2)/5 + e + 1; tm->tm_mon = (-m/10)*12 + m + 2; tm->tm_year = b*100 + d - 6700 + (m/10); return 0; } int SetBinPath(std::string bin_path, std::string self) { // 获取bin目录 char dir_path[256] = {'\0'}; if (bin_path.size() == 0) { // 可执行文件路径 int len = readlink(self.c_str(), dir_path, 256); if (len < 0 || len >= 256) { memcpy(dir_path, kRuntimePath, strlen(kRuntimePath) + 1); } else { for (int i = len; i >= 0; --i) { if (dir_path[i] == '/') { dir_path[i+1] = '\0'; break; } } } } else { memcpy(dir_path, bin_path.c_str(), bin_path.size() + 1); } // 切换目录 if (chdir(dir_path) == -1) { return -1; } umask(0); return 0; } } // namespace misc namespace error { const int32_t kSysNerr = 132; std::map<int32_t, const std::string> gSysErrlist; void StrerrorInit() { char* msg; for (int32_t err = 0; err < kSysNerr; err++) { msg = ::strerror(err); gSysErrlist.insert(std::make_pair(err, msg)); } gSysErrlist.insert(std::make_pair(kSysNerr, "Unknown error")); } const std::string& Strerror(int32_t err) { if (err >= 0 && err < kSysNerr) { return gSysErrlist[err]; } return gSysErrlist[kSysNerr]; } } //namespace error namespace http { static struct StatusCode_t statusCodes[] = { {"100", "Continue"}, {"101", "Switching Protocols"}, {"200", "Ok"}, {"201", "Created"}, {"202", "Accepted"}, {"203", "Non-authoritative Information"}, {"204", "No Content"}, {"205", "Reset Content"}, {"206", "Partial Content"}, {"300", "Multiple Choices"}, {"301", "Moved Permanently"}, {"302", "Found"}, {"303", "See Other"}, {"304", "Not Modified"}, {"305", "Use Proxy"}, {"306", "Unused"}, {"307", "Temporary Redirect"}, {"400", "Bad Request"}, {"401", "Unauthorized"}, {"402", "Payment Required"}, {"403", "Forbidden"}, {"404", "Not Found"}, {"405", "Method Not Allowed"}, {"406", "Not Acceptable"}, {"407", "Proxy Authentication Required"}, {"408", "Request Timeout"}, {"409", "Conflict"}, {"410", "Gone"}, {"411", "Length Required"}, {"412", "Precondition Failed"}, {"413", "Request Entity Too Large"}, {"414", "Request-url Too Long"}, {"415", "Unsupported Media Type"}, {"416", ""}, {"417", "Expectation Failed"}, {"500", "Internal Server Error"}, {"501", "Not Implemented"}, {"502", "Bad Gateway"}, {"503", "Service Unavailable"}, {"504", "Gateway Timeout"}, {"505", "HTTP Version Not Supported"}, {"", ""} }; std::map<const std::string, const std::string> gStatusCode; void StatusCodeInit() { for (int i = 0; strlen(statusCodes[i].code); i++) { gStatusCode.insert(std::make_pair(statusCodes[i].code, statusCodes[i].status)); } } const std::string& Status(const std::string& code) { return gStatusCode[code]; } static unsigned char toHex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } static unsigned char fromHex(unsigned char x) { unsigned char y; if (x >= 'A' && x <= 'Z') { y = x - 'A' + 10; } else if (x >= 'a' && x <= 'z') { y = x - 'a' + 10; } else { y = x - '0'; } return y; } std::string UrlEncode(const std::string& str) { std::string strTemp = ""; for (size_t i = 0; i < str.length(); i++) { if (isalnum(static_cast<unsigned char>(str[i])) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) { strTemp += str[i]; } else if (str[i] == ' ') { strTemp += "+"; } else { strTemp += '%'; strTemp += toHex(static_cast<unsigned char>(str[i]) >> 4); strTemp += toHex(static_cast<unsigned char>(str[i]) % 16); } } return strTemp; } std::string UrlDecode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (str[i] == '+') { strTemp += ' '; } else if (str[i] == '%') { if (i+2 >= length) { return ""; } unsigned char high = fromHex(static_cast<unsigned char>(str[++i])); unsigned char low = fromHex(static_cast<unsigned char>(str[++i])); strTemp += high*16 + low; } else { strTemp += str[i]; } } return strTemp; } } // namespace http namespace soft { static wAtomic<int64_t> hnet_currentTime(0); int64_t TimeUpdate() { int64_t tm = misc::GetTimeofday(); hnet_currentTime.ReleaseStore(tm); return tm; } int64_t TimeUsec() { return hnet_currentTime.AcquireLoad(); } time_t TimeUnix() { return static_cast<time_t>(hnet_currentTime.AcquireLoad()/1000000); } static uid_t hnet_deamonUser = kDeamonUser; static gid_t hnet_deamonGroup = kDeamonGroup; static std::string hnet_softwareName = kSoftwareName; static std::string hnet_softwareVer = kSoftwareVer; static std::string hnet_runtimePath = kRuntimePath; static std::string hnet_logdirPath = kLogdirPath; static std::string hnet_acceptFilename = kAcceptFilename; static std::string hnet_lockFilename = kLockFilename; static std::string hnet_pidFilename = kPidFilename; static std::string hnet_logFilename = kLogFilename; static std::string hnet_acceptFullPath = hnet_runtimePath + kAcceptFilename; static std::string hnet_lockFullPath = hnet_runtimePath + kLockFilename; static std::string hnet_pidFullPath = hnet_runtimePath + kPidFilename; static std::string hnet_logFullPath = hnet_logdirPath + kLogFilename; // 设置运行用户 uid_t SetUser(uid_t uid) { return hnet_deamonUser = uid;} gid_t SetGroup(gid_t gid) { return hnet_deamonGroup = gid;} // 设置版本信息 const std::string& SetSoftName(const std::string& name) { return hnet_softwareName = name;} const std::string& SetSoftVer(const std::string& ver) { return hnet_softwareVer = ver;} // 设置路径 void SetRuntimePath(const std::string& path) { hnet_runtimePath = path; hnet_acceptFullPath = path + hnet_acceptFilename; hnet_lockFullPath = path + hnet_lockFilename; hnet_pidFullPath = path + hnet_pidFilename; } void SetLogdirPath(const std::string& path) { hnet_logdirPath = path; hnet_logFullPath = path + hnet_logFilename; } // 设置文件名 void SetAcceptFilename(const std::string& filename) { hnet_acceptFilename = filename; hnet_acceptFullPath = hnet_runtimePath + filename; } void SetLockFilename(const std::string& filename) { hnet_lockFilename = filename; hnet_lockFullPath = hnet_runtimePath + filename; } void SetPidFilename(const std::string& filename) { hnet_pidFilename = filename; hnet_pidFullPath = hnet_runtimePath + filename; } void SetLogFilename(const std::string& filename) { hnet_logFilename = filename; hnet_logFullPath = hnet_logdirPath + filename; } uid_t GetUser() { return hnet_deamonUser;} gid_t GetGroup() { return hnet_deamonGroup;} const std::string& GetSoftName() { return hnet_softwareName;} const std::string& GetSoftVer() { return hnet_softwareVer;} const std::string& GetRuntimePath() { return hnet_runtimePath;} const std::string& GetLogdirPath() { return hnet_logdirPath;} const std::string& GetAcceptPath(bool fullpath) { return fullpath? hnet_acceptFullPath: hnet_acceptFilename;} const std::string& GetLockPath(bool fullpath) { return fullpath? hnet_lockFullPath: hnet_lockFilename;} const std::string& GetPidPath(bool fullpath) { return fullpath? hnet_pidFullPath: hnet_pidFilename;} const std::string& GetLogPath(bool fullpath) { return fullpath? hnet_logFullPath: hnet_logFilename;} } // namespace hnet } // namespace hnet
true
ed289e1347423458c0a50e3f9dadc42131754752
C++
AlanSavushkin/something
/template_matching.cpp
UTF-8
1,344
2.71875
3
[]
no_license
// // main.cpp // ObjFind // // Created by Алан Савушкин on 06.03.17. // Copyright © 2017 Алан Савушкин. All rights reserved. // #include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> using namespace std; using namespace cv; void obj_find(Mat &image, Mat &temp); int main(int argc, const char * argv[]) { if (argc != 2) { cout << "Use: " << argv[0] << "template_file" << endl; return -1; } Mat temp = imread(argv[1]); Mat frame; VideoCapture capture(0); if(!capture.isOpened()){ cout << "Error: can't open camera" << endl; return -1; } capture.set(CV_CAP_PROP_FRAME_HEIGHT, 640); capture.set(CV_CAP_PROP_FRAME_WIDTH, 480); namedWindow("Template matching"); while (1) { capture >> frame; flip(frame, frame, 1); obj_find1(frame, temp); imshow("Template matching", frame); if(waitKey(1) == 32){ break; } } return 0; } void obj_find(Mat &image, Mat &temp){ Mat res(Size(image.cols - temp.cols + 1, image.rows - temp.rows + 1), CV_32FC1); Point min_loc; matchTemplate(image, temp, res, 0); minMaxLoc(res,nullptr, nullptr, &min_loc); rectangle(image, min_loc, Point(min_loc.x + temp.cols, min_loc.y + temp.rows), Scalar(0, 0, 255)); }
true
ba6b7a02bf386322d6ab123db7c9b0010e16586a
C++
alexandraback/datacollection
/solutions_1484496_0/C++/Squarefk/cc.cpp
UTF-8
1,413
2.5625
3
[]
no_license
#include <cstdio> using namespace std; int list1[550],list2[550],hh[2002000]; int t,n,data[550],st[2002000]; bool can; void make(int now,int before) { list1[0]=0;int temp; temp=now; while (temp) {list1[++list1[0]]=hh[temp];temp-=hh[temp];} list2[0]=1;list2[1]=before; temp=now-before; while (temp) {list2[++list2[0]]=hh[temp];temp-=hh[temp];} for (int i=1;i<=list1[0];++i) for (int j=1;j<=list2[0];++j) if (list1[i]==list2[j]) {list1[i]=1;list2[j]=0;} for (int i=1;i<list1[0];++i) if (list1[i]) printf("%d ",list1[i]); printf("%d\n",list1[list1[0]]); for (int i=1;i<list2[0];++i) if (list2[i]) printf("%d ",list2[i]); printf("%d\n",list2[list2[0]]); } void insert_hash(int now,int before) { if (hh[now]) { make(now,before); can=true; return; } hh[now]=before; st[++st[0]]=now; } void work() { for (int i=1;i<=n;++i) { int tttt=st[0]; for (int j=1;j<=tttt;++j) { insert_hash(st[j]+data[i],data[i]); if (can) return; } insert_hash(data[i],data[i]); if (can) return; } } int main() { freopen("in","r",stdin); freopen("out","w",stdout); scanf("%d",&t); for (int tt=1;tt<=t;++tt) { scanf("%d",&n); for (int i=1;i<=n;++i) scanf("%d",&data[i]); can=false; printf("Case #%d:\n",tt); work(); for (int i=1;i<=st[0];++i) hh[st[0]]=0; st[0]=0; } return 0; }
true
f7e4f6a7a6ad8fe9fd9c1b8df596d0ba42caa9ff
C++
thanhtungdp/export-csv-to-html-cplusplus
/Source/libs/read_csv.h
UTF-8
3,396
3.375
3
[]
no_license
// // Created by Phan Tùng on 4/1/16. // #ifndef DO_AN_CUOI_KY_READ_CSV_H #define DO_AN_CUOI_KY_READ_CSV_H #include <iostream> #include <fstream> #include "memory.h" using namespace std; const string file_src = "data/students.csv"; const char file_string_delimiter = ','; const char file_string_quote = '\"'; /** * Next read index read delimiter * Example: string, test * ^ * Move ^ to next index * To: string, test * ^ */ void readCSV_NextIndexReadDelimiter(string line, int &index_read) { while (line[index_read] != file_string_delimiter && index_read < line.length()) { index_read++; } index_read++; } /** * Next read index over space to character * Example:" a " * ^ * Move ^ to a * After: " a " * ^ */ void readCSV_NextIndexReadSpace(string line, int &index_read) { while (line[index_read] == ' ' && index_read < line.length()) { index_read++; } } /** * Read variable have quote from string, and move index_read to new * Example: "test 1, tung thanh", "ok baby" * Ouput: (test 1, tung thanh) ; (ok baby) */ void readCSV_VariableQuote(const string line, int &index_read, string &string_read) { string_read = ""; index_read++; while (line[index_read] != file_string_quote && index_read < line.length()) { string_read += line[index_read]; index_read++; } readCSV_NextIndexReadDelimiter(line, index_read); readCSV_NextIndexReadSpace(line, index_read); } /** * Read variable normal from string, and move index_read to new * Example: hello world, hello one * Ouput: hello world ; hello one */ void readCSV_VariableNormal(const string line, int &index_read, string &string_read) { string_read = ""; while (line[index_read] != file_string_delimiter && index_read < line.length()) { string_read += line[index_read]; index_read++; } readCSV_NextIndexReadDelimiter(line, index_read); readCSV_NextIndexReadSpace(line, index_read); } /** * Read variable from line: * Example: line = "phan thanh tung","van tuan","obama" * With: index_read = 0 => string_read = "phan thanh tung" * index_read = 1 => string_read = "van tuan" * index_read = 3 => string_read = "obama" */ void readCSV_Variable(string line, int &index_read, string &string_read) { if (line[index_read] == file_string_quote) { readCSV_VariableQuote(line, index_read, string_read); } else readCSV_VariableNormal(line, index_read, string_read); } /** * Read lines in file scv * Example file csv: "hoc", cách, làm, "trò chơi" * "cuộc", sống, ôi, "đẹp quá" * string_lines = [ * 0 => string("hoc", cách, làm, "trò chơi") * 1 => string("cuộc", sống, ôi, "đẹp quá") * ] */ int readCSV_ToLines(string *&string_lines, bool &read_error) { ifstream file(file_src); int lines_count = 0; if (file.is_open()) { /* End get lines count */ string_lines = new string[1]; while (!file.eof()) { getline(file, string_lines[lines_count]); lines_count++; allocate_memory_string(string_lines, lines_count); // allocate new memory (+1 type) } file.close(); } else { read_error = true; } return lines_count; } #endif //DO_AN_CUOI_KY_READ_CSV_H
true
0c03ae784c44c4032f9ead3a622e4350d14585cc
C++
Sazanaizu33/RangeKutta4thOrder
/Runge-Kutta 4th order/Runge-Kutta 4th order/RungeKutta4.cpp
UTF-8
1,239
3.234375
3
[]
no_license
#include <math.h> #include <iostream> #include "RungeKutta4.h" RungeKutta4::RungeKutta4() { } RungeKutta4::~RungeKutta4() { } /*This function is responsible for the 4th-order Runge-Kutta method. It returns the calculated value at each t.*/ double RungeKutta4::DoRungeKutta4(const double N, const double h, const double yInitValue, const double tInitValue) { //Declaration and Initialization. Variables will be changed, so do NOT use CONST double k1 = 0.0; double k2 = 0.0; double k3 = 0.0; double k4 = 0.0; double t = 0.0; double t2 = 0.0; double y = 0.0; double y0 = yInitValue; double t0 = tInitValue; int j; for(j = 1; j <= N; j++) { t = j * h; t2 = t0 + 0.5 * h; k1 = f(t0, y0); k2 = f(t2, y0 + 0.5 * k1); k3 = f(t2, y0 + 0.5 * k2); k4 = f(t0 + h, y0 + k3); y = y0 + (h/6.0)*(k1 + 2.0 * (k2 + k3) + k4); y0 = y; t0 = t; printf("The approximate value at t = %0.3f is %0.14f\n", t0, y0); } return y0; } /*This function is responsible for generating equation to be used in the Runge-Kutta method above.*/ double RungeKutta4::f(const double t, const double y) { double log_result = 0.0; double result = 0.0; log_result = log(y); result = -y * log_result; return result; }
true
8f5c3a15489d0542dc61e6066ac62ffcd1ee237c
C++
EnricoGiordano1992/TesiMagistrale
/rechannel/old/src/sommatore.cc
UTF-8
284
2.703125
3
[]
no_license
// file sommatore.cpp #include "sommatore.hh" // Implementazione del metodo somma dichiarato nel modulo void sommatore::somma() { if(is_ready.read() == 1) { cout.write(static_cast< sc_int<32> >( a.read() ) + static_cast< sc_int<32> >( b.read() )); result_isready.write(1); } }
true
ccb02785886b83d5ee5dec26574728e057491c03
C++
Can1210/Team16_DxLib
/Team16/Actor/Enemies/Array.h
SHIFT_JIS
527
3.125
3
[]
no_license
#ifndef INCLUDED_ARRAY_1D_H #define INCLUDED_ARRAY_1D_H //1zNX template< class T > class Array { public: Array() : mArray(0) {} ~Array() { delete[] mArray; mArray = 0; //|C^0 } void setSize(int size0) { if (mArray) { delete[] mArray; mArray = 0; } mSize0 = size0; mArray = new T[size0]; } T& operator()(int index0) { return mArray[index0]; } const T& operator()(int index0) const { return mArray[index0]; } private: T* mArray; int mSize0; }; #endif
true
7100750d15c833f4c93f65006bff22ff423bee5f
C++
Harrix/Harrix-MathLibrary
/src/Непараметрика/HML_NonparametricEstimatorOfDerivative2.cpp
UTF-8
3,807
3.078125
3
[ "MIT", "Apache-2.0" ]
permissive
double HML_NonparametricEstimatorOfDerivative2(double x, double *X, double *Y, int VHML_N, double C, int V, bool *b) { /* Непараметрическая оценка производной при равномерном законе распределения элементов выборки в точке. Рассматривается одномерный случай: 1 вход и 1 выход. Отличается от HML_NonparametricEstimatorOfDerivative тем, что производная считается только в точках выборки, а потом в остальных точках вычисляется как в обычной непараметрической оценке регрессии в вновь полученной выборке. Входные параметры: x - входная переменная; X - выборка: значения входов; Y - выборка: соответствующие значения выходов; VHML_N - размер выборки; C - коэффициент размытости; V - тип ядра 0 - прямоугольное (не рекомендуется); 1 - треугольное; 2 - параболическое (считается оптимальным); 3 - экспоненциальное; b - сюда возвращается 1, если все прошло хорошо и 0, если C не захватывает никаких точек выборки (тогда функция возвращает 0). Возвращаемое значение: Восстановленное значение производной функции в точке. */ double *dY=new double [VHML_N]; double dy=0; bool b2; for (int i=0;i<VHML_N;i++) { //непараметрическая оценка производной dY[i]=HML_NonparametricEstimatorOfDerivative(X[i], X, Y, VHML_N, C, V, &b2); } //непараметрическая оценка регрессии dy=HML_NonparametricEstimatorOfRegression(x, X, dY, VHML_N, C, V, b); delete [] dY; return dy; } //--------------------------------------------------------------------------- double HML_NonparametricEstimatorOfDerivative2(double x, double *X, double *Y, int VHML_N, double C, int V) { /* Непараметрическая оценка производной при равномерном законе распределения элементов выборки в точке. Рассматривается одномерный случай: 1 вход и 1 выход. Отличается от HML_NonparametricEstimatorOfDerivative тем, что производная считается только в точках выборки, а потом в остальных точках вычисляется как в обычной непараметрической оценке регрессии в вновь полученной выборке. Входные параметры: x - входная переменная; X - выборка: значения входов; Y - выборка: соответствующие значения выходов; VHML_N - размер выборки; C - коэффициент размытости; V - тип ядра 0 - прямоугольное; 1 - треугольное; 2 - параболическое (считается оптимальным); 3 - экспоненциальное. Возвращаемое значение: Восстановленное значение производной функции в точке. */ double Result=0; bool b; Result = HML_NonparametricEstimatorOfDerivative2(x, X, Y, VHML_N, C, V, &b); return Result; }
true
09ab687adf54b1fc3a34df297c28aacdf4a9e336
C++
alexander-koval/HelloWorld
/Grafit/include/Grafit/Graphics/BlendMode.hpp
UTF-8
2,147
2.90625
3
[]
no_license
#ifndef BLENDMODE_HPP #define BLENDMODE_HPP namespace gf { struct BlendMode { enum Factor { Zero, ///< (0, 0, 0, 0) One, ///< (1, 1, 1, 1) SrcColor, ///< (src.r, src.g, src.b, src.a) OneMinusSrcColor, ///< (1, 1, 1, 1) - (src.r, src.g, src.b, src.a) DstColor, ///< (dst.r, dst.g, dst.b, dst.a) OneMinusDstColor, ///< (1, 1, 1, 1) - (dst.r, dst.g, dst.b, dst.a) SrcAlpha, ///< (src.a, src.a, src.a, src.a) OneMinusSrcAlpha, ///< (1, 1, 1, 1) - (src.a, src.a, src.a, src.a) DstAlpha, ///< (dst.a, dst.a, dst.a, dst.a) OneMinusDstAlpha ///< (1, 1, 1, 1) - (dst.a, dst.a, dst.a, dst.a) }; enum Equation { Add, ///< Pixel = Src * SrcFactor + Dst * DstFactor Subtract ///< Pixel = Src * SrcFactor - Dst * DstFactor }; BlendMode(); BlendMode(Factor sourceFactor, Factor destinationFactor, Equation blendEquation = Add); BlendMode(Factor colorSourceFactor, Factor colorDestinationFactor, Equation colorBlendEquation, Factor alphaSourceFactor, Factor alphaDestinationFactor, Equation alphaBlendEquation); Factor colorSrcFactor; ///< Source blending factor for the color channels Factor colorDstFactor; ///< Destination blending factor for the color channels Equation colorEquation; ///< Blending equation for the color channels Factor alphaSrcFactor; ///< Source blending factor for the alpha channel Factor alphaDstFactor; ///< Destination blending factor for the alpha channel Equation alphaEquation; ///< Blending equation for the alpha channel }; bool operator ==(const BlendMode& left, const BlendMode& right); bool operator !=(const BlendMode& left, const BlendMode& right); extern const BlendMode BlendAlpha; ///< Blend source and dest according to dest alpha extern const BlendMode BlendAdd; ///< Add source to dest extern const BlendMode BlendMultiply; ///< Multiply source and dest extern const BlendMode BlendNone; ///< Overwrite dest with source } #endif // BLENDMODE_HPP
true
a88ee8c21ee0d06b9288cc642b577b146e691658
C++
huchong0/TinySTL
/TinySTL/stack.h
UTF-8
466
3.015625
3
[]
no_license
#pragma once #ifndef STACK #define STACK #include"deque.h" namespace TinySTL { template <class T> class stack { deque<T> buffer; public: void push(const T& value) { buffer.push_back(value); } void pop() { buffer.pop_back(); } T top() { return buffer.back(); } void clear() { buffer.clear(); } bool empty() { return buffer.empty(); } size_t size() { return buffer.size(); } }; } #endif // ! STACK
true
8b08ea0c5fc84ba11412fab25efc424136cd1068
C++
searleser97/DistribuitedSystems
/SocketMulticast/MulticastSocket.cpp
UTF-8
1,536
2.65625
3
[]
no_license
#include "MulticastSocket.h" #include "DatagramSocket.h" #include <arpa/inet.h> #include <string.h> MulticastSocket::MulticastSocket() : DatagramSocket() {} MulticastSocket::MulticastSocket(uint16_t iport) : DatagramSocket(iport) {} MulticastSocket::~MulticastSocket() {} void MulticastSocket::joinGroup(uint16_t iport, const std::string &addr) { memset(&groupAddr, 0, sizeof(groupAddr)); groupAddr.imr_multiaddr.s_addr = inet_addr(addr.c_str()); groupAddr.imr_interface.s_addr = htons(iport); if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&groupAddr, sizeof(groupAddr)) < 0) throw std::string("Could not join group: ") + std::string(strerror(errno)); } void MulticastSocket::leaveGroup(uint16_t iport, const std::string &addr) { memset(&groupAddr, 0, sizeof(groupAddr)); groupAddr.imr_multiaddr.s_addr = inet_addr(addr.c_str()); groupAddr.imr_interface.s_addr = htons(iport); if (setsockopt(s, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void *)&groupAddr, sizeof(groupAddr)) < 0) throw std::string("Could not leave group") + std::string(strerror(errno)); } int MulticastSocket::send(DatagramPacket &p, uint8_t ttl) { setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (void *)&ttl, sizeof(ttl)); return DatagramSocket::send(p); } int MulticastSocket::receive(DatagramPacket &p) { return DatagramSocket::receive(p); } int MulticastSocket::receiveTimeout(DatagramPacket &p, time_t seconds, suseconds_t microseconds) { return DatagramSocket::receiveTimeout(p, seconds, microseconds); }
true
8c6f8a396be12c3b11d587ca87675fe6b138a87d
C++
rhaeus/basic_raytracer
/src/Cube.cpp
UTF-8
3,355
2.875
3
[]
no_license
#include "Cube.h" #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/transform.hpp> #include <glm/gtx/euler_angles.hpp> inline float deg2rad(const float &deg) { return deg * M_PI / 180.0f; } Cube::Cube(glm::vec3 center, std::shared_ptr<Material> material_, glm::vec3 scale, float roll_, float pitch_, float yaw_) : TriangleMesh(material_) { float roll = deg2rad(roll_); float pitch = deg2rad(pitch_); float yaw = deg2rad(yaw_); glm::mat4 translation = glm::translate(glm::mat4(1.0), center); glm::mat4 scaling = glm::scale(glm::mat4(1.0), scale); glm::mat4 rotation = glm::yawPitchRoll(yaw, pitch, roll); glm::mat4 transformation = translation * rotation * scaling; std::vector<glm::vec4> vertices; vertices.push_back(glm::vec4(-0.5f, -0.5f, -0.5f, 1)); vertices.push_back(glm::vec4(+0.5f, -0.5f, -0.5f, 1)); vertices.push_back(glm::vec4(+0.5f, +0.5f, -0.5f, 1)); vertices.push_back(glm::vec4(-0.5f, +0.5f, -0.5f, 1)); vertices.push_back(glm::vec4(-0.5f, -0.5f, +0.5f, 1)); vertices.push_back(glm::vec4(+0.5f, -0.5f, +0.5f, 1)); vertices.push_back(glm::vec4(+0.5f, +0.5f, +0.5f, 1)); vertices.push_back(glm::vec4(-0.5f, +0.5f, +0.5f, 1)); // transform cube std::vector<glm::vec3> vs; for (auto v : vertices) { glm::vec4 vertex = transformation * v; vs.push_back(glm::vec3(vertex.x/vertex.w, vertex.y/vertex.w, vertex.z/vertex.w)); } // front triangles.push_back(new Triangle(vs[0], vs[1], vs[2], glm::vec2(0.25, 0.66), glm::vec2(0.50, 0.66), glm::vec2(0.50, 0.33), material_)); triangles.push_back(new Triangle(vs[0], vs[2], vs[3], glm::vec2(0.25, 0.66), glm::vec2(0.50, 0.33), glm::vec2(0.25, 0.33), material_)); //left triangles.push_back(new Triangle(vs[4], vs[0], vs[3], glm::vec2(0.00, 0.66), glm::vec2(0.25, 0.66), glm::vec2(0.25, 0.33), material_)); triangles.push_back(new Triangle(vs[4], vs[3], vs[7], glm::vec2(0.00, 0.66), glm::vec2(0.25, 0.33), glm::vec2(0.00, 0.33), material_)); // right triangles.push_back(new Triangle(vs[1], vs[5], vs[2], glm::vec2(0.50, 0.66), glm::vec2(0.75, 0.66), glm::vec2(0.50, 0.33),material_)); triangles.push_back(new Triangle(vs[5], vs[6], vs[2], glm::vec2(0.75, 0.66), glm::vec2(0.75, 0.33), glm::vec2(0.55, 0.33),material_)); //back triangles.push_back(new Triangle(vs[5], vs[4], vs[7], glm::vec2(0.75, 0.66), glm::vec2(1.00, 0.66), glm::vec2(1.00, 0.33),material_)); triangles.push_back(new Triangle(vs[5], vs[7], vs[6], glm::vec2(0.75, 0.66), glm::vec2(1.00, 0.33), glm::vec2(0.75, 0.33),material_)); // top triangles.push_back(new Triangle(vs[3], vs[2], vs[7], glm::vec2(0.25, 0.33), glm::vec2(0.50, 0.33), glm::vec2(0.25, 0.00),material_)); triangles.push_back(new Triangle(vs[2], vs[6], vs[7], glm::vec2(0.50, 0.33), glm::vec2(0.50, 0.00), glm::vec2(0.25, 0.00),material_)); // bottom triangles.push_back(new Triangle(vs[5], vs[1], vs[0], glm::vec2(0.50, 1.00), glm::vec2(0.50, 0.66), glm::vec2(0.25, 0.66),material_)); triangles.push_back(new Triangle(vs[5], vs[0], vs[4], glm::vec2(0.50, 1.00), glm::vec2(0.25, 0.66), glm::vec2(0.25, 1.00),material_)); // calculate bounds // bounds = triangles.at(0)->getBounds(); // for (auto t : triangles) { // bounds = bounds + t->getBounds(); // } }
true
fd3cb6940a95b103e70e6abb309e3e87dfcc62e7
C++
tomasClavijo/A1-Obligatorios
/Obligatorio 2/ListaOrdIntImp.cpp
UTF-8
2,876
2.96875
3
[]
no_license
#include "ListaOrdInt.h" #ifdef LISTA_ORD_INT_IMP struct _cabezalListaOrdInt { NodoListaInt* ppio; unsigned int largo; }; /* AUXILIARES */ // PRE: // POS: Agrega el dato ordenado creando un nuevo nodo void agregar(NodoListaInt*& l, int dato) { if (l == NULL) { l = new NodoListaInt(dato); } else if (dato <= l->dato) { NodoListaInt* nuevo = new NodoListaInt(dato); nuevo->sig = l; l = nuevo; } else { // if (dato > l->dato) agregar(l->sig, dato); } } // PRE: // POS: Borra el nodo con el dato maximo bool borrarMaximo(NodoListaInt*& l) { if (l == NULL) { return false; } if (l->sig != NULL) { return borrarMaximo(l->sig); } NodoListaInt* temp = l; l = l->sig; delete temp; return true; } // PRE: // POS: Borra el nodo con el dato bool borrar(NodoListaInt*& l, int dato) { if (l == NULL) return false; if (dato > l->dato) { return borrar(l->sig, dato); } if (dato < l->dato) { return false; } NodoListaInt* temp = l; l = l->sig; delete temp; return true; } // PRE: // POS: Borra todos los nodos void vaciar(NodoListaInt*& l) { if (l != NULL) { vaciar(l->sig); delete l; l = NULL; } } // PRE: // POS: Retorna un puntero a la copia de todos los nodos NodoListaInt* clon(NodoListaInt* l) { if (l == NULL) return NULL; NodoListaInt* nuevo = new NodoListaInt; nuevo->dato = l->dato; nuevo->sig = clon(l->sig); return nuevo; } // PRE: // POS: Retorna si existe el dato en un nodo bool existe(NodoListaInt* l, int dato) { if (l == NULL) return false; if (dato > l->dato) { return existe(l->sig, dato); } if (dato < l->dato) { return false; } return true; } /* FIN AUXILIARES */ ListaOrdInt crearListaOrdInt() { ListaOrdInt cabezal = new _cabezalListaOrdInt; cabezal->ppio = NULL; cabezal->largo = 0; return cabezal; } void agregar(ListaOrdInt& l, int e) { agregar(l->ppio, e); l->largo++; } void borrarMinimo(ListaOrdInt& l) { if (l->ppio == NULL) return; NodoListaInt *borro = l->ppio; l->ppio = l->ppio->sig; l->largo--; delete borro; } void borrarMaximo(ListaOrdInt& l) { if (borrarMaximo(l->ppio)) l->largo--; } void borrar(ListaOrdInt& l, int e) { if (borrar(l->ppio, e)) l->largo--; } int minimo(ListaOrdInt l) { assert(!esVacia(l)); return l->ppio->dato; } int maximo(ListaOrdInt l) { assert(!esVacia(l)); NodoListaInt* aux = l->ppio; #pragma warning(suppress: 28182) while (aux->sig != NULL) { aux = aux->sig; } return aux->dato; } bool existe(ListaOrdInt l, int e) { return existe(l->ppio, e); } bool esVacia(ListaOrdInt l) { return l->largo == 0; } unsigned int cantidadElementos(ListaOrdInt l) { return l->largo; } ListaOrdInt clon(ListaOrdInt l) { ListaOrdInt cabezal = new _cabezalListaOrdInt; cabezal->ppio = clon(l->ppio); cabezal->largo = l->largo; return cabezal; } void destruir(ListaOrdInt& l) { vaciar(l->ppio); delete l; l = NULL; } #endif
true
acb4fc3bde0052e41df91e05023cfe648b631558
C++
DEVECLOVER/LeetCodeFighting_CPP
/LeetCode101-200/132.分割回文串-ii.cpp
UTF-8
3,710
3.125
3
[]
no_license
/* * @lc app=leetcode.cn id=132 lang=cpp * * [132] 分割回文串 II */ // @lc code=start class Solution { public: //暴力回溯 超时 这个方法是借用 前一题的思路 bool IsSym(string str) { int left = 0; int right = str.size() - 1; while(left < right) { if(str[left] != str[right]) return false; ++left; --right; } return true; } void CutCore(string& str,int index,vector<string>& result,int& minlen) { if(index >= str.size()) { int length = result.size(); minlen = min(minlen,length);//不能将result.size() 直接放入min函数中 return; } for(int i = index;i < str.size();++i) { int len = i - index + 1; if(!IsSym(str.substr(index,len))) continue; result.push_back(str.substr(index,len)); CutCore(str,i + 1,result,minlen); result.pop_back(); } } int minCut(string s) { //回溯算法 // vector<string> result; // int minlen = s.size(); // if(minlen < 1) // return 0; // CutCore(s,0,result,minlen); // return minlen - 1; //看看,这都是自己思维走过的路,吸取经验教训吧 // int len = s.size(); // int dp[len][len]; // memset(dp,0,len * len); // for(int i = 0;i < len - 1;++i) // { // if(s[i] == s[i + 1]) // dp[i][i + 1] = 0; // else // dp[i][i + 1] = 1; // } // for(int slen = 3;slen <= len;++slen) // { // for(int i = 0;i + slen - 1 < len;++i) // { // int j = i + slen - 1; // if(s[i] == s[j]) // dp[i][j] = dp[i + 1][j - 1]; // else // dp[i][j] = dp[i + 1][j - 1] + 2; // } // } // return dp[0][len - 1]; int len = s.size(); if(len < 1) return 0; int dp[len]; bool flag[len][len]; memset(flag,false,len * len); for(int i = 0;i < len;++i) { for(int j = 0;j <= i;++j) { if(s[i] == s[j] && ((i - j) < 3 || flag[j + 1][i - 1])) flag[j][i] = true; } } // for(int i = 0;i < len;++i) // dp[i] = i; // for(int i = 0;i < len;++i) // { // if(IsSym(s.substr(0,i + 1))) // { // dp[i] = 0; // continue; // } // for(int j = 0;j < i;++j) // { // if(IsSym(s.substr(j + 1,i - j))) // dp[i] = min(dp[i],dp[j] + 1); // } // } // return dp[len - 1]; for(int i = 0;i < len;++i) dp[i] = i; for(int i = 0;i < len;++i) { if(flag[0][i]) { dp[i] = 0; continue; } for(int j = 1;j <= i;++j) { //注意下标的含义 //flag是从j 到 i,是闭区间 //dp[j] 是从0到j 也是闭区间 所以下面是取dp[j - 1] 之前写为dp[j] 就报错了 if(flag[j][i]) dp[i] = min(dp[i],dp[j - 1] + 1); } } return dp[len - 1]; } }; // @lc code=end
true
aad4202ab5a1ca9df0d7634409d2760af3551e60
C++
JJRWalker/ChaosEngine
/ChaosEngine/src/Chaos/Debug/Timer.h
UTF-8
1,243
2.984375
3
[ "Apache-2.0" ]
permissive
#ifndef _TIMER_H #define _TIMER_H #include <chrono> #ifndef CHAOS_PROFILE #define PROFILED_FUNC() Timer t(__FUNCTION__) #else #define PROFILED_FUNC() #endif namespace Chaos { class Timer { public: Timer(const char* name) : mName(name) { mStartPoint = std::chrono::high_resolution_clock::now(); } ~Timer() { if (!mStopped) Stop(); } void Stop() { auto endPoint = std::chrono::high_resolution_clock::now(); long long start = std::chrono::time_point_cast<std::chrono::microseconds>(mStartPoint).time_since_epoch().count(); long long end = std::chrono::time_point_cast<std::chrono::microseconds>(endPoint).time_since_epoch().count(); float duration = (end - start) * 0.001f; std::unordered_map<const char*, float>::iterator it = s_times.find(mName); if (it == s_times.end()) { s_times.insert({mName, duration}); } else { it->second = duration; } mStopped = true; } static std::unordered_map<const char*, float>& GetTimers() { return s_times; } private: const char* mName; bool mStopped = false; std::chrono::time_point<std::chrono::steady_clock> mStartPoint; static std::unordered_map<const char*, float> s_times; }; } #endif
true
31366b3bcc81c9427b022bdc68c63431b23a53ba
C++
verymadjack/automatic-spork
/asasasasasasasasasasasas/main.cpp
UTF-8
1,222
2.703125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main() { fstream U1; int b=0; int i = 0; int a = 0; int c = 0; int ii=0; int howMany=1; string firstLetter; int pages; string word; int numberOfNames; int namesPerPage; U1.open("U1.txt"); U1>>numberOfNames; U1>>namesPerPage; if(numberOfNames/namesPerPage>0) { pages=numberOfNames/namesPerPage; } else if(numberOfNames/namesPerPage<=0) { pages=0; } //cout<<pages<<endl; string tablica [namesPerPage][pages]; while(!U1.eof()) { for(;b<pages;b++){i=0; for(;i<namesPerPage;i++){ U1>>tablica[pages][namesPerPage]; cout<<tablica[pages][namesPerPage]; } } } while(a != pages && c != namesPerPage) { for(;b<pages;b++){ii=0; for(;i<namesPerPage;i++){ word=tablica[pages][namesPerPage]; if(ii!=1){ firstLetter=word[0];ii++;} else if(firstLetter!=word[0]){ howMany++; } } } } //cout<<tablica[0][0]; return 0; }
true
324b66a1e31fedaf473df1ddbce3379b77fafa48
C++
rupav/cp
/competitive_coding/contests/602_virtual/C.cpp
UTF-8
1,264
2.53125
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; #define fr(i,n) for(int i=0; i<n; i++) #define rep(i, st, en) for(int i=st; i<=en; i++) #define repn(i, st, en) for(int i=st; i>=en; i--) #define sq(a) (a*a) typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; ll mod = 1e9+7; void solve(){ int n, k; cin>>n>>k; string s; cin>>s; string t; /// target string rep(i, 1, k-1){ t += "()"; } int z = (n - t.size())/2; rep(i, 1, z) t += "("; rep(i, 1, z) t += ")"; /// O(n^2) approach, for each s[i] != t[i] find next j>i, such that s[j] = t[i], swap vector<pii> ans; fr(i, n){ // break; if(t[i] != s[i]){ int j = i; while(s[j] != t[i]) j++; /// now s[j] = t[i];, so reverse the whole segment, in between elements will remain same, since are equal! s[j] = s[i]; s[i] = t[i]; ans.push_back({i, j}); } } cout<<ans.size()<<endl; for(auto it: ans){ cout<<it.first + 1<<" "<<it.second + 1<<endl; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t = 1; cin>>t; while(t--){ solve(); } return 0; }
true
cd864299e33faa5b5ed906439d185b4e652aa77f
C++
lehuyngo/game_plane
/Common_Function.cpp
UTF-8
3,184
2.90625
3
[]
no_license
#include "Common_Function.h" SDL_Surface* ComFunc:: LoadImage(std::string file_path) { SDL_Surface* load_image = NULL; SDL_Surface* optimize_image = NULL; //lưu ý: vị trí lưu ảnh phải cùng với vị trí lưu chương trình chính của các bạn để hàm IMG_Load đọc được ảnh load_image = IMG_Load(file_path.c_str()); if (load_image != NULL) { //hàm định dạng hiển thị tối ưu hóa kiểu dữ liệu cho phù hợp optimize_image = SDL_DisplayFormat(load_image); //dữ liệu đã được đưa vào optimize_image nên load_image không cần nữa, ta giải phóng load_image SDL_FreeSurface(load_image); if (optimize_image != NULL) { UINT32 color_key = SDL_MapRGB(optimize_image->format, 0, 0xFF, 0xFF); SDL_SetColorKey(optimize_image, SDL_SRCCOLORKEY, color_key); } } return optimize_image; } void ComFunc::ApplySurface(SDL_Surface* src, SDL_Surface* des, int x, int y) { SDL_Rect offset; offset.x = x; offset.y = y; SDL_BlitSurface(src, NULL, des, &offset); } void ComFunc::CleanUp() { SDL_FreeSurface(g_screen); SDL_FreeSurface(g_bkground); } bool ComFunc::CheckCollision(const SDL_Rect& object1, const SDL_Rect& object2) { int left_a = object1.x; int right_a = object1.x + object1.w; int top_a = object1.y; int bottom_a = object1.y + object1.h; int left_b = object2.x; int right_b = object2.x + object2.w; int top_b = object2.y; int bottom_b = object2.y + object2.h; // Case 1: size object 1 < size object 2 if (left_a > left_b && left_a < right_b) { if (top_a > top_b && top_a < bottom_b) { return true; } } if (left_a > left_b && left_a < right_b) { if (bottom_a > top_b && bottom_a < bottom_b) { return true; } } if (right_a > left_b && right_a < right_b) { if (top_a > top_b && top_a < bottom_b) { return true; } } if (right_a > left_b && right_a < right_b) { if (bottom_a > top_b && bottom_a < bottom_b) { return true; } } // Case 2: size object 1 < size object 2 if (left_b > left_a && left_b < right_a) { if (top_b > top_a && top_b < bottom_a) { return true; } } if (left_b > left_a && left_b < right_a) { if (bottom_b > top_a && bottom_b < bottom_a) { return true; } } if (right_b > left_a && right_b < right_a) { if (top_b > top_a && top_b < bottom_a) { return true; } } if (right_b > left_a && right_b < right_a) { if (bottom_b > top_a && bottom_b < bottom_a) { return true; } } // Case 3: size object 1 = size object 2 if (top_a == top_b && right_a == right_b && bottom_a == bottom_b) { return true; } return false; } void ComFunc::ApplySurfaceClip(SDL_Surface* src, SDL_Surface* des, SDL_Rect* clip, int x, int y) { SDL_Rect offset; offset.x = x; offset.y = y; SDL_BlitSurface(src, clip, des, &offset); }
true
7c74d36325670499ebc68d22df4f1a55f5f44679
C++
vcahlik/pa2-pacman
/src/Model/GameTimer.cpp
UTF-8
2,307
3.078125
3
[ "MIT" ]
permissive
#include "GameTimer.h" #include "Config.h" #include "Game.h" #include <stdexcept> GameTimer::GameTimer(const Game *game) : game(game) {} void GameTimer::requestTimer(const TimeoutEvent timeout) { if (isActive(timeout)) { return; } timeoutsCounter[timeout] = 0; } void GameTimer::stopTimer(const TimeoutEvent timeout) { timeoutsCounter.erase(timeout); } const bool GameTimer::isTimeoutEvent(const TimeoutEvent timeout) { if (timeoutExceeded(timeout)) { stopTimer(timeout); return true; } return false; } void GameTimer::notifyOfNextCycle() { for (auto &a : timeoutsCounter) { if (!timeoutExceeded(a.first)) { a.second += Config::CYCLE_TIME_MSECS; } } } const bool GameTimer::isActive(const TimeoutEvent timeout) const { return timeoutsCounter.find(timeout) != timeoutsCounter.end(); } const bool GameTimer::timeoutExceeded(const TimeoutEvent timeout) const { try { return timeoutsCounter.at(timeout) >= getTimeoutLimitValueMsecs(timeout); } catch (const std::out_of_range &) { return false; } } const uint32_t GameTimer::getTimeoutLimitValueMsecs(const TimeoutEvent timeout) const { switch (timeout) { case TimeoutEvent::GameStateGameWon: return Config::PLAYER_VICTORY_SCREEN_TIME_MSECS; case TimeoutEvent::GameStateLifeLost: return Config::PLAYER_DEATH_SCREEN_TIME_MSECS; case TimeoutEvent::GameStateGameOver: return Config::PLAYER_GAME_OVER_SCREEN_TIME_MSECS; case TimeoutEvent::GhostGeneration: return Config::GHOST_GENERATION_TIME_MSECS; case TimeoutEvent::CherryGeneration: return Config::CHERRY_GENERATION_INTERVAL_MSECS; case TimeoutEvent::CherryLifetime: return Config::CHERRY_LIFETIME_MSECS; case TimeoutEvent::GhostStateFrightened: return game->getDifficulty().getGhostFrightenedDurationMsecs(); case TimeoutEvent::GhostStateFrightenedEnd: return Config::GHOST_FRIGHTENED_END_DURATION_MSECS; case TimeoutEvent::GhostStateFrightenedBlink: return Config::GHOST_FRIGHTENED_BLINK_INTERVAL_MSECS; default: throw std::logic_error("timeout not handled"); } }
true
51dcedc18808ca9429cdca1a2d74df7f75558aec
C++
pemami4911/projecteuler.net
/projecteuler.net/Problem12.cpp
UTF-8
3,008
3.625
4
[]
no_license
/* Patrick Emami Problem 12 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? */ #include <iostream> #include "math.h" using namespace std; //Calculates the number of divisors of integer n int numOfDivisors(long long int n) { if( n == 1 ) return 1; else if( n <= 3 ) return 2; long long int num = n, i = 2, size = sqrt(n), lastPrime = 0; int numberOfDivisors = 1, index = -1; if( n <= 100 ) size += 10; else size += (size/2); int frequencyOfPrimes[size]; bool factors[size]; for(long long int k = 0; k <= size; k++) { frequencyOfPrimes[k] = 0; if(k > 1) factors[k] = 0; else factors[k] = 1; } while( i <= size) { if( (num % i) != 0 ) { for(long long int j = 1; i*j <= size; j++) factors[i*j] = 1; } else { if( i != lastPrime ) { index++; lastPrime = i; } frequencyOfPrimes[index]++; if( i == n || i == size || (i == num && i != n )) { for(long long int m = 0; m <= index; m++) numberOfDivisors *= (frequencyOfPrimes[m]+1); return numberOfDivisors; } num /= i; } //find next candidate while(factors[i] == 1) { if(i == size && num != n) { if( i != lastPrime ) { index++; lastPrime = i; } frequencyOfPrimes[index]++; for(long long int l = 0; l <= index; l++) numberOfDivisors *= (frequencyOfPrimes[l]+1); return numberOfDivisors; } else if( i == size ) { for(long long int r = 0; r <= index; r++) numberOfDivisors *= (frequencyOfPrimes[r]+1); return numberOfDivisors; } i++; } } } //Finds the first triangular number with over 500 divisors long long int solution() { bool check = true; long long int triangular = 0, maxD = 0, maxT = 0; long long int increment = 1; long long int numDivisors = 0; while(check) { //calculate the next triangular number {1, 3, 6, 10, ...} triangular += increment; increment++; numDivisors = numOfDivisors(triangular); if( numDivisors > maxD ) { maxD = numDivisors; maxT = triangular; } if( maxD > 500) return maxT; numDivisors = 0; } return -1; } int main() { cout << solution() << endl; return 0; }
true
04d47dd160f9a710762d074e7063defa034727a0
C++
tushargosavi/cpp-learn
/algo/heap.h
UTF-8
2,376
3.578125
4
[ "MIT" ]
permissive
#ifndef __HEAP_H #define __HEAP_H #include <vector> #include <iostream> #include <functional> #include <algorithm> #include <iterator> template <typename T, typename Cmp = std::less<T> > class Heap { private: std::vector<T> heap_arr; int len; inline int pidx(int n) { return (n-1) / 2; } inline int c1idx(int n ) { return n * 2 + 1; } inline int c2idx(int n ) { return n * 2 + 2; } public: Heap(): len(0) {} Heap(std::vector<T> arr) { heap_arr.resize(arr.size()); std::copy(arr.begin(), arr.end(), heap_arr.begin()); len = arr.size(); make_heap(); } bool verify() { Cmp __cmp__ = Cmp(); for(int i = 0; i < len; i++) { int c1 = c1idx(i); int c2 = c2idx(i); if (c1 < len && !__cmp__(heap_arr[i],heap_arr[c1])) return false; if (c2 < len && !__cmp__(heap_arr[i],heap_arr[c2])) return false; } return true; } int size() { return len; } bool empty() { return (len == 0); } void make_heap() { for(int i = len/2; i >= 0; i--) { push_down(i); } } void push_up(int n) { Cmp __cmp__ = Cmp(); int p = pidx(n); while (n > 0 && !__cmp__(heap_arr[p], heap_arr[n])) { std::swap(heap_arr[p], heap_arr[n]); n = p; p = pidx(n); } } void push_down(int n) { Cmp __cmp__ = Cmp(); // iterate until the item at leaf or heap property is // maintaied. // if childidex is greater than heap size then the item is // a leaf. while (c1idx(n) <= len-1) { // calculate index of minimum child. int c1 = c1idx(n); int min_idx = ((c1 < len-1) && !__cmp__(heap_arr[c1],heap_arr[c1+1]))? (c1+1) : c1; // If root is less than both of its children, then // heap property is satisfied, , no need to go further down. if (__cmp__(heap_arr[n], heap_arr[min_idx])) break; std::swap(heap_arr[n], heap_arr[min_idx]); n = min_idx; } } void add(T elem) { heap_arr.push_back(elem); len++; push_up(len); } T remove() { T elem = heap_arr[0]; std::swap(heap_arr[0], heap_arr[len-1]); len--; push_down(0); heap_arr.pop_back(); return elem; } void debug() { std::cout << " size " << len << " " ; std::copy(heap_arr.begin(), heap_arr.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } }; #endif
true
9f78ec0a0d50b58017b26b07d784bb10b1072283
C++
R-O-C-K-E-T/cosc363-assignment-1
/src/aabb.h
UTF-8
782
2.96875
3
[]
no_license
#pragma once #include <vector> #include <glm/glm.hpp> struct AABB { AABB(glm::vec3 lower, glm::vec3 upper) : lower(lower), upper(upper) {} AABB(const std::vector<glm::vec3>& points); AABB make_union(const AABB& other) const; AABB expand(float radius) const; AABB apply_transform(const glm::mat4& transform) const; AABB translate(const glm::vec3& offset) const; float volume() const { return (upper.x - lower.x) * (upper.y - lower.y) * (upper.z - lower.z); } bool contains(const AABB& other) const; bool intersect(const AABB& other) const; std::vector<glm::vec3> get_points() const; void render() const; glm::vec3 lower; glm::vec3 upper; }; const AABB NAN_BOUNDS = { glm::vec3(std::nanf("")), glm::vec3(std::nanf("")) };
true
e1b5be6b8bda005cca543d1e75afbda651478cf9
C++
sanstwy777/Leetcode
/MySolutions/485. Max Consecutive Ones/485.cpp
UTF-8
883
3.1875
3
[]
no_license
//============================================================================ // Name : Leetcode.485. Max Consecutive Ones // Author : sanstwy27 // Version : Version 1.0.0 // Copyright : // Description : Any % // Reference : //============================================================================ #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int maxCount = 0, tmpCount = 0; for(int i = 0; i < nums.size(); i++) { if(nums[i] == 1) { ++tmpCount; maxCount = max(maxCount, tmpCount); } else { tmpCount = 0; } } return maxCount; } }; int main() { // Test Case vector<int> nums{1}; Solution t; cout << t.findMaxConsecutiveOnes(nums) << endl; return 0; }
true
e892666ac3080ab3905ce793f038409bb0e418c0
C++
dlwjdqls/monke
/source/monke/main.cc
UTF-8
1,915
2.6875
3
[ "Apache-2.0" ]
permissive
// averysumner - monke // main.cc // contains entry point // Copyright 2021 averysumner // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org / licenses / LICENSE - 2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissionsand // limitations under the License. #include <iostream> #include <cstring> #include "pack.hh" #include "config.hh" void help() { std::cout << "monke v" << MONKE_VERSION_MAJOR << "." << MONKE_VERSION_MINOR << std::endl; std::cout << "Copyright 2021 averysumner" << std::endl << std::endl; std::cout << "Usage: monke <command> [arguments]" << std::endl << std::endl; std::cout << "Commands:" << std::endl; std::cout << " pack <input path> <output path> <password>" << std::endl; std::cout << " unpack <input path> <output path> <password>" << std::endl; } int main(int argc, char* argv[]) { if (argc == 1) { help(); return 0; } if (!strcmp(argv[1], "unpack") || !strcmp(argv[1], "u")) { if (argc != 5) { help(); return 0; } monke::Pack::unpack(argv[2], argv[3], argv[4]); std::cout << "Unpacked '" << argv[2] << "' with password '" << argv[4] << "' to '" << argv[3] << "'." << std::endl; } else if (!strcmp(argv[1], "pack") || !strcmp(argv[1], "p")) { if (argc != 5) { help(); return 0; } monke::Pack::pack(argv[2], argv[3], argv[4]); std::cout << "Packed '" << argv[2] << "' with password '" << argv[4] << "' to '" << argv[3] << "'." << std::endl; } else { help(); return 0; } return 0; }
true
7c66472caa4d34feaa92b27951e65da26c2e34e9
C++
AStockinger/Cpp-Projects
/Labs/Lab1/determinant.cpp
UTF-8
846
3.359375
3
[]
no_license
/******************************************************************************** ** Program Name: Matrix Calculator ** Author: Amy Stockinger ** Date: 9/20/18 ** Description: returns determinant of a 2x2 or 3x3 matrix based on size *********************************************************************************/ #include "determinant.hpp" // calculates determinant according to standard formulas on website linked in module int determinant(int size, int** matrix){ if(size == 2){ return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; } else{ return (matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1])) - (matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])) + (matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0])); } }
true
1443b863fd1585fcb846507ea74db152307795fb
C++
mirsking/mirsking_patest
/basic1020_mooncake/basic1020_mooncake/basic1020_mooncake.cpp
GB18030
1,250
3.171875
3
[]
no_license
// basic1020_mooncake.cpp : ̨Ӧóڵ㡣 // #include <iostream> #include <vector> #include <functional> #include <algorithm> using namespace std; bool cmp(const vector<float>& left, const vector<float>& right) { return left[1] >= right[1]; } int main(int argc, char* argv[]) { int n, need; cin >> n >> need; vector< vector<float> > moon_cake; vector<float> one_cake, sum_cake, sum_price_cake; sum_cake.clear(); sum_cake.resize(n); sum_price_cake.clear(); sum_price_cake.resize(n); for (int i = 0; i < n; i++) cin >> sum_cake[i]; for (int i = 0; i < n; i++) cin >> sum_price_cake[i]; for (int i = 0; i < n; i++) { one_cake.clear(); one_cake.push_back(sum_cake[i]); one_cake.push_back(sum_price_cake[i]/sum_cake[i]); moon_cake.push_back(one_cake); } sort(moon_cake.begin(), moon_cake.end(), cmp); float already_sum = 0; int index = 0; float sum_price = 0; while (index<moon_cake.size() && already_sum + moon_cake[index][0] < need ) { already_sum += moon_cake[index][0]; sum_price += moon_cake[index][0] * moon_cake[index][1]; index++; } if (index < moon_cake.size()) { sum_price += (need - already_sum) * moon_cake[index][1]; } printf("%.2f\n",sum_price); return 0; }
true
2ddc508661b4d45eeb1f1631500682e849cb6f2a
C++
monikagopisetti/mrnd_set_1
/type of triangle/type of triangle/type of triangle.cpp
UTF-8
1,737
3.265625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<math.h> #include<malloc.h> #define CASES 4 #define MAX 2 #define RANGE 20 // Write test cases char* equilateral = "equilateral"; char* isoceles = "isoceles"; char* scalen = "scalen"; typedef struct coordinates { double x; double y; }Coordinates; typedef struct triangle { Coordinates a; Coordinates b; Coordinates c; }Triangle; typedef struct string { char str[30]; }String; int iscompare(char* actual, string expected) { int i, flag = 1; for (i = 0; actual[i] != '\0'; i++) { if (actual[i] != expected.str[i]) { flag = 0; break; } } return flag; } double power(double x, int y) { double result = 1; for (int i = 0; i < y; i++) result *= x; return result; } char* typeOfTriangle(Triangle t) { double d1, d2, d3; d1 = roundf(sqrt(pow((t.a.x - t.b.x), 2) + pow((t.a.y - t.b.y), 2))*100)/100; d2 = roundf(sqrt(pow((t.b.x - t.c.x), 2) + pow((t.b.y - t.c.y), 2)) * 100) / 100; d3 = roundf(sqrt(pow((t.c.x - t.a.x), 2) + pow((t.c.y - t.a.y), 2)) * 100) / 100; if ((d1 == d2) && (d2 == d3)) { return equilateral; } else if ((d1 == d2) || (d2 == d3) || (d3 == d1)) { return isoceles; } else { return scalen; } } void testcases() { Triangle t1 = { { 1, 0 }, { 0, 1 }, { 0, 0 } }; Triangle t2 = { { 1, 2 }, { 2, 3 }, { 3, 4 } }; triangle t3 = { { 1, 0 }, { -1, 0 }, { 0, 1.732050807569 } }; Triangle input[3] = { t1, t2,t3 }; string output[3] = { { "isoceles" }, { "isoceles" }, { "equilateral" } }; char* res = (char*)malloc(RANGE*sizeof(char)); for (int i = 0; i < 3; i++) { res = typeOfTriangle(input[i]); if (iscompare(res, output[i])) printf("Passed\n"); else printf("Failed\n"); } } void main() { testcases(); }
true
a912aa01daef435014525c02e6716eaa8cdd1709
C++
amross/GameDemo
/card.h
UTF-8
682
2.65625
3
[]
no_license
#pragma once #include <Symbols/coloredSymbol.h> #include <Modifiers/modifysymbol.h> #include <QObject> // Represents a card with symbol on face and modifier on back // Can be draw into a QObject class Card { public: Card(); Card(const ColoredSymbol* pFaceSymbol, const ModifySymbol* pModifier); void Flip(); void FaceUp(); void FaceDown(); bool IsFaceUp(); Qt::GlobalColor GetColor() const; bool IsSameShape(Card& card); int ApplyModifier(int value) const; void Draw(QPainter& painter); operator QString() const ; private: const ColoredSymbol* pFaceSymbol; const ModifySymbol* pModifier; bool faceUp; QString desc; };
true
62eb74537567a9829fb25c688d0a1a788da79eaa
C++
yczheng-hit/gensim
/support/libgvnc/inc/libgvnc/Keyboard.h
UTF-8
524
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ #pragma once #include <stdint.h> #include <functional> namespace libgvnc { struct KeyEvent { bool Down; uint32_t KeySym; }; using KeyboardCallback = std::function<void(const KeyEvent&) >; class Keyboard { public: void SendEvent(struct KeyEvent &event) { callback_(event); } void SetCallback(const KeyboardCallback &callback) { callback_ = callback; } private: KeyboardCallback callback_; }; }
true
4e38f3309f143010cb189e471a88c988cd21ffdd
C++
jiangshen95/UbuntuLeetCode
/PathSumII2.cpp
UTF-8
2,539
3.453125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int> > pathSum(TreeNode* root, int sum) { vector<vector<int> > result; vector<int> line; vector<TreeNode*> stack; TreeNode *cur=root, *pre=NULL; int SUM=0; while(cur || !stack.empty()){ while(cur){ stack.push_back(cur); SUM+=cur->val; line.push_back(cur->val); cur=cur->left; } cur=stack.back(); if(cur->right!=NULL && cur->right!=pre){ cur=cur->right; continue; } if(cur->left==NULL && cur->right==NULL && SUM==sum){ result.push_back(line); } pre=cur; stack.pop_back(); line.pop_back(); SUM-=cur->val; cur=NULL; } return result; } void pathSum(vector<vector<int> >& result, vector<int>& line, TreeNode *root, int sum){ if(root==NULL) return; if(root->left==NULL && root->right==NULL && sum==root->val){ line.push_back(root->val); result.push_back(line); line.pop_back(); }else{ line.push_back(root->val); pathSum(result, line, root->left, sum-root->val); pathSum(result, line, root->right, sum-root->val); line.pop_back(); } } }; int main(){ TreeNode *root=new TreeNode(5); TreeNode *a=new TreeNode(4); TreeNode *b=new TreeNode(8); TreeNode *c=new TreeNode(11); TreeNode *d=new TreeNode(13); TreeNode *e=new TreeNode(4); TreeNode *f=new TreeNode(7); TreeNode *g=new TreeNode(2); TreeNode *h=new TreeNode(1); TreeNode *k=new TreeNode(5); root->left=a; root->right=b; a->left=c; b->left=d; b->right=e; c->left=f; c->right=g; e->left=k; e->right=h; int sum; cin>>sum; Solution *solution=new Solution(); vector<vector<int> > result=solution->pathSum(root, sum); for(int i=0;i<result.size();i++){ for(int j=0;j<result[i].size();j++){ cout<<result[i][j]<<" "; } cout<<endl; } return 0; }
true
e29b35e4cf03f6af2202cf74f989b1f59318db20
C++
codgician/Competitive-Programming
/POJ/3667/segment_tree_lazy.cpp
UTF-8
5,150
2.53125
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> #include <vector> #include <queue> #include <set> #include <map> #define SIZE 80100 #define leftSon ((segPt << 1) + 1) #define rightSon ((segPt << 1) + 2) using namespace std; typedef struct _SegTree { int leftPt, rightPt; int preLen, sufLen; int maxLen; int lazy; } SegTree; SegTree segTree[SIZE << 2]; void pushUp(int segPt) { segTree[segPt].maxLen = max(segTree[leftSon].sufLen + segTree[rightSon].preLen, max(segTree[leftSon].maxLen, segTree[rightSon].maxLen)); segTree[segPt].preLen = segTree[leftSon].preLen; if (segTree[leftSon].preLen == segTree[leftSon].rightPt - segTree[leftSon].leftPt + 1) { segTree[segPt].preLen += segTree[rightSon].preLen; } segTree[segPt].sufLen = segTree[rightSon].sufLen; if (segTree[rightSon].sufLen == segTree[rightSon].rightPt - segTree[rightSon].leftPt + 1) { segTree[segPt].sufLen += segTree[leftSon].sufLen; } } void pushDown(int segPt) { if (segTree[segPt].lazy > -1) { if (segTree[segPt].lazy == 0) { segTree[leftSon].maxLen = segTree[leftSon].rightPt - segTree[leftSon].leftPt + 1; segTree[leftSon].preLen = segTree[leftSon].rightPt - segTree[leftSon].leftPt + 1; segTree[leftSon].sufLen = segTree[leftSon].rightPt - segTree[leftSon].leftPt + 1; segTree[rightSon].maxLen = segTree[rightSon].rightPt - segTree[rightSon].leftPt + 1; segTree[rightSon].preLen = segTree[rightSon].rightPt - segTree[rightSon].leftPt + 1; segTree[rightSon].sufLen = segTree[rightSon].rightPt - segTree[rightSon].leftPt + 1; } else { segTree[leftSon].maxLen = 0; segTree[leftSon].preLen = 0; segTree[leftSon].sufLen = 0; segTree[rightSon].maxLen = 0; segTree[rightSon].preLen = 0; segTree[rightSon].sufLen = 0; } segTree[leftSon].lazy = segTree[segPt].lazy; segTree[rightSon].lazy = segTree[segPt].lazy; segTree[segPt].lazy = -1; } } void build(int segPt, int leftPt, int rightPt) { segTree[segPt].leftPt = leftPt; segTree[segPt].rightPt = rightPt; if (segTree[segPt].leftPt == segTree[segPt].rightPt) { segTree[segPt].preLen = 1; segTree[segPt].sufLen = 1; segTree[segPt].maxLen = 1; segTree[segPt].lazy = -1; return; } int midPt = (leftPt + rightPt) >> 1; build(leftSon, leftPt, midPt); build(rightSon, midPt + 1, rightPt); pushUp(segPt); segTree[segPt].lazy = -1; } void rangeUpdate(int segPt, int leftPt, int rightPt, bool typeId) { if (segTree[segPt].leftPt >= leftPt && segTree[segPt].rightPt <= rightPt) { if (typeId == 0) { segTree[segPt].maxLen = segTree[segPt].rightPt - segTree[segPt].leftPt + 1; segTree[segPt].preLen = segTree[segPt].rightPt - segTree[segPt].leftPt + 1; segTree[segPt].sufLen = segTree[segPt].rightPt - segTree[segPt].leftPt + 1; segTree[segPt].lazy = 0; } else { segTree[segPt].maxLen = 0; segTree[segPt].preLen = 0; segTree[segPt].sufLen = 0; segTree[segPt].lazy = 1; } return; } pushDown(segPt); int midPt = (segTree[segPt].leftPt + segTree[segPt].rightPt) >> 1; if (leftPt <= midPt) rangeUpdate(leftSon, leftPt, rightPt, typeId); if (rightPt > midPt) rangeUpdate(rightSon, leftPt, rightPt, typeId); pushUp(segPt); } int query(int segPt, int needNum) { pushDown(segPt); if (segTree[segPt].maxLen < needNum) return -1; if (segTree[segPt].leftPt == segTree[segPt].rightPt) return segTree[leftSon].leftPt; if (segTree[leftSon].maxLen >= needNum) return query(leftSon, needNum); if (segTree[leftSon].sufLen + segTree[rightSon].preLen >= needNum) return segTree[leftSon].rightPt - segTree[leftSon].sufLen + 1; return query(rightSon, needNum); } int main() { ios::sync_with_stdio(false); int cowNum, oprNum; while (cin >> cowNum >> oprNum) { build(0, 0, cowNum - 1); for (int t = 0; t < oprNum; t++) { int opr; cin >> opr; if (opr == 1) { int groupSize; cin >> groupSize; int ans = query(0, groupSize); if (ans > -1) { rangeUpdate(0, ans, ans + groupSize - 1, 1); cout << ans + 1 << endl; } else { cout << 0 << endl; } } else if (opr == 2) { int startPt, groupSize; cin >> startPt >> groupSize; startPt--; rangeUpdate(0, startPt, startPt + groupSize - 1, 0); } } } return 0; }
true
fa8a1cd3e438a6dc2f77a7390a960ced6052491e
C++
pankhuri-52/Data-Structures-Codes
/Graphs/adjacency_list.cpp
UTF-8
790
3.4375
3
[]
no_license
#include<iostream> #include<list> #include<iterator> using namespace std; void displayAdjList(list<int> adj_list[], int v) { for(int i = 0; i<v; i++) { cout << i << "--->"; list<int> :: iterator it; for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) { cout << *it << " "; } cout << endl; } } void addEdge(list<int> adj_list[], int u, int v) { adj_list[u].push_back(v); adj_list[v].push_back(u); } int main() { int v = 5; list<int> adj_list[v]; addEdge(adj_list, 0, 0); addEdge(adj_list, 0, 3); addEdge(adj_list, 1, 1); addEdge(adj_list, 2, 1); addEdge(adj_list, 2, 3); addEdge(adj_list, 3, 1); addEdge(adj_list, 3, 4); addEdge(adj_list,4,1); addEdge(adj_list,4,2); displayAdjList(adj_list, v); return 0; }
true
0febf92273d589617b99b22ad4d0ad83f0e7175c
C++
sirAdarsh/CP-files
/ALGORITHMS/3. Ax + By = C (solutions)/One Solution(prac).cpp
UTF-8
634
2.890625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int gcdExtended(int a,int b,int *x,int *y){ if(a==0){ *x=0; *y=1; return b; } int x1,y1; int gcd=gcdExtended(b%a,a,&x1,&y1); *x=y1-(b/a)*x1; *y=x1; return gcd; } bool solve(int a,int b,int c,int *x,int *y){ int g=gcdExtended(abs(a),abs(b),x,y); if(c%g){ return false; } *x = *x*(c/g); *y = *y*(c/g); if(a<0){ *x=-(*x); } if(b<0){ *y=-(*y); } return true; } int main(){ int a,b,c,x,y; cin>>a>>b>>c; // cout<<gcdExtended(a,b,&x,&y); if(solve(a,b,c,&x,&y)){ cout<<"x = "<<x<<" y = "<<y<<endl; } else{ cout<<" No integer solution."<<endl; } }
true
a9c9bfbe96fb6ecb2040c630533a8f5b7191093a
C++
yashkapoor007/geeksforgeeks
/btreevc.h
UTF-8
190
2.71875
3
[]
no_license
template <typename T> class Btree { public: T data; int vc; Btree<T> *left; Btree<T> *right; Btree(T data) { this->data=data; vc=0; left=NULL; right=NULL; } };
true
a40a96ada029b0f8f9c7233c1749542724954c14
C++
wwwwodddd/Zukunft
/codechef/CLRL.cpp
UTF-8
573
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int t, n, r; int low, high; int main() { scanf("%d", &t); for (int tt = 0; tt < t; tt++) { scanf("%d%d", &n, &r); low = high = -1; bool ok = true; for (int i = 0; i < n; i++) { int x; scanf("%d", &x); if (x > r) { if (high == -1) { high = x; } else { if (high < x) { ok = false; } high = x; } } else { if (low == -1) { low = x; } else { if (low > x) { ok = false; } low = x; } } } puts(ok ? "YES" : "NO"); } return 0; }
true
5fabb2049f5fc7b75e653199cfccfa4649deb464
C++
xueyinglu/BiotSystem_EG
/source/data/RightHandSide.cc
UTF-8
1,206
2.90625
3
[]
no_license
#include "../include/RightHandSide.h" RightHandSide::RightHandSide () : Function<dim> (dim) {} inline void RightHandSide::vector_value (const Point<dim> &p, Vector<double> &values) const { Assert (values.size() == dim, ExcDimensionMismatch (values.size(), dim)); Assert (dim >= 2, ExcNotImplemented()); Point<dim> point_1, point_2; point_1(0) = 0.5; point_2(0) = -0.5; if (((p-point_1).norm_square() < 0.2*0.2) || ((p-point_2).norm_square() < 0.2*0.2)) values(0) = 1; else values(0) = 0; if (p.norm_square() < 0.2*0.2) values(1) = 1; else values(1) = 0; } void RightHandSide::vector_value_list (const std::vector<Point<dim> > &points, std::vector<Vector<double> > &value_list) const { Assert (value_list.size() == points.size(), ExcDimensionMismatch (value_list.size(), points.size())); const unsigned int n_points = points.size(); for (unsigned int p=0; p<n_points; ++p) RightHandSide::vector_value (points[p], value_list[p]); }
true
6d4dfea5e353a7265a2340eb6c1be131e1332c8a
C++
sasaki-seiji/ProgrammingLanguageCPP4th
/part2/ch12/12-5-pointer-to-overloaded-function/src/pointer_to_overloaded_function.cpp
UTF-8
1,012
3.453125
3
[]
no_license
/* * pointer_to_overloaded_function.cpp * * Created on: 2016/05/11 * Author: sasaki */ #include <iostream> using namespace std; void f(int); int f(char); void (*pf1)(int) = &f; int (*pf2)(char) = &f; //void (*pf3)(char) = &f; // error: no matches converting function 'f' to type 'void (*)(char)' void ff(int) noexcept; void gg(int); void (*p1)(int) = ff; void (*p2)(int) noexcept = ff; void (*p3)(int) noexcept = gg; // 2017.03.07 エラーとならない //using Pc = extern "C" void(int); // error: expected type-specifier before ‘extern’ using Pn = void(int) noexcept; // 2017.03.07 エラーとならない int main() { pf1(12); int ret = pf2('x'); cout << "pf2('x') returns " << ret << '\n'; p1(123); p2(456); p3(789); } // undefs void f(int i) { cout << "f(int: " << i << ")\n"; } int f(char c) { cout << "f(char: " << c << ")\n"; return int{c}; } void ff(int i) noexcept { cout << "ff(int: " << i << ")\n"; } void gg(int i) { cout << "gg(int: " << i << ")\n"; }
true
46118939248c150c3cd9cd1b3648964889522840
C++
Paresh-Wadhwani/Competitive_Programming
/GeeksforGeeks/Ways To Tile A Floor/Solutions/C++/numberOfWays.cpp
UTF-8
728
3.390625
3
[ "MIT" ]
permissive
long long numberOfWays(long long N) { long long modulo = 1000000007; // This is nothing but fibonacci series in modulo 10^9 + 7. // For N = 1 or 2, we return N itself. if (N == 1 || N == 2) return N; // In other cases, we calculate the Nth fibonacci number using Dynamic Programming. long long fb_minus_1 = 2; // This variable holds the (i - 1)th fibonacci number. long long fb_minus_2 = 1; // This variable holds the (i - 2)th fibonacci number. long long fb; // This variable holds the (i)th fibonacci number. for (long long i = 3; i <= N; i++) { fb = fb_minus_1 + fb_minus_2; fb_minus_2 = fb_minus_1; fb_minus_1 = fb; fb %= modulo; fb_minus_1 %= modulo; fb_minus_2 %= modulo; } return fb; }
true
599f1d6b96d9ee9e40e4262cb249031b775a4a2b
C++
ayushoo6/Data-Structure-And-Algorithms-Code-In-c-
/insertion sort.cpp
UTF-8
589
3.578125
4
[]
no_license
#include<iostream> using namespace std; int insertionSort(int a[]) { int key=0; int j=0; for(int i=1;i<5;i++) { key=a[i]; j=i-1; while(j>=0 && a[j]>key) { a[j+1]=a[j]; j=j-1; } a[j+1]=key; } } int main() { int arr[5]; cout<<"enter 5 integer element :"<<endl; for(int i=0;i<5;i++) { cin>>arr[i]; } cout<<"Unsorted array list :"<<endl; for(int i=0;i<5;i++) { cout<<arr[i]<<" "; } cout<<endl; insertionSort(arr); cout<<"sorted array list :"<<endl; for(int i=0;i<5;i++) { cout<<arr[i]<<" "; } }
true
aa2d702875162efcbb93509207b4e9375ce2e077
C++
felipefoschiera/Competitive-Programming
/URI Online Judge/AD-HOC/2366 - Maratona/maratona.cpp
UTF-8
421
2.671875
3
[]
no_license
/** * URI 2366 - Maratona * Felipe G. Foschiera */ #include <stdio.h> int main(){ int N, M; scanf("%d %d", &N, &M); int pos[N]; scanf("%d", &pos[0]); bool can = true; for(int i = 1; i < N; i++){ scanf("%d", pos+i); if(pos[i] - pos[i-1] > M){ can = false; } } if(42195 - pos[N-1] > M){ can = false; } printf(can ? "S\n" : "N\n"); return 0; }
true
151d10b14922e51a5ee2048e08b863020bbe2337
C++
dianatibre/School
/Parallel and distributed programming/training/threadedPermutation.cpp
UTF-8
1,614
3.25
3
[]
no_license
// // Created by potra on 23.01.2019. // #include <iostream> #include <thread> #include <vector> #include <mutex> #include <atomic> #include "util.hpp" using namespace std; const int N = 7; atomic<int> count(0); bool predicate(const vector<int>& perm) { return true; } /** * Calculates all the permutations of N elements */ void ThreadedPermutations(const vector<int> &current_permutation) { if (current_permutation.size() == N && predicate(current_permutation)) count++; vector<thread> threads; for (int i = 1; i <= N; ++i) { if (!alreadyIn(current_permutation, i)) { // should create a new thread and add the value i vector<int> new_permutation(current_permutation); new_permutation.push_back(i); threads.emplace_back([new_permutation](){ ThreadedPermutations(new_permutation); }); } } for (auto& i : threads) { i.join(); } } /** * Calculates all the permutations of N elements */ void permutations(const vector<int> &current_permutation) { if (current_permutation.size() == N && predicate(current_permutation)) count++; for (int i = 1; i <= N; ++i) { if (!alreadyIn(current_permutation, i)) { // should create a new thread and add the value i vector<int> new_permutation(current_permutation); new_permutation.push_back(i); ThreadedPermutations(new_permutation); } } } int main() { vector<int> x; ThreadedPermutations(x); cout << count << '\n'; return 0; }
true
dd5c02a4e105b9fd6fa7b1d45727eaa8b5d31ce7
C++
tdragon00/CS1C
/assignment 13/main.cpp
UTF-8
307
2.515625
3
[]
no_license
/* * main.cpp * * Created on: Dec 2, 2019 * Author: Slickback */ #include <node.h> #include <linkedlist.h> using std; int main() { std::cout<<"Part one"; int arr = {1,2,3,4,5}; int size =5; List<int>intLList; for (int i=0; i<= size-1; i++) { intLList.insertNewNode(arr<i>); } }
true
b35ed2fa671dba8ab3aa1dff20d4e395cb380f80
C++
aldebaran/libqi
/src/messaging/url.cpp
UTF-8
8,048
2.921875
3
[]
permissive
/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <qi/url.hpp> #include <sstream> #include <qi/type/typeinterface.hpp> qiLogCategory("qi.url"); namespace qi { class UrlPrivate { public: UrlPrivate(); UrlPrivate(const UrlPrivate* url_p); UrlPrivate(const std::string& url); UrlPrivate(const std::string& url, unsigned short defaultPort); UrlPrivate(const std::string& url, const std::string& defaultProtocol); UrlPrivate(const std::string& url, const std::string& defaultProtocol, unsigned short defaultPort); UrlPrivate(const char* url); void updateUrl(); const std::string& str() const; bool isValid() const; std::string url; std::string protocol; std::string host; unsigned short port; enum UrlComponents { SCHEME = 2, HOST = 4, PORT = 1, None = 0, }; int components; private: // Explodes the url in different part and fill the fields of the class. //@return a bitmask of UrlComponents with the elements that were found int split_me(const std::string& url); }; Url::Url() : _p(new UrlPrivate()) { } Url::Url(const std::string &url) : _p(new UrlPrivate(url)) { } Url::Url(const std::string &url, unsigned short defaultPort) : _p(new UrlPrivate(url, defaultPort)) { } Url::Url(const std::string &url, const std::string &defaultProtocol) : _p(new UrlPrivate(url, defaultProtocol)) { } Url::Url(const std::string &url, const std::string &defaultProtocol, unsigned short defaultPort) : _p(new UrlPrivate(url, defaultProtocol, defaultPort)) { } Url::Url(const char *url) : _p(new UrlPrivate(url)) { } Url::~Url() { delete _p; } Url::Url(const qi::Url& url) : _p(new UrlPrivate(url._p)) { } Url& Url::operator= (const Url &rhs) { *_p = *rhs._p; return *this; } bool Url::operator< (const Url &rhs) const { return (this->str() < rhs.str()); } bool Url::isValid() const { return _p->isValid(); } const std::string& Url::str() const { return _p->url; } const std::string& Url::protocol() const { return _p->protocol; } bool Url::hasProtocol() const { return (_p->components & UrlPrivate::SCHEME) != 0; } void Url::setProtocol(const std::string &protocol) { _p->protocol = protocol; _p->components |= UrlPrivate::SCHEME; _p->updateUrl(); } const std::string& Url::host() const { return _p->host; } bool Url::hasHost() const { return (_p->components & UrlPrivate::HOST) != 0; } void Url::setHost(const std::string &host) { _p->host = host; _p->components |= UrlPrivate::HOST; _p->updateUrl(); } unsigned short Url::port() const { return _p->port; } bool Url::hasPort() const { return _p->components & UrlPrivate::PORT; } void Url::setPort(unsigned short port) { _p->port = port; _p->components |= UrlPrivate::PORT; _p->updateUrl(); } Url specifyUrl(const Url& specification, const Url& baseUrl) { Url url; if(specification.hasProtocol()) url.setProtocol(specification.protocol()); else if(baseUrl.hasProtocol()) url.setProtocol(baseUrl.protocol()); if(specification.hasHost()) url.setHost(specification.host()); else if(baseUrl.hasHost()) url.setHost(baseUrl.host()); if(specification.hasPort()) url.setPort(specification.port()); else if(baseUrl.hasPort()) url.setPort(baseUrl.port()); return url; } UrlPrivate::UrlPrivate() : url() , protocol() , host() , port(0) , components(0) { } UrlPrivate::UrlPrivate(const UrlPrivate* url_p) : url(url_p->url) , protocol(url_p->protocol) , host(url_p->host) , port(url_p->port) , components(url_p->components) { } UrlPrivate::UrlPrivate(const char* url) : url(url) , protocol() , host() , port(0) , components(0) { split_me(url); updateUrl(); } UrlPrivate::UrlPrivate(const std::string& url) : url(url) , protocol() , host() , port(0) , components(0) { split_me(url); updateUrl(); } UrlPrivate::UrlPrivate(const std::string& url, unsigned short defaultPort) : url(url) , protocol() , host() , port(defaultPort) , components(0) { if (!(split_me(url) & PORT)) { port = defaultPort; components |= PORT; } updateUrl(); } UrlPrivate::UrlPrivate(const std::string& url, const std::string& defaultProtocol) : url(url) , protocol() , host() , port(0) , components(0) { if (!(split_me(url) & SCHEME)) { protocol = defaultProtocol; components |= SCHEME; } updateUrl(); } UrlPrivate::UrlPrivate(const std::string& url, const std::string& defaultProtocol, unsigned short defaultPort) : url(url) , protocol() , host() , port(0) , components(0) { int result = split_me(url); if (!(result & SCHEME)) { protocol = defaultProtocol; components |= SCHEME; } if (!(result & PORT)) { port = defaultPort; components |= PORT; } updateUrl(); } void UrlPrivate::updateUrl() { url = std::string(); if(components & SCHEME) url += protocol + "://"; if(components & HOST) url += host; if(components & PORT) url += std::string(":") + boost::lexical_cast<std::string>(port); } bool UrlPrivate::isValid() const { return components == (SCHEME | HOST | PORT); } int UrlPrivate::split_me(const std::string& url) { /****** * Not compliant with RFC 3986 * This function can parse: * scheme://host:port and return SCHEME | HOST | PORT * scheme://host and return SCHEME | HOST * host:port and return HOST | PORT * host and return HOST * scheme://:port return SCHEME | PORT * scheme:// return SCHEME * :port return PORT * return 0 */ std::string _url = url; std::string _scheme = ""; std::string _host = ""; unsigned short _port = 0; components = 0; size_t place = 0; place = _url.find("://"); if (place != std::string::npos) { _scheme = url.substr(0, place); components |= SCHEME; place += 3; } else place = 0; _url = _url.substr(place); place = _url.find(":"); _host = _url.substr(0, place); if (!_host.empty()) components |= HOST; if (place != std::string::npos) { const auto strPort = _url.substr(place+1); // std::stol raises an exception if the conversion fails, instead prefer strtol that sets errno char* end = nullptr; errno = 0; const auto longPort = std::strtol(strPort.data(), &end, 10); if (errno == 0 && end == strPort.data() + strPort.size() && longPort >= std::numeric_limits<uint16_t>::min() && longPort <= std::numeric_limits<uint16_t>::max()) { _port = static_cast<uint16_t>(longPort); components |= PORT; } else { const auto localErrno = errno; qiLogWarning() << "Could not parse port '" << strPort << "' from url '" << url << "' (errno:" << localErrno << ", strerror:'" << std::strerror(localErrno) << "')"; } } port = _port; host = _host; protocol = _scheme; return components; } bool operator==(const Url& lhs, const Url& rhs) { return lhs.str() == rhs.str(); } std::ostream& operator<<(std::ostream& out, const Url& url) { return out << url.str(); } Url toUrl(const Uri& uri) { Url url; url.setProtocol(uri.scheme()); const auto optAuth = uri.authority(); if (!optAuth.empty()) { const auto auth = *optAuth; url.setHost(auth.host()); const auto optPort = auth.port(); if (!optPort.empty()) { const auto port = *optPort; url.setPort(port); } } return url; } }
true
1a05d284215509ce9840f510d739bcfdab162106
C++
intel/riggingtools
/kp2rig/src/SmoothFactory.cpp
UTF-8
1,129
2.546875
3
[ "MIT" ]
permissive
#include <sstream> #include <unordered_map> #include "SmoothFactory.hpp" // Include implemented smooth classes here #include "Smooth_lpfIpp.hpp" SMOOTH_TYPE SmoothFactory::SmoothType( std::string type ) { static std::unordered_map< std::string, SMOOTH_TYPE > map = { { "none", SMOOTH_TYPE_NONE }, { "lpf_ipp", SMOOTH_TYPE_LPF_IPP } }; auto it = map.find( type ); if ( it == map.end() ) return SMOOTH_TYPE_NONE; else return (*it).second; } std::string SmoothFactory::SmoothType( SMOOTH_TYPE type ) { static std::unordered_map< SMOOTH_TYPE, std::string > map = { { SMOOTH_TYPE_NONE, "none" }, { SMOOTH_TYPE_LPF_IPP, "lpf_ipp" } }; auto it = map.find( type ); if ( it == map.end() ) return "none"; else return (*it).second; } std::unique_ptr< Smooth > SmoothFactory::Create( SMOOTH_TYPE type ) { // Create a new importer switch ( type ) { #ifdef HAVE_IPP case SMOOTH_TYPE_LPF_IPP: return std::unique_ptr< Smooth >( new Smooth_lpfIpp() ); #endif default: return std::unique_ptr< Smooth >( nullptr ); } }
true
e53348697c23dd12a4ce017e073e7ae53df62409
C++
crazygao/study
/leetcode/31_next_permutation/next_permutation.cpp
UTF-8
1,364
3.421875
3
[]
no_license
#include <vector> #include <iostream> #include <algorithm> using namespace std; class Solution { public: void nextPermutation(vector<int>& nums) { int k = -1; int l = -1; int numK = 0; if (nums.size() < 2) { return; } for (auto iter = nums.begin() + 1; iter != nums.end(); iter++) { if (*iter > *(iter - 1)) { k = iter - nums.begin() - 1; numK = *(iter - 1); } if (k != -1 && *iter > numK) { l = iter - nums.begin(); } } if (k == -1) { reverse(nums.begin(), nums.end()); } swap(nums[k], nums[l]); reverse(nums.begin() + k + 1, nums.end()); } }; template <class T> ostream& operator<<(ostream& os, vector<T>& nums) { for (typename vector<T>::iterator p = nums.begin(); p != nums.end(); ++p) { os << *p << ' '; } return os; } int main() { Solution sol; vector<int> nums{1, 1}; sol.nextPermutation(nums); cout << nums << endl; sol.nextPermutation(nums); cout << nums << endl; sol.nextPermutation(nums); cout << nums << endl; sol.nextPermutation(nums); cout << nums << endl; sol.nextPermutation(nums); cout << nums << endl; sol.nextPermutation(nums); cout << nums << endl; }
true
0b045d5055b6d85201e0cfb340e7ef3ccd209f27
C++
CaoHaoyuan/ECE17-CPPandOOP
/HW6 Text Compression/ProcessController.cpp
UTF-8
10,145
3.375
3
[]
no_license
// // STLWordProcessor.cpp // assignment6 // // Created by rick gessner on 11/12/19. // Copyright © 2019 rick gessner. All rights reserved. // #include "ProcessController.hpp" #include <fstream> #include <iostream> #include <sstream> #include <list> #include <map> #include <ctype.h> using std::cout; using std::endl; using std::string; namespace ECE17 { std::string columnPad(std::string str, int column_width) { if(str.length() < column_width) str = str + std::string(column_width - str.length(), ' '); return str; } bool isPunct(char aChar) { static std::string punct(".;?!:,'-()"); return std::string::npos != punct.find(aChar); } void removePunct(std::string &str) { std::string str_orig = str; str.clear(); for(char c: str_orig) { if(!isPunct(c)) str.push_back(c); } } ProcessController::ProcessController() { //don't forget to initialze your data members... } ProcessController::ProcessController(const ProcessController &aCopy) { //ocf requirement } ProcessController::~ProcessController() { //dont forget me! } ProcessController &ProcessController::operator=(const ProcessController &aCopy) { return *this; } //This drives your statistical functions... void ProcessController::showStatistics(std::string &anInput, std::ostream &anOutput) { anOutput << "\nWord Counts: \n"; showWordUsage(anInput, anOutput); anOutput << "\nWord Pairs: \n"; showWordPairs(anInput, anOutput); } void ProcessController::showWordUsage(std::string &anInput, std::ostream &anOutput) { std::list<std::string> word_col; std::list<int> count_col; calcWordUsage(word_col, count_col, anInput); printTable("Word", "Count", word_col, count_col, anOutput); } void ProcessController::showWordPairs(std::string &anInput, std::ostream &anOutput) { std::list<std::string> word_pairs_col; std::list<int> count_col; calcWordPairs(word_pairs_col, count_col, anInput); printTable("Word Pairs", "Count", word_pairs_col, count_col, anOutput); } void ProcessController::printTable(std::string col1_label, std::string col2_label, std::list<std::string> &col1, std::list<int> &col2, std::ostream &anOutput) { std::cout << "| " << columnPad(col1_label, 30); std::cout << "| " << columnPad(col2_label, 10) << " |" << std::endl; std::cout << std::string(46, '-') << std::endl; std::list<std::string>::iterator col1_it = col1.begin(); std::list<int>::iterator col2_it = col2.begin(); while(col1_it != col1.end() && col2_it != col2.end()) { std::cout << "| " << columnPad(*col1_it++, 30); std::cout << "| " << columnPad(std::to_string(*col2_it++), 10) << " |" << std::endl; } } void ProcessController::cleanWord(string &aWord){ // Remove the punctuation on two sides of the word while(aWord.size()>0){ if(isalpha(aWord.front())) break; else aWord.erase(0,1); } while(aWord.size()>0){ if(isalpha((aWord.back()))) break; else aWord.pop_back(); } } void ProcessController::calcWordUsage(std::list<std::string> &word_col, std::list<int> &count_col, std::string &anInput) { word_col.clear(); count_col.clear(); size_t l = anInput.size(); //cout << "Input string length is: " << l << endl; std::istringstream InputStringStream(anInput); string theWord; std::map<std::string,int> wordCount; //wordCount[a word] = the word's count string theLine; //read word from anInput while(std::getline(InputStringStream,theLine)){ std::istringstream LineStringStream(theLine); while(!LineStringStream.eof() and theLine!=""){ LineStringStream >> theWord; cleanWord(theWord); auto ret = wordCount.insert({theWord,1}); if(ret.second == false){ // pair already exist wordCount[theWord]++; } } } // move word count from wordMap to word_col and count_col for(auto i = wordCount.begin();i!=wordCount.end();i++){ word_col.push_back(i->first); count_col.push_back(i->second); } // construct the encodeDict and decodeDict. // encodeDict[a word] = the words' code // decodeDict[a code] = the word unsigned short code = 0; for(auto i = wordCount.begin();i!=wordCount.end();i++){ encodeDict.insert({i->first,code}); decodeDict.push_back(i->first); code ++; } } void ProcessController::calcWordPairs(std::list<std::string> &word_pairs_col, std::list<int> &count_col, std::string &anInput) { word_pairs_col.clear(); count_col.clear(); std::istringstream InputStringStream(anInput); string cur,next,theWord; if(anInput.size()==0) return; //cur cannot be assigned InputStringStream >> cur; std::map<string,int> wordPairCount; //wordPair[a Pair] = the pair's count while(!InputStringStream.eof()){ InputStringStream >> next; theWord = cur+" "+next; auto ret = wordPairCount.insert({theWord,1}); if(ret.second == false){ // pair already exist wordPairCount[theWord]++; } cur = next; } // move word pair count from wordPairCount to word_pairs_col and count_col for(auto i = wordPairCount.begin();i!=wordPairCount.end();i++){ if(i->second>1){ word_pairs_col.push_back(i->first); count_col.push_back(i->second); } } } void ProcessController::encodeWord(string aWord,std::ostream &anOutput){ auto copy = aWord; size_t i,j; for(i=0;i<aWord.length();i++){ if(isalpha(aWord[i])) break; } anOutput << aWord.substr(0,i); cleanWord(copy); try { int Index = encodeDict.at(copy); if(Index<100){ // need one char to encode anOutput << (char) (Index+128); } else if(Index<10000){ // need two chars to encode int firsthalf = Index/100+128; int secondhalf = Index-100*firsthalf+128; anOutput << (char) firsthalf << (char) secondhalf; } else{ // need three chars to encode int firsthalf = Index/10000+128; Index -= 10000*firsthalf; int secondhalf = Index/100+128; Index -= 100*secondhalf; int thirdhalf = Index+128; anOutput << (char)firsthalf << (char)secondhalf <<(char)thirdhalf; } } catch (const std::out_of_range &oor) { std::cerr << "Input stream contains words not in the list." << oor.what() << endl; } for(j=aWord.length()-1;j>=0;j--){ if(isalpha(aWord[j])) break; } anOutput<< aWord.substr(j+1,aWord.length()-j); } //output your compressed version input the anOutput stream... bool ProcessController::compress(std::string &anInput, std::ostream &anOutput) { //STUDENT: implement this method... //original string -> unsigned short int -> encoded string std::istringstream InputStringStream(anInput); string theLine,theWord; //read word from anInput bool addLb = (anInput.back()=='\n'); bool flag_lb = false; while(std::getline(InputStringStream,theLine)){ if(flag_lb) anOutput << "\n"; flag_lb = true; std::istringstream LineStringStream(theLine); if(theLine.empty()){ } else { bool flag_ws = false; while (!LineStringStream.eof()) { if(flag_ws) anOutput << " "; flag_ws = true; LineStringStream >> theWord; encodeWord(theWord,anOutput); } } } if(addLb) anOutput << "\n"; return true; } void ProcessController::decodeWord(string aString, std::ostream &anOutput){ size_t i,j; for(i=0;i<aString.length();i++){ if((int)aString[i]<0) break; } for(j=aString.length()-1;j>=0;j--){ if((int)aString[j]<0) break; } auto copy = aString.substr(i,j-i+1); auto l = copy.length(); int Index; if(l>3){ cout<< "Decode error.Coded word should not have more than 3 chars." << endl; } if(l==1){ // index 0-99 // cout << i << " " << j << endl; // cout << copy[0] << (int)copy[0] << endl; Index = (int)copy[0]+128; } else if(l==2){ Index = 100*(int)(copy[0]+128)+(int)copy[1]+128; } else{ Index = 10000*((int)copy[0]+128)+100*((int)copy[1]+128)+(int)copy[2]+128; } // cout << "Index is " << Index << endl; string aWord = decodeDict[Index]; anOutput << aString.substr(0,i) << aWord << aString.substr(j+1,aString.length()-j); } //de-compress given string back to original form, and write it out to anOutput... bool ProcessController::decompress(std::string &aBuffer, std::ostream &anOutput) { //STUDENT: implement this method... //encoded string -> unsigned short -> original string std::istringstream InputStringStream(aBuffer); string theLine,theString; //read word from a buffer bool addLb = aBuffer.back()=='\n'; bool flag_lb = false; while(std::getline(InputStringStream,theLine)){ if(flag_lb) anOutput << "\n"; flag_lb = true; std::istringstream LineStringStream(theLine); if(theLine==""){ } else { bool flag_ws = false; while (!LineStringStream.eof()) { if(flag_ws) anOutput << " "; flag_ws = true; LineStringStream >> theString; decodeWord(theString,anOutput); } } } if(addLb) anOutput << '\n'; return true; } }
true
410248afeddfc88bd11d51aaadc36eaedd881324
C++
EricJWest/sandbox
/C++/lesson_17/listing17.6/listing17.6.cpp
UTF-8
992
4.4375
4
[]
no_license
/* Listing 17.6: Using 'vector::pop_back()' to Delete the Last Element Teach Yourself C++ in One Hour a Day (8th edition) by Siddhartha Rao */ #include <iostream> #include <vector> using namespace std; template <typename T> void DisplayVector(const vector<T>& inVec) { for (auto element = inVec.cbegin(); // auto and cbegin(): C++11 element != inVec.cend(); // cend(): C++11 ++ element) cout << *element << ' '; cout << endl; } int main() { vector <int> integers; // Insert sample integers into the vector: integers.push_back (50); integers.push_back (1); integers.push_back (987); integers.push_back (1001); cout << "Vector contains " << integers.size() << " elements: "; DisplayVector(integers); cout << endl; // Erase one element at the end integers.pop_back(); cout << "After a call to pop_back()" << endl; cout << "Vector contains " << integers.size() << " elements: "; DisplayVector(integers); return 0; }
true
e764b7b2cf9606e589874780fa2a54f66d1039fe
C++
braeden-kurz/Black-Jack-Program
/Card.cpp
UTF-8
7,402
3.8125
4
[]
no_license
#ifndef CARD_H #define CARD_H #include "Card.h" #endif /******************************* * CARD CLASS *******************************/ /* * Card::Card(): Initializes the card object to null characters and sets * the weight to an abitrary value (-999 in this case) * * Return value: N/A */ Card::Card() { suit = '\0'; value = '\0'; weight = 0; } /* * Card::Card(char, char): Sets the suit and value of the card to that * of the specified parameter variables. Sets the weight of the card * based on the suit and * * char suit: The suit of the card (Clubs, Spades, etc) * * car value: The number or type of card that carries weight * (ace, king, 9, etc) * * Return Value: N/A */ Card::Card(char suit, char value) { this->suit = suit; this->value = value; switch(value) { case 'A': case 'K': case 'Q': case 'J': case 'T': weight = 10; break; case '9': weight = 9; break; case '8': weight = 8; break; case '7': weight = 7; break; case '6': weight = 6; break; case '5': weight = 5; break; case '4': weight = 4; break; case '3': weight = 3; break; case '2': weight = 2; break; default: break; } } /* * std::string Card::printCard() const: Prints the card of the player/ * dealer * * Return Value: The card, along with it's suit and value */ std::string Card::printCard() const { std::string thisCard; thisCard += '|'; thisCard += '['; thisCard += suit; thisCard += value; thisCard += ']'; thisCard += '|'; return thisCard; } /* * char Card::getValue() const: Getter function that returns the weight * of the card * * Return Value: The value of the card */ char Card::getValue() const { return value; } /* * char Card::getSuit() const: Getter function that returns the the suit * of the card * * Return Value: The suit of the card */ char Card::getSuit() const { return suit; } /* * int Card::getWeight() const: Getter function that returns the weight * of the card * * Return Value: The weight of the card */ int Card::getWeight() const { return weight; } /* * bool Card::operator<(Card) const: Compares the value of two cards * * Card rhsCard: The right-hand card being compared * * Return Value: A boolean comparison of the left and right hand-cards */ bool Card::operator<(Card rhsCard) const { return this->getValue() < rhsCard.getValue(); } /* * bool Card::operator>(Card) const: Compares the value of two cards * * Card rhsCard: The right-hand card being compared * * Return Value: A boolean comparison of the left and right hand-cards */ bool Card::operator>(Card rhsCard) const { return this->getValue() > rhsCard.getValue(); } /* * bool Card::operator!=(Card) const: Compares the value of two cards * * Card rhsCard: The right-hand card being compared * * Return Value: A boolean comparison of the left and right hand-cards */ bool Card::operator!=(Card rhsCard) const { return this->getValue() != rhsCard.getValue() && this->getSuit() != rhsCard.getSuit(); } /* * bool Card::operator==(Card) const: Compares the value of two cards * * Card rhsCard: The right-hand card being compared * * Return Value: A boolean comparison of the left and right hand-cards */ bool Card::operator==(Card rhsCard) const { return this->getValue() == rhsCard.getValue() && this->getSuit() == rhsCard.getSuit(); } /******************************* * DECK CLASS *******************************/ /* * Deck::Deck(): Deck contructor that sets the sizeOfDeck variable to 0 * and sets the head node to NULL * * Card rhsCard: The right-hand card being compared * * Return Value: A boolean comparison of the left and right hand-cards */ Deck::Deck() { head = NULL; sizeOfDeck = 0; } /* * Deck::~Deck(): Deck deconstructor that calls ClearDeck() to * deallocate the deck * * Return Value: N/A */ Deck::~Deck() { ClearDeck(); } /* * void Deck::AddToTopOfDeck(Card): Places a new card to the head node of * the deck, making it the first card of the deck * * Card card: The card to be added to the top (head node) of the deck * * Return Value: N/A */ void Deck::AddToTopOfDeck(Card card) { Hand* newHand = new Hand; newHand->card = card; newHand->next = head; head = newHand; ++sizeOfDeck; } /* * Card Deck::RemoveTopCard(): Takes the top card of the deck * deallocates the card, pushes the next card to the top and decrements * the sizeOfDeck * * Return Value: The card of the deck being removed */ Card Deck::RemoveTopCard() { Hand* temp = new Hand; temp->card = head->card; temp = head->next; delete head; head = temp; --sizeOfDeck; return head->card; } /* * void Deck::ShuffleDeck(): Randomly swaps the place of the cards within * the deck * * Return Value: N/A */ void Deck::ShuffleDeck() { for (int i = 0; i < GetSizeOfDeck(); i++) { SwapCards((*this)[i], (*this)[GetRandomCardIndex()]); } } /* * void Deck::ClearDeck(): Deallocates the deck and sets the sizeOfDeck * variable to 0 * * Return Value: N/A */ void Deck::ClearDeck() { Hand* temp = NULL; while (head != NULL) { temp = head; head = head->next; delete temp; } sizeOfDeck = 0; } /* * voiid Deck::SwapCards(Hand*, Hand*): Changes the place of the cards * in the deck * * Hand* h1, h2: The cards being swapped * * Return Value: N/A */ void Deck::SwapCards(Hand* h1, Hand* h2) { Card temp = h1->card; h1->card = h2->card; h2->card = temp; } /* * int Deck::GetSizeOfDeck() const: Returns the the size of the deck * * Return Value: An integer value representing the number of cards * in the deck */ int Deck::GetSizeOfDeck() const { return sizeOfDeck; } /* * int Deck::GetRandomCardIndex() const: Using rand, this function * returns a random number that's within the size of the deck * * Return Value: A random integer value of that will be used to grab a * random card fro the deck */ int Deck::GetRandomCardIndex() const { return (rand() % sizeOfDeck); } /* * void Deck::PrintDeck(): Simply prints the deck * * Return Value: N/A */ void Deck::PrintDeck() { std::cout << "-------------------------" << std::endl; for(int i = 0; i < sizeOfDeck; i++){ std::cout << (*this)[i]->card.printCard(); if((i + 1) % 4 == 0){ std::cout << std::endl; } } std::cout << std::endl << "-------------------------" << std::endl; } /* * Deck::Hand* Deck::operator[](int): Returns the index of the deck. * Makes indexing/finding specific elements in the list much * easier * * int index: The so-called 'index' of the linked list * * Return Value: The indexed node of the list * */ Deck::Hand* Deck::operator[](int index) { Hand* temp = new Hand; temp = head; int iterate = 0; while (iterate < index) { if (index > sizeOfDeck || index < 0) { break; } temp = temp->next; iterate++; } return temp; }
true
1b51b4ea67332915795122ede682eda4eaa89f08
C++
CaptainSlowWZY/OI-Code
/XJOI/pigeon.cpp
UTF-8
3,495
2.6875
3
[]
no_license
// pigeon #include <cstdio> #include <algorithm> #ifdef DEBUG_MD #define debug(format, ...) fprintf(stderr, format, __VA_ARGS__) #else #define debug(format, ...) #endif const int MAXN = 2e5 + 10; struct Opt { int tp, op1, op2, op3; Opt() { tp = 1; } Opt(int v_) : tp(2), op1(v_) {} Opt(int l_, int r_, int k_) : tp(3), op1(l_), op2(r_), op3(k_) {} operator int() const { return tp; } } O[MAXN]; int N, M, rk, A[MAXN], num[MAXN << 1]; namespace FastIO { template <typename T> void read(T & x); template <typename T> void write(T x); template <typename T> inline void writeln(T x) { write(x), putchar('\n'); } } namespace seg { const int ARSIZE = 3e5 + 10; int sz, lstsz, top; struct Node { int sum; Node *lson, *rson; } T[MAXN << 6], *root[ARSIZE]; Node *build(int l, int r); Node *updata(int k, int l, int r, Node *hst); inline void init() { root[top = sz = lstsz = 0] = build(1, rk); } inline void push_back(int k) { lstsz = sz; root[top + 1] = updata(k, 1, rk, root[top]); ++top; } inline void pop_back() { --top, sz = lstsz; } int query(int l, int r, int k); } inline int get_id(int v) { return std::lower_bound(num, num + rk, v) - num + 1; } int main() { using FastIO::read; read(N), read(M); for (int i = 0; i < N; i++) read(A[i]), num[rk++] = A[i]; for (int i = 0, tp, v, l, r, k; i < M; i++) { read(tp); if (tp == 2) { read(v); O[i] = Opt(v); num[rk++] = v; } if (tp == 3) { read(l), read(r), read(k); O[i] = Opt(l, r, k); } } std::sort(num, num + rk); rk = std::unique(num, num + rk) - num; seg::init(); for (int i = N - 1; i >= 0; i--) seg::push_back(get_id(A[i])); for (int i = 0; i < M; i++) { if (O[i] == 1) seg::pop_back(); if (O[i] == 2) seg::push_back(get_id(O[i].op1)); if (O[i] == 3) FastIO::writeln(seg::query(O[i].op1, O[i].op2, O[i].op3)); } return 0; } namespace seg { Node *New() { T[sz].sum = 0, T[sz].lson = T[sz].rson = NULL; return &T[sz++]; } Node *build(int l, int r) { Node *rt = New(); if (l == r) return rt; int mid = l + r >> 1; rt->lson = build(l, mid); rt->rson = build(mid + 1, r); return rt; } Node *updata(int k, int l, int r, Node *hst) { Node *rt = New(); rt->sum = hst->sum + 1, rt->lson = hst->lson, rt->rson = hst->rson; if (l == r) return rt; int mid = l + r >> 1; if (k <= mid) rt->lson = updata(k, l, mid, hst->lson); else rt->rson = updata(k, mid + 1, r, hst->rson); return rt; } int _query(Node *pre, Node *cur, int l, int r, int k) { if (l == r) return l; int sum = cur->lson->sum - pre->lson->sum, mid = l + r >> 1; if (k <= sum) return _query(pre->lson, cur->lson, l, mid, k); else return _query(pre->rson, cur->rson, mid + 1, r, k - sum); } int query(int l, int r, int k) { int len = r - l + 1; debug("query: from left to right[%d, %d], len=%d\n", l, r, len); l = top - r + 1, r = l + len - 1; debug("top=%d, [%d, %d]\n", top, l, r); return num[_query(root[l - 1], root[r], 1, rk, k) - 1]; } } namespace FastIO { template <typename T> void read(T & x) { register char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()); for (x = 0; ch >= '0' && ch <= '9'; x = (x << 3) + (x << 1) + (ch ^ '0'), ch = getchar()); } template <typename T> void write(T x) { if (!x) return (void)putchar('0'); if (x < 0) x = -x, putchar('-'); int arr[20], len = 0; for (; x; x /= 10) arr[len++] = x % 10; while (len) putchar(arr[--len] ^ '0'); } } // AC!!!
true