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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
119dbcffb079d4eb7d444945af79c46ba2b330e7 | C++ | herambchaudhari4121/Hacktoberfest-KIIT-2021 | /ROHIT KUMAR SINGH (Hacktober Contribution)/HackerRank/Intro_to_Tutorial_Challenges.cpp | UTF-8 | 373 | 2.75 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int introTutorial(int V, vector<int> arr) {
int ind = (find(arr.begin(), arr.end(), V) - arr.begin());
return ind;
}
int main()
{
int V,n;
cin>>V;
cin>>n;
vector<int> arr(n);
for(int &it:arr) cin>>it;
int result = introTutorial(V, arr);
cout<<result<<endl;
return 0;
} | true |
64aa4e218e88013715cf44c755eb3198b3a190ae | C++ | unwag001/CS14-SPRING2015 | /lab02/lab2.h | UTF-8 | 956 | 3.78125 | 4 | [] | no_license | template <class T> class List
{
private:
struct Node
{
T data;
Node* next;
}
Node* head;
public:
List(): data(0), next(NULL) {}
void push_front(T value);
void pop_front();
void display();
void elementSwap(int pos);
};
template <class T>
void List::push_front(T value)
{
Node<T>* temp = new Node<T>(value);
temp->next = head;
head = temp;
}
template <class T>
void List::display()
{
if (!head) {return;}
for (Node<T> * curr = head; curr->next != 0; curr = curr->next)
{
std::cout << curr->data << " ";
}
}
template <class T>
void List::elementSwap(int pos)
{
Node<T> * posit_plus_one = head;
Node<T> * posit = 0;
for (int i =0; i < pos; i++)
{
if(posit_plus_one->next ==0)
{
break;
}
posit = posit_plus_one;
posit_plus_one = posit_plus_one->next;
}
} | true |
2be2d5b944897ce5b509bd7b5832bb89714f8404 | C++ | w135110392/students_question | /students_question/飞机大战.cpp | GB18030 | 1,309 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void mainfeiji()
{
int i, j;
int x = 5;
int y = 10;
char input;
int isFire = 0;
int ny = 5; // һӣڵһУny
int isKilled = 0;
while (1)
{
system("cls"); //
//
if (!isKilled) //
{
for (j = 0; j < ny; j++)
printf(" ");
printf("+\n");
}
if (isFire == 0) // ɻĿ
{
for (i = 0; i < x; i++)
printf("\n");
}
else // ɻļ
{
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
printf(" ");
printf(" |\n");
}
if (y + 2 == ny)
isKilled = 1; // а
isFire = 0;
}
// һӵķɻͼ
for (j = 0; j < y; j++)
printf(" ");
printf(" *\n");
for (j = 0; j < y; j++)
printf(" ");
printf("*****\n");
for (j = 0; j < y; j++)
printf(" ");
printf(" * * \n");
if (kbhit()) // жǷ
{
input = getch(); // ûIJͬƶس
if (input == 'a')
y--; // λ
if (input == 'd')
y++; // λ
if (input == 'w')
x--; // λ
if (input == 's')
x++; // λ
if (input == ' ')
isFire = 1;
}
}
} | true |
9fea1720b21ad82fc7862c88f5f96d435497c8b2 | C++ | jiwoo-kimm/epoll-chat-server | /server.cpp | UTF-8 | 6,601 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define DEFAULT_PORT 10007 // default server port
#define MAX_EVENTS 1000 // events limit
#define MAX_CLIENTS 1000 // clients limit
#define BACKLOG 1000 // connection queue limit
#define TIME_OUT -1 // timeout
#define BUFFER_SIZE 1024 // temporary buffer limit
#define IP_LEN 20
#define EMPTY -1
int server_socket_fd; // server socket fd
int server_port; // server port number
int epoll_fd; // epoll fd
char buffer[BUFFER_SIZE]; // buffer
epoll_event events[MAX_EVENTS];
struct
{
int socket_fd;
char ip[IP_LEN];
} clients[MAX_CLIENTS];
static void die(const char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
static void init_socket()
{
struct sockaddr_in server_addr;
/* Open TCP Socket */
if ((server_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
die("[FAIL] server start failed : can't open stream socket\n");
}
/* Set Address */
memset(&server_addr, 0, sizeof server_addr);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(DEFAULT_PORT);
/* Bind Socket */
if (bind(server_socket_fd, (struct sockaddr *)&server_addr, sizeof server_addr) < 0)
{
close(server_socket_fd);
die("[FAIL] server start failed : can't bind local address\n");
}
/* Listen */
if (listen(server_socket_fd, BACKLOG) < 0)
{
close(server_socket_fd);
die("[FAIL] server start failed : can't start listening on port\n");
}
printf("[SUCCESS] server socket initialized\n");
}
static void init_epoll()
{
/* Create Epoll */
if ((epoll_fd = epoll_create(MAX_EVENTS)) < 0)
{
close(server_socket_fd);
die("[FAIL] epoll create failed\n");
}
/* Set Event Control */
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = server_socket_fd;
/* Set Server Events */
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_socket_fd, &event) < 0)
{
close(epoll_fd);
close(server_socket_fd);
die("[FAIL] epoll control failed\n");
}
printf("[SUCCESS] epoll events initialized for the server\n");
}
static void init_clients()
{
for (int i = 0; i < MAX_CLIENTS; i++)
{
clients[i].socket_fd = EMPTY;
}
}
void add_client_to_epoll(struct epoll_event event)
{
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, event.data.fd, &event) < 0)
{
printf("[FAIL] epoll control failed while adding client\n");
}
}
void add_client_to_pool(int client_socket_fd, char *client_ip)
{
int i;
for (i = 0; i < MAX_CLIENTS; i++)
{
if (clients[i].socket_fd == EMPTY)
break;
}
if (i >= MAX_CLIENTS)
{
printf("[FAIL] max clients exceeded\n");
close(client_socket_fd);
return;
}
clients[i].socket_fd = client_socket_fd;
memset(&clients[i].ip[0], 0, IP_LEN);
strcpy(&clients[i].ip[0], client_ip);
}
void remove_client_from_epoll(struct epoll_event event)
{
if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, event.data.fd, &event) < 0)
{
printf("[FAIL] epoll control failed while removing client\n");
}
}
void remove_client_from_pool(int target_fd)
{
for (int i = 0; i < MAX_CLIENTS; i++)
{
if (clients[i].socket_fd == target_fd)
{
clients[i].socket_fd = EMPTY;
break;
}
}
}
void broadcast(int sender_fd, int len)
{
int i;
for (i = 0; i < MAX_CLIENTS; i++)
{
if (clients[i].socket_fd != EMPTY && clients[i].socket_fd != sender_fd)
{
len = write(clients[i].socket_fd, buffer, len);
}
}
memset(buffer, NULL, sizeof(char) * BUFFER_SIZE);
}
void process_message(struct epoll_event event)
{
/* Read from Socket */
int len = read(event.data.fd, buffer, sizeof buffer);
if (len < 0)
{
/* Error while Reading */
remove_client_from_epoll(event);
remove_client_from_pool(event.data.fd);
close(event.data.fd);
perror("[FAIL] read from socket failed\n");
return;
}
if (len == 0)
{
/* Disconnect Client */
remove_client_from_epoll(event);
remove_client_from_pool(event.data.fd);
close(event.data.fd);
printf("[SUCCESS] client disconnected (fd:%d)\n", event.data.fd);
return;
}
/* Broadcast to Clients */
broadcast(event.data.fd, len);
}
void set_non_blocking(int socket)
{
int flag = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flag | O_NONBLOCK);
}
void run_process()
{
/* Wait for Events */
int num_of_fds = epoll_wait(epoll_fd, events, MAX_EVENTS, TIME_OUT);
if (num_of_fds < 0)
{
perror("[FAIL] epoll wait failed\n");
return;
}
for (int i = 0; i < num_of_fds; i++)
{
/* Create Event */
struct epoll_event event;
event.events = EPOLLIN;
if (events[i].data.fd == server_socket_fd)
{
/* Accept Connection Request */
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_socket_fd = accept(server_socket_fd,
(struct sockaddr *)&client_addr,
&client_len);
/* Handle Connection Request */
if (client_socket_fd < 0)
{
perror("[FAIL] epoll accept failed\n");
}
else
{
event.data.fd = client_socket_fd;
set_non_blocking(client_socket_fd);
add_client_to_epoll(event);
add_client_to_pool(client_socket_fd, inet_ntoa(client_addr.sin_addr));
printf("[SUCCESS] new client connected (fd:%d, ip:%s)\n",
client_socket_fd, inet_ntoa(client_addr.sin_addr));
}
}
else
{
/* Read and Broadcast Message to Clients */
event.data.fd = events[i].data.fd;
process_message(event);
}
}
}
int main()
{
init_socket();
init_epoll();
init_clients();
printf("======= SERVER RUNNING =======\n");
while (1)
{
run_process();
}
printf("======= SERVER STOPPED =======");
return 0;
} | true |
ee788ff0ea460272cb53bcdfd39ec29f1e842ce6 | C++ | BlackFox101/OOP | /lw2/Dictionary/Dictionary/Dictionary.cpp | WINDOWS-1251 | 3,531 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include "Dictionary.h"
using namespace std;
bool OpenFile(fstream& file, string fileName)
{
file.open(fileName);
if (!file.is_open())
{
return false;
}
return true;
}
void InitDictionary(fstream& initFile, map<string, string>& dictionary)
{
string line;
while (getline(initFile, line))
{
if (line.find("-") == std::string::npos)
{
break;;
}
string eng = line.substr(0, line.find("-"));
string rus = line.substr(eng.length() + 1);
dictionary[eng] = rus;
}
}
void SaveDictionary(fstream& vocabularyFile, const map<string, string>& dictionary)
{
map<string, string>::const_iterator it;
for (it = dictionary.begin(); it != dictionary.end(); ++it) {
vocabularyFile << it->first << "-" << it->second << endl;
}
}
void Save(fstream& vocabularyFile, const map<string, string>& dictionary)
{
if (vocabularyFile.is_open())
{
vocabularyFile.clear();
vocabularyFile.seekg(0);
SaveDictionary(vocabularyFile, dictionary);
return;
}
fstream output;
while (true)
{
cout << " :";
string path;
cin >> path;
output.open(path);
if (!output.is_open())
{
cout << "Failed to open '"<< path <<"' for writing\n";
continue;
}
break;
}
SaveDictionary(output, dictionary);
}
bool TranslateWord(const string& word, const map<string, string>& dictionary, ostream& output)
{
if (dictionary.find(word) != dictionary.end())
{
output << dictionary.at(word) << endl;
return true;
}
return false;
}
bool SaveWord(map<string, string>& dictionary, const string& word, istream& input)
{
string translation;
getline(input, translation);
if (translation != "")
{
dictionary[word] = translation;
return true;
}
return false;
}
void WorkingDictionary(fstream& vocabularyFile, map<string, string>& dictionary)
{
const int initialNumberElements = dictionary.size();
string word;
getline(cin, word);
while (word != "...")
{
string tempWord = word;
transform(word.begin(), word.end(), word.begin(), tolower);
if (!TranslateWord(word, dictionary, cout))
{
cout << " " << tempWord << ". .\n";
if (SaveWord(dictionary, word, cin))
{
cout << " " << tempWord << " " << dictionary[word] << ".\n";
}
else
{
cout << " " << tempWord << ".\n";
}
}
getline(cin, word);
}
if (initialNumberElements != dictionary.size())
{
char ch;
cout << " . Y y .\n";
cin >> ch;
if (ch == 'Y' || ch == 'y')
{
Save(vocabularyFile, dictionary);
cout << " . .\n";
}
}
} | true |
17959050a5934f04db017cc25453f42dac19cdc8 | C++ | sasaki-seiji/ProgrammingLanguageCPP4th | /part4/ch36/36-3-4-input-string/src/input_string.cpp | UTF-8 | 692 | 3.34375 | 3 | [] | no_license | /*
* input_string.cpp
*
* Created on: 2016/12/18
* Author: sasaki
*/
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void successive_input()
{
cout << "-- successive_input() --\n";
cout << "enter first_name and second_name: " << flush;
string first_name;
string second_name;
cin >> first_name >> second_name;
cout << "first_name: " << first_name << ", second_name: " << second_name << endl << flush;
}
void echo_lines()
{
cout << "-- echo_lines() --\n" << flush;
vector<string> lines;
for (string s; getline(cin,s);)
lines.push_back(s);
for (auto& x : lines)
cout << x << endl;
}
int main()
{
successive_input();
echo_lines();
}
| true |
aa73e5d90c3044d7d84dd123bb615014c89db625 | C++ | toddnguyen-gf/embedded-training | /ece-18-642/lec-01-to-04/project02/p02_noid_student_turtle.cpp | UTF-8 | 6,821 | 2.75 | 3 | [] | no_license | /*
* Originally by Philip Koopman (koopman@cmu.edu)
* and Milda Zizyte (milda@cmu.edu)
*
* STUDENT NAME: Todd Nguyen
* ANDREW ID: noid
* LAST UPDATE: Sunday 2021-03-14 10:49
*
* This file is an algorithm to solve the ece642rtle maze
* using the left-hand rule. The code is intentionaly left obfuscated.
*
*/
#include "student.h"
#include <stdint.h>
// Ignore this line until project 5
turtleMove studentTurtleStep(bool bumped) { return MOVE; }
// OK TO MODIFY BELOW THIS LINE
#define TIMEOUT 40 // bigger number slows down simulation so you can see what's happening
float _current_timeout;
float _fx1, _fy1, _fx2, _fy2;
bool _has_this_orientation_been_traveled, _is_end_of_maze, _maze_contains_wall;
enum class Orientation
{
kWest = 0,
kNorth,
kEast,
kSouth,
};
const char *ORIENTATION_STR[] = {"WEST", "NORTH", "EAST", "SOUTH"};
enum class State
{
kNoWall = 0,
kHasWall,
kGoThisOrientation,
};
const char *STATE_STR[] = {"NO WALL", "HAS A WALL", "GO THIS ORIENTATION"};
State _current_state;
bool moveLeftHandRule(QPointF &pos_, int &nw_or);
bool moveRightHandRule(QPointF &pos_, int &nw_or);
Orientation _set_orientation_and_current_state(
Orientation orientation, Orientation orientationGoThisOrientation,
Orientation orientationMazeContainsWall);
bool _returnTimeout();
void _moveTurtle(QPointF &pos_, Orientation orientation);
void _setTurtlePosition(QPointF &pos_, Orientation orientation);
/**
* this procedure takes the current turtle position and orientation and returns
* true=submit changes, false=do not submit changes
* Ground rule -- you are only allowed to call the helper functions "bumped(..)" and "atend(..)",
* and NO other turtle methods or maze methods (no peeking at the maze!)
*/
bool studentMoveTurtle(QPointF &pos_, int &nw_or)
{
// return moveLeftHandRule(pos_, nw_or);
return moveRightHandRule(pos_, nw_or);
}
bool moveRightHandRule(QPointF &pos_, int &nw_or)
{
// ROS_INFO("Turtle update Called w=%f", _current_timeout);
Orientation orientation = static_cast<Orientation>(nw_or);
if (0 == _current_timeout)
{
_setTurtlePosition(pos_, orientation);
_maze_contains_wall = bumped(_fx1, _fy1, _fx2, _fy2);
_is_end_of_maze = atend(pos_.x(), pos_.y());
switch (orientation)
{
case Orientation::kWest:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kNorth, Orientation::kSouth);
break;
case Orientation::kNorth:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kEast, Orientation::kWest);
break;
case Orientation::kEast:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kSouth, Orientation::kNorth);
break;
case Orientation::kSouth:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kWest, Orientation::kEast);
break;
}
ROS_INFO("Orientation='%s' State='%s'",
ORIENTATION_STR[static_cast<int>(orientation)],
STATE_STR[static_cast<int>(_current_state)]);
_moveTurtle(pos_, orientation);
}
nw_or = static_cast<int>(orientation);
return _returnTimeout();
}
bool moveLeftHandRule(QPointF &pos_, int &nw_or)
{
// ROS_INFO("Turtle update Called w=%f", _current_timeout);
Orientation orientation = static_cast<Orientation>(nw_or);
if (0 == _current_timeout)
{
_setTurtlePosition(pos_, orientation);
_maze_contains_wall = bumped(_fx1, _fy1, _fx2, _fy2);
_is_end_of_maze = atend(pos_.x(), pos_.y());
switch (orientation)
{
case Orientation::kWest:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kSouth, Orientation::kNorth);
break;
case Orientation::kNorth:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kWest, Orientation::kEast);
break;
case Orientation::kEast:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kNorth, Orientation::kSouth);
break;
case Orientation::kSouth:
orientation = _set_orientation_and_current_state(
orientation, Orientation::kEast, Orientation::kWest);
break;
}
ROS_INFO("Orientation='%s' State='%s'",
ORIENTATION_STR[static_cast<int>(orientation)],
STATE_STR[static_cast<int>(_current_state)]);
_moveTurtle(pos_, orientation);
}
nw_or = static_cast<int>(orientation);
return _returnTimeout();
}
Orientation _set_orientation_and_current_state(
Orientation orientation, Orientation orientationGoThisOrientation,
Orientation orientationMazeContainsWall)
{
if (_current_state == State::kGoThisOrientation)
{
orientation = orientationGoThisOrientation;
_current_state = State::kHasWall;
}
else if (_maze_contains_wall)
{
orientation = orientationMazeContainsWall;
_current_state = State::kNoWall;
}
else
{
_current_state = State::kGoThisOrientation;
}
return orientation;
}
bool _returnTimeout()
{
if (_is_end_of_maze)
return false;
if (_current_timeout == 0)
_current_timeout = TIMEOUT;
else
_current_timeout -= 1;
if (_current_timeout == TIMEOUT)
return true;
return false;
}
void _moveTurtle(QPointF &pos_, Orientation orientation)
{
_has_this_orientation_been_traveled = _current_state == State::kGoThisOrientation;
if (_has_this_orientation_been_traveled == true && _is_end_of_maze == false)
{
switch (orientation)
{
case Orientation::kNorth:
pos_.setY(pos_.y() - 1);
break;
case Orientation::kEast:
pos_.setX(pos_.x() + 1);
break;
case Orientation::kSouth:
pos_.setY(pos_.y() + 1);
break;
case Orientation::kWest:
pos_.setX(pos_.x() - 1);
break;
}
_has_this_orientation_been_traveled = false;
}
}
void _setTurtlePosition(QPointF &pos_, Orientation orientation)
{
_fx1 = pos_.x();
_fy1 = pos_.y();
_fx2 = pos_.x();
_fy2 = pos_.y();
if (orientation < Orientation::kEast)
{
if (orientation == Orientation::kWest)
_fy2 += 1;
else
_fx2 += 1;
}
else
{
_fx2 += 1;
_fy2 += 1;
if (orientation == Orientation::kEast)
_fx1 += 1;
else
_fy1 += 1;
}
}
| true |
7dad3c5243c3a8543e01a94039e1b9121f666035 | C++ | askshaik/design_pattern | /CodeCOR.cpp | UTF-8 | 1,558 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
namespace cor {
class Handler {
protected:
Handler *next;
public:
Handler(Handler *n) : next(n){}
virtual void handle_request(string message) = 0;
virtual ~Handler() { delete next;}
};
class Spam_handler : public Handler {
public:
Spam_handler(Handler *n) : Handler(n){}
void handle_request(string message) override {
if (message.find("yahoo.com") != string::npos)
cout << "spam found\n";
else
next->handle_request(message);
}
};
class Fan_handler : public Handler {
public:
Fan_handler(Handler *n) : Handler(n){}
void handle_request(string message) override {
if (message.find("great") != string::npos)
cout << "Fan mail\n";
else
next->handle_request(message);
}
};
class Complaint_handler : public Handler {
public:
Complaint_handler(Handler *n) : Handler(n){}
void handle_request(string message) override {
if (message.find("refund") != string::npos)
cout << "Complaint mail\n";
else
next->handle_request(message);
}
};
class Default_handler : public Handler {
public:
Default_handler() : Handler(nullptr){}
void handle_request(string message) override {
cout << "Email will be handled manually\n";
}
};
}
using namespace cor;
void process(Handler &h, char *email) {
h.handle_request(email);
}
void cor_main() {
Spam_handler sh ( new Fan_handler(new Complaint_handler(new Default_handler())));
process(sh, "yahoo.com");
process(sh, "great");
process(sh, "refund");
process(sh, "what is this?");
}
| true |
76afb0f13f5646343d8604983a180c724041a69c | C++ | zhangyilin/leetcode | /leetcode/palindromeNumber.cpp | UTF-8 | 556 | 3.015625 | 3 | [] | no_license | class Solution {
public:
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (x<0){
return false;
}
int x_copy=x;
int y=0;
while (x){
int bit = x%10;
x = x/10;
y*=10;
y+=bit;
}
if (x_copy-y==0){
return true;
}else{
return false;
}
}
};
| true |
af0adcbc7e2640580ec669af48b52687a6c0a707 | C++ | HanaYukii/Algorithm | /hw1/217-2.cpp | UTF-8 | 1,525 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define INF 1e14
int n,k;
struct P
{
long long x, y;
int pos;
} p[500005], t[500005];
bool cmpx(P i, P j) {return i.x < j.x;}
bool cmpy(P i, P j) {return i.y < j.y;}
priority_queue<long long> max_heap;
void DnC(int L, int R)
{
if (L >= R)
{
max_heap.push(INF);
return;
}
else if(L+1==R)
{
max_heap.push((p[L].x-p[R].x)*(p[L].x-p[R].x)+(p[L].y-p[R].y)*(p[L].y-p[R].y));
return;
}
int M = (L + R) >> 1;
DnC(L,M);
DnC(M+1,R);
int N = 0;
while(max_heap.size()>k)
{
max_heap.pop();
}
for (int i=M; i>=L && (p[M].x - p[i].x)< max_heap.top(); --i)
{
t[N] = p[i];
t[N++].pos=-1;
}
for (int i=M+1; i<=R && (p[i].x - p[M].x)< max_heap.top(); ++i)
{
t[N] = p[i];
t[N++].pos=1;
}
sort(t, t+N, cmpy);
for (int i=0; i<N-1; ++i)
for (int j=1; j<=8 && i+j<N; ++j)
{
if(t[i].pos!=t[i+j].pos)
{
max_heap.push((t[i].x-t[i+j].x)*(t[i].x-t[i+j].x)+(t[i].y-t[i+j].y)*(t[i].y-t[i+j].y));
}
}
}
void closest_pair()
{
sort(p, p+n, cmpx);
return DnC(0, n-1);
}
int main()
{
scanf("%d %d",&n,&k);
for(int i=0;i<n;i++)
{
scanf("%lld %lld",&p[i].x,&p[i].y);
}
for(int i=0;i<n;i++)
{
max_heap.push(INF);
}
closest_pair();
while(max_heap.size()>k)
{
max_heap.pop();
}
cout<<max_heap.top()<<endl;
}
| true |
2b94f9b2b36e7f9230d7cc3079c89561828580a6 | C++ | ParkSunW00/CppNote | /0612/0612/Circle.cpp | UHC | 425 | 3.53125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Circle
{
public:
int radius;
Circle(); Circle(int r); ~Circle();
};
Circle::Circle()
{
radius = 10;
cout << "" << radius << " " << endl;
}
Circle::Circle(int r) {
radius = r;
cout << "" << radius << " " << endl;
}
Circle::~Circle() { cout << " " << radius << " Ҹ" << endl; }
void main()
{
Circle c1; Circle c2(50);
} | true |
785aae38889be0a6969a070fea3b973437e4f23b | C++ | mdamt/erpiko | /include/erpiko/oid.h | UTF-8 | 879 | 3.078125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef _OBJECT_ID_H_
#define _OBJECT_ID_H_
#include <string>
#include <memory>
namespace Erpiko {
/**
* ASN1 Object ID
*/
class ObjectId {
public:
/**
* Creates a new ObjectId from a string
*/
ObjectId(const std::string fromString);
virtual ~ObjectId();
/**
* Gets string representation of the object
* @return string representation
*/
const std::string toString() const;
/**
* Gets string representation of the object which we human is familiar with
* @return string representation
*/
const std::string humanize() const;
/**
* Operator ==
**/
bool operator== (const ObjectId& other) const;
/**
* Operator =
**/
void operator= (const ObjectId& other);
private:
class Impl;
std::unique_ptr<Impl> impl;
};
} // namespace Erpiko
#endif // _OBJECT_ID_H_
| true |
0d81a53c9ad872c68abc052d062a5268c9578c33 | C++ | gui-works/luigui-OpenGL3.3-Plus | /examples/main.cpp | UTF-8 | 1,427 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <luigui.hpp>
#include <GLFW/glfw3.h>
constexpr int WIDTH = 640, HEIGHT = 480;
GLFWwindow *createWindow() {
GLFWwindow *window = NULL;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, "luigui example", NULL, NULL);
glfwMakeContextCurrent(window);
return window;
}
int main() {
glfwInit();
GLFWwindow *window = createWindow();
luigui::init();
luigui::GUIObject e({1, 2}, {3, 4});
luigui::GUIObject f({5, 6});
luigui::GUIObject g;
luigui::GUIObject h({7, 8}, {9, 10}, {11, 12, 13});
for (auto i : e.getVertices()) {
std::cout << i << ", ";
}
std::cout << std::endl;
for (auto i : f.getVertices()) {
std::cout << i << ", ";
}
std::cout << std::endl;
for (auto i : g.getVertices()) {
std::cout << i << ", ";
}
std::cout << std::endl;
for (auto i : h.getVertices()) {
std::cout << i << ", ";
}
std::cout << std::endl;
glClear(GL_COLOR_BUFFER_BIT);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
} | true |
b435118a4c2233bbe3180b40ba639cbfd38503c4 | C++ | Ferror/particle-shaders | /ShaderBasics/Particle.h | UTF-8 | 720 | 2.671875 | 3 | [] | no_license | #pragma once
class Particle
{
private:
//***** TODO *****//
float age;
float deathTime;
float sPosX;
float sPosY;
float sPosZ;
float phaseX;
float phaseY;
public:
//***** TODO *****//
Particle() = delete;
Particle(float _deathTime, float _sPosX, float _sPosY, float _sPosZ, float _phaseX, float _phaseY) :
age(0), deathTime(_deathTime), sPosX(_sPosX), sPosY(_sPosY), sPosZ(_sPosZ), phaseX(_phaseX), phaseY(_phaseY) {};
virtual void operator()(float* vertieces, int& index, float dT, bool updateAge = true);
virtual bool isDeath() { return age > deathTime; };
static int VertiecesPerParticle() { return 1; };
static int VertexDimentionality() { return 10; };
~Particle();
};
| true |
745339a4ed8c56ee14d0173092ee092225e9781f | C++ | SaisriramVaddadi/LeetCode | /25-Reverse Nodes in k-Group.cpp | UTF-8 | 1,472 | 3.171875 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rev_helper(ListNode* hed,int k )
{
ListNode *pres,*next,*prev;
pres = hed->next;
next = pres;
prev = hed;
int i = 1;
while(i<k)
{
next = next->next;
pres->next = prev;
prev = pres;
pres = next;
i++;
}
return prev;
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (k == 1)
return head;
ListNode *newhead = NULL;
ListNode *temp,*next,*prev;
temp = head;
while(temp!=NULL)
{
int i=0;
while(i<k && temp!=NULL)
{
temp = temp->next;
i++;
}
if(i==k)
{
next = rev_helper(head,k);
if(newhead == NULL)
newhead = next;
else
{
prev->next = next;
}
prev = head;
head = temp ;
}
if(newhead == NULL)
return head;
else
{
prev->next = head;
}
}
return newhead;
}
};
| true |
6e0573e13f0f62f2ecf9e8b6a90f55d9e2a85ae0 | C++ | erossi/cpp_tips | /bind_functions.cpp | UTF-8 | 4,774 | 3.234375 | 3 | [] | no_license | /* Bind functions in C++, a working example.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
Compile with:
g++ -Wall -pedantic -std=c++14 -g <ThisFilename.cpp>
*/
/* Create two classes with pre-defined
* static functions, add these functions to a catalog and then
* use the catalog to trigger all these functions.
*
* output:
1st: 0
2nd: 0
After the set_Map_all()
1st: 1
2nd: 1
After the clear_Map_all()
1st: 0
2nd: 0
After the set_Vector_all()
1st: 1
2nd: 1
After the clear_Vector_all()
1st: 0
2nd: 0
After the set_Map_all() with 1st removed
1st: 0
2nd: 1
*/
#include <vector>
#include <map>
#include <iostream>
#include <functional>
using namespace std;
class FirstClass {
public:
static bool sstatus;
static void set() { sstatus = true; };
static void clear() { sstatus = false; };
static bool check() { return(sstatus); };
};
// A copy of the FirstClass
class SecondClass {
public:
static bool sstatus;
static void set() { sstatus = true; };
static void clear() { sstatus = false; };
static bool check() { return(sstatus); };
};
class Manager {
private:
// The struct we use to store in the catalog.
struct record_t {
string name; // a name, useless with maps.
function<void()> set;
function<void()> clear;
};
vector<struct record_t> vcatalog; // The catalog as a vector.
map<string, struct record_t> mcatalog; // The catalog as an associative array.
public:
// Add the two set() and clear() functions to both catalogs.
void add(string s, function<void()> f1, function<void()> f2)
{
struct record_t r {s, f1, f2};
vcatalog.push_back(r); // add it as a vector element.
mcatalog.insert( pair<string, struct record_t>(s, r)); // a map element.
};
/* To remove an element from the vector, first we have to scan it,
* find what we need to remove, then erase() it.
*/
void remove(string s) { mcatalog.erase(s); }; // remove only from the map.
// Call All the set() registered in the Map catalog.
// Using the constant begin/end, no modification allowed.
void set_mall(void)
{
for (auto i = mcatalog.cbegin(); i != mcatalog.cend(); i++) {
i->second.set();
}
};
// Call all the clear() registered in the Map catalog, in reverse order.
void clear_mall(void)
{
for (auto i = mcatalog.rbegin(); i != mcatalog.rend(); i++) {
i->second.clear();
}
};
// Call all the set() registered in the Vector catalog.
void set_vall(void)
{
for (auto i = vcatalog.begin(); i != vcatalog.end(); i++) {
i->set();
}
};
// Call all the clear() registered in the Vector catalog.
void clear_vall(void)
{
for (auto i = vcatalog.begin(); i != vcatalog.end(); i++) {
i->clear();
}
};
};
// allocate the two variables
bool FirstClass::sstatus {false};
bool SecondClass::sstatus {false};
int main () {
Manager manager; // Instantiate the object
// add the FirstClass
manager.add("1st_elem", FirstClass::set, FirstClass::clear);
// add the SecondClass
manager.add("2nd_elem", SecondClass::set, SecondClass::clear);
// Print both statuses
cout << "1st: " << FirstClass::sstatus << endl;
cout << "2nd: " << SecondClass::sstatus << endl;
// Set all using the Map catalog
manager.set_mall();
// Print both statuses
cout << "After the set_Map_all()" << endl;
cout << "1st: " << FirstClass::sstatus << endl;
cout << "2nd: " << SecondClass::sstatus << endl;
// Clear all using the Map catalog
manager.clear_mall();
cout << "After the clear_Map_all()" << endl;
cout << "1st: " << FirstClass::sstatus << endl;
cout << "2nd: " << SecondClass::sstatus << endl;
// Set all using the Vector catalog
manager.set_vall();
cout << "After the set_Vector_all()" << endl;
cout << "1st: " << FirstClass::sstatus << endl;
cout << "2nd: " << SecondClass::sstatus << endl;
// Clear all using the Vector catalog
manager.clear_vall();
cout << "After the clear_Vector_all()" << endl;
cout << "1st: " << FirstClass::sstatus << endl;
cout << "2nd: " << SecondClass::sstatus << endl;
// Remove the FirstClass from the Map catalog
manager.remove("1st_elem");
// Set all using the Map catalog
manager.set_mall();
// and print it
cout << "After the set_Map_all() with 1st removed" << endl;
cout << "1st: " << FirstClass::sstatus << endl;
cout << "2nd: " << SecondClass::sstatus << endl;
return 0;
}
| true |
1e617391ad8de9d2204c5cf907c0480009789f42 | C++ | nacl1415/Arduino | /watchDogTest.ino | UTF-8 | 1,664 | 2.578125 | 3 | [] | no_license |
#include <JeeLib.h>
#include "DHT.h"
#include <SoftwareSerial.h>
#define DHTPIN 2//D2 pin is DHT11's singal
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
SoftwareSerial mLoraPort(6, 7); // RX, TX
int mM0 = 4;
int mM1 = 5;
ISR(WDT_vect)
{
Sleepy::watchdogEvent();
}
int mCount = 0;
int mLedPin = 9;
String mSendStr = "";
void setup() {
Serial.begin(9600);
pinMode(mLedPin, OUTPUT);
//dht11
dht.begin();
//lora
pinMode(mM0, OUTPUT);
pinMode(mM1, OUTPUT);
digitalWrite(mM0, LOW);
digitalWrite(mM1, LOW);
mLoraPort.begin(9600);
mLoraPort.println("Hello, world");
}
void loop() {
//Serial.println("LED:" + String(mCount));
//lora wakeup
digitalWrite(mM0, LOW);
digitalWrite(mM1, LOW);
delay(1000);
sendCoor();
digitalWrite(mLedPin, HIGH);
delay(10*1000);
digitalWrite(mLedPin, LOW);
delay(1000);
//lora sleep
digitalWrite(mM0, HIGH);
digitalWrite(mM1, HIGH);
delay(100);
Sleepy::loseSomeTime(60*1000);//60 * 60 = 3600 = 1小時
mCount++;
}
void sendCoor()
{
mSendStr = "";
int h = dht.readHumidity();
int t = dht.readTemperature();
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
//Serial.println("Failed to read from DHT sensor!");
delay(10000);
return;
}
// float hif = dht.computeHeatIndex(f, h);
// float hic = dht.computeHeatIndex(t, h, false);
mSendStr = "H" + String(h) + "i" + String(t) + "C" + String(mCount);
mLoraPort.print(mSendStr);
// Serial.print("H");
// Serial.print(h);
// Serial.print("i");
// Serial.print(t);
// Serial.print("C");
}
| true |
5355839c7896890800717df352125a16a1cdf0be | C++ | Tanzimul-Hasib/All-C-Programs-Algorithms | /power.cpp | UTF-8 | 318 | 3.15625 | 3 | [] | no_license | #include<stdio.h>
int main ()
{
int power=1, i , base, expo;
printf("Enter the number base: ");
scanf("%d", &base);
printf("Enter the power number : ");
scanf("%d", &expo);
for(i=1; i<=expo; i++)
{
power=power*base;
}
printf("%d\n", power);
return 0;
}
| true |
792170ba28e401b0f1429cdb7792735cb180bbd3 | C++ | velocic/opengl-tutorial-solutions | /17-ambient-lighting/src/renderwindow.cpp | UTF-8 | 1,280 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <renderwindow.h>
RenderWindow::RenderWindow(unsigned int screenWidth, unsigned int screenHeight)
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_SetRelativeMouseMode(SDL_TRUE);
window = SDL_CreateWindow(
"ogldev.atspace.co.uk Tutorial 17 -- Ambient Lighting",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
screenWidth,
screenHeight,
SDL_WINDOW_OPENGL
);
//Create the OpenGL context before trying to initialize OpenGL API functions
renderContext = SDL_GL_CreateContext(window);
//Initialize OpenGL API functions, exit if we couldn't load the core functions
if (gl3wInit()) {
std::cout << "gl3w failed to initialize OpenGL" << std::endl;
}
}
RenderWindow::~RenderWindow()
{
freeResources();
}
void RenderWindow::freeResources()
{
if (window != nullptr) {
SDL_GL_DeleteContext(renderContext);
SDL_DestroyWindow(window);
SDL_Quit();
window = nullptr;
}
}
SDL_Window* RenderWindow::getRenderWindowHandle()
{
return window;
}
| true |
8ba72443f2e08ad10370273f01bffccfae081fe3 | C++ | jfellus/pg_learning | /src/Normalize.h | UTF-8 | 618 | 2.59375 | 3 | [] | no_license | /*
* Normalize.h
*
* Created on: 15 avr. 2015
* Author: jfellus
*/
#ifndef NORMALIZE_H_
#define NORMALIZE_H_
#include <pg.h>
#include <matrix.h>
class Normalize {
public:
Matrix* out;
OUTPUT(Matrix, *out);
public:
Normalize() {out = 0;}
void init() {}
void process(Matrix& m) {
for(uint i=m.h;i--;) normalize(m.get_row(i), m.w);
out = &m;
}
private:
float n2(float *v, uint dim) {
float s = 0;
for(uint i=dim; i--;) s+=v[i]*v[i];
return sqrt(s);
}
void normalize(float* v, uint dim) {
float l2 = n2(v,dim);
for(uint i=dim; i--;) v[i]/=l2;
}
};
#endif /* NORMALIZE_H_ */
| true |
ea72675bedd4b647ceafbcfb09e3aedf1065f61f | C++ | sorcery-p5/Asteraiser | /ls/Collide/CollideTypes.h | SHIFT_JIS | 4,441 | 2.859375 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
///////////////////////////////////////////////////////////////////////////////
//
// ֘A^`
//
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// 背C[
//-----------------------------------------------------------------------------
enum COLLIDE_LAYER
{
COLLIDE_LAYER_PLAYER, // @
COLLIDE_LAYER_BLADE, // u[hEXsA
COLLIDE_LAYER_RULER, // [[
COLLIDE_LAYER_ENEMY, // G{
COLLIDE_LAYER_ITEM, // ACe
COLLIDE_LAYER_GROUND, // n`
COLLIDE_LAYER_NUM,
COLLIDE_LAYER_DEFAULT = COLLIDE_LAYER_PLAYER,
};
//-----------------------------------------------------------------------------
// tB^[
//-----------------------------------------------------------------------------
enum COLLIDE_FILTER
{
COLLIDE_FILTER_PLAYER = (1<<COLLIDE_LAYER_ENEMY) | (1<<COLLIDE_LAYER_ITEM) | (1<<COLLIDE_LAYER_RULER) | (1<<COLLIDE_LAYER_GROUND),
COLLIDE_FILTER_BLADE = (1<<COLLIDE_LAYER_ENEMY) | (1<<COLLIDE_LAYER_ITEM) | (1<<COLLIDE_LAYER_GROUND),
COLLIDE_FILTER_SPEAR = (1<<COLLIDE_LAYER_ENEMY) | (1<<COLLIDE_LAYER_GROUND),
COLLIDE_FILTER_SPLASH = (1<<COLLIDE_LAYER_ENEMY) | (1<<COLLIDE_LAYER_ITEM),
COLLIDE_FILTER_ENEMY = (1<<COLLIDE_LAYER_GROUND) | (1<<COLLIDE_LAYER_RULER),
COLLIDE_FILTER_ATTACK = (1<<COLLIDE_LAYER_PLAYER) | (1<<COLLIDE_LAYER_BLADE) | (1<<COLLIDE_LAYER_RULER) | (1<<COLLIDE_LAYER_GROUND),
COLLIDE_FILTER_ALL = 0xFFFFFFFFU, // S
};
//-----------------------------------------------------------------------------
// `
//-----------------------------------------------------------------------------
enum COLLIDE_SHAPE_TYPE
{
COLLIDE_SHAPE_POINT,
COLLIDE_SHAPE_LINE,
COLLIDE_SHAPE_RECT,
COLLIDE_SHAPE_FRAME,
COLLIDE_SHAPE_TYPE_NUM,
};
//------------------------------------------------------------------------------
// 蔻̌vZ
//------------------------------------------------------------------------------
enum COLLIDE_CALC_TYPE
{
COLLIDE_CALC_POS = (1 << 0), // ʒu̎Zos
COLLIDE_CALC_NORMAL = (1 << 1), // @̎Zos
COLLIDE_CALC_SOLVE = (1 << 2), // ߂荞݉si_̂ݗLj
COLLIDE_CALC_POS_NORMAL = COLLIDE_CALC_POS | COLLIDE_CALC_NORMAL, // ʒu{@
COLLIDE_CALC_ALL = 0xFFFFFFFFU, // S
};
//------------------------------------------------------------------------------
// 蔻̃I[i[
//------------------------------------------------------------------------------
enum COLLIDE_OWNER_TYPE
{
COLLIDE_OWNER_NULL,
COLLIDE_OWNER_PLAYER,
COLLIDE_OWNER_BLADE,
COLLIDE_OWNER_SPEAR,
COLLIDE_OWNER_RULER,
COLLIDE_OWNER_ENEMY,
COLLIDE_OWNER_ATTACK,
COLLIDE_OWNER_ITEM,
COLLIDE_OWNER_GROUND,
COLLIDE_OWNER_NUM,
};
//------------------------------------------------------------------------------
// 蔻̃I[i[f[^
//------------------------------------------------------------------------------
struct COLLIDE_OWNER
{
COLLIDE_OWNER( void )
{
Type = COLLIDE_OWNER_NULL;
pData = NULL;
}
COLLIDE_OWNER_TYPE Type;
void* pData;
};
//------------------------------------------------------------------------------
// 茋
//------------------------------------------------------------------------------
struct COLLIDE_RESULT
{
COLLIDE_LAYER Layer;
const COLLIDE_OWNER* pOwner;
Point HitPos;
Point Normal;
float Length;
int BoneID;
COLLIDE_RESULT( void )
{
Layer = COLLIDE_LAYER_DEFAULT;
pOwner = NULL;
Length = FLT_MAX;
BoneID = -1;
}
Matrix3 GetHitMatrix( void ) const { return Matrix3::TransRotZ( HitPos, Normal.GetAngle() ); }
Matrix3 GetHitMatrix( float AddAngle ) const { return Matrix3::TransRotZ( HitPos, Normal.GetAngle() + AddAngle ); }
bool operator < ( const COLLIDE_RESULT& r ) const { return Length < r.Length; }
};
typedef std::set<COLLIDE_RESULT> COLLIDE_RESULT_LIST;
//------------------------------------------------------------------------------
// LXǧ
//------------------------------------------------------------------------------
struct COLLIDE_CAST_RESULT
{
COLLIDE_RESULT_LIST ResultList;
Point SolvePos;
}; | true |
4e34217933b48bbc97293c6718cf813b96329680 | C++ | Mashiatmm/Offlines | /2-2/Data Structure and Algorithms Part 2/Offline 9/offline9.cpp | UTF-8 | 5,004 | 2.96875 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<sstream>
#include<queue>
#include<chrono>
#include<ctime>
#define INF 99999
using namespace std;
int startvertex;
int n;
int exact(int** tsp,int path[],int s,int f){
if(s==f){
int dis = tsp[startvertex][path[0]];
for(int i=0;i<n-1;i++){
//cout<<path[i]<<" ";
if(i == n-2){
dis += tsp[path[i]][startvertex];
continue;
}
dis+=tsp[path[i]][path[i+1]];
}
//cout<<endl;
return dis;
}
int min = INF;
for(int i = s;i <= f; i++){
int temp = path[i-1];
path[i-1] = path[s-1];
path[s-1] = temp;
int dis = exact(tsp,path,s+1,f);
if(dis<min) min = dis;
temp = path[i-1];
path[i-1] = path[s-1];
path[s-1] = temp;
}
return min;
}
class Node{
public:
int** ReducedMatrix;
int cost;
int vertex;
int level;
};
Node* NewNode(int** ParentMatrix,int level,int i,int j){
Node* node = new Node;
node->level = level;
node->vertex = j;
node->ReducedMatrix = new int*[n];
for(int r = 0; r<n; r++){
node->ReducedMatrix[r] = new int[n];
for(int col = 0; col<n; col++){
node->ReducedMatrix[r][col] = ParentMatrix[r][col];
}
}
if(level != 0){
for(int k = 0;k<n;k++){
node->ReducedMatrix[i][k] = INF;
node->ReducedMatrix[k][j] = INF;
}
node->ReducedMatrix[j][startvertex] = INF;
}
return node;
}
int RowReduction(int** ReducedMatrix){
int row[n];
int sum = 0;
for(int r = 0; r<n; r++){
row[r] = INF;
for(int col = 0; col<n; col++){
if(row[r]>ReducedMatrix[r][col]){
row[r] = ReducedMatrix[r][col];
}
}
}
for(int r = 0; r<n; r++){
for(int col = 0; col<n; col++){
if(ReducedMatrix[r][col]!= INF && row[r]!=INF){
ReducedMatrix[r][col]-=row[r];
}
}
if(row[r] != INF){
sum += row[r];
}
}
return sum;
}
int ColumnReduction(int** ReducedMatrix){
int column[n];
int sum = 0;
for(int col = 0; col<n; col++){
column[col] = INF;
for(int r = 0; r<n; r++){
if(column[col]>ReducedMatrix[r][col]){
column[col] = ReducedMatrix[r][col];
}
}
}
for(int col = 0; col<n; col++){
for(int r = 0; r<n; r++){
if(ReducedMatrix[r][col]!= INF && column[col]!=INF){
ReducedMatrix[r][col]-=column[col];
}
}
if(column[col] != INF){
sum += column[col];
}
}
return sum;
}
int calculateCost(int** ReducedMatrix){
return RowReduction(ReducedMatrix) + ColumnReduction(ReducedMatrix) ;
}
struct comp {
bool operator()(const Node* lhs, const Node* rhs) const
{
return lhs->cost > rhs->cost;
}
};
int BranchAndBound(int** tsp){
priority_queue<Node*, std::vector<Node*>, comp> pq;
Node* root = NewNode(tsp,0,-1,0);
root->cost = calculateCost(root->ReducedMatrix);
pq.push(root);
while(!pq.empty()){
Node* parent = pq.top();
pq.pop();
int i = parent->vertex;
if(parent->level == n-1){
return parent->cost;
}
for(int k = 0;k<n;k++){
if(parent->ReducedMatrix[i][k] != INF){
Node *child = NewNode(parent->ReducedMatrix,parent->level+1,i,k);
child->cost = parent->cost + parent->ReducedMatrix[i][k] + calculateCost(child->ReducedMatrix);
pq.push(child);
}
}
delete parent;
}
}
int main(){
startvertex = 0;
int **tsp = new int*[n];
int **costMatrix = new int*[n];
ifstream in;
in.open("input.txt");
in>>n;
for(int k = 0 ;k<n;k++){
tsp[k] = new int[n];
costMatrix[k] = new int[n];
for(int l = 0 ;l<n;l++){
in>>tsp[k][l];
costMatrix[k][l] = tsp[k][l];
if(k == l){
costMatrix[k][l] = INF;
tsp[k][l] = 0;
}
//cout<<tsp[k][l]<<" ";
}
}
int j = 0;
int path[n-1];
for(int i = 0; i<n;i++){
if(i == startvertex){
continue;
}
path[j] = i;
j++;
}
auto start=chrono::steady_clock::now();
int exactdis = exact(tsp,path,1,n-1);
auto finish=chrono::steady_clock::now();
int exact_time=chrono::duration_cast<chrono::microseconds>(finish- start).count()/10.0;
cout<<exactdis<<": "<<exact_time<<endl;
start=chrono::steady_clock::now();
int bbdis = BranchAndBound(costMatrix);
finish=chrono::steady_clock::now();
int bb_time=chrono::duration_cast<chrono::microseconds>(finish- start).count()/10.0;
cout<<bbdis<<": "<<bb_time<<endl;
in.close();
}
| true |
ef7895ebe954b85520cc78929502d883aa3f9e54 | C++ | pierug/programs | /cppCourse/pointers/main.cpp | UTF-8 | 240 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <memory>
using namespace std;
int main(int argc, char *argv[])
{
unique_ptr<int> uPtr1(new int(13));
shared_ptr<int> uPtr2(new int(14));
//uPtr1=uPtr2;
cout << *uPtr1 << endl;
return 0;
}
| true |
3e63b88eefb5e6df8c061d6fd8a03a291fbc6a5c | C++ | ruifshi/LeetCode | /LeetCode/KokoEatingBananas.cpp | UTF-8 | 859 | 3.59375 | 4 | [] | no_license | #include "stdafx.h"
#include "KokoEatingBananas.h"
#include <algorithm>
bool canEatAll(vector<int> &piles, int K, int H) {
int countHour = 0; // Hours take to eat all bananas at speed K.
for (int pile : piles) {
countHour += pile / K;
if (pile % K != 0)
countHour++;
}
return countHour <= H;
}
int Solution::minEatingSpeed(vector<int>& piles, int H) {
int left = 1; //minimum speed Koko can eat
int right = 1; // maximum speed Koko can eat which is max value in piles
for (int i = 0; i < piles.size(); i++) {
right = max(right, piles[i]);
}
// do binary search. If choosen K results in less hours than given, then it can be lowered
while (left <= right) {
int K = left + ((right - left) / 2);
if (canEatAll(piles, K, H)) {
right = K - 1;
}
else {
left = K + 1;
}
}
return left;
} | true |
67af122b3dc8c13ef8561fc81cdc5c06f9bab2df | C++ | BIT-zhaoyang/uva | /uva10048-AudioPhobia/src/uva10048-AudioPhobia.cpp | UTF-8 | 2,253 | 3.109375 | 3 | [] | no_license | //============================================================================
// Name : uva10048-AudioPhobia.cpp
//============================================================================
#include <iostream>
#include <vector>
#include <stack>
#include <cassert>
using namespace std;
struct Edge {
Edge(int dst, int weight) :
_dst(dst), _weight(weight) {}
int dst() const {
return _dst;
}
int weight() const {
return _weight;
}
private:
int _dst;
int _weight;
};
struct AdjList {
AdjList(int n) :
_size(n),
_edges(n, vector<Edge>()) {}
const vector<Edge>& getEdges(int node) const {
assert(node >= 0 && node < _size);
return _edges[node];
}
void addEdge(int src, int dst, int weight, bool isDirected = false) {
assert(src >= 0 && src < _size);
assert(dst >= 0 && dst < _size);
_edges[src].push_back(Edge(dst, weight));
if (!isDirected) {
_edges[dst].push_back(Edge(src, weight));
}
}
int getSize() const {
return _size;
}
private:
int _size;
vector<vector<Edge> > _edges;
};
int solve(const AdjList& g, int src, int dst) {
vector<int> visited(g.getSize(), -1);
stack<int> s;
s.push(src);
visited[src] = 0;
while (!s.empty()) {
int curr = s.top();
s.pop();
const vector<Edge>& edges = g.getEdges(curr);
for (vector<Edge>::const_iterator eIt = edges.begin(), eItEnd = edges.end();
eIt != eItEnd;
++eIt)
{
int next = eIt->dst();
if (visited[next] < 0 ||
max(visited[curr], eIt->weight()) < visited[next]) {
visited[next] = max(visited[curr], eIt->weight());
s.push(next);
}
}
}
return visited[dst];
}
int main() {
int crossings, streets, queries;
int mCase = 0;
while (cin >> crossings >> streets >> queries) {
if (!crossings && !streets && !queries) {
break;
}
AdjList graph(crossings);
for (int i = 0; i < streets; ++i) {
int c1, c2, d;
cin >> c1 >> c2 >> d;
--c1; --c2;
graph.addEdge(c1, c2, d);
}
if (mCase) cout << endl;
cout << "Case #" << ++mCase << endl;
for (int i = 0; i < queries; ++i) {
int c1, c2;
cin >> c1 >> c2;
--c1; --c2;
int s = solve(graph, c1, c2);
if (s >= 0) {
cout << s << endl;
}
else {
cout << "no path" << endl;
}
}
}
return 0;
}
| true |
e26ee89a1b188002bf72f6f71873c259413b9b19 | C++ | PLUkraine/Battle-City-Qt | /entities/bullet.h | UTF-8 | 402 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef BULLET_H
#define BULLET_H
#include"entities/entity.h"
#include"entities/tank.h"
class Bullet : public Entity
{
Q_OBJECT
public:
Bullet(Body*body, Renderer*renderer, Physics* physics, Entity* sender, int damage);
virtual ~Bullet();
void update();
Entity *sender() const;
int damage() const;
protected:
Entity* m_sender;
int m_damage;
};
#endif // BULLET_H
| true |
155bce1a5acb0b845458b53652d489bde379a42b | C++ | seahorn/seahorn | /test/devirt/devirt_cha_04.false.cpp | UTF-8 | 1,076 | 2.703125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /* Diamond inheritance */
// RUN: %sea pf -O0 --devirt-functions-with-cha --horn-use-mbqi "%s" 2>&1 | OutputCheck %s
// RUN: %sea pf -O3 --devirt-functions-with-cha --horn-use-mbqi "%s" 2>&1 | OutputCheck %s
// CHECK: ^sat$
#include "seahorn/seahorn.h"
extern void foo(int);
extern int nd_int();
class A {
public:
A() {}
virtual ~A(){}
virtual int f() { return 5;}
};
class B: virtual public A {
public:
B(): A() {}
virtual ~B(){}
virtual int f() { return 10;}
};
class C: virtual public A {
public:
C(): A() {}
virtual ~C(){}
virtual int f() { return 15;}
};
class D: public B, public C {
public:
D(): B(), C() {}
virtual int f() { return 20; }
};
int main(int argc, char* argv[]) {
A* p = 0;
if (nd_int()) {
p = new B();
} else if (nd_int()) {
p = new C();
} else {
p = new D();
}
int r1 = p->f();
sassert(r1 >= 5 && r1 <= 20);
delete p;
C* q = 0;
if (nd_int()) {
q = new C();
} else {
q = new D();
}
int r2 = q->f();
delete q;
sassert(r2 >= 16 && r2 <= 20);
return 0;
}
| true |
d248aa04c86c34235a0de1fef76f692ca830c616 | C++ | MuhammadAlaminMir/CPP | /9_Strings/4.Compare.cpp | UTF-8 | 510 | 4 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
// Compare two strings
string a, b;
a = "abc";
b = "def";
// if our output greater or less than zero its means a and b are not equal
// if we get 0 then its means a and b are equal.
cout << b.compare(a) << endl;
b = "abc";
cout << b.compare(a) << endl;
// we can create a condition statement hare
if (b.compare(a) == 0)
{
cout << "a and b are equal" << endl;
}
return 0;
} | true |
9b51a4301b1f8970e209587d767f7c85355a555d | C++ | include-minimaltools/windows-c | /INCLUDE/Registro.H | UTF-8 | 64,580 | 2.5625 | 3 | [] | no_license | /*---- Registro Academico ---- created by Gabriel Ortiz ---- version A3.3g ---- tested by Luis Pineda and Engel Reyes*/
/*--------1----------------------- Library --------------------------------*/
#include "covpagbv.h"
/*--------M----------------------- Constant -------------------------------*/
#define cursor 16/* | S Y M B O L S */
#define cursor2 26/* | */
#define MaxAccounts 5/* | L I M I T S */
#define MaxStds 10/* | */
/*--------1----------------------- Structs --------------------------------*/
typedef struct Account
{
char user[MaxStrLn], password[MaxStrLn];
} account;
typedef struct Class
{
char *nameClass;
int nota, _isActive;
} class;
typedef struct Student
{
int ID_student;
char name[MaxStrLn], lastname[MaxStrLn], carnet[MaxStrLn];
class class[9];
} student;
typedef struct Classroom
{
int ID;
student student[MaxStds];
} classroom;
struct Configuration
{
int semester,ID_database,searchOption;
} configuration;
/*-------------------------------- Prototyping ----------------------------*/
void MenuDesigner(void);/* | */
void LoginAndRegisterDesigner(void);/* | */
void RegisterDesigner(void);/* |- Designers (single execution) */
void SearchDesigner(void);/* | */
void ShowDatabaseDesigner(void);/* | */
void Menu(void);/* | */
int More(void);/* | */
int Login(void);/* | */
void LoginAndRegister(void);/* | */
void Add(void);/* | */
void Register(void);/* |- Buttons (cicles funtions) */
void Search(void);/* | */
void ShowDatabase(void);/* | */
void editStudent(int ID);/* | */
void about(void);/* | */
void clearscreen(void);/* | */
void addFramework(void);/* | */
void clearwindow(char window);/* | */
void loadStudentData(student student);/*|- Funtions */
void save(void);/* | */
void load(void);/* | */
void saveConfiguration(void);/* | */
void loadConfiguration(void);/* | */
/*-------------------------------- Global var -----------------------------*/
account user;
classroom database[4];
char *lessons[2][5]={{"Introduccion a la computacion","Ingles","Filosofia","Geometria Analitica"," "},
{"Lenguaje de Programacion","Conceptos de Lenguaje","Matematicas I","Ingles II","Redaccion Tecnica"}};
char *searchMethod[3]={"Nombre","Apellido","Carnet"};
char *cleaner[] = {" "," "," "," "," "," "," "," "," "," "," "};
char key;
char *groupInformation[]= {"Elija con cual de los ","grupos desea trabajar."," ","Tome en cuenta ","que cada grupo es ","independiente uno del ","otro. "};
char *semesterInformation[]= {"Cambie el semestre en ","el cual se encuentre. "," ","Dependiendo de ","cual se elija se veran","las clases de ese ","semestre. "};
char *aboutInformation[]= {"Creditos e informacion","de los desarrolladores","del programa Registro ","Academico, ","compilado en Turbo C ","y realizado para el SO","de MS - DOS. "};
char *closeSessionInformation[]={"Cierra la cuenta en la","que se encuentra, tome"," ","Se pediran las ","credenciales otra vez."," "," "};
char *registerInformation[]= {"Registre una cuenta ","nueva, se le pedira un","usuario y password el ","cual debe guardar","Las mayusculas se toma","en cuenta a la hora de","guardar los datos." };
char *exitInformation[]= {"Se terminara ","la ejecucion del ","programa. "," "," "," "," "};
char *searchMethodInformation[]={"Elija el parametro con","el que desea buscar al","estudiante. "};
char *getStringInformation[]= {"Ingrese el ","del estudiante que ","desea buscar. "};
char *searchInformation[]= {"Presione enter para ","buscar al estudiante "," "};
char *nameInformation[] = {"Debe ingresar el ","nombre del estudiante ","que desea agregar. "," ","(Maximo 10 caracteres)"};
char *lastNameInformation[] = {"Digite el apellido ","del estudiante que ","desea agregar. "," ","(Maximo 10 caracteres)"};
char *carnetInformation[]= {"Digite un numero de ","carnet, recuerde que ","los primeros 4 digitos","corresponden a la","fecha anual. "};
char *classInformation[]= {"Inscriba las clases ","que el alumno llevara ","Para desinscribir una ","clase, debe dejar","vacia la nota. "};
char *cancelInformation[]= {"No se guardara ningun ","cambio realizado en el","estudiante "," "," "};
char *deleteInformation[]= {"El alumno se eliminara","del registro academico","de la UNI. ","Los datos se ","perderan. "};
char *updateInformation[]= {"Se guardaran los ","cambios realizados en ","el alumno, los datos ","anteriores se ","perderan "};
char *addInformation[]= {"Se agregara este ","alumno al registro ","academico de la UNI "," ","Revise la informacion "};
char *enableClass[] = {"Esta clase no necesita","de una clase previa "," ","El alumno puede ","llevar esta clase. "};
char *disabledClass0[] = {"Esta clase requiere ","que el estudiante haya","recibido la clase de ","Introduccion a la","Computacion. "};
char *disabledClass1[] = {"Esta clase requiere ","que el estudiante haya","aprobado la clase de ","Introduccion a la","Computacion. "};
char *disabledClass2[] = {"Esta clase requiere ","que el estudiante haya","aprobado la clase de ","Ingles I "," "};
int loginCount=0, accountCount=0, screen, option, suboption, i,j;
/*-------------------------------- Initializer -----------------------------*/
void runAcademicRegister()
{
InitializeComponent();
load();
loadConfiguration();
MenuDesigner();
addFramework();
loginCount=0;
if(Login())
Menu();
}
/*--------------------------------- Designers ------------------------------*/
void RegisterDesigner(void)
{
MessageBox();
textbackground(BLUE);
textcolor(WHITE);
gotoxy(31,7);
cprintf(" Registrar cuenta ");
Register();
}
void LoginAndRegisterDesigner(void)
{
option = 0;
MessageBox();
textbackground(BLUE);
textcolor(WHITE);
gotoxy(30,7); cprintf(" Registro Academico ");
LoginAndRegister();
addFramework();
clearwindow('a');
}
void MenuDesigner(void)
{
textbackground(BLUE);
clrscr();
textcolor(WHITE);
gotoxy(2,25);
cprintf("Esc - Salir Enter - Ir %c%c - Desplazarse",24,25);
clearscreen();
for(i=1;i<=80;i++)
{
textbackground(CYAN);
gotoxy(i,1);
cprintf("%c",0);
}
textcolor(BLACK);
gotoxy(26,1);
cprintf("REGISTRO ACADEMICO DE LA UNI");
}
void ShowDatabaseDesigner(void)
{
char *titles[2][7]={
{"Nombre & Apellido","Carnet", "IICC", "Ingles", "Filosofia", "Geometria", ""},
{"Nombre & Apellido","Carnet", "LLPP", "CCLL", "Mat.I", "InglesII", "Redaccion"}};
int k=0;
option=0;
textcolor(BLACK);
if(configuration.semester==0)
for(j=3;j<=24;j++)
for(i=1;i<=80;i++)
{
gotoxy(i,j);
if( (j==3||j==5||j==24) && i>=1 && i<=80)
cprintf("%c",lineaH);
else if( (i==1||i==23||i==34||i==45||i==56||i==68||i==80) && j<=24 && j>=3)
cprintf("%c",lineaV);
gotoxy(i,j);
if((j==3||j==5||j==24) && (i==1||i==23||i==34||i==45||i==56||i==68||i==80))
cprintf("%c", j==3? i==1?esquinaNW: i==80?esquinaNE: cruceWES : j==5? i==1? cruceNSW: i==80?cruceNSE: cruceNSWE : i==1? esquinaSW: i==80?esquinaSE: cruceNWE);
if( (j==4) && (i==4||i==26||i==38||i==48||i==58||i==70) )
{
cprintf("%s",titles[configuration.semester][k]);
k++;
}
}
else
for(j=3;j<=24;j++)
for(i=1;i<=80;i++)
{
gotoxy(i,j);
if( (j==3||j==5||j==24) && i>=1 && i<=80)
cprintf("%c",lineaH);
else if( (i==1||i==23||i==34||i==43||i==52||i==61||i==70||i==80) && j<=24 && j>=3)
cprintf("%c",lineaV);
gotoxy(i,j);
if((j==3||j==5||j==24) && (i==1||i==23||i==34||i==43||i==52||i==61||i==70||i==80))
cprintf("%c", j==3? i==1?esquinaNW: i==80?esquinaNE: cruceWES : j==5? i==1? cruceNSW: i==80?cruceNSE: cruceNSWE : i==1? esquinaSW: i==80?esquinaSE: cruceNWE);
if( (j==4) && (i==4||i==26||i==37||i==46||i==54||i==62||i==71) )
{
cprintf("%s",titles[configuration.semester][k]);
k++;
}
}
}
void SearchDesigner(void)
{
char * titles[3][11]={{" "," ","Intr","Geo ","Filo","In- ","Leng","Cpto","Mat.","Re ","In- "},
{"Nombre & Apellido","Carnet","a la","me ","so ","gles" ,"de ","de ","I ","dac ","gles"},
{"\0","\0","comp","tria","fia ","\0" ,"prog","leng","\0" ,"cion","In- "}};
int k=0;
textcolor(BLACK);
for(j=3;j<=24;j++)
for(i=1;i<=80;i++)
{
gotoxy(i,j);
if( (j==12||j==16||j==24) && i>=1 && i<=80)
cprintf("%c",lineaH);
else if( (i==1||i==23||i==34||i==39||i==44||i==49||i==54||i==55||i==60||i==65||i==70||i==75||i==80) && j<=24 && j>=12)
cprintf("%c",lineaV);
gotoxy(i,j);
if( (j==3||j==11) && i>=1 && i<=80 )
cprintf("%c",lineaH);
else if( (i==1 || i==57 ||i==80) && j<=11 && j>=3 )
cprintf("%c",lineaV);
gotoxy(i,j);
if( (j==3||j==11) && (i==1 || i==57 || i==80))
if(j==3)
cprintf("%c",i==1?esquinaNW: i==57?cruceWES:esquinaNE);
else if(j==11)
cprintf("%c",i==1?esquinaSW: i==57?cruceNWE:esquinaSE);
gotoxy(i,j);
if((j==12||j==16||j==24) && (i==1||i==23||i==34||i==39||i==44||i==49||i==54||i==55||i==60||i==65||i==70||i==75||i==80))
cprintf("%c", j==12? i==1?esquinaNW: i==80?esquinaNE: cruceWES : j==16? i==1? cruceNSW: i==80?cruceNSE: cruceNSWE : i==1? esquinaSW: i==80?esquinaSE: cruceNWE);
if((j>=13&&j<=15) && (i==4||i==26||i==35||i==40||i==45||i==50||i==56||i==61||i==66||i==71||i==76))
{
gotoxy(i,j);
cprintf("%s",titles[j-13][k]);
k = k==10 ? 0 : k+1;
}
}
gotoxy(35,5);
cprintf("[ %s ]",searchMethod[configuration.searchOption]);
gotoxy(34,7);
cprintf("[ ]");
Search();
}
/*--------------------------------- Buttons -------------------------------*/
void ShowDatabase(void)
{
int PositionX[2][7] = {
{2,24,38,49,60,72,0},
{2,24,37,46,55,64,73}};
int ID;
for(i=0;i<database[configuration.ID_database].ID;i++)
for(j=0;configuration.semester==0?j<6:j<7;j++)
{
gotoxy( PositionX[configuration.semester][j] , i+6);
if(option==i)
textcolor(BLUE);
else
textcolor(BLACK);
switch(j)
{
case 0:
cprintf("%s %s",database[configuration.ID_database].student[i].name, database[configuration.ID_database].student[i].lastname);
break;
case 1:
cprintf("%s",database[configuration.ID_database].student[i].carnet);
break;
default:
if(database[configuration.ID_database].student[i].class[ (configuration.semester==0?j:j+4) -2]._isActive == true)
{
if(database[configuration.ID_database].student[i].class[ (configuration.semester==0?j:j+4) -2].nota>=60)
textcolor(GREEN);
else
textcolor(RED);
cprintf("%d",database[configuration.ID_database].student[i].class[ (configuration.semester==0?j:j+4) -2].nota);
}
else
cprintf(" n/a ");
break;
}
}
RemoveCursor(3,4);
do
key=getch();
while(key!=up && key!=down && key!=enter && key!=esc && key!=tab);
if(key==up)
option = option==0 ? 0 : option - 1;
else if(key==down)
option = option==database[configuration.ID_database].ID-1 ? database[configuration.ID_database].ID-1 : option + 1;
else if(key==enter)
{
ID = option;
option = 0;
editStudent(ID);
return;
}
else if(key==esc || key==tab)
{
for(j=0;configuration.semester==0?j<6:j<7;j++)
{
gotoxy( PositionX[configuration.semester][j] , option+6);
textcolor(BLACK);
switch(j)
{
case 0:
cprintf("%s %s",database[configuration.ID_database].student[option].name, database[configuration.ID_database].student[option].lastname);
break;
case 1:
cprintf("%s",database[configuration.ID_database].student[option].carnet);
break;
default:
if(database[configuration.ID_database].student[option].class[ (configuration.semester==0?j:j+4) -2]._isActive == true)
{
if(database[configuration.ID_database].student[option].class[ (configuration.semester==0?j:j+4) -2].nota>=60)
textcolor(GREEN);
else
textcolor(RED);
cprintf("%d",database[configuration.ID_database].student[option].class[ (configuration.semester==0?j:j+4) -2].nota);
}
else
cprintf(" n/a ");
break;
}
}
return;
}
ShowDatabase();
}
void Search(void)
{
char *commands[] = {"Metodo de busqueda","Ingrese el","Buscar"};
int PositionX[11] = {2,24,35,40,45,50,56,61,66,71,76};
int positionY=0;
student student;
student.carnet[0]='\0';
student.name[0]='\0';
student.lastname[0]='\0';
textcolor(BLACK);
gotoxy(63,4);
cprintf("INFORMACION");
do
{
for(i=0;i<3;i++)
{
if(i==option)
textcolor(BLUE);
else
textcolor(BLACK);
gotoxy(4,(i*2)+5);
cprintf("%c %s %s ", i==option?cursor:0 , commands[i], i==1?searchMethod[configuration.searchOption]:" ");
textcolor(BLACK);
gotoxy(58,6+i);
cprintf("%s", option==0?searchMethodInformation[i]: option==1?getStringInformation[i]: searchInformation[i]);
}
RemoveCursor(3,4);
do
key = getch();
while(key!=enter&&key!=up&&key!=down&&key!=tab&&key!=esc);
if(key==up)
option = option==0 ? 2 : option - 1;
else if(key==down)
option = option==2 ? 0 : option + 1;
else if(key==tab || key == esc)
{
gotoxy(4,(option*2)+5);
textcolor(BLACK);
cprintf("%c %s",0,commands[option]);
return;
}
else if(key==enter)
switch(option)
{
case 0:
do
{
textcolor(BLUE);
gotoxy(35,5);
cprintf("[ %s ] ",searchMethod[configuration.searchOption]);
RemoveCursor(4,4);
do
key = getch();
while(key!=up&&key!=down&&key!=enter&&key!=esc&&key!=tab);
if(key==up)
configuration.searchOption = configuration.searchOption==0 ? 2 : configuration.searchOption-1;
else if(key==down)
configuration.searchOption = configuration.searchOption==2 ? 0 : configuration.searchOption+1;
}
while(key!=enter&&key!=esc&&key!=tab);
saveConfiguration();
key=NULL;
gotoxy(37,7);
cprintf(" ");
textcolor(BLACK);
gotoxy(35,5);
cprintf("[ %s ]",searchMethod[configuration.searchOption]);
break;
case 1:
gotoxy(37,7);
cprintf(" ");
textcolor(BLUE);
if(configuration.searchOption==0)
getString(37,7,false,student.name);
else if(configuration.searchOption==1)
getString(37,7,false,student.lastname);
else if(configuration.searchOption==2)
getCarnet(37,7,student.carnet);
textcolor(BLACK);
gotoxy(37,7);
cprintf("%s", configuration.searchOption==2 ? student.carnet : configuration.searchOption==1? student.lastname : student.name);
key=NULL;
break;
case 2:
textcolor(BLACK);
positionY=0;
for(i=0;i<=6;i++)
for(j=0;j<11;j++)
{
gotoxy(PositionX[j],i+17);
cprintf("%s",cleaner[j]);
}
for(i=0;i<database[configuration.ID_database].ID;i++)
if(strcmp(database[configuration.ID_database].student[i].name,student.name)==0 || strcmp(database[configuration.ID_database].student[i].lastname,student.lastname)==0 || strcmp(database[configuration.ID_database].student[i].carnet,student.carnet)==0)
{
for(j=0;j<11;j++)
{
gotoxy( PositionX[j] , positionY+17);
switch(j)
{
case 0:
textcolor(BLACK);
cprintf("%s %s",database[configuration.ID_database].student[i].name, database[configuration.ID_database].student[i].lastname);
break;
case 1:
textcolor(BLACK);
cprintf("%s",database[configuration.ID_database].student[i].carnet);
break;
default:
if(database[configuration.ID_database].student[i].class[j-2]._isActive == true)
{
if(database[configuration.ID_database].student[i].class[j-2].nota>=60)
textcolor(GREEN);
else
textcolor(RED);
cprintf("%d",database[configuration.ID_database].student[i].class[j-2].nota);
}
else
{
textcolor(BLACK);
cprintf(" - ");
}
break;
}
}
positionY++;
if(positionY>6)
break;
}
if(positionY==0)
{
gotoxy(60,9); cprintf("No se ha encontrado");
gotoxy(60,10); cprintf("ese registro");
}
else
{
gotoxy(60,9); cprintf(" ");
gotoxy(60,10); cprintf(" ");
}
student.carnet[0]='\0';
student.name[0]='\0';
student.lastname[0]='\0';
gotoxy(37,7);
cprintf(" ");
key=NULL;
break;
default:
FatalError();
break;
}
}
while(key!=enter&&key!=tab&&key!=esc);
}
int Login(void)
{
FILE * file;
account temporaryAccount,validAccount;
MessageBox();
textbackground(BLUE);
textcolor(WHITE);
gotoxy(23,16);
if(loginCount==0)
cprintf(" ");
else if(loginCount==1)
cprintf("Incorrecto, intente nuevamente...");
else if(loginCount==2)
cprintf("Incorrecto, intente por ultima vez");
else if(loginCount==3)
return 0;
gotoxy(32,7); cprintf(" Inicio de Sesion ");
gotoxy(24,10); cprintf("Usuario: ");
gotoxy(24,14); cprintf("Contrase%ca: ",enye);
getString(24+9,10,false,temporaryAccount.user);
getString(24+12,14,true,temporaryAccount.password);
file = fopen("Accounts.txt","r");
if(file==NULL)
{
strcpy(validAccount.user,"admin");
strcpy(validAccount.password,"admin");
file = fopen("Accounts.txt","w");
fwrite(&validAccount,sizeof(account),1,file);
fclose(file);
file = fopen("Accounts.txt","r");
}
while(!feof(file))
{
fread(&validAccount,sizeof(validAccount),1,file);
if(strcmp(validAccount.user,temporaryAccount.user)==0 && strcmp(validAccount.password,temporaryAccount.password)==0)
{
textcolor(WHITE);
gotoxy(2,25);
cprintf("Esc - Atras Enter - Ir %c%c - Desplazarse Tab - Siguiente pesta%ca",24,25,enye);
user = temporaryAccount;
textcolor(LIGHTGRAY);
gotoxy(60,2); cprintf(" ");
gotoxy(60,2); cprintf("Usuario: %s",user.user);
clearwindow('a');
addFramework();
about();
return 1;
}
}
fclose(file);
loginCount++;
Login();
}
void Register(void)
{
char *commands[]={"Usuario","Password","Cancelar","Registrar"};
FILE * file;
account newAccount, registeredAccount;
int isAvailable=false;
newAccount.user[0]='\0';
newAccount.password[0]='\0';
option = 0;
do
{
for(i=0;i<4;i++)
{
if(i==option)
textbackground(BLACK);
else
textbackground(BLUE);
textcolor(WHITE);
gotoxy(24,(i*2)+10);
cprintf("%s",commands[i]);
}
RemoveCursor(3,4);
do
key=getch();
while(key!=up&&key!=down&&key!=esc&&key!=enter);
textcolor(WHITE);
if(key==up)
option = option==0 ? 3 : option - 1;
else if(key==down)
option = option==3 ? 0 : option + 1;
else if(key==esc)
{
clearwindow('a');
addFramework();
return;
}
else if(key==enter)
switch(option)
{
case 0:
isAvailable=true;
gotoxy(32,10); cprintf(" ");
getString(32,10,false,newAccount.user);
file = fopen("Accounts.txt","a++");
if(file==NULL)
{
gotoxy(26,18);
cprintf("No se ha podido abrir el fichero");
RemoveCursor(4,4);
getch();
clearscreen();
addFramework();
return;
}
while(!feof(file))
{
fread(®isteredAccount,sizeof(registeredAccount),1,file);
if(strcmp(registeredAccount.user,newAccount.user)==0)
{
isAvailable=false;
textcolor(LIGHTRED);
gotoxy(32,10); cprintf("%s",newAccount.user);
RemoveCursor(4,4);
}
}
break;
case 1:
gotoxy(33,12); cprintf(" ");
getString(33,12,true,newAccount.password);
break;
case 2:
option=3;
clearwindow('a');
addFramework();
More();
return;
case 3:
textbackground(BLUE);
if(strcmp(newAccount.user,NULL)==0)
{
gotoxy(26,18);
cprintf(" Debe escribir un usuario ");
RemoveCursor(4,4);
}
else if(strcmp(newAccount.password,NULL)==0)
{
gotoxy(26,18);
cprintf("Debe escribir una contrase%ca",enye);
RemoveCursor(4,4);
}
else if(isAvailable==false)
{
textcolor(LIGHTRED);
gotoxy(26,18);
cprintf(" El usuario ya existe ");
RemoveCursor(4,4);
}
else
{
file = fopen("Accounts.txt","a++");
if(file==NULL)
{
gotoxy(26,18);
cprintf("No se ha podido abrir el fichero");
RemoveCursor(4,4);
getch();
clearscreen();
addFramework();
return;
}
fwrite(&newAccount,sizeof(newAccount),1,file);
fclose(file);
gotoxy(27,18); cprintf("La cuenta se ha registrado");
RemoveCursor(4,4);
getch();
LoginAndRegisterDesigner();
return;
}
break;
default:
FatalError();
break;
}
}
while(key!=esc);
}
void LoginAndRegister(void)
{
char *commands[]={"Iniciar Sesion","Registrarse"};
int positionY[2]={10,14};
for(i=0;i<2;i++)
{
if(i==option)
textbackground(BLACK);
else
textbackground(BLUE);
textcolor(WHITE);
gotoxy(24,positionY[i]);
cprintf("%c %s",i==option ? 16 : 0,commands[i]);
}
RemoveCursor(4,4);
do
key = getch();
while(key!=up && key!=down && key!=enter && key!=esc);
if(key==up)
option = option == 0 ? 1 : 0 ;
else if(key==down)
option = option == 1 ? 0 : 1 ;
else if(key==esc)
return;
else
switch(option)
{
case 0:
loginCount=0;
Login();
return;
case 1:
RegisterDesigner();
return;
default:
break;
}
LoginAndRegister();
}
void Menu(void)
{
char *commands[] = {"Agregar","Buscar","Registro","Mas"};
gotoxy(3,2);
for(i=0;i<4;i++)
{
if(i!=screen)
{
textbackground(BLUE);
textcolor(LIGHTGRAY);
}
else
{
textbackground(LIGHTGRAY);
textcolor(BLUE);
}
cprintf(" %s ",commands[i]);
}
RemoveCursor(3,4);
do
key = getch();
while(key!=tab && key!=enter && key!=left && key!=right);
if(key==tab || key==right)
screen = screen!=3 ? screen + 1 : 0;
else if(key==left)
screen = screen!=0 ? screen - 1 : 3;
else
{
option=0;
clearwindow('a');
switch(screen)
{
case 0:
addFramework();
Add();
break;
case 1:
clearscreen();
SearchDesigner();
break;
case 2:
clearscreen();
ShowDatabaseDesigner();
if(database[configuration.ID_database].ID > 0)
ShowDatabase();
break;
case 3:
addFramework();
if(More())
return;
break;
default:
FatalError();
break;
}
}
Menu();
}
int More(void)
{
char *group[]= {"1M1 - CO","1M2 - CO","1M3 - CO","1M4 - CO"}, *chosenSemestre[] = {"I ","II"}, *commands[] = {"Grupo","Semestre","Acerca de","Registrar Cuenta","Cerrar Sesion","Salir"};
textbackground(WHITE);
for(i=0;i<6;i++)
{
if(i==option)
textcolor(BLUE);
else
textcolor(BLACK);
gotoxy(4,(i*2)+6);
cprintf("%c %s",i==option ? cursor : false,commands[i]);
}
textcolor(BLACK);
gotoxy(32,6);
cprintf("[ %s ]",group[configuration.ID_database]);
gotoxy(32,8);
cprintf("[ %s ]",chosenSemestre[configuration.semester]);
for(i=0;i<7;i++)
{
gotoxy(58,6+i);
cprintf("%s", option==0?groupInformation[i]:option==1?semesterInformation[i]:option==2?aboutInformation[i]:option==3?registerInformation[i]:option==4?closeSessionInformation[i]:exitInformation[i]);
}
RemoveCursor(4,4);
do
key = getch();
while(key!=up && key!=down && key!=enter && key!=esc && key!=tab);
if(key == up)
option = option==0 ? 5 : option - 1;
else if(key == down)
option = option==5 ? 0 : option + 1;
else if(key == esc||key == tab)
{
textcolor(BLACK);
gotoxy(4,(option*2)+6);
cprintf("%c %s",0,commands[option]);
return 0;
}
else if(key == enter)
{
switch(option)
{
case 0:
suboption=configuration.ID_database;
do
{
gotoxy(32,6);
textcolor(BLUE);
cprintf("[ %s ]",group[suboption]);
RemoveCursor(4,4);
do
key = getch();
while(key!=up && key!=down && key!=enter && key!=esc);
if(key==up)
suboption = suboption==0 ? 3 : suboption - 1;
else if(key==down)
suboption = suboption==3 ? 0 : suboption + 1;
else if(key==enter || key==esc)
{
configuration.ID_database = suboption;
saveConfiguration();
gotoxy(32,6);
textcolor(BLACK);
cprintf("[ %s ]",group[suboption]);
}
}
while(key!=enter && key!=esc);
key=NULL;
break;
case 1:
suboption=configuration.semester;
do
{
textcolor(BLUE);
gotoxy(32,8);
cprintf("[ %s ]",chosenSemestre[suboption]);
RemoveCursor(4,4);
do
key = getch();
while(key!=up && key!=down && key!=enter && key!=esc);
if(key==up)
suboption = suboption == 0 ? 1 : 0;
else if(key==down)
suboption = suboption == 1 ? 0 : 1;
else if(key==enter || key==esc)
{
configuration.semester = suboption;
saveConfiguration();
gotoxy(32,8);
textcolor(BLACK);
cprintf("[ %s ]",chosenSemestre[suboption]);
}
}
while(key!=enter && key!=esc);
key=NULL;
break;
case 2:
about();
RemoveCursor(4,4);
getch();
clearwindow('a');
break;
case 3:
RegisterDesigner();
break;
case 4:
clearwindow('a');
LoginAndRegisterDesigner();
addFramework();
about();
return 1;
default:
save();
system("cls");
return 1;
}
}
More();
}
void about(void)
{
char *info[] = {"PROYECTO REGISTRO ACADEMICO","Lider en ciencia y tecnologia","FEC - FACULTAD DE ELECTROTECNIA Y COMPUTACION","1M1 - CO","Integrantes","Gabriel Ortiz","2020-0325U","Luis Pineda","2020-0251U","Engel Reyes","2020-0505U","Ing. Nelson Barrios"};
int positionxy[2][12] = {
{16,15,07,24,63,60,67,60,67,60,67,59},
{05,16,18,20,05,7,9,11,13,15,17,21}};
clearwindow('a');
textcolor(BLACK);
for (i=0;i<12;i++)
{
gotoxy(positionxy[0][i],positionxy[1][i]);
cprintf("%s",info[i]);
}
LogoSmall(21,7);
}
void Add(void)
{
char *commands[5] = {"Nombre:","Apellido:","Carnet:","Asignaturas","Agregar"};
int positionY[5] = {5,7,9,11,22};
char *subcommands[2]={"Si","No"};
int subPositionX[2]={32,43};
char *limitsCommands[]={"Limite de estudiantes por","aula alcanzado...","OK"};
int limitsPosition[2][3]={{27,27,39},{11,12,16}};
student student;
student.name[0]=NULL;
student.lastname[0]=NULL;
student.carnet[0]=NULL;
for(i=0;i<9;i++)
{
if(i<4)
student.class->nameClass=lessons[0][i];
else
student.class->nameClass=lessons[1][i];
student.class[i].nota=-1;
student.class[i]._isActive=false;
}
textcolor(BLACK);
gotoxy(19,11);
cprintf("Clase Nota");
do
{
textbackground(WHITE);
for(i=0;i<5;i++)
{
if(i==option)
textcolor(BLUE);
else
textcolor(BLACK);
gotoxy(4,positionY[i]);
cprintf("%c %s",i==option ? cursor : 0,commands[i]);
gotoxy(17,(i*2)+13);
textcolor(BLACK);
cprintf("%c %s",student.class[configuration.semester==0?i:i+4]._isActive==true?cursor2:0, lessons[configuration.semester][i]);
}
textcolor(BLACK);
for(i=0;i<5;i++)
{
gotoxy(58,6+i);
cprintf("%s", option==0? nameInformation[i] : option==1? lastNameInformation[i] : option==2? carnetInformation[i] : option==3? classInformation[i] : addInformation[i]);
}
RemoveCursor(3,4);
do
key = getch();
while(key!=up && key!=down && key!=esc && key!=enter && key!=tab);
if(key==up)
option = option==0 ? 4 : option - 1 ;
else if(key==down)
option = option==4 ? 0 : option + 1 ;
else if(key==esc||key==tab)
{
textcolor(BLACK);
gotoxy(4,positionY[option]);
cprintf("%c %s",0,commands[option]);
return;
}
else if(key==enter)
{
textcolor(WHITE);
switch(option)
{
case 0:
gotoxy(14,5);
cprintf(" ");
getString(14,5,false,student.name);
textcolor(BLACK);
gotoxy(14,5);
cprintf("%s",student.name);
break;
case 1:
gotoxy(16,7);
cprintf(" ");
getString(16, 7,false,student.lastname);
textcolor(BLACK);
gotoxy(16,7);
cprintf("%s",student.lastname);
break;
case 2:
gotoxy(14,9);
cprintf(" ");
getCarnet(14,9,student.carnet);
textcolor(RED);
gotoxy(14,9);
cprintf("%s",student.carnet);
for(i=0;i<4;i++)
for(j=0;j<database[i].ID;j++)
if(strcmp(database[i].student[j].carnet,student.carnet)==0)
student.carnet[0]='\0';
if(!strcmp(NULL,student.carnet)==0)
{
textcolor(BLACK);
gotoxy(14,9);
cprintf("%s",student.carnet);
}
break;
case 3:
textcolor(BLACK);
gotoxy(19,11);
cprintf("Clase Nota");
suboption=0;
do
{
for(i=0;i<5;i++)
{
if(suboption==i)
textcolor(BLUE);
else
textcolor(BLACK);
gotoxy(17,(i*2)+13);
cprintf("%c %s",student.class[configuration.semester==0?i:i+4]._isActive==true?cursor2:0, lessons[configuration.semester][i]);
}
for(i=0;i<5;i++)
{
gotoxy(58,14+i);
if(configuration.semester==0)
cprintf("%s", enableClass[i]);
else
cprintf("%s", suboption==4 ? enableClass[i] : suboption==3 ? disabledClass2[i] : suboption==0 ? disabledClass1[i] : disabledClass0[i]);
}
RemoveCursor(4,4);
do
key = getch();
while (key!=up && key!=down && key!=enter && key!=esc);
if(key==up)
suboption = suboption==0 ? 0 : suboption-1 ;
else if(key==down)
if(configuration.semester==0)
suboption = suboption==3 ? 3 : suboption+1;
else
suboption = suboption==4 ? 4 : suboption+1;
else if (key==enter)
if(!((configuration.semester==1) && ( (suboption==0&&student.class[0].nota<60) || ((suboption==1||suboption==2)&&student.class[0]._isActive==false)||(suboption==3&&student.class[1].nota<60))))
{
textcolor(BLUE);
gotoxy(51,(suboption*2)+13);
cprintf(" ");
student.class[configuration.semester==0 ? suboption : suboption+4].nota = getScore(51,(suboption*2)+13);
if(student.class[configuration.semester==0 ? suboption : suboption+4].nota>=0)
{
textcolor(BLACK);
gotoxy(51,(suboption*2)+13);
cprintf("%d ",student.class[configuration.semester==0 ? suboption : suboption+4].nota);
student.class[configuration.semester==0 ? suboption : suboption+4]._isActive=true;
}
else
{
gotoxy(51,(suboption*2)+13);
cprintf(" ");
student.class[configuration.semester==0 ? suboption : suboption+4]._isActive=false;
}
}
else if (key==esc)
{
textcolor(BLACK);
gotoxy(17,(suboption*2)+13);
cprintf("%c %s",student.class[configuration.semester==0 ? suboption : suboption+4]._isActive==true?cursor2:0, lessons[configuration.semester][suboption]);
}
}
while(key!=esc);
clearwindow('r');
key=NULL;
break;
case 4:
if(strcmp(student.name,NULL)==0||strcmp(student.lastname,NULL)==0||strcmp(student.carnet,NULL)==0)
break;
MessageBox();
gotoxy(27,11);
textbackground(BLUE);
cprintf("%cDesea agregar el usuario?",opensing);
suboption=0;
do
{
textcolor(WHITE);
for(i=0;i<2;i++)
{
if(i==suboption)
textbackground(BLACK);
else
textbackground(BLUE);
gotoxy(subPositionX[i],15);
cprintf("%c %s",i==suboption?cursor:0,subcommands[i]);
}
RemoveCursor(4,4);
do
key=getch();
while(key!=left&&key!=right&&key!=enter&&key!=esc);
if(key==left)
suboption = suboption == 0 ? 1 : 0;
else if(key==right)
suboption = suboption == 1 ? 0 : 1;
else if(key==esc)
{
clearscreen();
addFramework();
loadStudentData(student);
}
else if(key==enter)
{
if(suboption==1)
{
clearscreen();
addFramework();
loadStudentData(student);
}
else if(database[configuration.ID_database].ID>=MaxStds)
{
MessageBox();
textcolor(WHITE);
for(i=0;i<3;i++)
{
if(i==2)
textbackground(BLACK);
else
textbackground(BLUE);
gotoxy(limitsPosition[0][i],limitsPosition[1][i]);
cprintf("%s",limitsCommands[i]);
}
getch();
clearscreen();
addFramework();
Add();
return;
}
else if(suboption==0)
{
database[configuration.ID_database].student[database[configuration.ID_database].ID]=student;
database[configuration.ID_database].ID++;
clearscreen();
addFramework();
save();
Add();
return;
}
}
}
while(key!=esc && key!=enter);
key=NULL;
break;
default:
FatalError();
break;
}
}
}
while(key!=esc);
}
void editStudent(int ID)
{
char *commands[7] = {"Nombre:","Apellido:","Carnet:","Asignaturas","Cancelar","Eliminar","Actualizar"};
int positionY[7] = {5,7,9,11,18,20,22};
char *subcommands[2]={"Si","No"};
int subPositionX[2]={32,43};
int acumulation,activeClass,semesterAcumulation,semesterActiveClass;
float average,semesterAverage;
student student=database[configuration.ID_database].student[ID];
clearscreen();
addFramework();
loadStudentData(student);
gotoxy(30,5);
cprintf("Promedio anual: -");
gotoxy(30,7);
cprintf("Promedio semestral: -");
do
{
acumulation=0;
activeClass=0;
semesterAcumulation=0;
semesterActiveClass=0;
for(i=0;i<9;i++)
{
if(configuration.semester==0 && i<4 && student.class[i]._isActive==true)
{
semesterAcumulation += student.class[i].nota;
semesterActiveClass++;
}
else if (configuration.semester==1 && i>=4 && student.class[i]._isActive==true)
{
semesterAcumulation += student.class[i].nota;
semesterActiveClass++;
}
if(student.class[i]._isActive==true)
{
acumulation += student.class[i].nota;
activeClass++;
}
}
textcolor(BLACK);
if(activeClass!=0)
{
average = acumulation/activeClass;
gotoxy(46,5);
cprintf("%.2f", average);
}
if(semesterActiveClass)
{
semesterAverage = semesterAcumulation/semesterActiveClass;
gotoxy(50,7);
cprintf("%.2f",semesterAverage);
}
textbackground(WHITE);
for(i=0;i<7;i++)
{
if(i==option)
textcolor(BLUE);
else
textcolor(BLACK);
gotoxy(4,positionY[i]);
cprintf("%c %s",i==option ? cursor : 0,commands[i]);
}
for(i=0;i<5;i++)
{
gotoxy(58,6+i);
cprintf("%s", option==0? nameInformation[i] : option==1? lastNameInformation[i] : option==2? carnetInformation[i] : option==3? classInformation[i] : option==4? cancelInformation[i] : option==5? deleteInformation[i] : updateInformation[i]);
}
RemoveCursor(3,4);
do
key = getch();
while(key!=up && key!=down && key!=esc && key!=enter && key!=tab);
if(key==up)
option = option==0 ? 6 : option - 1 ;
else if(key==down)
option = option==6 ? 0 : option + 1 ;
else if(key==esc||key==tab)
{
clearscreen();
ShowDatabaseDesigner();
if(database[configuration.ID_database].ID > 0)
ShowDatabase();
return;
}
else if(key==enter)
{
textcolor(WHITE);
switch(option)
{
case 0:
gotoxy(14,5);
cprintf(" ");
getString(14,5,false,student.name);
textcolor(BLACK);
gotoxy(14,5);
cprintf("%s",student.name);
break;
case 1:
gotoxy(16,7);
cprintf(" ");
getString(16, 7,false,student.lastname);
textcolor(BLACK);
gotoxy(16,7);
cprintf("%s",student.lastname);
break;
case 2:
break;
case 3:
textcolor(BLACK);
gotoxy(19,11);
cprintf("Clase Nota");
suboption=0;
do
{
for(i=0;configuration.semester==1?i<5:i<4;i++)
{
if(suboption==i)
textcolor(BLUE);
else
textcolor(BLACK);
gotoxy(17,(i*2)+13);
cprintf("%c %s",student.class[configuration.semester==0?i:i+4]._isActive==true?cursor2:0, lessons[configuration.semester][i]);
}
for(i=0;i<5;i++)
{
textcolor(BLACK);
gotoxy(58,14+i);
if(configuration.semester==0)
cprintf("%s", enableClass[i]);
else
cprintf("%s", suboption==4 ? enableClass[i] : suboption==3 ? disabledClass2[i] : suboption==0 ? disabledClass1[i] : disabledClass0[i]);
}
RemoveCursor(3,4);
do
key = getch();
while (key!=up && key!=down && key!=enter && key!=esc);
if(key==up)
suboption = suboption==0 ? 0 : suboption-1 ;
else if(key==down)
if(configuration.semester==0)
suboption = suboption==3 ? 3 : suboption+1;
else
suboption = suboption==4 ? 4 : suboption+1;
else if (key==enter)
{
if(!((configuration.semester==1) && ( (suboption==0&&student.class[0].nota<60) || ((suboption==1||suboption==2)&&student.class[0]._isActive==false)||(suboption==3&&student.class[1].nota<60))))
{
gotoxy(51,(suboption*2)+13);
cprintf(" ");
textcolor(BLUE);
student.class[configuration.semester==0 ? suboption : suboption+4].nota = getScore(51,(suboption*2)+13);
if(configuration.semester == 0 && suboption==0 && student.class[0].nota<60 && student.class[4]._isActive==true)
student.class[0].nota=60;
else if(configuration.semester==0 && suboption==0 && student.class[0].nota<0 && (student.class[5]._isActive==true || student.class[6]._isActive==true))
student.class[0].nota=0;
if(configuration.semester==0 && suboption==1 && student.class[1].nota<60 && student.class[7]._isActive==true)
student.class[1].nota=60;
if(student.class[configuration.semester==0 ? suboption : suboption+4].nota>=0)
{
textcolor(BLACK);
gotoxy(51,(suboption*2)+13);
cprintf("%d ",student.class[configuration.semester==0 ? suboption : suboption+4].nota);
student.class[configuration.semester==0 ? suboption : suboption+4]._isActive=true;
}
else
{
gotoxy(51,(suboption*2)+13);
cprintf(" ");
student.class[configuration.semester==0 ? suboption : suboption+4]._isActive=false;
}
}
}
else if (key==esc)
{
textcolor(BLACK);
gotoxy(17,(suboption*2)+13);
cprintf("%c %s",student.class[configuration.semester==0 ? suboption : suboption+4]._isActive==true?cursor2:0, lessons[configuration.semester][suboption]);
}
}
while(key!=esc);
clearwindow('r');
key=NULL;
break;
case 4:
option=ID;
clearscreen();
ShowDatabaseDesigner();
if(database[configuration.ID_database].ID > 0)
ShowDatabase();
return;
case 5:
Login();
for(i=ID;i<database[configuration.ID_database].ID-1;i++)
database[configuration.ID_database].student[i]=database[configuration.ID_database].student[i+1];
database[configuration.ID_database].ID--;
option=0;
save();
clearscreen();
ShowDatabaseDesigner();
if(database[configuration.ID_database].ID > 0)
ShowDatabase();
return;
case 6:
if(strcmp(student.name,NULL)==0||strcmp(student.lastname,NULL)==0||strcmp(student.carnet,NULL)==0)
break;
MessageBox();
gotoxy(27,11);
textbackground(BLUE);
cprintf("%cDesea actualizar el usuario?",opensing);
suboption=0;
do
{
textcolor(WHITE);
for(i=0;i<2;i++)
{
if(i==suboption)
textbackground(BLACK);
else
textbackground(BLUE);
gotoxy(subPositionX[i],15);
cprintf("%c %s",i==suboption?cursor:0,subcommands[i]);
}
RemoveCursor(3,4);
do
key=getch();
while(key!=left&&key!=right&&key!=enter&&key!=esc);
if(key==left)
suboption = suboption == 0 ? 1 : 0;
else if(key==right)
suboption = suboption == 1 ? 0 : 1;
else if(key==enter||key==esc)
{
clearscreen();
addFramework();
textcolor(BLACK);
if(suboption==1)
for(i=0;i<3;i++)
{
gotoxy(i==1?16:14,positionY[i]);
cprintf("%s",i==0?student.name:i==1?student.lastname:student.carnet);
}
else
{
database[configuration.ID_database].student[ID]=student;
save();
clearscreen();
ShowDatabaseDesigner();
ShowDatabaseDesigner();
if(database[configuration.ID_database].ID > 0)
ShowDatabase();
return;
}
}
}
while(key!=esc && key!=enter);
key=NULL;
break;
default:
FatalError();
break;
}
}
}
while(key!=esc);
}
/*--------------------------------- Funtions -------------------------------*/
void saveConfiguration(void)
{
FILE * file;
file = fopen("Config.txt","w");
fwrite(&configuration,sizeof(configuration),1,file);
fclose(file);
}
void loadConfiguration(void)
{
FILE * file;
file = fopen("Config.txt","r");
if(file==NULL)
{
file = fopen("Config.txt","w");
fwrite(&configuration,sizeof(configuration),1,file);
}
else
fread(&configuration,sizeof(configuration),1,file);
fclose(file);
}
void save(void)
{
FILE * file;
file = fopen("DATABASE.txt","w");
if(!file == NULL)
for(i=0;i<4;i++)
{
fwrite(&database[i],sizeof(database[i]),1,file);
}
fclose(file);
}
void load(void)
{
FILE * file;
file = fopen("DATABASE.txt","r");
if(!file==NULL)
for(i=0;i<4;i++)
fread(&database[i],sizeof(database),1,file);
else
file = fopen("DATABASE.txt","w");
fclose(file);
}
void loadStudentData(student student)
{
textcolor(BLACK);
gotoxy(19,11);
cprintf("Clase Nota");
gotoxy(63,4);
cprintf("INFORMACION");
gotoxy(14,5);
cprintf("%s",student.name);
gotoxy(16,7);
cprintf("%s",student.lastname);
gotoxy(14,9);
cprintf("%s",student.carnet);
for(i=0; configuration.semester == 0 ? i<4 : i<5;i++)
{
textcolor(BLACK);
gotoxy(17,(i*2)+13);
cprintf("%c %s",student.class[configuration.semester==0?i:i+4]._isActive==true?cursor2:0, lessons[configuration.semester][i]);
gotoxy(17,(i*2)+13);
textcolor(BLACK);
cprintf("%c %s",student.class[configuration.semester==0?i:i+4]._isActive==true?cursor2:0, lessons[configuration.semester][i]);
gotoxy(51,(i*2)+13);
if(student.class[configuration.semester==0 ? i : i+4]._isActive==true)
cprintf("%d",student.class[configuration.semester==0 ? i : i+4].nota);
}
}
void clearscreen(void)
{
textbackground(WHITE);
for(i=1;i<=80;i+=20)
for(j=3;j<=24;j++)
{
gotoxy(i,j);
cprintf("%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
}
}
void clearwindow(char window)
{
textbackground(WHITE);
if(window == 'l' || window == 'a')
{
for(i=2;i<=56;i+=11)
for(j=4;j<=23;j++)
{
gotoxy(i,j);
cprintf("%c%c%c%c%c%c%c%c%c%c%c",0,0,0,0,0,0,0,0,0,0,0);
}
}
for(i=58;i<=79;i+=11)
for(j=4;j<=23;j++)
{
gotoxy(i,j);
cprintf("%c%c%c%c%c%c%c%c%c%c%c",0,0,0,0,0,0,0,0,0,0,0);
}
textcolor(BLACK);
gotoxy(63,4);
cprintf("INFORMACION");
}
void addFramework(void)
{
textbackground(WHITE);
textcolor(BLACK);
for(i=1;i<=80;i++)
{
gotoxy(i,3);
if(i==80)
cprintf("%c",esquinaNE);
else if(i==1)
cprintf("%c",esquinaNW);
else if(i==57)
cprintf("%c",194);
else
cprintf("%c",lineaH);
gotoxy(i,24);
if(i==80)
cprintf("%c",esquinaSE);
else if(i==1)
cprintf("%c",esquinaSW);
else if(i==57)
cprintf("%c",193);
else
cprintf("%c",lineaH);
if(i>=4&&i<=23)
{
gotoxy(1,i);
cprintf("%c",lineaV);
gotoxy(57,i);
cprintf("%c",lineaV);
gotoxy(80,i);
cprintf("%c",lineaV);
}
}
}
| true |
05226aeab13c45b0dc45cc28c48e8e947f71a371 | C++ | Aniganesh/100daysofcode | /Mystery-1.cpp | UTF-8 | 601 | 2.671875 | 3 | [] | no_license | // https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/mystery-30/
// 13-06-2020 Very-easy/easy
#include<bits/stdc++.h>
#define MOD % 1000000007
typedef long long ll;
using namespace std;
ll countSetBits(ll& n){
ll count = 0;
while(n){
n &= (n-1);
++count;
};
return count;
}
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
cout.tie(NULL);
ll num;
while(!cin.eof()){
cin >> num;
cout << countSetBits(num) << "\n";
}
return 0;
} | true |
fc6bbf03d87cf785cc854df34fb6ffbd05ca280d | C++ | Xangis/magma | /editors/de310/source/misc/keywords.cpp | UTF-8 | 5,350 | 3.046875 | 3 | [] | no_license | //
// File: keywords.cpp originally part of dikuEdit
//
// Usage: functions used to handle keyword lists
//
// Copyright 1995-98 (C) Michael Glosenger
//
#include <string.h>
#include "../fh.h"
//
// createKeywordList : Taking keywordStrn as input, breaks the individual
// words in the string (separated by spaces) into
// "keywords." Each keyword goes into its own stringNode,
// and a linked list is created. The head of this linked
// list is returned to the calling function.
//
// *keywordStrn : Pointer to the keyword string as read from the data file
//
stringNode *createKeywordList(const char *keywordStrn)
{
ulong i, i2 = 0, len = strlen(keywordStrn);
stringNode *homeSNode, *SNode, *oldSNode = NULL;
if (keywordStrn[0] == '~') return NULL;
homeSNode = SNode = new stringNode;
if (!homeSNode)
{
_outtext("\ncreateKeywordList: couldn't allocate memory for homeSNode\n\n");
return NULL;
}
homeSNode->string[0] = '\0';
homeSNode->Next = NULL;
for (i = 0; i < len; i++)
{
if (((keywordStrn[i] == ' ') || (keywordStrn[i] == '~')) && (i2 > 0))
{
// null-terminate the string
SNode->string[i2] = '\0';
i2 = 0;
// uppercase it..
upstrn(SNode->string);
if (oldSNode) oldSNode->Next = SNode;
oldSNode = SNode;
// reset SNode to NULL so that a new one is only created if it is needed
SNode = NULL;
}
else
{
if (!SNode)
{
SNode = new stringNode;
if (!SNode)
{
_outtext("\ncreateKeywordList(): couldn't allocate memory for SNode\n\n");
return NULL;
}
SNode->Next = NULL;
SNode->string[0] = '\0';
}
SNode->string[i2] = keywordStrn[i];
i2++;
}
}
if (homeSNode->string[0] == '\0')
{
delete homeSNode;
return NULL;
}
else return homeSNode;
}
//
// addKeywordtoList : returns FALSE if there's an error, TRUE if success
//
char addKeywordtoList(stringNode **keywordHead, const char *keyword)
{
stringNode *strnNode, *strnNode2;
if (!keywordHead) return FALSE; // might happen
strnNode = new stringNode;
if (!strnNode) return FALSE;
memset(strnNode, 0, sizeof(stringNode));
strcpy(strnNode->string, keyword);
if (!*keywordHead) *keywordHead = strnNode;
else
{
strnNode2 = *keywordHead;
while (strnNode2->Next)
{
strnNode2 = strnNode2->Next;
}
strnNode2->Next = strnNode;
strnNode->Last = strnNode2;
}
return TRUE;
}
//
// getReadableKeywordStrn :
// Creates a user-readable string of keywords from the list
// pointed to by keywordHead, with each keyword separated by
// a comma.
//
// *keywordHead : pointer to the head of the stringNode keyword list
// *endStrn : pointer to string that contains user-readable string
//
char *getReadableKeywordStrn(stringNode *keywordHead, char *endStrn)
{
endStrn[0] = '\0';
while (keywordHead)
{
strcat(endStrn, keywordHead->string);
keywordHead = keywordHead->Next;
if (keywordHead) strcat(endStrn, ", ");
}
return endStrn;
}
//
// scanKeyword : Searches through the list pointed to by keywordListHead for
// a substring constructed using userinput and keywordpos. If
// a match is found, TRUE is returned, else FALSE is returned.
//
// *userinput : Points to the string where the substring to search for
// resides
// *keywordListHead : Pointer to the head of a list of stringNodes
// keywordpos : Point in userinput to start at in order to make the
// substring
//
char scanKeyword(const char *userinput, stringNode *keywordListHead)
{
char *keyword;
if (!keywordListHead) return FALSE;
keyword = new char[strlen(userinput) + 1];
if (!keyword)
{
_outtext("\n\nscanKeyword(): couldn't alloc keyword\n\n");
return FALSE;
}
strcpy(keyword, userinput);
remLeadingSpaces(keyword);
remTrailingSpaces(keyword);
while (keywordListHead)
{
if (!strcmp(keyword, keywordListHead->string))
{
delete[] keyword;
return TRUE;
}
keywordListHead = keywordListHead->Next;
}
delete[] keyword;
return FALSE;
}
//
// createKeywordString : Creates a standard Diku tilde-terminated keyword
// string from a list of stringNodes, altering strn
// and returning the address of the new string.
//
// *strnNode : Head of linked list of stringNodes
// *keyStrn : String to put new string into
//
char *createKeywordString(stringNode *strnNode, char *keyStrn)
{
if (!keyStrn)
{
_outtext("\n\ncreateKeywordString(): got NULL ptr\n\n");
return "error in createKeywordString~";
}
keyStrn[0] = '\0';
while (strnNode)
{
strcat(keyStrn, strnNode->string);
strnNode = strnNode->Next;
if (strnNode) strcat(keyStrn, " ");
}
strcat(keyStrn, "~");
lowstrn(keyStrn);
return keyStrn;
}
| true |
39313532bd192a5dcc4f6dc64c781e022b8f8c2d | C++ | Forrest-Z/gcy_tmap | /src/Tmapping/include/tmapping/StructedMap.h | UTF-8 | 2,039 | 2.515625 | 3 | [
"MIT"
] | permissive | //
// Created by stumbo on 2019/11/17.
//
#ifndef TMAPPING_STRUCTEDMAP_H
#define TMAPPING_STRUCTEDMAP_H
#include <utility>
#include <vector>
#include "tools/TopoParams.h"
#include "tools/TopoVec2.h"
#include "expDataTypes/ExpDataTypes.h"
namespace tmap
{
struct MapNode : std::enable_shared_from_this<MapNode>
{
public:
struct Link {
Link() : to(), at(GATEID_NO_MAPPING) {}
Link(const MapNodePtr& to, GateID at) : to(to), at(at) {}
MapNodeWe to;
GateID at = GATEID_NO_MAPPING;
};
private:
/// 用于方便各种构造的时候知道links[i].to指向的是哪里
size_t mSerial = 0;
MergedExpPtr mRelatedMergedExp;
std::vector<Link> mLinks;
protected:
explicit MapNode(MergedExpPtr relatedExp, size_t serial);
public:
static MapNodePtr makeOneFromMergedExp(MergedExpPtr relatedExp, size_t serial = 0);
void addNewLink(const MapNodePtr& to, GateID at);
void addNewDanglingLink();
void setLinkAtIndex(size_t index, const MapNodePtr& to, GateID at);
Link& linkAt(size_t index);
GateID linkedGIDAt(size_t index);
size_t nLinks() const;
size_t getSerial() const;
ExpDataPtr expData() const;
void setSerial(size_t serial);
const MergedExpPtr& getRelatedMergedExp() const;
virtual ~MapNode();
};
class StructedMapImpl
{
std::vector<MapNodePtr> mNodes;
MapTwigWePtr mRelatedTwig;
size_t mAgentAt;
double mPossibility;
#ifdef TMAPPING_CONFIG_RECORD_POSS
std::vector<double> mPossHistory;
public:
const std::vector<double>& getPossHistory() const
{
return mPossHistory;
}
#endif
public:
StructedMapImpl(std::vector<MapNodePtr> nodes, const MapTwigPtr& twigUsed, double poss);
explicit StructedMapImpl(const Json::Value& jmap);
const MapTwigWePtr& relatedTwig() const;
Json::Value toJS() const;
const std::vector<MapNodePtr>& getNodes() const;
double getPsblt() const;
void setPsblt(double psbly);
};
}
#endif //TMAPPING_STRUCTEDMAP_H
| true |
86f8f02b1e850f71f7ad1ed77611fbc18588d717 | C++ | qwb2333/got7 | /src/lib/common/config.cpp | UTF-8 | 1,066 | 2.828125 | 3 | [] | no_license | #include "config.h"
using namespace qwb;
ConfigReaderPtr ConfigReaderFactory::createFromFile(const char *path) {
FILE *file = fopen(path, "r");
char buffer[4096];
ConfigReaderPtr ptr(new ConfigReader);
std::map<std::string, std::string> &kv = ptr->getKv();
while(fgets(buffer, sizeof(buffer), file)) {
size_t len = strlen(buffer);
for(size_t i = 0; i < len; i++) {
if(buffer[i] == '=') {
std::string k, v;
k = Utils::trim(buffer, 0, i - 1);
v = Utils::trim(buffer, i + 1, len - 1);
kv[k] = v;
break;
}
}
}
return ptr;
}
std::string ConfigReader::getAsString(const std::string &k, std::string defaultValue) {
auto iter = kv.find(k);
if(iter == kv.end()) return defaultValue;
return iter->second;
}
int32_t ConfigReader::getAsInt(const std::string &k, int32_t defaultValue) {
auto iter = kv.find(k);
if(iter == kv.end()) return defaultValue;
return std::atoi(iter->second.c_str());
} | true |
1882eac269200920c932f8b8cc8984b08f91b713 | C++ | MoonOrchid18/P31- | /testing.cpp | UTF-8 | 1,242 | 3.1875 | 3 | [] | no_license | // ??????????? ?????.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;
class SimpleClass
{
int *ptr; //pointer for someone memory area
public:
SimpleClass() // Construct
{
cout << "\nNormal constr\n";
}
SimpleClass(const SimpleClass &obj)
{
cout << "\nCopy constr \n";
}
~SimpleClass()
{
cout << "\nDestruct\n";
}
};
void funcShow(SimpleClass object)
{
cout << "\nFunction accepted object like parametr\n";
}
SimpleClass funcReturnObject()
{
SimpleClass object;
cout << "\nFunction return object\n";
return object;
}
int main()
{
const int NotUsed = system("color F0");
cout << "1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
SimpleClass obj1; // creating an object
cout << "2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
funcShow(obj1); // give that object in fuction
cout << "3 - 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
funcReturnObject(); // this function return object
cout << "5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
SimpleClass obj2 = obj1; // object initialization at creation
cout<<"hi my little programmer";
cout<<"how are you";
system("pause");
return 0;
system("pause");
//_getch();
}
| true |
3745ecb85939d20b0e659f64963754725b8d97b7 | C++ | xwy27/CrackingTheCodingInterview | /Chapter 4 Trees and Graphs/cpp/4_3.cpp | UTF-8 | 1,006 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
typedef struct treeNode {
int val;
treeNode* left;
treeNode* right;
}treeNode;
treeNode* addToTree(int* arr, int start, int end) {
if (end < start) return NULL;
int mid = (start + end ) / 2;
treeNode* temp = new treeNode;
temp->val = arr[mid];
temp->left = addToTree(arr, start, mid-1);
temp->right = addToTree(arr, mid+1, end);
return temp;
}
char symbol[] = {"-/\\<"};
void treeGraph(treeNode* root, int level) {
int i;
if (root != NULL) {
treeGraph(root->right, level+1);
for (i = 0; i < level; ++i) cout << "\t";
cout << root->val << " ";
cout << symbol[((NULL!=root->left)<<1)|(NULL!=root->right)] << endl;
treeGraph(root->left, level+1);
}
}
int main() {
int n;
cin >> n;
int *arr = new int[n];
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
treeNode* root = addToTree(arr, 0, n-1);
treeGraph(root,0);
} | true |
a3dad962d46fb5d3ec2768862f59b4bc76860f1e | C++ | wada811/MeikaiClangNyumon | /Capter06/0605.cpp | SHIFT_JIS | 360 | 3.515625 | 4 | [] | no_license | /*
K6-5:xnovoid alert(int no)쐬B
*/
#include <stdio.h>
/*--- xno ---*/
void alert(int no){
while(no-- > 0){
putchar('\a');
}
}
int main(void){
int no;
printf("͂ĂF");
scanf("%d", &no);
alert(no);
return 0;
} | true |
f104729ef7d53d141d21f33bb3223c0cc60b06b5 | C++ | TimGoll/projektpraktikum | /controller/src/ownlibs/pca9555.cpp | UTF-8 | 2,261 | 3.015625 | 3 | [] | no_license | #include "pca9555.h"
Pca9555::Pca9555(uint8_t address) {
this->_address = address;
this->_valueRegister = 0b0000000000000000; //alle Pins auf LOW
this->_configurationRegister = 0b0000000000000000; //alle PINS als OUTPUT
Wire.begin();
}
Pca9555::~Pca9555() {
}
void Pca9555::begin() {
//setze alle 16 Pins auf OUTPUT
this->writeI2CValue(PCA9555_CONFIG , _configurationRegister_low);
this->writeI2CValue(PCA9555_CONFIG + 1, _configurationRegister_high);
//setzte alle 16 Pins auf low
this->writeI2CValue(PCA9555_OUTPUT , _valueRegister_low);
this->writeI2CValue(PCA9555_OUTPUT + 1, _valueRegister_high);
}
void Pca9555::digitalWrite(uint8_t pin, uint8_t value) {
if (pin > 15) { //falsche Pinnummer!
return;
}
//BITSHIFTING + MASKING
//Folgeder Code bearbeitet das ValueRegister so, dass sich nur
//das fuer uns interessante Bit aendert.
//mittels ~(1 << bit) wird eine Maske erstellt:
//Wenn das dritte bit 1 sein soll, dann sind alle anderen 0 und umgekehrt
//mittels bitweise logischen Verknuepfungen (| &) wird diese Maske
//auf das ValueRegister aufgetragen und nur das fuer uns interessante Bit
//aender sich
if (value == 0) {
//interessantes Bit hat Wert 0, Maske 1, daher &
//(da beliebiger Wert &1 den beliebigen vorherigen Wert ergibt)
_valueRegister = _valueRegister & ~(1 << pin);
} else {
//interessantes Bit hat Wert 1, Maske 0, daher |
//(da beliebiger Wert |0 den beliebigen vorherigen Wert ergibt)
_valueRegister = _valueRegister | (1 << pin);
}
//schreibe nun den 16-bit Wert in zwei Schritten (je 8 Bit) ueber I2C
this->writeI2CValue(PCA9555_OUTPUT , _valueRegister_low);
this->writeI2CValue(PCA9555_OUTPUT + 1, _valueRegister_high);
}
void Pca9555::writeI2CValue(uint8_t reg, uint8_t value) {
Wire.beginTransmission(this->_address); //Beginne Uebertragung mit Adresse des Empfaengers
Wire.write(reg); //setze das Zielregister
Wire.write(value); //setze den Wert
Wire.endTransmission(); //beende die Uebertragung
}
| true |
b69e08e5d3653c24e2c0f7b44b0023e6ab7bf9b2 | C++ | therealendrju/WorkshopContent | /examplecontent/ExampleAlgorithms/MergeClustersAlgorithm.cc | UTF-8 | 3,460 | 2.546875 | 3 | [] | no_license | /**
* @file WorkshopContent/examplecontent/ExampleAlgorithms/MergeClustersAlgorithm.cc
*
* @brief Implementation of the merge clusters algorithm class.
*
* $Log: $
*/
#include "Pandora/AlgorithmHeaders.h"
#include "examplecontent/ExampleAlgorithms/MergeClustersAlgorithm.h"
#include "examplecontent/ExampleHelpers/ExampleHelper.h"
using namespace pandora;
namespace example_content
{
MergeClustersAlgorithm::MergeClustersAlgorithm() :
m_nClusterMergesToMake(1),
m_maxClusterDistance(std::numeric_limits<float>::max())
{
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode MergeClustersAlgorithm::Run()
{
// Make a number of cluster merge operations, with each merge enlarging a parent cluster and deleting a daughter cluster.
const ClusterList *pClusterList(nullptr);
PANDORA_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::GetCurrentList(*this, pClusterList));
if (pClusterList->size() < 2)
return STATUS_CODE_SUCCESS;
unsigned int nClusterMerges(0);
// Need to be very careful with cluster list iterators here, as we are deleting elements from the std::unordered_set owned by the manager.
// If user chooses to iterate over that same list, must adhere to rule that iterators pointing at the deleted element will be invalidated.
// Here, iterate over an ordered copy of the cluster list
ClusterVector clusterVector(pClusterList->begin(), pClusterList->end());
std::sort(clusterVector.begin(), clusterVector.end(), ExampleHelper::ExampleClusterSort);
for (const Cluster *const pParentCluster : clusterVector)
{
try
{
// Check to see whether parent cluster (address stored in local vector) still exists in manager-owned list, and hasn't been
// removed by the cluster merging operations in this algorithm. Many alternative methods to check this, of course.
if (!pClusterList->count(pParentCluster))
continue;
const Cluster *const pBestDaughterCluster(ExampleHelper::FindClosestCluster(pParentCluster, pClusterList, m_maxClusterDistance));
if (++nClusterMerges > m_nClusterMergesToMake)
break;
// The API implementation will enforce the availability of the daughter cluster and ensure that the parent and daughter are not one and the same
PANDORA_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, PandoraContentApi::MergeAndDeleteClusters(*this, pParentCluster, pBestDaughterCluster));
// pBestDaughterCluster is now a dangling pointer, which exists only in the local cluster vector - do not deference!
}
catch (StatusCodeException &)
{
}
}
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode MergeClustersAlgorithm::ReadSettings(const TiXmlHandle xmlHandle)
{
PANDORA_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, XmlHelper::ReadValue(xmlHandle,
"NClusterMergesToMake", m_nClusterMergesToMake));
PANDORA_RETURN_RESULT_IF_AND_IF(STATUS_CODE_SUCCESS, STATUS_CODE_NOT_FOUND, !=, XmlHelper::ReadValue(xmlHandle,
"MaxClusterDistance", m_maxClusterDistance));
return STATUS_CODE_SUCCESS;
}
} // namespace example_content
| true |
74c334e2189a1c6dc1960fce41fe4f66f48746c8 | C++ | lyc2345/delicateiOS | /delicateiOS/include/com/tastenkunst/cpp/brf/nxt/utils/AllocUtils.hpp | UTF-8 | 1,115 | 2.921875 | 3 | [] | no_license | #ifndef __brf_AllocUtils__
#define __brf_AllocUtils__
#include <cstdlib>
#include "com/tastenkunst/cpp/brf/nxt/utils/StringUtils.hpp"
namespace brf {
/**
* Utility functions to alloc, free and align pointers.
* Borrowed from OpenCV memory alignment:
*
* Aligns pointer by the certain number of bytes.
*
* This small inline function aligns the pointer by the certian number of bytes by shifting
* it forward by 0 or a positive offset.
*/
template<typename _Tp>
inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) {
return (_Tp*)(((size_t)ptr + n-1) & -n);
}
/**
* Allocs and aligns a pointer
*/
inline void* fastMalloc(size_t size) {
unsigned char* udata = (unsigned char*)malloc(size + sizeof(void*) + 16);
if(!udata) {
Err("Failed to allocate memory");
}
unsigned char** adata = brf::alignPtr((unsigned char**)udata + 1, 16);
adata[-1] = udata;
return adata;
}
/**
* Frees an aligned pointer.
*/
inline void fastFree(void* ptr) {
if(ptr) {
unsigned char* udata = ((unsigned char**)ptr)[-1];
free(udata);
}
}
}
#endif /* __brf_AllocUtils__ */
| true |
c3a2ce7815c540dffe2e2068cc45d817a468572b | C++ | GTSKA/LinearAlgebra | /LinearAlgebra/MatrixClass.hpp | UTF-8 | 16,159 | 3.328125 | 3 | [] | no_license | #ifndef _MATRIX_CLASS_H
#define _MATRIX_CLASS_H
#include <assert.h>
#include "VectorClass.hpp"
#include <iostream>
#include <vector>
template<typename T, size_t m, size_t n>
class Matrix
{
public:
T** mat;
Matrix()
{
mat = new T*[m];
for (size_t i = 0; i < m; ++i)
{
mat[i] = new T[n];
for (size_t j = 0; j < n; ++j)
mat[i][j] = 0;
}
}
Matrix(const Matrix<T, m, n>& mat2)
{
mat = new T*[m];
for (size_t i = 0; i < m; ++i)
{
mat[i] = new T[n];
for (size_t j = 0; j < n; ++j)
mat[i][j] = mat2.mat[i][j];
}
}
Matrix(std::initializer_list<T> list)
{
assert(list.size() == m*n);
mat = new T*[m];
for (size_t i = 0; i < m; ++i)
{
mat[i] = new T[n];
}
size_t i = 0, j = 0;
for (const auto& l : list)
{
mat[i][j] = l;
j++;
if (j == n)
{
j = 0;
i++;
}
}
}
~Matrix()
{
if (mat != nullptr)
{
for (size_t i = 0; i < m; ++i)
delete[] mat[i];
delete[] mat;
}
}
size_t rowSize()
{
return m;
}
size_t colSize()
{
return n;
}
#pragma region operators
T* operator [](size_t i)
{
return mat[i];
}
Matrix<T, m, n>& operator =(const Matrix<T, m, n>& mat2)
{
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
mat[i][j] = mat2.mat[i][j];
}
return *this;
}
Matrix<T, m, n>& operator +=(const Matrix<T, m, n>& mat2)
{
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
mat[i][j] += mat2[i][j];
}
return *this;
}
Matrix<T, m, n> operator +(const Matrix<T, m, n>& mat2)
{
Matrix<T, m, n> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
res[i][j] = mat[i][j] + mat2.mat[i][j];
return res;
}
Matrix<T, m, n>& operator -=(const Matrix<T, m, n>& mat2)
{
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
mat[i][j] -= mat2.mat[i][j];
}
return *this;
}
Matrix<T, m, n> operator -(const Matrix<T, m, n>& mat2)
{
Matrix<T, m, n> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
res[i][j] = mat[i][j] - mat2.mat[i][j];
return res;
}
Matrix<T, m, n> operator-()
{
Matrix<T, m, n> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
res[i][j] = -mat[i][j];
return res;
}
Matrix<T, m, n>& operator *=(const T k)
{
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
mat[i][j] *= k;
}
return *this;
}
Matrix<T, m, n> operator * (const T& k)
{
Matrix<T, m, n> res;
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
res[i][j] = mat[i][j] * k;
}
return res;
}
friend Matrix<T, m, n> operator *(const T& k,const Matrix<T, m, n>& mat2)
{
Matrix<T, m, n> res;
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
res[i][j] = k*mat2[i][j];
}
return res;
}
Vector<T, m> operator * (const Vector<T, m>& v)
{
assert(m == n);
Vector<T, m> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < m; ++j)
res[i] += mat[i][j] * v[j];
return res;
}
Vector<T, m> operator * (Vector<T, n>& v)
{
Vector<T, m> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
res[i] += mat[i][j] * v[j];
return res;
}
friend Vector<T, n> operator *(const Vector<T, m>& v, const Matrix<T, m, n>& mat2)
{
Vector<T, n> res;
for (size_t i = 0; i < n; ++i)
for (size_t j = 0; j < m; ++j)
res[i] += v[j] * mat2[j][i];
return res;
}
friend Vector<T, n> operator *(Vector<T, m>& v, Matrix<T, m, n>& mat2)
{
Vector<T, n> res;
for (size_t i = 0; i < n; ++i)
for (size_t j = 0; j < m; ++j)
res[i] += v[j] * mat2[j][i];
return res;
}
template<size_t n2>
Matrix<T, m, n2> operator *(const Matrix<T, n, n2>& mat2)
{
Matrix<T, m, n2> res;
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n2; ++j)
{
for (size_t k = 0; k < n; ++k)
{
res[i][j] += mat[i][k] * mat2.mat[k][j];
}
}
}
return res;
}
bool operator ==(const Matrix<T, m, n>& mat2)
{
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
if (mat[i][j] != mat[i][j])
return false;
return true;
}
bool operator !=(const Matrix<T, m, n>& mat2)
{
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
if (mat[i][j] != mat[i][j])
return true;
return false;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix<T, m, n>& mat2)
{
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
os << mat2.mat[i][j] << "\t";
os << std::endl;
}
return os;
}
#pragma endregion
void SetIdentity()
{
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
if (i == j)
mat[i][j] = (T)1;
else
mat[i][j] = (T)0;
}
void Transpose()
{
Matrix<T, n, m> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
res[j][i] = mat[i][j];
return res;
}
void SetRotationX(float angle)
{
assert(n >= 3);
assert(n == m);
float cosa = cosf(angle);
float sina = sinf(angle);
SetIdentity();
mat[1][1] = cosa;
mat[1][2] = -sina;
mat[2][1] = sina;
mat[2][2] = cosa;
}
void SetRotationY(float angle)
{
assert(n >= 3);
assert(n == m);
SetIdentity();
float cosa = cosf(angle);
float sina = sinf(angle);
mat[0][0] = cosa;
mat[0][2] = sina;
mat[2][0] = -sina;
mat[2][2] = cosa;
}
void SetRotationZ(float angle)//can rotate 2D coordinates;
{
assert(n >= 2);
assert(n == m);
SetIdentity();
float cosa = cosf(angle);
float sina = sinf(angle);
mat[0][0] = cosa;
mat[0][1] = -sina;
mat[1][0] = sina;
mat[1][1] = cosa;
}
void SetRotationAxis(float angle, const Vector<T, 3>& v)
{
Vector<T, 3> u = v.normalize();
assert(u.module());
assert(n >= 3);
assert(n == m);
float cosa = cosf(angle);
float sina = sinf(angle);
SetIdentity();
mat[0][0] = cosa + u[0]*u[0]*(1-cosa); mat[0][1] = u[0] * u[1] * (1 - cosa) - u[2]*sina; mat[0][2] = u[0] * u[2] * (1 - cosa) + u[1] * sina;
mat[1][0] = u[1] * u[0] * (1 - cosa) + u[2] * sina; mat[1][1] = cosa + u[1] * u[1] * (1 - cosa); mat[1][2] = u[1] * u[2] * (1 - cosa) - u[0] * sina;
mat[2][0] = u[2] * u[0] * (1 - cosa) - u[1] * sina; mat[2][1] = u[2] * u[1] * (1 - cosa) + u[0] * sina; mat[2][2] = cosa + u[2] * u[2] * (1 - cosa);
}
void SetScale(const Vector<T, m>& v)
{
assert(m == n);
SetIdentity();
for (size_t i = 0; i < m; ++i)
mat[i][i] *= v[i];
}
void SetTranslation(const Vector<T, m-1>& p)
{
assert(m == n);
res.SetIdentity();
for (size_t i = 0; i < m - 1; ++i)
mat[i][m - 1] = p[i];
}
Matrix<T, m, n + 1> AdjuntCol(Vector<T, m>& v)
{
Matrix<T, m, n + 1> res;
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
res[i][j] = mat[i][j];
res[i][n] = v[i];
}
return res;
}
Matrix<T, m + 1, n> AdjuntRow(Vector<T, n>& v)
{
Matrix<T, m + 1, n> res;
for (size_t i = 0; i < m; ++i)
for (size_t j = 0; j < n; ++j)
res[i][j] = mat[i][j];
for (size_t j = 0; j < n; ++j)
res[m][j] = v[j];
return res;
}
Vector<T, n> getRow(size_t i)
{
assert(i >= 0 && i < m);
Vector<T, n> res;
for (size_t j = 0; j < n; ++j)
res[j] = mat[i][j];
return res;
}
Vector<T, m> getCol(size_t j)
{
assert(i >= 0 && i < n);
Vector<T, m> res;
for (size_t i = 0; i < m; ++i)
res[i] = mat[i][j];
return res;
}
T determinant()
{
assert(m == n);
if (m == 1)
return mat[0][0];
T det;
std::vector<bool> col;
col.resize(m);
for (size_t i = 0; i < m; ++i)
col[i] = true;
det = detAux(col);
return det;
}
private:
T detAux(std::vector<bool>& col)
{
size_t cont, cont2;
T aux, det = T(0);
cont = 0;
for (size_t i = 0; i < col.size(); ++i)
if (col[i])
++cont;
if (cont > 2)
{
cont2 = 0;
for (size_t i = 0; i < col.size(); ++i)
{
if (col[i])
{
if (mat[col.size() - cont][i] != 0)
{
std::vector<bool> cols;
cols.resize(col.size());
for (size_t j = 0; j < col.size(); ++j)
cols[j] = col[j];
cols[i] = false;
T powMinusOne = (cont2 % 2) ? (T)(-1.0) : (T)1.0;
aux = mat[col.size() - cont][i] * detAux(cols) * powMinusOne;
det += aux;
}
++cont2;
}
}
return det;
}
else
{
T mataux[2][2];
cont2 = 0;
for(size_t i =0;i<col.size();++i)
if (col[i])
{
mataux[0][cont2] = mat[col.size() - 2][i];
mataux[1][cont2] = mat[col.size() - 1][i];
++cont2;
}
return mataux[0][0] * mataux[1][1] - mataux[1][0] * mataux[0][1];
}
}
public:
Matrix<T, m, n> Inverse()
{
assert(m == n);
T det = determinant();
if (det == 0)
return *this;
if (m == 1)
{
Matrix<T, m, n> res;
res[0][0] = T(1) / mat[0][0];
return res;
}
if (m == 2)
{
Matrix<T, m, n> res;
res[0][0] = mat[1][1]/det; res[0][1] = -mat[0][1]/det;
res[1][0] = -mat[1][0]/det; res[1][1] = mat[0][0]/det;
return res;
}
if (m == 3)
{
T a, b, c, d, e, f, g, h, i;
a = mat[0][0]; b = mat[0][1]; c = mat[0][2];
d = mat[1][0]; e = mat[1][1]; f = mat[1][2];
g = mat[2][0]; h = mat[2][1]; i = mat[2][2];
Matrix<T, m, n> res;
res[0][0] = e*i - f*h; res[0][1] = -(b*i - c*h); res[0][2] = b*f - c*e;
res[1][0] = -(d*i - f*g); res[1][1] = a*i - c*g; res[1][2] = -(a*f - c*d);
res[2][0] = d*h - e*g; res[2][1] = -(a*h - b*g); res[2][2] = a*c - b*d;
res *= T(1) / det;
return res;
}
if (m == 4)
{
Matrix<T, 2, 2> A, B, C, D, A2,B2,C2,D2,DI,A_BDIC_1;//(A-BD.Inverse()*C).Inverse()
for (size_t i = 0; i < 2; ++i)
{
for (size_t j = 0; j < 2; ++j)
{
A[i][j] = mat[i][j];
B[i][j] = mat[i][j + 2];
C[i][j] = mat[i + 2][j];
D[i][j] = mat[i + 2][j + 2];
}
}
A_BDIC_1 = (A - B*(D.Inverse())*C).Inverse();
DI = D.Inverse();
A2 = A_BDIC_1;
B2 = -A_BDIC_1*B*DI;
C2 = -DI*C*A_BDIC_1;
D2 = DI + DI*C*A_BDIC_1*B*DI;
Matrix<T, m, n> res;
for (size_t i = 0; i < 2; ++i)
{
for (size_t j = 0; j < 2; ++j)
{
res[i][j] = A2[i][j];
res[i][j + 2] = B2[i][j];
res[i + 2][j] = C2[i][j];
res[i + 2][j + 2] = D2[i][j];
}
}
return res;
}
if (m > 4)
{
//TO DO, still this class is recomendated for low size matrix only
return *this;
}
}
};
typedef Matrix<float, 4, 4> Mat44f;
typedef Matrix<float, 3, 3> Mat33f;
typedef Matrix<float, 2, 2> Mat22f;
Mat44f lookAtRH(vec3f& pos, vec3f& target, vec3f& up)
{
Mat44f lookAt;
vec3f zaxis, xaxis, yaxis;
zaxis = (pos - target).normalize();
xaxis = Cross(up, zaxis).normalize();
yaxis = Cross(zaxis, xaxis);
lookAt.SetIdentity();
lookAt[0][0] = xaxis[0]; lookAt[0][1] = yaxis[0]; lookAt[0][2] = zaxis[0];
lookAt[1][0] = xaxis[1]; lookAt[1][1] = yaxis[1]; lookAt[1][2] = zaxis[1];
lookAt[2][0] = xaxis[2]; lookAt[2][1] = yaxis[2]; lookAt[2][2] = zaxis[2];
lookAt[3][0] = -(xaxis.Dot(pos)); lookAt[3][1] = -(yaxis.Dot(pos)); lookAt[3][2] = -(zaxis.Dot(pos));
return lookAt;
}
Mat44f lookAtLH(vec3f& pos, vec3f& target, vec3f& up)
{
Mat44f lookAt;
vec3f zaxis, xaxis, yaxis;
zaxis = (target-pos).normalize();
xaxis = Cross(up, zaxis).normalize();
yaxis = Cross(zaxis, xaxis);
lookAt.SetIdentity();
lookAt[0][0] = xaxis[0]; lookAt[0][1] = yaxis[0]; lookAt[0][2] = zaxis[0];
lookAt[1][0] = xaxis[1]; lookAt[1][1] = yaxis[1]; lookAt[1][2] = zaxis[1];
lookAt[2][0] = xaxis[2]; lookAt[2][1] = yaxis[2]; lookAt[2][2] = zaxis[2];
lookAt[3][0] = -(xaxis.Dot(pos)); lookAt[3][1] = -(yaxis.Dot(pos)); lookAt[3][2] = -(zaxis.Dot(pos));
return lookAt;
}
Mat44f perspectiveRH(float w, float h, float near, float far)
{
assert(w && h);
assert(far != near);
Mat44f res;
res[0][0] = 2 * near / w;
res[1][1] = 2 * near / h;
res[2][2] = far / (near - far); res[2][3] = -1;
res[3][2] = near*far / (near - far);
return res;
}
Mat44f perspectiveLH(float w, float h, float near, float far)
{
assert(w && h);
assert(far != near);
Mat44f res;
res[0][0] = 2 * near / w;
res[1][1] = 2 * near / h;
res[2][2] = far / (far - near); res[2][3] = 1;
res[3][2] = near*far / (near - far);
return res;
}
Mat44f perspectiveFovRH(float fov, float aspectRatio, float near, float far)
{
assert(fov);
assert(far != near);
float h = 1.0f / tan(fov * 0.5f);
float w = h * aspectRatio;
Mat44f res;
res[0][0] = w;
res[1][1] = h;
res[2][2] = far / (near-far); res[2][3] = -1;
res[3][2] = near*far / (near - far);
return res;
}
Mat44f perspectiveFovLH(float fov, float aspectRatio, float near, float far)
{
assert(fov);
assert(far != near);
float h = 1.0f / tan(fov * 0.5f);
float w = h * aspectRatio;
Mat44f res;
res[0][0] = w;
res[1][1] = h;
res[2][2] = far / (far-near); res[2][3] = 1;
res[3][2] = near*far / (near - far);
return res;
}
Mat44f perspectiveOffCenterRH(float left, float right, float bottom, float top, float near, float far)
{
assert(right != left);
assert(top != bottom);
assert(far != near);
Mat44f res;
res[0][0] = 2 * near / (right - left);
res[1][1] = 2 * near / (top - bottom);
res[2][0] = (left + right) / (right - left); res[2][1] = (top + bottom) / (top - bottom); res[2][2] = far / (near - far); res[2][3] = -1;
res[3][2] = near*far / (near - far);
return res;
}
Mat44f perspectiveOffCenterLH(float left, float right, float bottom, float top, float near, float far)
{
assert(right != left);
assert(top != bottom);
assert(far != near);
Mat44f res;
res[0][0] = 2 * near / (right - left);
res[1][1] = 2 * near / (top - bottom);
res[2][0] = (left + right) / (right - left); res[2][1] = (top + bottom) / (top - bottom); res[2][2] = far / (far - near); res[2][3] = 1;
res[3][2] = near*far / (near - far);
return res;
}
//true:oriented counterclockwise(Right hand rule)
//false:oriented clockwise(Left handed)
enum Orientation
{
CW,//clockwise
CCW,//counterclockwise
COLLINEAR,//Colineal
COPLANAR,//coplanar
ABOVE,//above the plane
BELOW, //below the plane
INSIDE,
OUTSIDE,
COCIRCULAR,
COSPHERICAL,
ERROR
};
Orientation Orient2D(vec2f& a, vec2f& b, vec2f& c)
{
Mat33f m{ a[0], a[1], 1.0f,
b[0], b[1], 1.0f,
c[0], c[1], 1.0f };
float det = m.determinant();
if (det > 0) return Orientation::CCW;
if (det < 0) return Orientation::CW;
return Orientation::COLLINEAR;
}
float SignedArea(vec2f& a, vec2f& b, vec2f& c)
{
Mat33f m{ a[0], a[1], 1.0f,
b[0], b[1], 1.0f,
c[0], c[1], 1.0f };
return m.determinant();
}
Orientation Orient3D(vec3f& a, vec3f& b, vec3f& c, vec3f& d)
{
Mat44f m{ a[0],a[1],a[2],1.0f,
b[0],b[1],b[2],1.0f,
c[0],c[1],c[2],1.0f,
d[0],d[1],d[2],1.0f };
float det = m.determinant();
if (det < 0)return Orientation::ABOVE;
if (det > 0)return Orientation::BELOW;
return Orientation::COPLANAR;
}
Orientation incircle2D(vec2f&a, vec2f& b, vec2f& c, vec2f& d)
{
Orientation p3o;//first three point orientation
p3o = Orient2D(a, b, c);
if (p3o == Orientation::COLLINEAR)
return Orientation::ERROR;
Mat44f m{ a[0],a[1],a.sqmodule(),1.0f,
b[0],b[1],b.sqmodule(),1.0f,
c[0],c[1],c.sqmodule(),1.0f,
d[0],d[1],d.sqmodule(),1.0f };
float det = m.determinant();
if(p3o>0)
{
if (det < 0) return Orientation::OUTSIDE;
if (det > 0) return Orientation::INSIDE;
}
else
{
if (det < 0) return Orientation::INSIDE;
if (det > 0) return Orientation::OUTSIDE;
}
return Orientation::COCIRCULAR;
}
Orientation insphere(vec3f& a, vec3f& b, vec3f& c, vec3f& d, vec3f& e)
{
Orientation p4o;//first four points orientation
p4o = Orient3D(a, b, c, d);
if (p4o == Orientation::COPLANAR)
return Orientation::ERROR;
Matrix<float, 5, 5> m{ a[0],a[1],a[2],a.sqmodule(),1.0f,
b[0],b[1],b[2],b.sqmodule(),1.0f,
c[0],c[1],c[2],c.sqmodule(),1.0f,
d[0],d[1],d[2],d.sqmodule(),1.0f,
e[0],e[1],e[2],e.sqmodule(),1.0f, };
float det = m.determinant();
if (p4o > 0)
{
if (det > 0) return Orientation::INSIDE;
if (det < 0) return Orientation::OUTSIDE;
}
else
{
if (det > 0) return Orientation::OUTSIDE;
if (det < 0) return Orientation::INSIDE;
}
return Orientation::COSPHERICAL;
}
typedef Matrix<double, 4, 4> Mat44d;
typedef Matrix<double, 3, 3> Mat33d;
typedef Matrix<double, 2, 2> Mat22d;
#endif // !_MATRIX_CLASS_H
| true |
af60f48a20b220d7876911e533d890faaf390b4d | C++ | namnani/cplusplus | /pointer/InitialPointerVariable.cpp | UTF-8 | 186 | 2.890625 | 3 | [] | no_license | #include <iostream>
class Nani {
public:
std::string* namnani;
Nani() : namnani(NULL) { }
};
int main(void)
{
Nani nani;
std::cout << nani.namnani << std::endl;
return 0;
}
| true |
807ee86d958f4d3b3107ab23a864bb8b201c802e | C++ | Jason-Dominguez/Arena-Management-System- | /bankacc.cpp | UTF-8 | 5,586 | 3.34375 | 3 | [] | no_license | #include "bankacc.h"
double bank::getSales(){
return sales;
}
void bank::setSales(double inSales){
sales=inSales;
}
double bank::getCash(){
return cash;
}
void bank::setCash(double inCash){
cash = inCash;
}
double bank::getDebt(){
return debt;
}
void bank::setDebt(double inDebt){
debt = inDebt;
}
double bank::getCon(){
return conSales;
}
void bank::setCon(double inConSales){
conSales = inConSales;
}
void readBank(bank &bankData)/// reads data from bank.txt and stores it in bankData
{
double sales=0, cash=0, debt=0, conSales=0;
ifstream inFile;
inFile.open("bank.txt");
if(!inFile){
cout<<endl<<"Cannot open the file";
}
inFile >> sales >> cash >> debt >> conSales;/// conSales is not read from given file but will be on saved file after first use
bankData.setSales(sales);
bankData.setCash(cash);
bankData.setDebt(debt);
bankData.setCon(conSales);
}
void bankFile(bank bankData)
{
ofstream outFile; /// prints bankData vector to bank.txt
outFile.open("bank.txt");
outFile << bankData.getSales()<<" "<< bankData.getCash()<<" "<<bankData.getDebt()<<" "<<bankData.getCon();
return;
}
bool inputYNb()
{
char YN = ' ';
while(true)
{
cout<<"Enter Y for YES or N for NO"<<endl;
cin>>YN;
if(!cin)
{
cin.clear();
cin.ignore(256, '\n');
cout<<"\rInvalid Input::: ";
continue;
}
cin.clear();
cin.ignore(256, '\n');
if(YN == 'y' || YN == 'Y')
return true;
if(YN == 'n' || YN == 'N')
return false;
else
cout<<"\rInvalid Input::: ";
}
}
void printBank(bank bankData)
{
cout<<"\n Bank Account Information"<<endl;
cout<<"Sales: $"<<bankData.getSales()<<endl;
cout<<"Concession Sales: $"<<bankData.getCon()<<endl;
cout<<"Cash: $"<<bankData.getCash()<<endl;
cout<<"Debt: $"<<bankData.getDebt()<<endl<<endl;
}
char adjMenu()
{
char edit=' ';
while(true)
{
cout<<"\nWhat would you like to edit?"<<endl;
cout<<"1. Sales\n2. Cash\n3. Debt\n4. Exit"<<endl;
cin>>edit;
cin.clear();
cin.ignore(256, '\n');
if(edit=='1'||edit=='2'||edit=='3'||edit=='4')
return edit;
cout<<"Invalid entry. Enter a number 1-4"<<endl;
}
}
double change()
{
while(true){
double temp=0;
cout<<"What would you like to change it to?"<<endl;
cin>>temp;
if(!cin || temp < 0)
{
cin.clear();
cin.ignore(256, '\n');
cout<<"Invalid entry"<<endl;
}
else
return temp;
}
}
void adjustBank(bank &bankData)
{
double temp=0;
char edit=adjMenu();
switch(edit)
{
case '1':
cout<<"\nSales account is currently "<<bankData.getSales()<<endl;
temp=change();
bankData.setSales(temp);
cout<<"Sales account is now "<<bankData.getSales()<<endl<<endl;
break;
case '2':
cout<<"\nCash account is currently $"<<bankData.getCash()<<endl;
temp=change();
bankData.setCash(temp);
cout<<"Cash account is now $"<<bankData.getCash()<<endl<<endl;
break;
case '3':
cout<<"\nDebt account is currently $"<<bankData.getDebt()<<endl;
temp=change();
bankData.setDebt(temp);
cout<<"Debt account is now $"<<bankData.getDebt()<<endl<<endl;
break;
}
}
void payOff(bank &bankData)
{
while(true){
double pay=0;
cout<<"\nThe arena currently has $"<<bankData.getCash()<<" cash on hand"<<endl;
cout<<"and carries a debt of $"<<bankData.getDebt()<<endl;
cout<<"How much would you like to pay off?\n$";
cin>>pay;
if(!cin || pay<0)
{
cin.clear();
cin.ignore(256, '\n');
cout<<"Invalid entry"<<endl<<endl;
}
else if(pay > bankData.getCash())
cout<<"The arena does not have that much cash on hand"<<endl;
else if(pay > bankData.getDebt())
cout<<"The arena does not need to pay more than it owes"<<endl;
else
{
bankData.setCash(bankData.getCash()-pay);
bankData.setDebt(bankData.getDebt()-pay);
cout<<"Payment complete"<<endl;
break;
}
}
}
char bankMenu()
{
char menu=' ';
while(true)
{
cout<<"\n Bank Account"<<endl<<endl;
cout<<"1. View all accounts"<<endl;
cout<<"2. Adjust accounts"<<endl;
cout<<"3. Pay off debt"<<endl;
cout<<"4. Main Menu"<<endl;
cin>>menu;
cin.clear();
cin.ignore(256, '\n');
if(menu=='1'||menu=='2'||menu=='3'||menu=='4')
return menu;
cout<<"Invalid entry. Enter a number 1-4"<<endl;
}
}
void bankManager(bank &bankData)
{
system ("CLS");
while(true){
char menu=bankMenu();
switch(menu)
{
case '1':
printBank(bankData);
break;
case '2':
adjustBank(bankData);
break;
case '3':
payOff(bankData);
break;
case '4':
return;
}
}
}
| true |
6c79c0126bb8e1807f3f16aeeb213d4fb0c9ccea | C++ | SebastianRobayo/Curso_de_Cpp | /Bloque1_Entrada,Salida_y_Expresiones/Ejercicio12.cpp | UTF-8 | 875 | 3.921875 | 4 | [] | no_license | //Ejercicio 12
/*Escriba un programa que lea de la entrada estandar los dos catetos de
un triangulo rectangunlo y escriba en la salida su hipotenusa*/
#include<iostream>
#include<math.h>//Esta libreria nos sirve para usar funciones matematicas, si se piensan usar hay que importarla.
using namespace std;
int main()
{
float catetoo,catetoa,hipotenusa;
cout<<"Ingrese el valor del cateto opuesto: "; cin>>catetoo;
cout<<"Ingrese el valor del cateto adyacente: "; cin>>catetoa;
/*
sqrt = Esta funcion sirve para usar raices.
pow = Esta funcion sirve para elevar numeros a cualquier exponente.
*/
hipotenusa = sqrt(pow(catetoo,2)+pow(catetoa,2));
cout.precision(2);//Esta funcion es usada para que el resultado unicamente salda con n numeros decimales en este caso decidi tomar solo dos.
cout<<"El resultado de la hipotenusa es: "<<hipotenusa;
return 0;
}
| true |
e0168b0f09fce4d4894cb734d9dcd9195c9d7902 | C++ | wangqiangcc/samples | /udp_bench/src/server.cpp | UTF-8 | 5,169 | 2.90625 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <string>
#include <functional>
#include <asio.hpp>
using asio::ip::udp;
enum PacketType
{
E_INFO = 1,
E_HEARTBEAT,
E_PACKET,
E_BAD_PACKET,
E_QUIT
};
class server
{
public:
server(asio::io_service& io_service, short port)
: io_service_(io_service),
socket_(io_service, udp::endpoint(udp::v4(), port)),
bytes(0), packets(0), bad_packets(0)
{
socket_.async_receive_from(asio::buffer(data_, max_length),
sender_endpoint_,
std::bind(&server::handle_receive_from, this,
std::placeholders::_1,
std::placeholders::_2));
}
void handle_receive_from(const asio::error_code& error,
size_t bytes_recvd)
{
if (!error && bytes_recvd > 0)
{
PacketType packet_type = checkPacket(data_, bytes_recvd);
switch (packet_type)
{
case E_QUIT:
{
std::stringstream sstr;
sstr << "Packets " << packets << "\nBytes " << bytes << "\nBad packets " << bad_packets << std::ends;
size_t response_length = sstr.str().length();
if (response_length > max_length)
{
response_length = max_length;
}
strncpy(data_, sstr.str().c_str(), response_length);
/* Echo back the quit message to terminate the session */
socket_.async_send_to(asio::buffer(data_, response_length),
sender_endpoint_,
std::bind(&server::handle_send_to, this,
std::placeholders::_1,
std::placeholders::_2));
break;
}
default:
{
socket_.async_receive_from(asio::buffer(data_, max_length),
sender_endpoint_,
std::bind(&server::handle_receive_from, this,
std::placeholders::_1,
std::placeholders::_2));
break;
}
}
}
else
{
if (error)
{
std::cout << "Error code " << error << " bytes received " << bytes_recvd << std::endl;
++bad_packets;
}
socket_.async_receive_from(asio::buffer(data_, max_length),
sender_endpoint_,
std::bind(&server::handle_receive_from, this,
std::placeholders::_1,
std::placeholders::_2));
}
return;
}
void handle_send_to(const asio::error_code& /*error*/, size_t /*bytes_sent*/)
{
std::cout << "Quit message sent\n";
std::cout << "Packets " << packets << "\nBytes " << bytes << "\nBad packets " << bad_packets << std::endl;
return; // io_service will complete with one worker
}
private:
bool validatePacket(const char *data, size_t length)
{
struct packet_header
{
uint32_t version_mark; // 'quit' or version pattern
uint32_t packet_length;
} checkHeader;
if (length < sizeof(packet_header))
{
return false;
}
/* can't cast due to possible alignment issues so copy minimum amount */
memcpy(&checkHeader, data, sizeof(packet_header));
if (checkHeader.packet_length != length)
{
return false;
}
return true;
}
PacketType checkPacket(const char *data, size_t length)
{
bytes += length;
++packets;
if (length >= 4 && strncmp(data, "quit",4) == 0)
{
std::cout << "detected quit request\n";
return E_QUIT;
}
if (!validatePacket(data, length))
{
++bad_packets;
return E_BAD_PACKET;
}
return E_PACKET;
}
asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint sender_endpoint_;
enum { max_length = 1468 };
char data_[max_length];
size_t bytes;
size_t packets;
size_t bad_packets;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: async_udp_server <port>\n";
return 1;
}
asio::io_service io_service;
using namespace std; // For atoi.
server s(io_service, atoi(argv[1]));
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
} | true |
96705dc1798b81b07e2414ae75809d3ff3e47f5b | C++ | cs142ta/style-unit-test | /NonConstGlobalChecker.h | UTF-8 | 5,493 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef NON_CONST_GLOBAL_CHECKER_H_
#define NON_CONST_GLOBAL_CHECKER_H_
#include <string>
#include <stack>
#include <algorithm>
#include "Token.h"
#ifdef DEBUG
#include <iostream>
#endif
struct GlobalsMachineData {
int firstBadLine;
int currLineNum;
std::string currWS;
int namespaceDepth;
int braceDepth;
std::vector<Lossy::Token> currNormalLine;
GlobalsMachineData()
: firstBadLine(-1),
currLineNum(1),
currWS("\n"),
namespaceDepth(0),
braceDepth (0) {}
int badLineNum() {
return firstBadLine;
}
void checkForNonConst() {
std::vector<Lossy::Token>::const_iterator begin = currNormalLine.cbegin();
std::vector<Lossy::Token>::const_iterator end = currNormalLine.cend();
if (std::find(begin, end, Lossy::CONST_T) == end
&& std::find(begin, end, Lossy::CONSTEXPR_T) == end
&& std::find(begin, end, Lossy::USING_T) == end
&& std::find(begin, end, Lossy::TYPEDEF_T) == end
&& !isAFunctionHeadLine(currNormalLine)) {
firstBadLine = currLineNum;
}
}
void stepWS(Lossy::Token t) {
if (t == Lossy::NEWLINE_T) {
currLineNum++;
}
}
};
#ifdef DEBUG
const char* nonConstCheckerStateToStr(int s) {
switch (s) {
case 0:
return "START_S";
case 1:
return "STRUCTURE_START_LINE_S";
case 2:
return "STRUCTURE_BODY_S";
case 3:
return "STRUCTURE_CLOSE_LINE_S";
case 4:
return "NORMAL_LINE_S";
case 5:
return "FUNC_BODY_S";
case 6:
return "BRACES_IN_NORMAL_LINE_S";
case 7:
return "NAMESPACE_START_LINE_S";
case 8:
return "PREPROC_LINE_S";
default:
return "??";
}
}
#endif
int getFirstNonConstGlobalLine(const std::vector<Lossy::Token>& tokens) {
GlobalsMachineData data;
enum State {
START_S,
STRUCTURE_START_LINE_S,
STRUCTURE_BODY_S,
STRUCTURE_CLOSE_LINE_S,
NORMAL_LINE_S,
FUNC_BODY_S,
BRACES_IN_NORMAL_LINE_S,
NAMESPACE_START_LINE_S,
PREPROC_LINE_S,
} currState = START_S;
for (Lossy::Token t : tokens) {
//printf("State:%s, Token:%s\n", nonConstCheckerStateToStr(currState), tokenToStr(t));
switch (currState) {
case START_S:
switch (t) {
case Lossy::SINGLE_SPACE_T:
case Lossy::TAB_T:
case Lossy::NEWLINE_T:
break;//just needed to stepws
case Lossy::CLASS_T:
case Lossy::STRUCT_T:
case Lossy::UNION_T:
case Lossy::ENUM_T:
currState = STRUCTURE_START_LINE_S;
break;
case Lossy::OCTOTHORPE_T:
currState = PREPROC_LINE_S;
break;
case Lossy::NAMESPACE_T:
currState = NAMESPACE_START_LINE_S;
break;
case Lossy::R_BRACE_T:
data.namespaceDepth--;
break;
case Lossy::EOF_T:
break; //do nothing
case Lossy::CASE_T:
case Lossy::DEFAULT_T:
case Lossy::PUBLIC_T:
case Lossy::PRIVATE_T:
case Lossy::PROTECTED_T:
case Lossy::SEMICOLON_T:
case Lossy::L_BRACE_T:
case Lossy::ELSE_T:
case Lossy::SWITCH_T:
case Lossy::CATCH_T:
case Lossy::IF_T:
case Lossy::WHILE_T:
case Lossy::FOR_T:
case Lossy::DO_T:
case Lossy::TRY_T:
case Lossy::L_PAREN_T:
case Lossy::R_PAREN_T:
case Lossy::SINGLE_COLON_T:
case Lossy::OTHER_STUFF_T:
default: //shouldn't happen, but same as above
data.currNormalLine.clear();
data.currNormalLine.push_back(t);
currState = NORMAL_LINE_S;
break;
}
break;
case STRUCTURE_START_LINE_S:
if (t == Lossy::L_BRACE_T) {
data.braceDepth = 1;
currState = STRUCTURE_BODY_S;
}
break;
case STRUCTURE_BODY_S:
if (t == Lossy::L_BRACE_T) {
data.braceDepth++;
}
else if (t == Lossy::R_BRACE_T) {
data.braceDepth--;
if (data.braceDepth == 0) {
currState = STRUCTURE_CLOSE_LINE_S;
}
}
break;
case STRUCTURE_CLOSE_LINE_S:
if (t == Lossy::SEMICOLON_T) {
currState = START_S;
}
break;
case NORMAL_LINE_S:
data.currNormalLine.push_back(t);
if (t == Lossy::SEMICOLON_T) {
currState = START_S;
data.checkForNonConst();
if (data.badLineNum() != -1) {
return data.badLineNum();
}
}
else if (t == Lossy::L_BRACE_T) {
data.braceDepth = 1;
if (isBraceInLineFunctionOpen(data.currNormalLine)) {
currState = FUNC_BODY_S;
}
else {
currState = BRACES_IN_NORMAL_LINE_S;
}
}
break;
case FUNC_BODY_S:
if (t == Lossy::L_BRACE_T) {
data.braceDepth++;
}
else if (t == Lossy::R_BRACE_T) {
data.braceDepth--;
if (data.braceDepth == 0) {
currState = START_S;
}
}
break;
case BRACES_IN_NORMAL_LINE_S:
if (t == Lossy::L_BRACE_T) {
data.braceDepth++;
}
else if (t == Lossy::R_BRACE_T) {
data.braceDepth--;
if (data.braceDepth == 0) {
currState = NORMAL_LINE_S;
}
}
break;
case NAMESPACE_START_LINE_S:
if (t == Lossy::L_BRACE_T) {
data.namespaceDepth++;
currState = START_S;
}
break;
case PREPROC_LINE_S:
if (t == Lossy::NEWLINE_T) {
currState = START_S;
}
break;
}
data.stepWS(t);
}
return data.badLineNum();
}
#endif
| true |
deda38f196db9eb4f5351bc9fc3efb57467bbaa3 | C++ | ashishc534/Codeforces | /Chat room.cpp | UTF-8 | 450 | 2.984375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool isHello(string s)
{
string word="hello";
int a=0;
int i, count = 0;
for(i=0; i<s.size(); i++){
if(s[i]==word[a]){
a++;
count++;
}
}
if(count==5)
return true;
else
return false;
}
int main()
{
string s;
cin>>s;
isHello(s)? cout<<"YES\n" : cout<<"NO\n";
return 0;
}
| true |
47bfb3570176f38babed1d45890fedbd007c8d14 | C++ | briskware/randomstring | /main.cpp | UTF-8 | 3,327 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include "RandomString.h"
#define ASIZEOF(arr) sizeof(arr)/sizeof(*arr)
using namespace std;
int main()
{
// initialise a random vector of adjectives
const string arr[] = {
"awesome",
"cool",
"brilliant",
"incredibely smart",
"absolutely hilarious",
"pretty",
"dirty",
"silly",
"crazy",
"occasionally rude",
"stupid",
"ugly",
"annoying",
"careless",
"lazy",
"smelly",
"disgusting",
"incompetent",
"unsuccessful with girls",
"crazy about computers",
"destructive",
"disrespectfull",
"heavenly",
"gorgeous",
"very pretty",
"horny",
"clumsy"
};
RandomString adjectives(arr, ASIZEOF(arr));
const string arr2[] = { "Greetings", "Hello", "Hi"};
RandomString greetings(arr2, ASIZEOF(arr2));
const string arr3[] = {
"is",
"is never",
"is mostly",
"is very seldomly",
"never does anything",
"always does something",
"sometimes does something",
"is sometimes",
"can be",
"never is",
"always behaves",
"never behaves",
"sometimes behaves",
"does usually act"
};
RandomString verbs(arr3, ASIZEOF(arr3));
const string arr4[] = {
"it is verifiable",
"it happens very often",
"there is a good reason for this",
"there is never a good reason for this",
"everybody says so",
"all the people at school say so",
"it is proven beyond reasonable doubt",
"it is a proven fact",
"it is so obvious",
"it is never that obvious",
"it is written in the holy books",
"the internet says so",
"everybody disapproves",
"most people don't really care",
"everybody cares so much",
"the sun rises every morning",
"the moon never falls from the sky",
"people who landed on Mars said so",
"the Egyptians have carved it in stone",
"a 4 86 is slower than a Pentium",
"Mac OS 10 is better then Windows",
"iOS is better than Android",
"Star Trek beats Star Wars",
"stupid people voted for Donald Trump",
"Brexit"
};
RandomString reasons(arr4, ASIZEOF(arr4));
const string arr5[] = {
"because",
"while",
"if",
"since",
"as"
};
RandomString conjuctions(arr5, ASIZEOF(arr5));
// some variables
string name;
int howMany;
// read in the user's name
cout << "What is your name ? ";
cin >> name;
// read in a number
cout << greetings.getRandomString() << " " << name << ", how many times should I print out an awesome sentence? " << endl;
cin >> howMany;
// loop through a number of times to get a nice printout
for (int i=0; i<howMany; ++i) {
cout
<< name << " "
<< verbs.getRandomString() << " "
<< adjectives.getRandomString() << ", "
<< conjuctions.getRandomString() << " "
<< reasons.getRandomString() << "."
//<< (" << i+1 << ")"
<< endl;
}
return 0;
}
| true |
e8bd34786089053480ab997ed0b250d3b3c28f43 | C++ | TheShip1948/ObserverPattern | /main.cpp | UTF-8 | 712 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "observer.h"
int main() {
// Create Subject
WeatherData *wd = new WeatherData;
// Create Current Conditions Display
CurrentConditions *cd = new CurrentConditions;
// Create Statisitcs Display
StatisticsDisplay *sd = new StatisticsDisplay;
// Register observers
wd->registerObserver(cd);
wd->registerObserver(sd);
// Update weather data
wd->setMeasurements(10, 5, 20);
// Display updates
cd->display();
sd->display();
// Unregister Satistics Display
wd->unregisterObserver(sd);
// Update weather data
wd->setMeasurements(1, 2, 3);
// Display updates
std::cout << "\n \n \n";
cd->display();
sd->display();
}
| true |
1b2b18e179c51b1d541761991ab9e02881a12198 | C++ | BrayanMBeltre/CPP | /For Fun/logintry1.cpp | UTF-8 | 1,484 | 3.734375 | 4 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
void
registro ()
{
//Crear
fstream archivo ("registro.txt");
string nick, email, password;
int op, op2;
//menu
do
{
cout << "1.- Nuevo registro\n2.- Salir\nIntroduzca la opcion deseada: ";
cin >> op;
cin.ignore ();
if (op == 1)
{
//revisar si el archivo esta abierto
if (!archivo.is_open ())
{
archivo.open("registro.txt", fstream::app | fstream::out);
}
cout << "Nombre: ";
getline (cin, nick);
cout << "Email: ";
getline (cin, email);
cout << "Contrasena: ";
getline (cin, password);
cout <<
"1.- Guardar en registro\n2.- Regresar\nIntroduzca la opcion deseada: ";
cin >> op2;
if (op2 == 1)
{
//Guardar en archivo
archivo << "Nombre " << nick << endl;
archivo << "Email: " << email << endl;
archivo << "Contrasena: " << password << endl;
system ("cls");
cout << ("Registro guardado con exito..\n");
system ("pause");
system ("cls");
}
archivo.close ();
}
}
while (op != 2);
}
int
main ()
{
int inicio;
cout << "1.- Registrarse\n2.-Ingresar\n3.-Salir\nIntroduzca la opcion deseada: ";
cin >> inicio;
if (inicio == 1)
{
registro ();
}
else if (inicio == 2)
{
return 2;
}else if (inicio == 3) {
return 3;
}
return 0;
}
| true |
1dea434eb45d05bf066831e71a3150942705af6e | C++ | frustra/glomerate | /include/ecs/HandleImpl.hh | UTF-8 | 931 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
#include "ecs/Handle.hh"
namespace ecs
{
template <typename CompType>
Handle<CompType>::Handle()
: eId(), compPool(nullptr)
{
}
template <typename CompType>
Handle<CompType>::Handle(Entity::Id entityId, ComponentPool<CompType> *componentPool)
: eId(entityId), compPool(componentPool)
{
}
template <typename CompType>
Handle<CompType>::~Handle()
{
}
template <typename CompType>
CompType &Handle<CompType>::operator*() const
{
if (!compPool)
{
throw std::runtime_error("trying to dereference a null Handle!");
}
return *compPool->Get(eId);
}
template <typename CompType>
CompType *Handle<CompType>::operator->() const
{
if (!compPool)
{
throw std::runtime_error("trying to dereference a null Handle!");
}
return compPool->Get(eId);
}
template <typename CompType>
bool Handle<CompType>::operator!() const {
return compPool == nullptr || eId == Entity::Id();
}
} | true |
82cef635b769a12c204c2ab4f5a7b576e84bf1c2 | C++ | ITCGamesProg2/jp21-iz-sh | /JointProject/include/Cell.h | UTF-8 | 1,995 | 3.03125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <SFML/Graphics.hpp>
#include <queue>
class Cell
{
public:
Cell(int t_cellWidth, int t_cellHeight, int t_cellId = -1) : m_id(t_cellId)
{
m_isPassable = true;
findCentreXandCentreY(t_cellWidth, t_cellHeight);
m_cellShape.setSize(sf::Vector2f(t_cellWidth, t_cellHeight));
m_cellShape.setOrigin(m_cellShape.getGlobalBounds().width / 2, m_cellShape.getGlobalBounds().height / 2);
m_cellShape.setPosition(m_centreX, m_centreY);
m_cellShape.setFillColor(sf::Color::Transparent);
m_cellShape.setOutlineThickness(0.5);
m_cellShape.setOutlineColor(sf::Color::Green);
}
void findCentreXandCentreY(int t_cellWidth, int t_cellHeight);
void draw(sf::RenderWindow& t_window);
void update();
static void neighbours(std::vector<Cell>& t_grid);
/// <summary>
/// adds a neighbour
/// </summary>
/// <param name="t_cellId"></param>
void addNeighbour(int t_cellId)
{
m_neighbours.push_back(t_cellId);
}
/// <summary>
/// if sprite is drawn in a cell, marked impassable
/// </summary>
/// <param name="t_imPass"></param>
void setPassable(bool t_imPass)
{
m_isPassable = t_imPass;
}
bool isPassable()
{
return m_isPassable;
}
/// <summary>
/// returns list of neighbours
/// </summary>
/// <returns></returns>
std::vector<int>& neighbours()
{
return m_neighbours;
}
void setMarked(bool t_marked)
{
m_isMarked = t_marked;
}
bool isMarked() const
{
return m_isMarked;
}
int id() const
{
return m_id;
}
void setParentCellId(int t_cellId)
{
m_parentCellId = t_cellId;
}
int getParentCellId()
{
return m_parentCellId;
}
int getCentreX()
{
return m_centreX;
}
int getCentreY()
{
return m_centreY;
}
void colourPath(bool t_onpath)
{
m_onPath = t_onpath;
}
private:
int m_id;
int m_centreX;
int m_centreY;
bool m_isMarked{ false };
bool m_isPassable;
bool m_onPath = false;
std::vector<int> m_neighbours;
int m_parentCellId = -1;
sf::RectangleShape m_cellShape;
};
| true |
01f92f6239b4a6cd9149ae5bcdb510464b4ba253 | C++ | Mehuu26/MES---Metoda-Elementow-Skonczonych | /MES_4.0/MES_4.0/Trzypunktowy_s_c.cpp | UTF-8 | 973 | 3.03125 | 3 | [] | no_license | #pragma once
#include "pch.h"
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
float funkcja(float x, float y) {
return -5 * (x*x)*y + 2 * x*y*y + 10;
}
float oblicz() { //trzypunktowy schemat calkowania
float pc[3] = { -0.77, 0, 0.77 };
//cout << "pc1 = " << pc[0] << endl;
//cout << "pc2 = " << pc[1] << endl;
//cout << "pc3 = " << pc[2] << endl;
//float pc1 = -0.77;
//float pc2 = 0;
//float pc3 = 0.77;
float w[3] = { 5.0 / 9.0, 8.0 / 9.0, 5.0 / 9.0 };
//cout << "w1 = " << w[0] << endl;
//cout << "w2 = " << w[1] << endl;
//cout << "w3 = " << w[2] << endl;
//float w1 = 5.0 / 9.0;
//float w2 = 8.0 / 9.0;
//float w3 = w1;
float wynik = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
wynik += funkcja(pc[i], pc[j]) * w[i] * w[j];
//cout << "wynik = " << wynik << endl;
}
cout << "wynik = " << wynik << endl;
return wynik;
} | true |
5f67226bf9db3b1a1b7efd52e83aedbb32610f98 | C++ | kimduuukbae/Magic-Cat-Academy | /source/Physics.cpp | UTF-8 | 442 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "Physics.h"
#include "Object.h"
bool Physics::isCollide(Object * lhs, Object * rhs){
auto [lx,ly,lz] = lhs->getPosition();
auto[lvx, lvy, lvz] = lhs->getVolume();
auto[rx, ry, rz] = rhs->getPosition();
auto[rvx, rvy, rvz] = rhs->getVolume();
if (lx - lvx / 2 < rx + rvx / 2 &&
lx + lvx / 2 > rx - rvx / 2 &&
ly - lvy / 2 < ry + rvy / 2 &&
ly + lvy / 2 > ry - rvy / 2)
return true;
return false;
} | true |
fb6286d45721de745d1c2977b2f92cde36702c81 | C++ | ioneliabuzatu/fullyConnectedCpp | /include/fc.hpp | UTF-8 | 1,514 | 2.6875 | 3 | [] | no_license | #ifndef __FC__HPP_
#define __FC__HPP_
#include <iostream>
#include <vector>
#include "matrix.hpp"
#include "layer.hpp"
#include "utils/matrix_multiplication.hpp"
using namespace std;
class FC {
public:
FC(vector<int> architecture);
void set_input(vector<double> input);
void set_target(vector<double> target_) {this->target=target_;};
void feed_forward_move();
void back_propagation_move();
void print_model_to_stdout();
void set_errors();
Matrix *get_matrix(int index_) { return this->layers.at(index_)->flatten_matrix_values(); };
Matrix *get_activated_matrix(int index_) { return this->layers.at(index_)->flatten_matrix_activated_values(); };
Matrix *get_derived_matrix(int index_) { return this->layers.at(index_)->flatten_matrix_derivative_values(); };
Matrix *get_weighted_matrices(int layer_index) { return this->weighted_matrices.at(layer_index); };
void set_neuron_value(int layer_index, int neuron_index, double value) {
this->layers.at(layer_index)->set_value(neuron_index, value);
};
double get_total_error() { return this->total_error; };
vector<double> get_errors() { return this->errors; };
private:
vector<int> architecture;
int architecture_size;
vector<Layer *> layers;
vector<Matrix *> weighted_matrices;
vector<Matrix *> gradient_matrix;
vector<double> input;
vector<double> target;
double total_error;
vector<double> errors;
vector<double> errors_history;
};
#endif | true |
ee9c6abb9102ee398810b92e7aed7b08446f7606 | C++ | PhullFury/Random-CPP-Practice-Code | /FINISHED/class.cpp | UTF-8 | 1,001 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
class User
{
std::string status = "Gold";
public:
std::string first_name;
std::string last_name;
std::string get_stauts()
{
return status;
}
};
int add_user_if_not_exists(std::vector<User> &users, User user)
{
for(int i = 0; i < users.size(); i++)
{
if(users[i].first_name == user.first_name &&
users[i].last_name == user.last_name)
{
return i;
}
}
users.push_back(user);
return users.size() - 1;
}
int main()
{
User user1;
user1.first_name = "Harman";
user1.last_name = "Phull";
User user2;
user2.first_name = "Harman";
user2.last_name = "Phull";
User user3;
user3.first_name = "Harman";
user3.last_name = "Phull";
std::vector<User> users;
users.push_back(user1);
std::cout << users[0].first_name << std::endl;
std::cout << "Satuts: " << me.get_stauts();
} | true |
29cdc947d65f25b90efa8cb52051700edb126781 | C++ | Logan-Ashford/CougSat1-Software | /CougSat1-IHU/src/subsystems/ADCS.cpp | UTF-8 | 363 | 2.515625 | 3 | [] | no_license | #include "ADCS.h"
/**
* @brief Construct a new ADCS::ADCS object
*
* @param i2c connected to the ADCS
*/
ADCS::ADCS(I2C & i2c) : i2c(i2c) {}
/**
* @brief Destroy the ADCS::ADCS object
*
*/
ADCS::~ADCS() {}
/**
* @brief Initialize the ADCS
*
* @return mbed_error_status_t
*/
mbed_error_status_t ADCS::initialize() {
return MBED_ERROR_UNSUPPORTED;
} | true |
d73d1990b45bb8492b1e770f0a66a831274766f6 | C++ | semenovf/pfs | /tests/byte_string/test_operations.hpp | UTF-8 | 26,796 | 3.28125 | 3 | [] | no_license | #pragma once
void test_insert ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (insert) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
{
ADD_TESTS(2);
byte_string bs(bs_sample);
TEST_OK(bs.size() > 0)
bs.clear();
TEST_OK(bs.empty());
}
{
ADD_TESTS(20);
byte_string bsb("xmplr");
byte_string bsc("xmplr");
//
// byte_string & insert (size_type index, size_type count, value_type ch)
// byte_string & insert (size_type index, size_type count, char ch)
//
byte_string & bs_ref = bsb.insert(0, 1, value_type('E'));
bs_ref = bsc.insert(0, 1, 'E');
TEST_OK(std::strcmp(bsb.c_str(), "Exmplr") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "Exmplr") == 0);
//
// byte_string & insert (size_type index, const_pointer s)
// byte_string & insert (size_type index, char const * s)
//
char const * e = "e";
bs_ref = bsb.insert(2, reinterpret_cast<const_pointer>(e));
bs_ref = bsc.insert(2, e);
TEST_OK(std::strcmp(bsb.c_str(), "Exemplr") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "Exemplr") == 0);
//
// byte_string & insert (size_type index, const_pointer s, size_type count)
// byte_string & insert (size_type index, char const * s, size_type count)
//
char const * ol = "1.x";
bs_ref = bsb.insert(0, reinterpret_cast<const_pointer>(ol), 2);
bs_ref = bsc.insert(0, ol, 2);
TEST_OK(std::strcmp(bsb.c_str(), "1.Exemplr") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "1.Exemplr") == 0);
//
// byte_string & insert (size_type index, byte_string const & s)
// byte_string & insert (size_type index, std::string const & s)
//
char const * a = "a";
bs_ref = bsb.insert(8, byte_string(a));
bs_ref = bsc.insert(8, std::string(a));
TEST_OK(std::strcmp(bsb.c_str(), "1.Exemplar") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "1.Exemplar") == 0);
//
// basic_string & insert (size_type index, basic_string const & str
// , size_type index_str, size_type count)
// basic_string & insert (size_type index, std::string const & str
// , size_type index_str, size_type count)
//
char const * suffix = "xxx is an example string.";
bs_ref = bsb.insert(10, byte_string(suffix), 3, 14);
bs_ref = bsc.insert(10, std::string(suffix), 3, 14);
TEST_OK(std::strcmp(bsb.c_str(), "1.Exemplar is an example") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "1.Exemplar is an example") == 0);
//
// iterator insert (const_iterator pos, value_type ch)
// iterator insert (const_iterator pos, char ch)
//
iterator itb = bsb.insert(bsb.cend(), value_type('.'));
iterator itc = bsc.insert(bsc.cend(), '.');
TEST_OK(std::strcmp(bsb.c_str(), "1.Exemplar is an example.") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "1.Exemplar is an example.") == 0);
//
// iterator insert (const_iterator pos, size_type count, value_type ch)
// iterator insert (const_iterator pos, size_type count, char ch)
//
itb = bsb.insert(bsb.cend(), 3, value_type('!'));
itc = bsc.insert(bsc.cend(), 3, '!');
TEST_OK(std::strcmp(bsb.c_str(), "1.Exemplar is an example.!!!") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "1.Exemplar is an example.!!!") == 0);
TEST_OK(itb == bsb.begin() + 25);
TEST_OK(itc == bsc.begin() + 25);
//
// iterator insert (const_iterator pos, InputIt first, InputIt last)
//
std::string dash(" ---");
itb = bsb.insert(bsb.cbegin() + 10, dash.begin(), dash.end());
itc = bsc.insert(bsc.cbegin() + 10, dash.begin(), dash.end());
TEST_OK(std::strcmp(bsb.c_str(), "1.Exemplar --- is an example.!!!") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "1.Exemplar --- is an example.!!!") == 0);
TEST_OK(itb == bsb.begin() + 10);
TEST_OK(itc == bsc.begin() + 10);
#if PFS_COMPILER_CXX_GENERALIZED_INITIALIZERS
//
// iterator insert (const_iterator pos, std::initializer_list<value_type> ilist)
// iterator insert (const_iterator pos, std::initializer_list<char> ilist)
//
ADD_TESTS(4);
bsb = "abcghi";
bsc = "abcghi";
itb = bsb.insert(bsb.cbegin() + 3, {value_type('d'), value_type('e'), value_type('f')});
itc = bsc.insert(bsc.cbegin() + 3, {'d', 'e', 'f'});
TEST_OK(std::strcmp(bsb.c_str(), "abcdefghi") == 0);
TEST_OK(std::strcmp(bsc.c_str(), "abcdefghi") == 0);
TEST_OK(itb == bsb.begin() + 3);
TEST_OK(itc == bsc.begin() + 3);
#endif
}
}
void test_erase ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (erase) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(6);
//
// byte_string & erase (size_type index = 0, size_type count = npos)
//
byte_string bs("This is an example");
byte_string & bs_ref = bs.erase(0, 5);
TEST_OK(std::strcmp(bs.c_str(), "is an example") == 0);
bs_ref = bs.erase(5);
TEST_OK(std::strcmp(bs_ref.c_str(), "is an") == 0);
//
// iterator erase (const_iterator pos)
//
iterator it = bs.erase(bs.cbegin() + 2);
TEST_OK(std::strcmp(bs.c_str(), "isan") == 0);
TEST_OK(it == bs.cbegin() + 2);
//
// iterator erase (const_iterator first, const_iterator last)
//
it = bs.erase(bs.cbegin() + 1, bs.cbegin() + 3);
TEST_OK(std::strcmp(bs.c_str(), "in") == 0);
TEST_OK(it == bs.cbegin() + 1);
}
void test_push_back ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (push_back) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(1);
byte_string bs;
bs.push_back('H');
bs.push_back('e');
bs.push_back('l');
bs.push_back(value_type('l'));
bs.push_back(value_type('o'));
TEST_OK(std::strcmp(bs.c_str(), "Hello") == 0);
}
void test_pop_back ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (pop_back) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(8);
byte_string bs("Hello");
TEST_OK(std::strcmp(bs.c_str(), "Hello") == 0);
bs.pop_back();
TEST_OK(std::strcmp(bs.c_str(), "Hell") == 0);
bs.pop_back();
TEST_OK(std::strcmp(bs.c_str(), "Hel") == 0);
bs.pop_back();
TEST_OK(std::strcmp(bs.c_str(), "He") == 0);
bs.pop_back();
TEST_OK(std::strcmp(bs.c_str(), "H") == 0);
bs.pop_back();
TEST_OK(std::strcmp(bs.c_str(), "") == 0);
TEST_OK(bs.empty());
bs.pop_back();
TEST_OK(bs.empty());
}
void test_append ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (append) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
{
ADD_TESTS(1);
byte_string bs;
//
// byte_string & append (size_type count, value_type ch)
// byte_string & append (size_type count, char ch)
//
byte_string & bs_ref = bs.append(1, value_type('H'));
bs_ref = bs.append(1, 'e');
//
// byte_string & append (byte_string const & s)
// byte_string & append (std::string const & s)
//
bs_ref = bs.append(byte_string("l"));
bs_ref = bs.append(std::string("l"));
//
// byte_string & append (byte_string const & s, size_type pos, size_type count = npos)
// byte_string & append (std::string const & s, size_type pos, size_type count = npos)
//
bs_ref = bs.append(byte_string("oops, "), 1, 1);
bs_ref = bs.append(std::string("oops, "), 4, 2);
//
// byte_string & append (const_pointer s, size_type count)
// byte_string & append (const char * s, size_type count)
//
char const * chars = "World";
const_pointer bytes = reinterpret_cast<const_pointer>(chars);
bs_ref = bs.append(bytes, 2);
bs_ref = bs.append(chars + 2, 2);
//
// byte_string & append (const_pointer s)
// byte_string & append (const char * s)
//
chars = "d";
bytes = reinterpret_cast<const_pointer>(chars);
chars = "!";
bs_ref = bs.append(bytes);
bs_ref = bs.append(chars);
//
// template <typename InputIterator>
// byte_string & append (InputIterator first, InputIterator last)
//
std::string s("--- And Bye!---");
bs_ref = bs.append(s.begin() + 3, s.end() - 3);
TEST_OK(std::strcmp(bs.c_str(), "Hello, World! And Bye!") == 0);
#if PFS_COMPILER_CXX_GENERALIZED_INITIALIZERS
//
// byte_string & append (std::initializer_list<value_type> ilist)
// byte_string & append (std::initializer_list<char> ilist)
//
ADD_TESTS(1);
bs.clear();
bs_ref = bs.append({value_type('a'), value_type('b'), value_type('c')});
bs_ref = bs.append({'d', 'e', 'f'});
TEST_OK(std::strcmp(bs.c_str(), "abcdef") == 0);
#endif
}
{
ADD_TESTS(1);
byte_string bs;
//
// byte_string & operator += (byte_string const & s)
// byte_string & operator += (std::string const & s)
//
byte_string & bs_ref = bs += byte_string("Hel");
bs_ref = bs += std::string("lo");
//
// byte_string & operator += (value_type ch)
// byte_string & operator += (char ch)
//
bs_ref = bs += value_type(',');
bs_ref = bs += ' ';
//
// byte_string & operator += (const_pointer s)
// operator += (const char * s)
//
char const * chars = "Wor";
const_pointer bytes = reinterpret_cast<const_pointer>(chars);
bs_ref = bs += bytes;
bs_ref = bs += "ld!";
//TEST_OK(std::strcmp(bs.c_str(), "Hello, World! And Bye!") == 0);
TEST_OK(std::strcmp(bs.c_str(), "Hello, World!") == 0);
#if PFS_COMPILER_CXX_GENERALIZED_INITIALIZERS
ADD_TESTS(1);
bs.clear();
//
// byte_string & operator += (std::initializer_list<value_type> ilist)
// byte_string & operator += (std::initializer_list<char> ilist)
//
bs_ref = bs.append({value_type('a'), value_type('b'), value_type('c')});
bs_ref = bs.append({'d', 'e', 'f'});
TEST_OK(std::strcmp(bs.c_str(), "abcdef") == 0);
#endif
}
}
void test_compare ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (compare) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(35);
//
// int compare (byte_string const & s) const
//
byte_string bs("12345678");
byte_string bs_equal("12345678");
byte_string bs_less("012345678");
byte_string bs_greater("2345678");
TEST_OK(bs.compare(bs_equal) == 0);
TEST_OK(bs.compare(bs_less) > 0);
TEST_OK(bs.compare(bs_less) >= 0);
TEST_OK(bs.compare(bs_greater) < 0);
TEST_OK(bs.compare(bs_greater) <= 0);
//
// int compare (size_type pos1, size_type count1, byte_string const & s) const
//
TEST_OK(bs.compare(0, 8, bs_equal) == 0);
TEST_OK(bs.compare(0, 8, bs_less) > 0);
TEST_OK(bs.compare(0, 8, bs_less) >= 0);
TEST_OK(bs.compare(0, 8, bs_greater) < 0);
TEST_OK(bs.compare(0, 8, bs_greater) <= 0);
//
// int compare (size_type pos1, size_type count1
// , byte_string const & s
// , size_type pos2, size_type count2 = npos) const
//
TEST_OK(bs.compare(0, 8, bs_equal, 0) == 0);
TEST_OK(bs.compare(0, 8, bs_less, 0) > 0);
TEST_OK(bs.compare(0, 8, bs_less, 0) >= 0);
TEST_OK(bs.compare(0, 8, bs_greater, 0) < 0);
TEST_OK(bs.compare(0, 8, bs_greater, 0) <= 0);
TEST_OK(bs.compare(0, 8, bs_equal, 0, 8) == 0);
TEST_OK(bs.compare(0, 8, bs_less, 0, 9) > 0);
TEST_OK(bs.compare(0, 8, bs_less, 0, 9) >= 0);
TEST_OK(bs.compare(0, 8, bs_greater, 0, 7) < 0);
TEST_OK(bs.compare(0, 8, bs_greater, 0, 7) <= 0);
//
// int compare (const_pointer s) const
//
TEST_OK(bs.compare(bs_equal.data()) == 0);
TEST_OK(bs.compare(bs_less.data()) > 0);
TEST_OK(bs.compare(bs_less.data()) >= 0);
TEST_OK(bs.compare(bs_greater.data()) < 0);
TEST_OK(bs.compare(bs_greater.data()) <= 0);
//
// int compare (size_type pos1, size_type count1, const_pointer s) const
//
TEST_OK(bs.compare(0, 8, bs_equal.data()) == 0);
TEST_OK(bs.compare(0, 8, bs_less.data()) > 0);
TEST_OK(bs.compare(0, 8, bs_less.data()) >= 0);
TEST_OK(bs.compare(0, 8, bs_greater.data()) < 0);
TEST_OK(bs.compare(0, 8, bs_greater.data()) <= 0);
//
// int compare (size_type pos1, size_type count1, const_pointer s, size_type count2) const
//
TEST_OK(bs.compare(0, 8, bs_equal.data(), 8) == 0);
TEST_OK(bs.compare(0, 8, bs_less.data(), 9) > 0);
TEST_OK(bs.compare(0, 8, bs_less.data(), 9) >= 0);
TEST_OK(bs.compare(0, 8, bs_greater.data(), 7) < 0);
TEST_OK(bs.compare(0, 8, bs_greater.data(), 7) <= 0);
//
// Compare operators ==, !=, < , <= , >, >=
//
ADD_TESTS(36);
TEST_OK(bs == bs_equal);
TEST_OK(bs != bs_less);
TEST_OK(bs > bs_less);
TEST_OK(bs >= bs_less);
TEST_OK(bs < bs_greater);
TEST_OK(bs <= bs_greater);
TEST_OK(bs == bs_equal.data());
TEST_OK(bs != bs_less.data());
TEST_OK(bs > bs_less.data());
TEST_OK(bs >= bs_less.data());
TEST_OK(bs < bs_greater.data());
TEST_OK(bs <= bs_greater.data());
TEST_OK(bs == "12345678");
TEST_OK(bs != "012345678");
TEST_OK(bs > "012345678");
TEST_OK(bs >= "012345678");
TEST_OK(bs < "2345678");
TEST_OK(bs <= "2345678");
TEST_OK("12345678" == bs);
TEST_OK("012345678" != bs);
TEST_OK("012345678" < bs );
TEST_OK("012345678" <= bs);
TEST_OK("2345678" > bs);
TEST_OK("2345678" >= bs);
TEST_OK(bs == std::string("12345678"));
TEST_OK(bs != std::string("012345678"));
TEST_OK(bs > std::string("012345678"));
TEST_OK(bs >= std::string("012345678"));
TEST_OK(bs < std::string("2345678"));
TEST_OK(bs <= std::string("2345678"));
TEST_OK(std::string("12345678") == bs);
TEST_OK(std::string("012345678") != bs);
TEST_OK(std::string("012345678") < bs );
TEST_OK(std::string("012345678") <= bs);
TEST_OK(std::string("2345678") > bs);
TEST_OK(std::string("2345678") >= bs);
}
void test_starts_with ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (starts_with) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(12);
byte_string bs("0123456789");
//
// bool starts_with (byte_string const & rhs) const
//
TEST_OK(bs.starts_with(byte_string("0")));
TEST_OK(bs.starts_with(byte_string("0123")));
TEST_OK(bs.starts_with(byte_string("0123456789")));
TEST_OK(!bs.starts_with(byte_string("1")));
TEST_OK(!bs.starts_with(byte_string("123456789")));
//
// bool starts_with (value_type ch) const
//
TEST_OK(bs.starts_with(value_type('0')));
TEST_OK(!bs.starts_with(value_type('1')));
//
// bool starts_with (const_pointer s) const
//
TEST_OK(bs.starts_with(byte_string("0").data()));
TEST_OK(bs.starts_with(byte_string("0123").data()));
TEST_OK(bs.starts_with(byte_string("0123456789").data()));
TEST_OK(!bs.starts_with(byte_string("1").data()));
TEST_OK(!bs.starts_with(byte_string("123456789").data()));
}
void test_ends_with ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (ends_with) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(12);
byte_string bs("0123456789");
//
// bool ends_with (byte_string const & rhs) const
//
TEST_OK(bs.ends_with(byte_string("9")));
TEST_OK(bs.ends_with(byte_string("6789")));
TEST_OK(bs.ends_with(byte_string("0123456789")));
TEST_OK(!bs.ends_with(byte_string("0")));
TEST_OK(!bs.ends_with(byte_string("689")));
//
// bool ends_with (value_type ch) const
//
TEST_OK(bs.ends_with(value_type('9')));
TEST_OK(!bs.ends_with(value_type('1')));
//
// bool ends_with (const_pointer s) const
//
TEST_OK(bs.ends_with(byte_string("9").data()));
TEST_OK(bs.ends_with(byte_string("6789").data()));
TEST_OK(bs.ends_with(byte_string("0123456789").data()));
TEST_OK(!bs.ends_with(byte_string("0").data()));
TEST_OK(!bs.ends_with(byte_string("689").data()));
}
void test_replace ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (replace) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(11);
byte_string sample("The quick brown fox jumps over the lazy dog.");
char const * result = "The quick red fox jumps over the lazy dog.";
//
// byte_string & replace (size_type pos, size_type count, byte_string const & s)
//
byte_string bs(sample);
byte_string & bs_ref = bs.replace(10, 5, byte_string("red"));
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (size_type pos\n\t, size_type count\n\t, byte_string const & s)");
//
// byte_string & replace (const_iterator first, const_iterator last, byte_string const & s)
//
bs = sample;
bs_ref = bs.replace(bs.cbegin() + 10, bs.cbegin() + 15, byte_string("red"));
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (const_iterator first\n\t, const_iterator last\n\t, byte_string const & s)");
//
// byte_string & replace (size_type pos, size_type count
// , byte_string const & s
// , size_type pos2, size_type count2 = npos)
//
bs = sample;
bs_ref = bs.replace(10, 5, byte_string("quick red fox"), 6, 3);
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (size_type pos"
"\n\t, size_type count"
"\n\t, byte_string const & s"
"\n\t, size_type pos2"
"\n\t, size_type count2)");
bs = sample;
bs_ref = bs.replace(10, 5, byte_string("quick red"), 6);
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (size_type pos"
"\n\t, size_type count"
"\n\t, byte_string const & s"
"\n\t, size_type pos2"
"\n\t, size_type count2 = npos)");
//
// template <typename InputIterator>
// byte_string & replace (const_iterator first, const_iterator last
// , InputIterator first2, InputIterator last2)
//
bs = sample;
std::string str("red");
bs_ref = bs.replace(bs.cbegin() + 10, bs.cbegin() + 15, str.begin(), str.end());
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "template <typename InputIterator>"
"\n\tbyte_string & replace (const_iterator first"
"\n\t\t, const_iterator last"
"\n\t\t, InputIterator first2"
"\n\t\t, InputIterator last2)");
//
// byte_string & replace (size_type pos, size_type count, const_pointer s, size_type count2)
//
bs = sample;
byte_string bs1("red fox");
bs_ref = bs.replace(10, 5, bs1.data(), 3);
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (size_type pos"
"\n\t, size_type count"
"\n\t, const_pointer s"
"\n\t, size_type count2)");
//
// byte_string & replace (const_iterator first, const_iterator last, const_pointer s, size_type count2)
//
bs = sample;
bs1 = "red fox";
bs_ref = bs.replace(bs.cbegin() + 10, bs.cbegin() + 15, bs1.data(), 3);
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (const_iterator first"
"\n\t, const_iterator last"
"\n\t, const_pointer s"
"\n\t, size_type count2)");
//
// byte_string & replace (size_type pos, size_type count, const_pointer s)
//
bs = sample;
bs1 = "red";
bs_ref = bs.replace(10, 5, bs1.data());
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (size_type pos"
"\n\t, size_type count"
"\n\t, const_pointer s)");
//
// byte_string & replace (const_iterator first, const_iterator last, const_pointer s)
//
bs = sample;
bs1 = "red";
bs_ref = bs.replace(bs.cbegin() + 10, bs.cbegin() + 15, bs1.data(), 3);
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (const_iterator first"
"\n\t, const_iterator last"
"\n\t, const_pointer s)");
//
// byte_string & replace (size_type pos, size_type count, size_type count2, value_type ch)
//
bs = sample;
bs_ref = bs.replace(10, 5, 3, value_type('r'));
bs_ref = bs.replace(11, 2, 2, value_type('e'));
bs_ref = bs.replace(12, 1, 1, value_type('d'));
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (size_type pos"
"\n\t, size_type count"
"\n\t, size_type count2"
"\n\t, value_type ch)");
//
// byte_string & replace (const_iterator first, const_iterator last, size_type count2, value_type ch)
//
bs = sample;
bs_ref = bs.replace(bs.cbegin() + 10, bs.cbegin() + 15, 3, value_type('r'));
bs_ref = bs.replace(bs.cbegin() + 11, bs.cbegin() + 13, 2, value_type('e'));
bs_ref = bs.replace(bs.cbegin() + 12, bs.cbegin() + 13, 1, value_type('d'));
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (const_iterator first"
"\n\t, const_iterator last"
"\n\t, size_type count2"
"\n\t, value_type ch)");
#if PFS_COMPILER_CXX_GENERALIZED_INITIALIZERS
ADD_TESTS(1)
//
// basic_string & replace (const_iterator first, const_iterator last
// , initializer_list<value_type> ilist)
//
bs = sample;
bs_ref = bs.replace(bs.cbegin() + 10, bs.cbegin() + 15
, { value_type('r'), value_type('e'), value_type('d') });
TEST_OK2(std::strcmp(bs_ref.c_str(), result) == 0
, "byte_string & replace (const_iterator first"
"\n\t, const_iterator last"
"\n\t, initializer_list<value_type> ilist)");
#endif
}
void test_substr ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (substr) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(4);
byte_string bs("0123456789abcdefghij");
TEST_OK(bs.substr() == bs);
TEST_OK(bs.substr(10) == byte_string("abcdefghij"));
TEST_OK(bs.substr(5, 3) == byte_string("567"));
TEST_OK(bs.substr(bs.size() - 3, 50) == byte_string("hij"));
}
void test_copy ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (copy) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(2);
char const * chars = "__cplusplus";
byte_string bs(chars);
value_type bytes[20];
TEST_OK(bs.size() == bs.copy(bytes, sizeof(bytes)));
bytes[bs.size()] = '\x0';
TEST_OK(std::strcmp(chars, reinterpret_cast<char const *>(bytes)) == 0);
}
void test_resize ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (resize) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(4);
byte_string bs_long("This is a vary long string");
byte_string bs_short("short string");
bs_long.resize(9);
TEST_OK(bs_long.size() == 9);
TEST_OK(std::strcmp(bs_long.c_str(), "This is a") == 0);
bs_short.resize(15, '-');
TEST_OK(bs_short.size() == 15);
TEST_OK(std::strcmp(bs_short.c_str(), "short string---") == 0);
}
void test_swap ()
{
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
std::cout << "// Operations (swap) //\n";
std::cout << "///////////////////////////////////////////////////////////////////////////\n";
ADD_TESTS(4);
byte_string a("AAA");
byte_string b("BBB");
TEST_OK(std::strcmp(a.c_str(), "AAA") == 0)
TEST_OK(std::strcmp(b.c_str(), "BBB") == 0)
a.swap(b);
TEST_OK(std::strcmp(a.c_str(), "BBB") == 0)
TEST_OK(std::strcmp(b.c_str(), "AAA") == 0)
}
void test_operations ()
{
test_insert();
test_erase();
test_push_back();
test_pop_back();
test_append();
test_compare();
test_starts_with();
test_ends_with();
test_replace();
test_substr();
test_copy();
test_resize();
test_swap();
}
| true |
babb8170e1ada24c17ac4f8e3c0e21269e137c62 | C++ | osphea/zircon-rpi | /src/storage/fs_test/dot_dot.cc | UTF-8 | 4,977 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "src/storage/fs_test/fs_test_fixture.h"
#include "src/storage/fs_test/misc.h"
namespace fs_test {
namespace {
using DotDotTest = FilesystemTest;
// Test cases of '..' where the path can be canonicalized on the client.
TEST_P(DotDotTest, DotDotClient) {
ASSERT_EQ(mkdir(GetPath("foo").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bit").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bar").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bar/baz").c_str(), 0755), 0);
ExpectedDirectoryEntry foo_dir[] = {
{".", DT_DIR},
{"bar", DT_DIR},
{"bit", DT_DIR},
};
ExpectedDirectoryEntry bar_dir[] = {
{".", DT_DIR},
{"baz", DT_DIR},
};
// Test cases of client-side dot-dot when moving between directories.
DIR* dir = opendir(GetPath("foo/bar/..").c_str());
ASSERT_NE(dir, nullptr);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(dir, foo_dir));
ASSERT_EQ(closedir(dir), 0);
dir = opendir(GetPath("foo/bar/../bit/..//././//").c_str());
ASSERT_NE(dir, nullptr);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(dir, foo_dir));
ASSERT_EQ(closedir(dir), 0);
dir = opendir(GetPath("foo/bar/baz/../../../foo/bar/baz/..").c_str());
ASSERT_NE(dir, nullptr);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(dir, bar_dir));
ASSERT_EQ(closedir(dir), 0);
// Clean up
ASSERT_EQ(unlink(GetPath("foo/bar/baz").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo/bar").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo/bit").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo").c_str()), 0);
}
// Test cases of '..' where the path cannot be canonicalized on the client.
TEST_P(DotDotTest, DotDotServer) {
ASSERT_EQ(mkdir(GetPath("foo").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bar").c_str(), 0755), 0);
int foo_fd = open(GetPath("foo").c_str(), O_RDONLY | O_DIRECTORY);
ASSERT_GT(foo_fd, 0);
// ".." from foo --> Not Supported
ASSERT_LT(openat(foo_fd, "..", O_RDONLY | O_DIRECTORY), 0);
// "bar/../.." from foo --> Not supported
ASSERT_LT(openat(foo_fd, "bar/../..", O_RDONLY | O_DIRECTORY), 0);
// "../../../../../bar" --> Not supported
ASSERT_LT(openat(foo_fd, "../../../../../bar", O_RDONLY | O_DIRECTORY), 0);
// Try to create a file named '..'
ASSERT_LT(openat(foo_fd, "..", O_RDWR | O_CREAT), 0);
ASSERT_LT(openat(foo_fd, ".", O_RDWR | O_CREAT), 0);
// Try to create a directory named '..'
ASSERT_LT(mkdirat(foo_fd, "..", 0666), 0);
ASSERT_LT(mkdirat(foo_fd, ".", 0666), 0);
// Clean up
ASSERT_EQ(close(foo_fd), 0);
ASSERT_EQ(unlink(GetPath("foo/bar").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo").c_str()), 0);
}
// Test cases of '..' which operate on multiple paths.
// This is mostly intended to test other pathways for client-side
// cleaning operations.
TEST_P(DotDotTest, DotDotRename) {
ASSERT_EQ(mkdir(GetPath("foo").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bit").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bar").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("foo/bar/baz").c_str(), 0755), 0);
ExpectedDirectoryEntry foo_dir_bit[] = {
{".", DT_DIR},
{"bar", DT_DIR},
{"bit", DT_DIR},
};
ExpectedDirectoryEntry foo_dir_bits[] = {
{".", DT_DIR},
{"bar", DT_DIR},
{"bits", DT_DIR},
};
// Check that the source is cleaned
ASSERT_EQ(rename(GetPath("foo/bar/./../bit/./../bit").c_str(), GetPath("foo/bits").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(GetPath("foo").c_str(), foo_dir_bits));
// Check that the destination is cleaned
ASSERT_EQ(rename(GetPath("foo/bits").c_str(), GetPath("foo/bar/baz/../../././bit").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(GetPath("foo").c_str(), foo_dir_bit));
// Check that both are cleaned
ASSERT_EQ(rename(GetPath("foo/bar/../bit/.").c_str(), GetPath("foo/bar/baz/../../././bits").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(GetPath("foo").c_str(), foo_dir_bits));
// Check that both are cleaned (including trailing '/')
ASSERT_EQ(rename(GetPath("foo/./bar/../bits/").c_str(), GetPath("foo/bar/baz/../../././bit/.//").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckDirectoryContents(GetPath("foo").c_str(), foo_dir_bit));
// Clean up
ASSERT_EQ(unlink(GetPath("foo/bar/baz").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo/bar").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo/bit").c_str()), 0);
ASSERT_EQ(unlink(GetPath("foo").c_str()), 0);
}
INSTANTIATE_TEST_SUITE_P(/*no prefix*/, DotDotTest, testing::ValuesIn(AllTestFilesystems()),
testing::PrintToStringParamName());
} // namespace
} // namespace fs_test
| true |
9e92a8b0fc6e8263adfa7f442eee1e33ba2ecb62 | C++ | andrewhle/2sem | /test.cpp | UTF-8 | 2,269 | 3.3125 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct stud
{
string name; // имя
int group; //номер группы
int grades[5]; //оценки
int stipend; //стипендия
stud *next;
};
struct group
{
stud *begin = NULL; //указатель на начало списка студентов группы
group* nextgr = NULL; //следующая группа
int count = 0; //количество студентов в группе
int num = 0; //номер группы
};
struct idz
{
int stipend = 0;
stud *begin = NULL;
idz *nextgr = NULL;
};
group *beging = NULL;
void idzfunc(group *gr)
{
idz *beginidz = new idz;
beginidz->begin = gr->begin;
beginidz->stipend = gr->begin->stipend;
idz *idzgr = beginidz;
while(gr != NULL)
{
unsigned int step;
stud* st = gr->begin;
while(st != NULL)
{
step = st->stipend;
while(idzgr != NULL)
{
stud *idzst = beginidz->begin;
while(idzst != NULL)
{
if(step == idzgr->stipend)
{
if(idzst->next == NULL) idzst->next = new stud;
idzst->next = st;
}
idzst = idzst->next;
}
idzgr = idzgr->nextgr;
}
st = st->next;
}
gr = gr->nextgr;
}
}
void idzfunc(group *gr)
{
idz *beginidz = new idz;
beginidz->begin = gr->begin;
beginidz->stipend = gr->begin->stipend;
idz *idzgr = beginidz;
while(gr != NULL)
{
stud* st = gr->begin;
while(st != NULL)
{
unsigned int step = st->stipend;
if(step == idzgr->stipend)
{
stud *k = idzgr->begin->next;
while(k != NULL)
{
k = k->next;
}
if(k == NULL) k = new stud;
k = st;
}
st = st->next;
}
gr = gr->nextgr;
}
}
int main()
{
group *begin;
getchar();
cout << "Введите имя: ";
group *p = new group;
idzfunc(begin);
} | true |
f37a22b23d62fa86dc7b015c4605f5371fdddf79 | C++ | vvbetter/P1 | /CommonLib/ConfigManager.cpp | GB18030 | 2,024 | 2.59375 | 3 | [] | no_license | #include "stdafx.h"
#include "ConfigManager.h"
#include<iostream>
#include<boost/property_tree/ptree.hpp>
#include<boost/property_tree/json_parser.hpp>
#include<boost/filesystem.hpp>
using namespace boost::filesystem;
using namespace boost::property_tree;
ConfigManager* ConfigManager::GetInstance()
{
static ConfigManager manager;
return& manager;
}
ConfigManager::ConfigManager()
{
}
ConfigManager::~ConfigManager()
{
}
bool ConfigManager::ParseConfigFile(int serverId, const std::string & cfgFile)
{
boost::filesystem::path filePath(cfgFile);
if (is_regular_file(filePath))
{
try
{
ptree rootNode;
read_json(cfgFile, rootNode);
for (auto it = rootNode.begin(); it != rootNode.end(); ++it)
{
int cfgId = atoi(it->first.c_str());
if (cfgId != serverId)
{
continue;
}
auto& cfg = it->second;
ServerConfig config;
config.name = cfg.get<std::string>("name");
auto& TcpServer = cfg.get_child("TcpServer");
for (auto it = TcpServer.begin(); it != TcpServer.end(); ++it)
{
ServerInfo info;
info.ip = it->second.get<std::string>("ip");
info.uProt = it->second.get<uint32_t>("port");
config.tcpServer.push_back(info);
}
auto& TcpClient = cfg.get_child("TcpClient");
for (auto it = TcpClient.begin(); it != TcpClient.end(); ++it)
{
ServerInfo info;
info.ip = it->second.get<std::string>("ip");
info.uProt = it->second.get<uint32_t>("port");
config.tcpClient.push_back(info);
}
_cfg[cfgId] = config;
}
}
catch (ptree_error& e)
{
std::cout << "ļ" << e.what() << std::endl;
return false;
}
catch (...)
{
std::cout << "ParseConfigFile Error" << std::endl;
return false;
}
}
else
{
std::cout << "ļڣ" << cfgFile << std::endl;
return false;
}
return true;
}
const ServerConfig* ConfigManager::GetServerCfg()
{
assert(_cfg.size() == 1);
if (_cfg.size() != 1)
{
return NULL;
}
return &(_cfg.begin()->second);
}
| true |
8ad97706bd78c790171a60989d22f608d3eea4a4 | C++ | khanhdk0000/car-rental | /CarRentalManagement.cpp | UTF-8 | 10,438 | 3.03125 | 3 | [] | no_license | #include "CarRentalManagement.h"
using namespace std;
CarRentalManagement::CarRentalManagement(Vehicle* &veh)
{
arrVeh.push_back(veh);
}
int CarRentalManagement::getnumCar()
{
return arrVeh.size();
}
void CarRentalManagement::addVehicle(string ID, string brand, int cost,int trunkCap)
{
Vehicle* pVeh = new Sedan(ID, brand, cost, trunkCap);
arrVeh.push_back(pVeh);
}
void CarRentalManagement::addVehicle(string ID, string brand, int cost, int width, int length, int height)
{
Vehicle* pVeh = new PickUp(ID, brand, cost, width, length, height);
arrVeh.push_back(pVeh);
}
void CarRentalManagement::addVehicle(string ID, string brand, int cost, bool isFour)
{
Vehicle* pVeh = new SUV(ID, brand, cost, isFour);
arrVeh.push_back(pVeh);
}
void CarRentalManagement::ServiceFleet()
{
size_t num = arrVeh.size();
int preMile, curMile;
int choice;
for(int i = 0; i < num; i++)
{
arrVeh[i]->printDetail();
cout << "Enter your previous mile: ";
cin >> preMile;
cout << "Enter your current mile: ";
cin >> curMile;
if(curMile - preMile >= 3000)
{
cout << "Enter 1 for Engine Service, 2 for Transmission Service, 3 for Tire Service: ";
cin >> choice;
if(choice == 1)
{
arrVeh[i]->serviceEngine();
}
else if(choice == 2)
{
arrVeh[i]->serviceTransmission();
}
else if(choice == 3)
{
arrVeh[i]->serviceTires();
}
else cout << "Invalid choice." << endl;
}
else cout << "This vehicle is still functioning properly, no need for prepare." << endl;
cout << "\n/////////////////////////////\n\n";
}
}
int CarRentalManagement::Booking()
{
cout << "\n*****Welcome to booking service*****\n";
string tem_id, name, vehicle_id, user_date;
int size_num = contract.size(), size_num2;
int idx = -1, idx_veh = -1;
bool is_found1 = false, is_found2 = false, is_found3 = false, already_book = false;
cout << "Please enter your name: ";
while(true)
{
cin.clear();
cin.ignore();
getline(cin, name);
for(unsigned i = 0; i < size_num; i++)
{
if(contract[i]->GetUserName() == name)
{
idx = i;
is_found1 = true;
break;
}
}
if(is_found1)
{
break;
}
else
{
cout << "\nYour name does not exit in the database, please enter again: ";
}
}
cout << "\nEnter the ID you have entered when creating contract: ";
while(true)
{
cin >> tem_id;
if(contract[idx]->GetUserId() == tem_id)
{
is_found2 = true;
cout << "\n----Welcome back----\n";
}
if(is_found2)
break;
else cout << "\nPlease enter your id again: ";
}
int size_veh = contract[idx]->GetNumCar();
for(int k = 0; k < size_veh;k++)
{
if(contract[idx]->GetIfBooked(k))
{
cout << "You have already booked a vehicle, please return next time.\n";
already_book = true;
break;
}
}
if(!already_book)
{
cout << "Enter id of the vehicle you want to book: ";
while(true)
{
size_num2 = contract[idx]->GetNumCar();
cin >> vehicle_id;
for(unsigned i = 0; i < size_num2; i++)
{
if(contract[idx]->GetVehicleID(i)== vehicle_id)
{
idx_veh = i;
is_found3 = true;
break;
}
}
if(is_found3)
break;
cout << "\nPlease enter vehicle id again: ";
}
cout << "Enter the date you want to book(dd/mm/yyyy): ";
cin >> user_date;
contract[idx]->SetBookDate(user_date);
contract[idx]->SetIsBooked(idx_veh);
//contract[idx]->SetNotAvailable(idx_veh);
}
cout << "\n----------------------------\n";
if(already_book)
{
int userID
cin >> userID;
return userID;
}else return -1;
}
int CarRentalManagement::Renting()
{
cout << "\n*****Welcome to renting service*****\n";
string tem_id, name, vehicle_id;
int size_num = contract.size();
int idx = -1, idx_veh = -1;
bool is_found1 = false, is_found2 = false, is_found3 = false, already_rent = false;
cout << "Please enter your name: ";
while(true)
{
cin.clear();
cin.ignore();
getline(cin, name);
for(unsigned i = 0; i < size_num; i++)
{
if(contract[i]->GetUserName() == name)
{
idx = i;
is_found1 = true;
break;
}
}
if(is_found1)
{
break;
}
else
{
cout << "\nYour name does not exit in the database, please enter again: ";
}
}
cout << "\nEnter the ID you have entered when creating contract: ";
while(true)
{
cin >> tem_id;
if(contract[idx]->GetUserId() == tem_id)
{
is_found2 = true;
cout << "\n----Welcome back----\n";
}
if(is_found2)
break;
else cout << "\nPlease enter your id again: ";
}
int size_veh = contract[idx]->GetNumCar();
for(int k = 0; k < size_veh;k++)
{
if(!contract[idx]->GetRentStatus(k))
{
cout << "You have already rented a vehicle, please return next time.\n";
already_rent = true;
break;
}
}
if(!already_rent)
{
int size_num2 = contract[idx]->GetNumCar();
for(unsigned i = 0; i < size_num2; i++)
{
if(contract[idx]->GetIfBooked(i))
{
idx_veh = i;
is_found3 = true;
break;
}
}
if(is_found3)
{
bool is_agree = false, is_paid = false;
string decision, paid;
cout << "You have booked this vehicle on: ";
contract[idx]->PrintBookDate();
contract[idx]->PrintVehicle(idx_veh);
cout << "Would you wish to take this vehicle?(Enter yes or no)";
cin >> decision;
if(decision == "yes")
{
int cost = contract[idx]->GetCost(idx_veh);
cout << "The cost of this vehicle is: " << cost << endl;
cout << "Would you wish to pay it?(Enter yes or no)";
cin >> paid;
if(paid == "yes")
{
contract[idx]->SetNotAvailable(idx_veh);
cout << "You have successfully rented the vehicle, thank you for coming.\n";
}
}
}
else
{
cout << "You have not booked any vehicle, please book it first\n";
}
}
cout << "\n----------------------------\n";
if(already_rent)
{
int userID
cin >> userID;
return userID;
}else return -1;
}
void CarRentalManagement::Returning()
{
cout << "\n*****Welcome to returning service*****\n";
string tem_id, name, vehicle_id, user_choice;
int size_num = contract.size();
int idx = -1, idx_veh = -1;
bool is_found1 = false, is_found2 = false, is_found3 = false, is_return = false;
cout << "Please enter your name: ";
while(true)
{
cin.clear();
cin.ignore();
getline(cin, name);
for(unsigned i = 0; i < size_num; i++)
{
if(contract[i]->GetUserName() == name)
{
idx = i;
is_found1 = true;
break;
}
}
if(is_found1)
{
break;
}
else
{
cout << "\nYour name does not exit in the database, please enter again: ";
}
}
cout << "\nEnter the ID you have entered when creating contract: ";
while(true)
{
cin >> tem_id;
if(contract[idx]->GetUserId() == tem_id)
{
is_found2 = true;
cout << "\n----Welcome back----\n";
}
if(is_found2)
break;
else cout << "\nPlease enter your id again: ";
}
int size_veh = contract[idx]->GetNumCar();
for(int k = 0; k < size_veh;k++)
{
if(!contract[idx]->GetRentStatus(k))
{
cout << "You have rented this vehicle:\n";
idx_veh = k;
contract[idx]->PrintVehicle(idx_veh);
cout << "\nWould you want to return it?(enter yes or no):";
cin >> user_choice;
if(user_choice == "yes")
{
contract[idx]->SetAvailable(idx_veh);
cout << "You have returned the vehicle, thank you for using our service.";
}
is_return = true;
break;
}
}
if(!is_return)
{
cout << "You have not rented any vehicle, please rent it first.";
}
cout << "\n----------------------------\n";
}
CarRentalManagement::~CarRentalManagement()
{
arrVeh.clear();
}
void CarRentalManagement::addVehicle(Vehicle* &pVeh)
{
arrVeh.push_back(pVeh);
}
void CarRentalManagement::printInfo()
{
unsigned num_size = arrVeh.size();
for(unsigned i = 0; i < num_size; i++)
{
arrVeh[i]->printDetail();
}
}
void CarRentalManagement::AddContract()
{
RentalContract *pTem = new RentalContract();
contract.push_back(pTem);
}
void CarRentalManagement::AddVehicle(int idx)
{
int count_num = 0;
cout << "\nHow many vehicle do you wish to add? ";
cin >> count_num;
for(unsigned i = 0; i < count_num; i++)
{
Vehicle *pTem = contract[idx]->AddCar();
arrVeh.push_back(pTem);
}
cin.clear();
}
void CarRentalManagement::PrintService()
{
int num = contract.size(), num2;
for(int i = 0; i < num; i++)
{
num2 = contract[i]->GetNumCar();
for(int j = 0; j < num2; j++)
{
contract[i]->PrintHistoryService(j);
cout << "\n====================\n";
}
}
}
| true |
bf0727c668faf0b2ad27f12fbdd2791de6cb8b4d | C++ | linlinyeyu/C-C-Arithmetic | /循环链表.cpp | UTF-8 | 1,939 | 3.15625 | 3 | [
"MIT"
] | permissive | #include "stdio.h"
#include "stdlib.h"
typedef struct lnode
{
int data;
struct lnode *next;
}linklist;
typedef struct dlnode
{
int data;
struct dlnode *prior;
struct dlnode *next;
}dlinklist;
void createlist(linklist *&L,int a[],int n)
{
int i;
linklist *s;
L=(linklist *)malloc(sizeof(linklist));
L->next=NULL;
for(i=0;i<n;i++)
{
s=(linklist *)malloc(sizeof(linklist));
s->data=a[i];
s->next=L->next;
L->next=s;
}
}
void dcreatelist(dlinklist *&L,int a[],int n)
{
dlinklist *s;
int i;
L=(dlinklist *)malloc(sizeof(dlinklist));
L->prior=L->next=NULL;
for(i=0;i<n;i++)
{
s=(dlinklist *)malloc(sizeof(dlinklist));
s->data=a[i];
s->next=L->next;
if(L->next!=NULL)
L->next->prior=s;
s->prior=L;
L->next=s;
}
}
void displist(linklist *L)
{
linklist *p=L->next;
while(p!=NULL)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}
void ddisplist(dlinklist *L)
{
dlinklist *p=L->next;
while(p!=NULL)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}
int count(linklist *L,int x)
{
int n=0;
linklist *p=L->next;
while(p!=NULL)
{
if(p->data==x)
n++;
p=p->next;
}
return(n);
}
bool delelem(dlinklist *&L,int x)
{
dlinklist *p=L->next;
while(p!=NULL&&p->data!=x)
p=p->next;
if(p!=NULL)
{
p->next->prior=p->prior;
p->prior->next=p->next;
free(p);
return true;
}
else
return false;
}
int main()
{
linklist *A;
dlinklist *B;
int x[]={23,12,435,22,12,33,23,456,23,12},a;
dcreatelist(B,x,10);
delelem(B,12);
ddisplist(B);
system("pause");
return 0;
}
| true |
035ad2ce1fe4a2c319aee39f9617b4f49295c4b2 | C++ | Hondy000/Reso | /Source/HarmonyFrameWork/Collision/CollisionObject/Public/CollisionPlanesObject.h | SHIFT_JIS | 2,603 | 2.59375 | 3 | [] | no_license | #pragma once
#include "BaseCollisionObject.h"
class CollisionPlanesObject
:
public BaseCollisionObject
{
public:
CollisionPlanesObject()
{
m_type = PLANE;
};
virtual ~CollisionPlanesObject()
{
m_planeInfoArray.clear();
};
// n`f[^̖ʂ̕
class PLANE_INFO
{
public:
PLANE_INFO()
{
}
virtual ~PLANE_INFO()
{
}
HFVECTOR3 GetCenter(void)
{
HFVECTOR3 center = { 0,0,0 };
center += p0 + p1 + p2;
center /= 3;
return center;
}
HFPLANE plane; //ʂ̕
HFVECTOR3 p0, p1, p2; //_W
HFVECTOR3 normal;
};
bool Collision(std::shared_ptr<BaseCollisionObject>);
void AnalyzeSpaceSize(void)
{
HFVECTOR3 max, min;
for (auto it = m_planeInfoArray.begin(); it != m_planeInfoArray.end(); it++)
{
// őT
if (max.x < (*it)->p0.x)
{
max.x = (*it)->p0.x;
}
if (max.x < (*it)->p1.x)
{
max.x = (*it)->p1.x;
}
if (max.y < (*it)->p2.y)
{
max.y = (*it)->p2.y;
}
if (max.y < (*it)->p0.y)
{
max.y = (*it)->p0.y;
}
if (max.y < (*it)->p1.y)
{
max.y = (*it)->p1.y;
}
if (max.y < (*it)->p2.y)
{
max.y = (*it)->p2.y;
}
if (max.y < (*it)->p2.y)
{
max.y = (*it)->p2.y;
}
if (max.z < (*it)->p0.z)
{
max.z = (*it)->p0.z;
}
if (max.z < (*it)->p1.z)
{
max.z = (*it)->p1.z;
}
if (max.z < (*it)->p2.z)
{
max.z = (*it)->p2.z;
}
}
min = max;
for (auto it = m_planeInfoArray.begin(); it != m_planeInfoArray.end(); it++)
{
// ŏ߂
if (min.x > (*it)->p0.x)
{
min.x = (*it)->p0.x;
}
if (min.x > (*it)->p1.x)
{
min.x = (*it)->p1.x;
}
if (min.y > (*it)->p2.y)
{
min.y = (*it)->p2.y;
}
if (min.y > (*it)->p0.y)
{
min.y = (*it)->p0.y;
}
if (min.y > (*it)->p1.y)
{
min.y = (*it)->p1.y;
}
if (min.y > (*it)->p2.y)
{
min.y = (*it)->p2.y;
}
if (min.y > (*it)->p2.y)
{
min.y = (*it)->p2.y;
}
if (min.z > (*it)->p0.z)
{
min.z = (*it)->p0.z;
}
if (min.z > (*it)->p1.z)
{
min.z = (*it)->p1.z;
}
if (min.z > (*it)->p2.z)
{
min.z = (*it)->p2.z;
}
}
// TCY
m_spaceSize = max - min;
}
void GetSpaceSize(HFVECTOR3* center, HFVECTOR3* halfSize)
{
*center = GetCenter();
*halfSize = m_spaceSize*0.5;
}
std::vector<std::shared_ptr<PLANE_INFO>>& GetPlaneInfoArray(void);
int GetPlaneCount()
{
return m_planeInfoArray.size();
}
protected:
std::vector<std::shared_ptr<PLANE_INFO>> m_planeInfoArray;
HFVECTOR3 m_spaceSize;
}; | true |
db93f9e41ffebcf37b406d1e6ce6c5e9628cc488 | C++ | hedvik/IMT3612-GPU | /shader/Tutorial Project/Vertex Input/Structs.h | UTF-8 | 4,243 | 2.703125 | 3 | [] | no_license | #pragma once
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <glm\glm.hpp>
#include <array>
#include <glm/gtx/hash.hpp>
#include "consts.h"
struct RenderableUBO {
glm::mat4 mvp;
glm::mat4 projectionMatrix;
glm::mat4 viewMatrix;
glm::mat4 modelMatrix;
};
struct RenderableMaterialUBO {
float specularExponent{128.0};
float specularGain{1};
float diffuseGain{1};
bool selfShadowEnabled{true};
};
struct SceneUBO {
glm::mat4 projectionMatrix;
glm::mat4 lightOffsetMatrices[NUM_LIGHTS];
glm::vec4 lightPositions[NUM_LIGHTS];
glm::vec4 lightColors[NUM_LIGHTS];
};
struct PushConstants {
glm::mat4 vireMatrix;
int currentMatrixIndex;
PushConstants(glm::mat4 view, int index) {
vireMatrix = view;
currentMatrixIndex = index;
}
};
struct Vertex {
glm::vec4 position;
glm::vec4 color;
glm::vec4 texCoord;
glm::vec4 normal;
static VkVertexInputBindingDescription getBindingDescription() {
// The binding description describes at which rate the program will load data from memory throughout the vertices
VkVertexInputBindingDescription bindingDescription = {};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
static std::array<VkVertexInputAttributeDescription, NUM_VERTEX_ATTRIBUTES> getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, NUM_VERTEX_ATTRIBUTES> attributeDescriptions = {};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, position);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color);
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
attributeDescriptions[3].binding = 0;
attributeDescriptions[3].location = 3;
attributeDescriptions[3].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributeDescriptions[3].offset = offsetof(Vertex, normal);
return attributeDescriptions;
}
bool operator==(const Vertex& other) const {
return position == other.position && color == other.color && texCoord == other.texCoord && normal == other.normal;
}
};
// OffscreenPass and FrameBufferAttachment are used for shadow mapping
struct FrameBufferAttachment {
VkImage image;
VkDeviceMemory memory;
VkImageView view;
};
enum RenderableType {
RENDERABLE_PACMAN = 0,
RENDERABLE_MAZE,
RENDERABLE_GHOST
};
struct RenderableInformation {
bool castShadows{ true };
RenderableType type;
RenderableInformation(RenderableType renderType) {
type = renderType;
}
RenderableInformation(RenderableType renderType, bool castShadow) {
castShadows = castShadow;
type = renderType;
}
};
struct OffscreenPass {
int32_t width, height;
VkFramebuffer frameBuffer;
FrameBufferAttachment color, depth;
VkRenderPass renderPass;
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
// Semaphore used to synchronize between offscreen and final scene render pass
VkSemaphore semaphore = VK_NULL_HANDLE;
};
struct CollisionRect{
int x{0};
int y{0};
int h{0};
int w{0};
CollisionRect() {};
CollisionRect(int x, int y, int h, int w) {
this->x = x;
this->y = y;
this->h = h;
this->w = w;
}
};
struct GLFWKeyEvent {
GLFWwindow* window;
int key;
int scancode;
int action;
int mods;
GLFWKeyEvent(GLFWwindow* window, int key, int scancode, int action, int mods) {
this->window = window;
this->key = key;
this->scancode = scancode;
this->action = action;
this->mods = mods;
}
};
// http://en.cppreference.com/w/cpp/utility/hash
namespace std {
template<> struct hash<Vertex> {
size_t operator()(Vertex const& vertex) const {
return ((hash<glm::vec3>()(vertex.position) ^
(hash<glm::vec3>()(vertex.color) << 1)) >> 1) ^
(hash<glm::vec2>()(vertex.texCoord) << 1) ^
(hash<glm::vec3>()(vertex.normal) >> 1);
}
};
} | true |
495b0cc7beed3e6850ebed82230453cbc0e0fe63 | C++ | GhostofGoes/evo-comp | /3/population.cpp | UTF-8 | 7,089 | 3.484375 | 3 | [
"MIT"
] | permissive | // Project: Assignment 3 - Evolution Strategies
// Author: Christopher Goes
// Description: Function definitions for the Population class as defined in population.h
#include <iomanip>
#include "population.h"
#include "points.h"
// Constructor ** ASSUMES initRand() HAS BEEN CALLED! **
Population::Population( int nPoints, int pSize, int numGens, double mProb, double cProb, int tSize ) {
numPoints = nPoints;
popSize = pSize;
generations = numGens;
mutProb = mProb;
crosProb = cProb;
trnySize = tSize;
initPopulation(); // Initialize the population
} // end Population constructor
// Where the Evolution Strategies (ES) magic happens
Chromosome Population::evolve( OP es_op ) {
// Generational loop that evolves the population
for( int i = 0; i < generations; i++ ) {
vector<Chromosome> children;
// Generate children
for( int i = 0; i < popSize; i++ ) {
Chromosome c;
// Crossover two selected parents from current population
if( choose(crosProb) ) {
Chromosome p1 = select(pop);
Chromosome p2 = select(pop);
c = crossover(p1, p2);
} else
c = select(pop); // Simply select a child from current population
// Mutate the child
if( choose(mutProb) )
c.mutate(SIGMA, SIGMA);
// Add child to the children
children.push_back(c);
}
// Select for new population
if( es_op == PLUS ) // Plus operator (select from pop (parents) AND children)
genPlus(children);
else // Comma operator (select from ONLY children)
genComma(children);
}
return getBest(); // Return the best individual after evolving
} // end evolve
// Selects a chromosome out of p using simple tournament selection
// TODO: Could try fitness proportional selection or uniform parent selection at some point
Chromosome Population::select( vector<Chromosome> p ) const {
vector<int> t;
for( int i = 0; i < trnySize; i++ ) {
int temp;
do {
temp = randMod(p.size());
} while( isIn(t, temp));
t.push_back(temp);
}
double best = p[t[0]].fitness; // Fitness of the "best" seen thus far
int bestInd = t[0]; // Index of the best individual seen thus far
for( int i = 0; i < trnySize; i++ ) {
if(p[t[i]].fitness > best) {
best = p[t[i]].fitness;
bestInd = i;
}
}
return p[bestInd];
} // end select
// Checks if val is in vector t
bool Population::isIn( vector<int> t, int val ) const {
for( int i : t )
if(i == val)
return true;
return false;
} // end isIn
// Checks if val is in vector t
bool Population::isIn( vector<point> t, point val ) const {
for( point i : t )
if(i.theta == val.theta && i.r == val.r)
return true;
return false;
} // end isIN
// ES COMMA operator
// Selects from just the children?
// TODO: mu and lambda (could use children.size() and popSize for this)
// TODO: pretty sure i'm doing this wrong still.
void Population::genComma( vector<Chromosome> children ) {
for( int i = 0; i < popSize; i++ )
pop[i] = select(children);
} // end genComma
// ES PLUS operator
// Selects new population from previous population and children
// TODO: mu and lambda (could use children.size() for this)
void Population::genPlus( vector<Chromosome> children ) {
vector<Chromosome> newPop;
pop.insert( pop.end(), children.begin(), children.end()); // Add children to current population
for( int i = 0; i < popSize; i++ )
newPop.push_back(select(pop)); // Select from combined population and add to new population
pop = newPop; // Set current population to new population
} // end genPlus
// Order One crossover that generates a new child as the crossover of p1 and p2
// TODO: Crossover with only one parent is basically a sneaky way to save some of the parents when using the Comma operator
// TODO: verify this is implemented properly! (test)
// TODO: link to the source I used for the algorithm
Chromosome Population::crossover( Chromosome p1, Chromosome p2 ) const {
Chromosome c(numPoints, 0.0);
int swathLen = randMod(numPoints - 1); // TODO: tweak this?
int swathStart = randMod(numPoints - swathLen - 1); // Start of the swath
int swathEnd = swathStart + swathLen; // End position of the swath
vector<point> swath; // The swath generated from p1
vector<point> leftover; // Points that we can use from p2
// Grab swath from parent 1 and put into child
for( int j = swathStart; j < swathEnd; j++ ) {
swath.push_back(p1.points[j]);
c.points[j] = p1.points[j];
}
// Grab genes from parent 2 that aren't in swath from parent 1
for( int i = 0; i < numPoints; i++ ) {
if( !isIn(swath, p2.points[i]) ) {
leftover.push_back(p2.points[i]);
}
}
// Put the genes we grabbed from parent 2 into the child's open spots
int temp = 0;
for( int i = 0; i < swathStart; i++ ) {
c.points[i] = leftover[temp];
temp++;
}
for( int i = swathEnd; i < numPoints; i++ ) {
c.points[i] = leftover[temp];
temp++;
}
c.updateFitness(); // Calculate the newly minted child's fitness'
return c;
} // end crossover
// Finds and returns the best individual in the current population (highest fitness)
Chromosome Population::getBest() const {
double best = pop[0].fitness;
int bestInd = 0;
for(int i = 1; i < popSize; i++) {
if(pop[i].fitness > best) {
best = pop[i].fitness;
bestInd = i;
}
}
return pop[bestInd];
} // end getBest
// Prints the population, headed by title
void Population::printPop( string title ) const {
cout << "\n++ Population: " << title << " ++" << endl;
cout << setw(fieldWidth) << left << "Theta" << "\tRadius" << endl;
for( Chromosome c : pop ) {
cout << setw(fieldWidth) << left << "\nFitness: " << c.fitness << endl;
c.print();
}
cout << "++++++++++++++++++++++++++" << endl;
} // end printPop
// Basic print of all individuals in population
void Population::print() const {
for( Chromosome c : pop )
c.print();
} // end print
// Simple dump of the fitnesses in the current population
void Population::testPrint() const {
cout << "\n++++++++++++++++++++++++++" << endl;
for( Chromosome c : pop ) {
cout << "Fitness: " << c.fitness << endl;
}
} // end testPrint
// Initializes the population with random values, and calculates their fitnesses
void Population::initPopulation() {
for( int i = 0; i < popSize; i++ ) {
Chromosome c( numPoints ); // Initialize a new chromosome with random values and a fitness
pop.push_back(c); // Add chromosome to the population
}
if( (int)pop.size() != popSize ) { cerr << "pop.size() != popSize !!!" << endl; }
} // end initPopulation
| true |
78ed0fad8c3eb7cf95f5df4241a12a39dca546b5 | C++ | Graphics-Physics-Libraries/OpenGL-flight-simulator-1 | /GraphicsProject/GObject.cpp | UTF-8 | 2,109 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "GObject.h"
#include "ResourceManager.h"
GObject::GObject()
{
Parent = nullptr;
UpdateObject = true;
ResourceManager::AddGameObject(this);
}
GObject::GObject(GObject* Parent)
{
this->Parent = Parent;
UpdateObject = true;
ResourceManager::AddGameObject(this);
}
void GObject::SetParent(GObject* Parent)
{
this->Parent = Parent;
}
void GObject::SetTransform(const GTransform& NewTransform)
{
this->Transform = NewTransform;
}
void GObject::SetTransform(const GVector& Location, const GVector& Rotation, const GVector& Scale, const float & Angle)
{
this->Transform.Location = Location;
this->Transform.Rotation = Rotation;
this->Transform.Scale = Scale;
this->Transform.Angle = Angle;
}
void GObject::SetLocation(const GVector& NewLocation)
{
this->Transform.Location = NewLocation;
}
void GObject::SetRoation(const GVector& NewRotaion)
{
this->Transform.Rotation = NewRotaion;
}
void GObject::SetScale(const GVector& Scale)
{
this->Transform.Scale = Scale;
}
void GObject::SetScale(const float & NewScale)
{
this->Transform.Scale.x = this->Transform.Scale.y = this->Transform.Scale.z = NewScale;
}
void GObject::MultiplyScale(const float& Mul)
{
this->Transform.Scale *= Mul;
}
void GObject::SetAngle(const float& NewAngle)
{
this->Transform.Angle = NewAngle;
}
void GObject::AddRelativeLocation(const GVector& Amount)
{
this->Transform.Location += Amount;
}
void GObject::AddRelativeLocation(const float& AmountX, const float& AmountY, const float& AmountZ)
{
this->Transform.Location.AddFloatAmount(AmountX, AmountY, AmountZ);
}
void GObject::AddRelativeRotation(const GVector& Amount)
{
this->Transform.Rotation += Amount;
}
void GObject::AddRelativeRotation(const float& AmountX, const float& AmountY, const float& AmountZ)
{
this->Transform.Rotation.AddFloatAmount(AmountX, AmountY, AmountZ);
}
void GObject::AddRelativeScale(const GVector& Amount)
{
this->Transform.Scale += Amount;
}
void GObject::AddRelativeScale(const float& AmountX, const float& AmountY, const float& AmountZ)
{
this->Transform.Scale.AddFloatAmount(AmountX, AmountY, AmountZ);
}
| true |
f393eab13972ca9d1ea55aaeb627a04b261a9cd8 | C++ | kgifaldi/ThreadedWebCrawler | /temp.cpp | UTF-8 | 5,268 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <curl/curl.h>
#include <sstream>
#include <queue>
#include <pthread.h>
using namespace std;
// when the size of this queue is greater than 0
// the number of parse threads specified will be going
deque<string> toParse;
deque<string> finalContent;
int numParseRunning = 0;
pthread_mutex_t m;
pthread_cond_t c;
// every N seconds, this will be set to true
// when true, the number of threads specified will fetch web content
bool fetch = true;
// defaults:
int PERIOD_FETCH = 180;
int NUM_FETCH = 1;
int NUM_PARSE = 1;
string SEARCH_FILE = "Search.txt";
string SITE_FILE = "Sites.txt";
// fileToVector: returns vector of strings
// each entry is one line of file
vector<string> fileToVector(string fileName){
vector<string> tempVector;
ifstream file;
string tempString;
file.open(fileName.c_str());
while(getline(file, tempString)){
tempVector.push_back(tempString);
}
return tempVector;
}
// function called by licburl to write the data to a string
// found at this stackoverflow post: http://stackoverflow.com/questions/9786150/save-curl-content-result-into-a-string-in-c
static size_t WriteFunction(void * contents, size_t size, size_t nmemb, void *userp){
((string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
struct fetch_args{
string site;
};
struct parse_args{
string site;
string siteURL;
vector<string> terms;
};
void * fetchTask(void * data){
struct fetch_args * args = (struct thread_args *) data;
string websiteContent;
CURL * curl = curl_easy_init();
CURLcode res;
if(curl){
curl_easy_setopt(curl, CURLOPT_URL, args->site.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &websiteContent);
res = curl_easy_perform(curl);
// if error:
if(res != CURLE_OK)
cout << stderr << " curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
curl_easy_cleanup(curl);
pthread_mutex_lock(&c);
toParse.push_back(websiteContent);
// TODO: implement condition variabe
pthread_mutex_unlock(&c);
}
}
void * parseTask(void * data){
struct parse_args * args = (struct parse_args *) data;
string parse;
vector<string> fileEntries;
string writeToFile;
int count = 0;
for(int i = 0; i < (args->terms).size(); i++){
count = 0;
stringstream siteStream(args->site);
while(siteStream >> parse){
if(parse.find(args->terms[i]) != string::npos)
count++;
}
writeToFile.clear();
writeToFile.append("Time,Phrase,Site,Count\n");
writeToFile.append(asctime(localtime(&time));
writeToFile.append(",");
writeToFile.append(args->terms[i]);
writeToFile.append(",");
writeToFile.append(args->siteURL);
writeToFile.append(",");
writeToFile.append(count);
writeToFile.append("\n");
fileEntries.push_pack(writeToFile);
}
pthread_mutex_lock(&c);
toParse.pop_front();
for(int i = 0; i < fileEntries.size(); i++)
finalContent.push_back(fileEntries[i]);
pthread_mutex_unlock(&c);
// TODO: condition variable
}
int main(){
// Variables...
ofstream myfile;
myfile.open("outTmp.txt");
vector<string> sites = fileToVector(SITE_FILE);
vector<string> searchTerms = fileToVector(SEARCH_FILE);
CURL *curl;
CURLcode res;
string websiteContent;
time_t time; // = time(nullptr);
int searchWordCount = 0;
void * thread_result;
pthread_t tid_f[NUM_FETCH];
pthread_t tid_p[NUM_PARSE];
int siteCounter = 0;
clock_t begin;
clock_t end;
int parsed = 0;
// read in sites and search terms into vector<stirng>
for(int i = 0; i < sites.size(); i++)
cout << sites[i] << endl;
for(int i = 0; i < searchTerms.size(); i++)
cout << searchTerms[i] << endl;
while(siteCounter < sites.size()){
begin = clock();
for(int i = 0; i < NUM_FETCH; i++){
if(siteCounter == sites.size())
break;
struct fetch_args * args;
args = malloc(sizeof(struct fetch_args));
args->site = site[siteCounter];
siteCounter++;
pthread_create(&tid_f[i], NULL, fetch_task, (void *) args);
}
for(int i = 0; i < NUM_FETCH; i++){
// on last loop of fetch tasks, all of NUM_FETCH
// threads may not be used
// so I am checking if i >= (sites.size() mod NUM_FETCH)
// to break the loop
if(siteCounter == sites.size() && i > (sites.size() % NUM_FETCH))
break;
pthread_join(tid_f[i], &thread_result);
}
int toJoin = 0;
for(int i = 0; i < NUM_PARSE; i++){
if(to_parse.size() == 0)
break;
else{
parsed++;
toJoin++;
}
struct parse_args * args;
args = malloc(sizeof(struct parse_args));
args->site = toParse.front();
args->siteURL = sites[parsed-1];
vector<string> tempVec(searchTerm);
args->terms = tempVec;
pthread_create(&tid_p[i], NULL, parse_task, (void *) args);
}
for(int i = 0; i < NUM_PARSE; i++){
if(toJoin == 0)
break;
pthread_join(tid_p[i], &thread_result);
toJoin--;
}
// time segment at bottom of while loop
// so that threads begin immediately
// then wait proper time for next batch of threading
end = clock();
elapsed_time = double(end - begin) / CLOCKS_PER_SEC;
while(elapsed_time < PERIOD_FETCH){
end = clock();
elapsed_time = double(end - begin);
}
}
return 0;
}
| true |
fa5a845d3384bea47c4d9e49ea66f33b183b877b | C++ | CaterTsai/C_Square | /src/draw/DAudioMesh.cpp | UTF-8 | 2,247 | 2.65625 | 3 | [] | no_license | #include "DAudioMesh.h"
//-------------------------------------
void DAudioMesh::update(float delta)
{
CHECK_START();
}
//-------------------------------------
void DAudioMesh::draw(int x, int y, int w, int h)
{
CHECK_START();
float size = w * 0.005;
ofVec3f temp;
ofPushStyle();
ofSetLineWidth(2);
ofSetColor(255);
{
for (int y = 0; y < cDAudioMeshRows; y++)
{
if (!_needDraw[y])
{
continue;
}
for (int x = 0; x < cDAudioMeshCols; x++)
{
auto pos = _pointMesh[y][x] * w;
if (_isDrawLine && x != 0)
{
ofLine(temp, pos);
}
if (_isDrawBall)
{
ofDrawSphere(pos, size);
}
temp = pos;
}
}
}
ofPopStyle();
}
//-------------------------------------
void DAudioMesh::start()
{
_isStart = true;
initPointMesh();
}
//-------------------------------------
void DAudioMesh::stop()
{
_isStart = false;
}
//-------------------------------------
void DAudioMesh::setSoundValue(array<float, cBufferSize>& soundValue)
{
for (int y = 0; y < cDAudioMeshRows; y++)
{
int startIdx = y * 2;
int delta = rand() % 10;
for (int x = 0; x < cDAudioMeshCols; x++)
{
float val = soundValue[(startIdx + x * delta) % cBufferSize] * 1.0f;
if (val > _pointMesh[y][x].z)
{
_pointMesh[y][x].z = val;
}
else
{
_pointMesh[y][x].z *= 0.95;
}
}
}
}
//-------------------------------------
void DAudioMesh::toggleLine()
{
_isDrawLine ^= true;
}
//-------------------------------------
void DAudioMesh::toggleBall()
{
_isDrawBall ^= true;
}
//-------------------------------------
void DAudioMesh::setLineNum(int val)
{
ZeroMemory(_needDraw, sizeof(bool) * cDAudioMeshRows);
int center = cDAudioMeshRows * 0.5;
for (int i = 0; i < val; i++)
{
int idup = center + i;
int iddown = center - i;
_needDraw[idup] = true;
_needDraw[iddown] = true;
}
}
//-------------------------------------
void DAudioMesh::initPointMesh()
{
float yDelta = 1.0 / cDAudioMeshRows;
float xDelta = 1.0 / cDAudioMeshCols;
float posY = -0.5;
float posX = -0.5;
for (int y = 0; y < cDAudioMeshRows; y++)
{
posX = -0.5;
for (int x = 0; x < cDAudioMeshCols; x++)
{
_pointMesh[y][x].set(posX, posY, 0.0f);
posX += xDelta;
}
posY += yDelta;
}
}
| true |
2f941ec8c5d39909c1e51b9f5c83015549e028b3 | C++ | Plaristote/crails | /modules/mongodb/crails/mongodb/exception.hpp | UTF-8 | 437 | 2.5625 | 3 | [] | no_license | #ifndef CRAILS_MONGODB_EXCEPTION_HPP
# define CRAILS_MONGODB_EXCEPTION_HPP
# include <crails/utils/backtrace.hpp>
# include <string>
namespace MongoDB
{
class Exception : public boost_ext::exception
{
public:
Exception(const std::string& message) : message(message)
{
}
const char* what(void) const throw()
{
return (message.c_str());
}
private:
std::string message;
};
}
#endif
| true |
5a6f425b3f9b5d59b08e6a3fbc1ac132cc81a53d | C++ | infyloop/uva-solns | /Arranged/587. There's treasure everywhere/treasure1.cpp | UTF-8 | 1,093 | 2.875 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
char s[300],d[3]="";
int i,l,n=0,t=0,c=0;
float x,y,temp;
while(1)
{
scanf("%s",s);
if(strcmp(s,"END")==0) break;
x=y=0;c++;
l=strlen(s)-1;
for(i=0;i<=l;i++)
{
if(s[i]>='0' && s[i]<='9') n=n*10+s[i]-'0';
if(s[i]>='A' && s[i]<='Z') {d[t]=s[i];t++;d[t]='\0';}
if(s[i]==',' || s[i]=='.')
{
if(strcmp(d,"N")==0) y+=n;
else if(strcmp(d,"S")==0) y-=n;
else if(strcmp(d,"E")==0) x+=n;
else if(strcmp(d,"W")==0) x-=n;
else if(strcmp(d,"NE")==0) {temp=(float)n/M_SQRT2;x+=temp;y+=temp;}
else if(strcmp(d,"NW")==0) {temp=(float)n/M_SQRT2;x-=temp;y+=temp;}
else if(strcmp(d,"SE")==0) {temp=(float)n/M_SQRT2;x+=temp;y-=temp;}
else if(strcmp(d,"SW")==0) {temp=(float)n/M_SQRT2;x-=temp;y-=temp;}
n=t=0;
}
}
printf("Map #%d\nThe treasure is located at (%.3f,%.3f).\nThe distance to the treasure is %.3f.\n\n",c,x,y,sqrt(x*x+y*y));
}
return 0;
}
| true |
2e5edb485cc9298ace96cabfc44d8ba2e24c3e29 | C++ | Manav-Aggarwal/competitive-programming | /CodeJam/Google CodeJam 2015/Standing Ovation.cpp | UTF-8 | 817 | 2.515625 | 3 | [] | no_license | /* Written By Manav Aggarwal */
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define ll long long
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
freopen("A-small-attempt0.in", "r", stdin);
freopen("Standing-Ovation-Output.out", "w", stdout);
ll t, cases;
cin >> t;
cases = t;
while(t--)
{
ll numberStanding = 0, minReq = 0, maxShyness;
cin >> maxShyness;
string audience;
cin >> audience;
for(int i = 0; i < audience.length(); i++)
{
if(numberStanding >= i)
{
numberStanding += audience[i] - '0';
}
else if(audience[i] - '0' > 0)
{
minReq += (i - numberStanding);
numberStanding += audience[i] - '0' + (i - numberStanding);
}
}
cout << "Case #" << (cases - t) << ": " << minReq << endl;
}
return 0;
}
| true |
14bcd6ffece8e8827434506e4f5d1db832eb50eb | C++ | lagoproject/easy | /src/interp.cc | UTF-8 | 2,467 | 3.015625 | 3 | [
"BSD-3-Clause"
] | permissive | /* 3D interpolation code */
/* la idea es trabajar con álgebra vectorial, extendiendo lo que se hace en 2D a un vector de dimension n */
#include <vector>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// config
const double deg2rad = M_PI / 180.;
const double rad2deg = 180. / M_PI;
const double units = 10.; // in milimeters
// vamos a encontrar por interpolación el punto donde una línea intersecta a un cilindro de radio
const double tankR = 1784. / units;
const double tankH = 1200. / units;
const double dt = 1.; // temporal step
struct vect {
double r1;
double r2;
double r3;
} coordinate;
#include "interp_func.h"
int main() {
/*
ofstream dis,out,muo;
char nmuo[256], nout[256], ndis[256];
snprintf(nmuo,256, MU);
snprintf(nout,256, TR);
snprintf(ndis,256, DI);
muo.open(nmuo);
dis.open(ndis);
vector < vector <double> > traces;
traces.resize(maxL);
for (int i = 0; i < maxL; i++)
traces[i].resize(types);
for (int i = 0; i < maxL; i++)
for (int j = 0; j < types; j++)
traces[i][j] = 0.;
*/
/* handlers */
vect pcar = { 0., 0., 0.}; // photon position in cartesian
vect pcyl = { 0., 0., 0.}; // photon position in cylindrical
vect ppcar = { 0., 0., 0.}; // photon position in cylindrical
vect ppcyl = { 0., 0., 0.}; // photon position in cylindrical
vect vcar = { 0., 0., 0.}; // photon speed in cartesian
vect vsph = { 0., 0., 0.}; // photon speed in spherical
//photon at the top
pcar.r1 = 0.;
pcar.r2 = 0.;
pcar.r3= tankH;
pcyl = car2cyl(pcar);
// let's use 70 going down at phi=0, |v| = 1.; in sphericals:
vsph.r1 = -1.;
vsph.r2= 70.*deg2rad;
vsph.r3= 20.*deg2rad;
vcar = sph2car(vsph);
do {
// move the photon
ppcyl = pcyl;
pcar.r1 += vcar.r1 * dt;
pcar.r2 += vcar.r2 * dt;
pcar.r3 += vcar.r3 * dt;
pcyl = car2cyl(pcar);
} while (isIn(pcyl));
ppcar = cyl2car(pcyl);
vect ptnk=intersect(ppcar,pcar); // intersección con el tanque
ptnk = car2cyl(ptnk);
cout
<< ppcyl.r1 << " "
<< ppcyl.r2 << " "
<< ppcyl.r3 << " " << endl
<< ptnk.r1 << " "
<< ptnk.r2 << " "
<< ptnk.r3 << " " << endl
<< pcyl.r1 << " "
<< pcyl.r2 << " "
<< pcyl.r3 << " " << endl;
// pcyl tiene la ultima posición (fuera), ppcyl tiene la ultima posición dentro
} //main
| true |
a7b34578648fed77d72af770afe89b92fec4d76a | C++ | chromium/chromium | /components/feed/core/v2/public/stream_type_unittest.cc | UTF-8 | 2,891 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/feed/core/v2/public/stream_type.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace feed {
class StreamTypeTest : public testing::Test {
public:
StreamTypeTest() = default;
StreamTypeTest(StreamTypeTest&) = delete;
StreamTypeTest& operator=(const StreamTypeTest&) = delete;
~StreamTypeTest() override = default;
void SetUp() override { testing::Test::SetUp(); }
};
TEST_F(StreamTypeTest, ComparatorTest) {
StreamType for_you = StreamType(StreamKind::kForYou);
StreamType following = StreamType(StreamKind::kFollowing);
StreamType single_web_feed_a = StreamType(StreamKind::kSingleWebFeed, "A");
StreamType single_web_feed_b = StreamType(StreamKind::kSingleWebFeed, "B");
StreamType single_web_feed = StreamType(StreamKind::kSingleWebFeed);
ASSERT_TRUE(for_you < following);
ASSERT_TRUE(following < single_web_feed_a);
ASSERT_TRUE(single_web_feed_a < single_web_feed_b);
ASSERT_TRUE(for_you < single_web_feed_b);
ASSERT_TRUE(single_web_feed_b == single_web_feed_b);
ASSERT_FALSE(single_web_feed_a < single_web_feed);
ASSERT_FALSE(single_web_feed < for_you);
ASSERT_FALSE(for_you < for_you);
ASSERT_FALSE(single_web_feed_b < single_web_feed_b);
}
TEST_F(StreamTypeTest, IdentityTest) {
StreamType for_you = StreamType(StreamKind::kForYou);
StreamType following = StreamType(StreamKind::kFollowing);
StreamType single_web_feed = StreamType(StreamKind::kSingleWebFeed);
StreamType unknown = StreamType();
ASSERT_TRUE(for_you.IsForYou());
ASSERT_FALSE(for_you.IsWebFeed());
ASSERT_FALSE(for_you.IsSingleWebFeed());
ASSERT_TRUE(for_you.IsValid());
ASSERT_FALSE(following.IsForYou());
ASSERT_TRUE(following.IsWebFeed());
ASSERT_FALSE(following.IsSingleWebFeed());
ASSERT_TRUE(following.IsValid());
ASSERT_FALSE(single_web_feed.IsForYou());
ASSERT_FALSE(single_web_feed.IsWebFeed());
ASSERT_TRUE(single_web_feed.IsSingleWebFeed());
ASSERT_TRUE(single_web_feed.IsValid());
ASSERT_FALSE(unknown.IsForYou());
ASSERT_FALSE(unknown.IsWebFeed());
ASSERT_FALSE(unknown.IsSingleWebFeed());
ASSERT_FALSE(unknown.IsValid());
}
TEST_F(StreamTypeTest, StringTest) {
StreamType for_you = StreamType(StreamKind::kForYou);
StreamType following = StreamType(StreamKind::kFollowing);
StreamType single_web_feed = StreamType(StreamKind::kSingleWebFeed);
StreamType single_web_feed_a = StreamType(StreamKind::kSingleWebFeed, "A");
StreamType unknown = StreamType();
ASSERT_EQ(for_you.ToString(), "ForYou");
ASSERT_EQ(following.ToString(), "WebFeed");
ASSERT_EQ(single_web_feed.ToString(), "SingleWebFeed_");
ASSERT_EQ(single_web_feed_a.ToString(), "SingleWebFeed_A");
ASSERT_EQ(unknown.ToString(), "Unknown");
}
} // namespace feed
| true |
e52500cc2d3b5e52737261ca6089c92d898a583f | C++ | Aodai/c1 | /main.cpp | UTF-8 | 205 | 2.578125 | 3 | [] | no_license | #include <stdio.h>
int main(int argc, char** argv) {
if(argc < 2 || argc > 2) {
printf("Usage: greetings [name]\n");
return 0;
}
printf("Hello %s\n", argv[1]);
return 0;
}
| true |
e6fb3800e8007719b687f4c2c8a5f6c40308a606 | C++ | UnnamedOrange/Contests | /Source Code/李沿橙 2017-7-19/source/李沿橙/match Indirect + BIT.cpp | GB18030 | 2,073 | 2.8125 | 3 | [] | no_license | //Indirect sort + BIT
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
using std::cin;
using std::cout;
using std::endl;
typedef long long INT;
inline INT readIn()
{
bool minus = false;
INT a = 0;
char ch = getchar();
while (!(ch == '-' || ch >= '0' && ch <= '9')) ch = getchar();
if (ch == '-')
{
minus = true;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
a *= 10;
a += ch;
a -= '0';
ch = getchar();
}
if (minus) a = -a;
return a;
}
const INT mod = 99999997;
const INT maxn = 100005;
INT n;
INT height1[maxn];
INT index1[maxn];
INT height2[maxn];
INT index2[maxn];
bool comp1(const INT& a, const INT& b)
{
return height1[a] < height1[b];
}
bool comp2(const INT& a, const INT& b)
{
return height2[a] < height2[b];
}
INT sequence[maxn];
INT temp[maxn];
inline INT lowbit(INT x)
{
return x & -x;
}
INT getInv()
{
INT ans = 0;
std::vector<INT> BIT(n + 1);
for(int i = 0; i < n; i++)
{
INT x;
x = sequence[i] + 1; //1ʼر
while(x <= n)
{
BIT[x]++;
x += lowbit(x);
}
INT count_ = 0;
x = sequence[i] + 1;
while(x > 0)
{
count_ += BIT[x];
x -= lowbit(x);
}
ans += i + 1 - count_;
}
return ans;
}
void run()
{
n = readIn();
for (int i = 0; i < n; i++)
{
height1[i] = readIn();
index1[i] = i;
}
for (int i = 0; i < n; i++)
{
height2[i] = readIn();
index2[i] = i;
}
std::sort(index1, index1 + n, comp1);
std::sort(index2, index2 + n, comp2);
for (int i = 0; i < n; i++)
{
sequence[index1[i]] = index2[i];
}
cout << getInv() % mod << endl;
}
int main()
{
run();
return 0;
}
| true |
0456a7a281969d81e51223c04005a76dd72adf4c | C++ | leafyoung88/Virtual-Engine | /virtual_engine_origin/Common/vector.h | UTF-8 | 8,234 | 3.109375 | 3 | [] | no_license | #pragma once
#include <stdint.h>
#include <stdlib.h>
#include <memory>
#include <initializer_list>
#include <type_traits>
#include "ArrayList.h"
#include "Memory.h"
namespace vengine
{
template <typename T>
class vector
{
public:
struct ValueType
{
T value;
};
private:
T* arr;
uint64_t mSize;
uint64_t mCapacity;
int32_t poolIndex;
T* Allocate(uint64_t& capacity, int32_t& poolIndex)
{
/*T* ptr = (T*)vengine_malloc(capacity * sizeof(T));
uint64_t size = vengine_memory_size(ptr);
capacity = size / sizeof(T);
return ptr;*/
capacity *= sizeof(T);
T* ptr = (T*)vengine::AllocateString(capacity, poolIndex);
capacity /= sizeof(T);
return ptr;
}
public:
void reserve(uint64_t newCapacity) noexcept
{
if (newCapacity <= mCapacity) return;
int32_t newPoolIndex = 0;
T* newArr = Allocate(newCapacity, newPoolIndex);
if (arr)
{
//memcpy(newArr, arr, sizeof(T) * mSize);
for (uint64_t i = 0; i < mSize; ++i)
{
new (newArr + i)T(std::forward<T>(arr[i]));
((ValueType*)(arr + i))->~ValueType();
}
vengine::FreeString(arr, poolIndex);
}
poolIndex = newPoolIndex;
mCapacity = newCapacity;
arr = newArr;
}
T* data() const noexcept { return arr; }
uint64_t size() const noexcept { return mSize; }
uint64_t capacity() const noexcept { return mCapacity; }
struct Iterator
{
friend class vector<T>;
private:
const vector<T>* lst;
uint64_t index;
constexpr Iterator(const vector<T>* lst, uint64_t index) noexcept : lst(lst), index(index) {}
public:
bool constexpr operator==(const Iterator& ite) const noexcept
{
return index == ite.index;
}
bool constexpr operator!=(const Iterator& ite) const noexcept
{
return index != ite.index;
}
void operator++() noexcept
{
index++;
}
uint64_t GetIndex() const noexcept
{
return index;
}
void operator++(int) noexcept
{
index++;
}
Iterator constexpr operator+(uint64_t value) const noexcept
{
return Iterator(lst, index + value);
}
Iterator constexpr operator-(uint64_t value) const noexcept
{
return Iterator(lst, index - value);
}
Iterator& operator+=(uint64_t value) noexcept
{
index += value;
return *this;
}
Iterator& operator-=(uint64_t value) noexcept
{
index -= value;
return *this;
}
T* operator->() const noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= lst->mSize) throw "Out of Range!";
#endif
return &(*lst).arr[index];
}
T& operator*() const noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= lst->mSize) throw "Out of Range!";
#endif
return (*lst).arr[index];
}
};
vector(uint64_t mSize) noexcept : mSize(mSize), mCapacity(mSize)
{
arr = Allocate(mCapacity, poolIndex);
for (uint64_t i = 0; i < mSize; ++i)
{
new (arr + i)T();
}
}
vector(std::initializer_list<T> const& lst) : mSize(lst.size()), mCapacity(lst.size())
{
arr = Allocate(mCapacity, poolIndex);
for (uint64_t i = 0; i < mSize; ++i)
{
new (arr + i)T(lst.begin()[i]);
}
}
vector(const vector<T>& another) noexcept :
mSize(another.mSize), mCapacity(another.mCapacity)
{
arr = Allocate(mCapacity, poolIndex);
for (uint64_t i = 0; i < mSize; ++i)
{
new (arr + i)T(another.arr[i]);
}
//memcpy(arr, another.arr, sizeof(T) * mSize);
}
vector(vector<T>&& another) noexcept :
mSize(another.mSize), mCapacity(another.mCapacity)
{
arr = Allocate(mCapacity, poolIndex);
for (uint64_t i = 0; i < mSize; ++i)
{
new (arr + i)T(std::forward<T>(another.arr[i]));
}
//memcpy(arr, another.arr, sizeof(T) * mSize);
}
void operator=(const vector<T>& another) noexcept
{
clear();
reserve(another.mSize);
mSize = another.mSize;
for (uint64_t i = 0; i < mSize; ++i)
{
new (arr + i)T(another.arr[i]);
}
}
void operator=(vector<T>&& another) noexcept
{
clear();
reserve(another.mSize);
mSize = another.mSize;
for (uint64_t i = 0; i < mSize; ++i)
{
new (arr + i)T(std::forward<T>(another.arr[i]));
}
}
vector() noexcept : mCapacity(0), mSize(0), arr(nullptr)
{
}
~vector() noexcept
{
if (arr)
{
for (uint64_t i = 0; i < mSize; ++i)
{
((ValueType*)(arr + i))->~ValueType();
}
vengine::FreeString(arr, poolIndex);
}
}
bool empty() const noexcept
{
return mSize == 0;
}
template <typename ... Args>
T& emplace_back(Args&&... args)
{
if (mSize >= mCapacity)
{
uint64_t newCapacity = mCapacity * 1.5 + 8;
reserve(newCapacity);
}
T* ptr = arr + mSize;
new (ptr)T(std::forward<Args>(args)...);
mSize++;
return *ptr;
}
void push_back(const T& value) noexcept
{
emplace_back(value);
}
void push_back(T&& value) noexcept
{
emplace_back(std::forward<T>(value));
}
Iterator begin() const noexcept
{
return Iterator(this, 0);
}
Iterator end() const noexcept
{
return Iterator(this, mSize);
}
void erase(const Iterator& ite) noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (ite.index >= mSize) throw "Out of Range!";
#endif
if (ite.index < mSize - 1)
{
for (uint64_t i = ite.index; i < mSize - 1; ++i)
{
arr[i] = arr[i + 1];
}
((ValueType*)(arr + mSize - 1))->~ValueType();
// memmove(arr + ite.index, arr + ite.index + 1, (mSize - ite.index - 1) * sizeof(T));
}
mSize--;
}
void clear() noexcept
{
for (uint64_t i = 0; i < mSize; ++i)
{
((ValueType*)(arr + i))->~ValueType();
}
mSize = 0;
}
void dispose() noexcept
{
clear();
mCapacity = 0;
if (arr)
{
vengine::FreeString(arr, poolIndex);
arr = nullptr;
}
}
void resize(uint64_t newSize) noexcept
{
if (mSize == newSize) return;
if (mSize > newSize)
{
for (uint64_t i = newSize; i < mSize; ++i)
{
((ValueType*)(arr + i))->~ValueType();
}
}
else
{
reserve(newSize);
for (uint64_t i = mSize; i < newSize; ++i)
{
new (arr + i)T();
}
}
mSize = newSize;
}
T& operator[](uint64_t index) noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
const T& operator[](uint64_t index) const noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
T& operator[](int64_t index) noexcept
{
return operator[]((uint64_t)index);
}
const T& operator[](int64_t index) const noexcept
{
return operator[]((uint64_t)index);
}
T& operator[](uint32_t index) noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
const T& operator[](uint32_t index) const noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
T& operator[](int32_t index) noexcept
{
return operator[]((uint32_t)index);
}
const T& operator[](int32_t index) const noexcept
{
return operator[]((uint32_t)index);
}
T& operator[](uint16_t index) noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
const T& operator[](uint16_t index) const noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
T& operator[](int16_t index) noexcept
{
return operator[]((uint16_t)index);
}
const T& operator[](int16_t index) const noexcept
{
return operator[]((uint16_t)index);
}
T& operator[](uint8_t index) noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
const T& operator[](uint8_t index) const noexcept
{
#if defined(DEBUG) || defined(_DEBUG)
if (index >= mSize) throw "Out of Range!";
#endif
return arr[index];
}
T& operator[](int8_t index) noexcept
{
return operator[]((uint8_t)index);
}
const T& operator[](int8_t index) const noexcept
{
return operator[]((uint8_t)index);
}
};
} | true |
7615c65dadcd4e97e94fa5885ce1eda250a3aea0 | C++ | seader025/CplusPlus-Examples | /Class Examples/Dog.cpp | UTF-8 | 1,110 | 3.328125 | 3 | [] | no_license | // ClassPractice4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<conio.h>
using namespace std;
class Dog
{
private:
string name;
string breed;
int age;
const static double fee;
public:
void setDogName(string);
void setDogBreed(string);
void setDogAge(int);
void displayDogInfo();
};
const double Dog::fee = 12.25;
void Dog::setDogName(string dogName)
{
name = dogName;
}
void Dog::setDogBreed(string dogBreed)
{
breed = dogBreed;
}
void Dog::setDogAge(int dogAge)
{
age = dogAge;
}
void Dog::displayDogInfo()
{
cout << "Dog Details: " << endl
<< "Name: " << name << endl
<< "Breed: " << breed << endl
<< "Age: " << age << endl
<< "License Fee: " << fee << endl << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Dog sally;
sally.setDogAge(12);
sally.setDogBreed("Husky");
sally.setDogName("Sally");
sally.displayDogInfo();
// Force the console to stay open until a key is pressed
cout << endl;
system("pause");
return 0;
}
| true |
826a2dd3ea4863d70b31f0679b84910439be81a5 | C++ | Archibald-300/The-second-semester | /2_week/Problem_4.cpp | UTF-8 | 533 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int prime ( int num)
{
int count = 1, act_num = 2;
bool is_simple = false;
while (count < num) {
act_num += 1;
is_simple = true;
for (int i = 2; i * i < act_num + 1; i++) {
if (act_num % i == 0) {
is_simple = false;
i = act_num;
}
}
if (is_simple == true)
count++;
}
return act_num;
}
int main() {
cout << prime(21);
} | true |
d21baab953f421ad87999d1098e9996fa5375aa0 | C++ | aceduce/leetcode-practice | /leetcode/p543.cpp | UTF-8 | 502 | 2.734375 | 3 | [] | no_license | #include"Solutions.h"
// a true thinking process very much similar to p124
int p543::helper(TreeNode * r, int &ans) {
if (!r) return 0;
int diam_l = helper(r->left, ans);
int diam_r = helper(r->right, ans);
if (r->left) diam_l++;
if (r->right) diam_r++;
ans = max(ans, diam_l + diam_r); // diam_r/l >= 0;
int ret = max(diam_l, diam_r); // return one branch
return ret;
}
int p543::diameterOfBinaryTree(TreeNode* root) {
int ans = 0;
helper(root, ans);
return ans;
}
void p543::test() {
} | true |
fd44dd3c027cd1c26286ad5c5f63c7319bd741d0 | C++ | kaist-jisungpark/ImageRegistration | /app/imagefusion.hpp | UTF-8 | 1,947 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef IMAGEFUSION_HPP
#define IMAGEFUSION_HPP
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "../core/domain/fusion_services.hpp"
#include "../interfaces/image_repository.hpp"
#include "../infastructure/file_repository.hpp"
class imagefusion
{
public:
/**
* @brief perform_fusion_from_files is an application service which
* performs fusion of two images and the given register / fusion
* algorithms
* @param path_reference_image path to the reference image
* @param path_floating_image path to the floating image
* @param register_strategy name of the register strategy
* @param fusion_strategy name of the fusion strategy
* @return fused image
*/
static cv::Mat perform_fusion_from_files(
std::string path_reference_image,
std::string path_floating_image,
std::string register_strategy,
std::string fusion_strategy)
{
file_repository files(path_reference_image, path_floating_image);
cv::Mat reference_image = files.reference_image();
cv::Mat floating_image = files.floating_image();
return fuse_images(reference_image, floating_image,
register_strategy, fusion_strategy);
}
/**
* @brief fusion_strategies queries availabe fusion strategies
* @return a list of availabe fusion strategies
*/
static std::vector<std::string> fusion_strategies()
{
return available_fusion_algorithms();
}
/**
* @brief register_strategies queries availabe register strategies
* @return a list of availabe register strategies
*/
static std::vector<std::string> register_strategies()
{
return available_registration_algorithms();
}
};
#endif // IMAGEFUSION_HPP
| true |
e044695b7bbf0a8e780cac6db988bd23f27002fa | C++ | zsims/af | /bslib/src/bslib/blob/Address.cpp | UTF-8 | 2,148 | 3.078125 | 3 | [] | no_license | #include "bslib/blob/Address.hpp"
#include <boost/uuid/sha1.hpp>
#include <sstream>
#include <iomanip>
#include <algorithm>
namespace af {
namespace bslib {
namespace blob {
Address::Address(const void* rawBuffer, int bufferLength)
{
if (bufferLength != static_cast<int>(_address.max_size()))
{
throw InvalidAddressException("Given buffer is not of the correct size, expected " + _address.max_size());
}
std::copy_n(static_cast<const uint8_t*>(rawBuffer), bufferLength, _address.begin());
}
Address::Address(const binary_address& address)
: _address(address)
{
}
Address::Address(const std::string& address)
{
const auto length = 40;
if (address.length() != length)
{
throw InvalidAddressException("Given address is not a valid string-encoded address");
}
auto ai = 0;
for (auto i = 0; i < length; i += 2)
{
// The stream overload for hex will treat the parsing differently if the target is a char
int tmp;
std::istringstream(address.substr(i, 2)) >> std::hex >> tmp;
_address[ai] = static_cast<uint8_t>(tmp);
ai++;
}
}
bool Address::operator<(const Address& rhs) const
{
return _address < rhs._address;
}
bool Address::operator==(const Address& rhs) const
{
return _address == rhs._address;
}
bool Address::operator!=(const Address& rhs) const
{
return _address != rhs._address;
}
binary_address Address::ToBinary() const
{
return _address;
}
std::string Address::ToString() const
{
std::ostringstream result;
for (auto c: _address)
{
result << std::setfill('0') << std::setw(2) << std::hex << static_cast<uint16_t>(c);
}
return result.str();
}
Address Address::CalculateFromContent(const std::vector<uint8_t>& content)
{
if (content.size() == 0)
{
// Null value hash for SHA1
return Address("da39a3ee5e6b4b0d3255bfef95601890afd80709");
}
boost::uuids::detail::sha1 sha;
sha.process_bytes(&content[0], content.size());
unsigned int digest[5];
sha.get_digest(digest);
auto i = 0;
binary_address hash;
for (auto d : digest)
{
hash[i++] = (d >> 24) & 0xFF;
hash[i++] = (d >> 16) & 0xFF;
hash[i++] = (d >> 8) & 0xFF;
hash[i++] = d & 0xFF;
}
return Address(hash);
}
}
}
}
| true |
e4522ea6c37c73ccd0acfd78bc65f5e61043e1e4 | C++ | paalkristian/sb_mpc | /obstacle.cpp | UTF-8 | 1,517 | 2.65625 | 3 | [] | no_license | /*
* obstacle.cpp
*
* Created on: Dec 22, 2016
* Author: ingerbha
*/
#include "obstacle.h"
obstacle::obstacle(const Eigen::Matrix<double,9,1>& state, double T, double dt)
: n_samp_(T/dt)
{
T_ = T;
dt_ = dt;
x_.resize(n_samp_);
y_.resize(n_samp_);
u_.resize(n_samp_);
v_.resize(n_samp_);
A_ = state(5);
B_ = state(6);
C_ = state(7);
D_ = state(8);
l = A_ + B_;
w = C_ + D_;
calculatePosOffsets();
psi_ = state(2);
x_(0) = state(0) + os_x*cos(psi_) - os_y*sin(psi_);
y_(0) = state(1) + os_x*sin(psi_) + os_y*cos(psi_);
u_(0) = state(3);
v_(0) = state(4);
r11_ = cos(psi_);
r12_ = -sin(psi_);
r21_ = sin(psi_);
r22_ = cos(psi_);
calculateTrajectory();
};
obstacle::~obstacle(){
};
Eigen::VectorXd obstacle::getX(){
return x_;
}
Eigen::VectorXd obstacle::getY(){
return y_;
}
Eigen::VectorXd obstacle::getU(){
return u_;
}
Eigen::VectorXd obstacle::getV(){
return v_;
}
double obstacle::getPsi(){
return psi_;
}
double obstacle::getA(){
return A_;
}
double obstacle::getB(){
return B_;
}
double obstacle::getC(){
return C_;
}
double obstacle::getD(){
return D_;
}
double obstacle::getL(){
return l;
}
double obstacle::getW(){
return w;
}
void obstacle::calculatePosOffsets(){
os_x = A_-B_;
os_y = D_-C_;
}
void obstacle::calculateTrajectory()
{
for (int i = 1; i < n_samp_; i++)
{
x_(i) = (x_(i-1) + (r11_*u_(i-1) + r12_*v_(i-1))*dt_);
y_(i) = (y_(i-1) + (r21_*u_(i-1) + r22_*v_(i-1))*dt_);
u_(i) = (u_(i-1));
v_(i) = (v_(i-1));
}
};
| true |
5bbbf483390604f072b24f47ce0e2a73e91d378c | C++ | Suleiman99Hesham/OOP-Course | /Assignment_1/code/VendingMachine.cpp | UTF-8 | 4,469 | 3.078125 | 3 | [] | no_license | #include "VendingMachine.h"
#include "MoneyDrawer.h"
#include "FoodItem.h"
#include <iostream>
using namespace std;
class FoodItem;
class MoneyDrawer;
MoneyDrawer adding;
FoodItem listing;
VendingMachine::VendingMachine()
{
temp_twenty=0;
temp_ten=0;
temp_five=0;
temp_one=0;
temp_half=0;
temp_quarter=0;
checked_choice=0;
}
void VendingMachine::reset_temps()
{
temp_ten=0;
temp_five=0;
temp_one=0;
temp_half=0;
temp_quarter=0;
}
void VendingMachine::welcoming ()
{
adding.money=0;
listing.write_title();
listing.showlist();
getting_input();
}
int VendingMachine::converting_choice(string of_choice)
{
if(of_choice=="1")
return 1;
else if (of_choice=="2")
return 2;
else if (of_choice=="3")
return 3;
else if (of_choice=="4")
return 4;
else if (of_choice=="5")
return 5;
else if (of_choice=="6")
return 6;
else if (of_choice=="7")
return 7;
else if (of_choice=="8")
return 8;
else if (of_choice=="9")
return 9;
else if (of_choice=="9")
return 9;
else if (of_choice=="10")
return 10;
}
void VendingMachine::adding_temps()
{
adding.twenty+=temp_twenty;
adding.ten+=temp_ten;
adding.five+=temp_five;
adding.one+=temp_one;
adding.half+=temp_half;
adding.quarter+=temp_quarter;
reset_temps();
}
void VendingMachine::getting_input()
{
choose:
while(true){
cout<<"please deposit a coin or a bill in L.E: (0.25,0.5,1,5 or 10,20,e to end or 0 to cancel) ====>";
cin>>input;
if (input=="0")
{
adding.money=0;
cout<<"-------------------------------------------------------------------------------------------"<<endl;
listing.write_title();
listing.showlist();
goto choose;
}
else if(input=="0.25"){
adding.money+=0.25;
cout<<adding.getcredit()<<endl;
temp_quarter++;
}
else if(input=="0.5"){
adding.money+=0.5;
cout<<adding.getcredit()<<endl;
temp_half++;
}
else if(input=="1"){
adding.money+=1;
cout<<adding.getcredit()<<endl;
temp_one++;
}
else if(input=="5"){
adding.money+=5;
cout<<adding.getcredit()<<endl;
temp_five++;
}
else if(input=="10"){
adding.money+=10;
cout<<adding.getcredit()<<endl;
temp_ten++;
}
else if(input=="20"){
adding.money+=20;
cout<<adding.getcredit()<<endl;
temp_twenty++;
}
else if(input=="E"||input=="e"){
break;
}
else {
cout<<"invalid coin or bill !!"<<endl;
continue;
}
}
cout<<adding.getcredit()<<endl;
if((input=="e"||input=="E")&&adding.money==0)
{
cout<<"you can't buy anything as your credit isn't enough... thank you !"<<endl;
cout<<"-------------------------------------------------------------------------------------------"<<endl;
listing.write_title();
listing.showlist();
goto choose;
}
cout<<"-------------------------------------------------------------------------------------------"<<endl;
listing.showlist();
choose_2:
cout<<"\nplease enter your choice or e to end =====>";
cin>>choice;
if(choice=="e"||choice=="e")
{
cout<<adding.getcredit()<<endl;
cout<<"you choose to not buy any item..and you will get back your money..thank you !!"<<endl;
cout<<"------------------------------------------------------------------------------"<<endl;
adding.money=0;
reset_temps();
listing.write_title();
listing.showlist();
goto choose;
}
else if(choice=="1"||choice=="2"||choice=="3"||choice=="4"||choice=="5"
||choice=="6"||choice=="7"||choice=="8"||choice=="9"||choice=="10")
{
checked_choice=converting_choice(choice);
adding_temps();
}
else
{
cout<<"your choice is not correct.."<<endl;
goto choose_2;
}
final_decision=listing.choosing(checked_choice,adding);
if (final_decision==0)
{
welcoming();
}
if (final_decision==1)
{
listing.showlist();
goto choose;
}
}
| true |
8661454386629537f5995e33e521102e7aa805a0 | C++ | ziixu/Pro1 | /p5/x50141/x40141.cc | UTF-8 | 291 | 3.09375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int engreixa (int n) {
if (n < 10) return n;
else {
int e = engreixa(n/10);
int m = max(e%10, n%10);
return e*10 + m;
}
}
int main () {
int n;
cin >> n;
cout << engreixa(n) << endl;
} | true |
dc187903af89bf3a9103f151a0440aa6d360822a | C++ | landrew2/friendly-octo-waffle | /trace/Object.hpp | UTF-8 | 830 | 3.015625 | 3 | [] | no_license | // virtual class for any object
#ifndef OBJECT_HPP
#define OBJECT_HPP
// other classes we use DIRECTLY in our interface
#include "Appearance.hpp"
#include "Intersection.hpp"
#include "Vec3.hpp"
// classes we only use by pointer or reference
class World;
class Ray;
class Object {
protected: // data visible to children
Appearance d_appearance; // this object's appearance parameters
public: // constructor & destructor
Object();
Object(const Appearance &_appearance);
virtual ~Object();
public: // computational members
// return t for closest intersection with ray
virtual const Intersection intersect(const Ray &ray) const = 0;
// return color for intersection at t along ray r
virtual const Vec3 appearance(const World &w,
const Ray &r, float t) const = 0;
};
#endif
| true |
e2fa1f8d4f22209f8d1cf0e40f4e751cfdb02086 | C++ | echiou/caps-loc | /ex-2-rotary/ex-2-rotary.ino | UTF-8 | 4,722 | 2.796875 | 3 | [] | no_license | #include <Wire.h>
#include <Adafruit_NeoPixel.h>
#include <math.h>
#include "Adafruit_MPR121.h"
// Put n = number of capacitors here, n > 1.
#define NUMCAPS 3
// This code assumes that you are using a dielectric the same size of the capacitors,
// Put m = number of neopixels here.
#define NUMNEOPIXELS 16
#define NEOPIXELPIN 6
Adafruit_MPR121 cap = Adafruit_MPR121();
// Stores min, max, & current capacitance.
int channelMinMax[NUMCAPS * 3];
double channelRatios[NUMCAPS];
double segmentLen;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMNEOPIXELS, NEOPIXELPIN, NEO_GRB + NEO_KHZ800);
void setup() {
while (!Serial); // needed to keep leonardo/micro from starting too fast!
Serial.begin(9600);
// Default address is 0x5A, if tied to 3.3V its 0x5B
// If tied to SDA its 0x5C and if SCL then 0x5D
if (!cap.begin(0x5A)) {
Serial.println("MPR121 not found, check wiring?");
while(1);
}
Serial.println("MPR121 found.");
for (int i = 0; i < NUMCAPS * 3; i+=3) {
channelMinMax[i] = 9999; // Some large number.
channelMinMax[i + 1] = 0;
channelMinMax[i + 2] = 0;
}
// Set the segment lengths
segmentLen = 360.0 / NUMCAPS;
// Calibration time (2s)
unsigned long setupStart = millis();
Serial.println("Starting calibration (2 seconds). Move the slider or knob as much as possible!");
while(millis() - setupStart < 2000) {
for (int i = 0; i < NUMCAPS; i++ ) {
readAndCalibrate(i);
}
}
Serial.println("Finished calibration.");
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
// Reading & Calibration
for (int i = 0; i < NUMCAPS; i++ ) {
readAndCalibrate(i);
channelRatios[i] = getRatio(i);
}
// Finding Location
// Get two highest ratios.
int largestIndex = -1;
double largestValue = -1;
int secondIndex = -1;
double secondValue = -1;
for (int i = 0; i < NUMCAPS; i++) {
if (channelRatios[i] >= secondValue) {
if (channelRatios[i] >= largestValue) {
secondIndex = largestIndex;
secondValue = largestValue;
largestIndex = i;
largestValue = channelRatios[i];
} else {
secondIndex = i;
secondValue = channelRatios[i];
}
}
}
// Use locations to get index.
double loc;
if (largestIndex == 0 && secondIndex == NUMCAPS - 1) {
// Edge case, between capacitor 0 & last (closer to 0)
double center = 0;
loc = center + (largestValue - secondValue) / largestValue * (segmentLen / 2);
} else if (secondIndex == 0 && largestIndex == NUMCAPS - 1) {
// Edge case, between capacitor 0 & last (closer to last)
double center = 360;
loc = center - (largestValue - secondValue) / largestValue * (segmentLen / 2);
} else if (largestIndex < secondIndex) { //adjust from in front of largest index.
double center = segmentLen * (largestIndex + 1);
loc = center - (largestValue - secondValue) / largestValue * (segmentLen / 2);
} else { //adjust from below largest index.
double center = segmentLen * (largestIndex);
loc = center + (largestValue - secondValue) / largestValue * (segmentLen / 2);
}
Serial.print("Detected at location: ");
Serial.print(loc);
Serial.print(" degrees");
Serial.println();
singlePositionWhite(loc, 2);
strip.show();
// One reading every 0.1 second.
delay(50);
}
void readAndCalibrate(int i) {
int curData = cap.filteredData(i);
if (curData != 0) {
if (channelMinMax[i * 3] > curData) { // new Min
channelMinMax[i * 3] = curData;
} else if (channelMinMax[i * 3 + 2] < curData) { // new Max
channelMinMax[i * 3 + 2] = curData;
}
}
channelMinMax[i * 3 + 1] = curData;
}
double getRatio(int i) {
// Ratio is (cur - min) / (max - min)
double diffMaxMin = (channelMinMax[i * 3 + 2] - channelMinMax[i * 3]);
if (diffMaxMin == 0) { // don't divide by zero.
diffMaxMin + 1;
}
double ratio = double(channelMinMax[i * 3 + 1] - channelMinMax[i * 3]) / diffMaxMin;
return 1 - ratio; // Invert, so higher number when blocked.
}
// Parameter 1 pos = position of slider (double out of 100).
// Parameter 2 numPixels = number of pixels on either side to turn on (faded).
// Parameter 3 color = color of pixel.
void singlePositionWhite(double pos, int numPixels) {
int posScaled = (int) (pos / 360 * NUMNEOPIXELS);
// Debugging (lights on)
// Serial.print("Lighting up pixel ");
// Serial.print(posScaled);
// Serial.println();
for (int i=0; i < NUMNEOPIXELS; i++) {
int posDiff = posScaled - numPixels;
if (i == posScaled){
strip.setPixelColor(15 - i, strip.Color(100, 100, 100));
} else {
strip.setPixelColor(15 - i, 0);
}
}
}
| true |
e83b34370bd482634e64a46275ff5253be1235b9 | C++ | f516106199/flowchar | /include/token.hpp | UTF-8 | 2,499 | 2.90625 | 3 | [] | no_license | #pragma once
#ifndef _TOKEN_HPP_
#define _TOKEN_Hpp_
#include<string>
#include<utility>
#include<set>
namespace fc{
namespace ft{
class token{
public:
enum class Kind:int{
BEGIN,
STM,
LBRACE,
RBRACE,
IF,
COND,
WHILE,
END,
SEM,
ELSE,
}kind;
std::pair<int,int>pos;
static const char space;
static const char lbrace ;
static const char rbrace;
static const char lparen;
static const char rparen;
static const char semicolon;
static const std::string ifToken;
static const std::string whileToken;
static const std::string elseToken;
static const std::set<char>blank;
token(Kind kind):kind(kind){}
token(Kind kind ,std::pair<int,int>pos):kind(kind),pos(pos){}
};
class StmToken:public token{
public:
std::string text;
StmToken(std::pair<int,int>pos,std::string text):token(Kind::STM,pos),text(text){}
};
class CondToken:public token{
public:
std::string text;
CondToken(std::pair<int,int>pos,std::string text):token(Kind::COND,pos),text(text){}
};
class IfToken:public token{
public:
IfToken(std::pair<int,int>pos):token(Kind::IF,pos){}
};
class ElseToken:public token{
public:
ElseToken(std::pair<int,int>pos):token(Kind::ELSE,pos){}
};
class RbraceToken:public token{
public:
RbraceToken(std::pair<int,int>pos):token(Kind::RBRACE,pos){}
};
class LbraceToken:public token{
public:
LbraceToken(std::pair<int,int>pos):token(Kind::LBRACE,pos){}
};
class WhileToken:public token{
public:
WhileToken(std::pair<int,int>pos):token(Kind::WHILE,pos){}
};
class BeginToken:public token{
public:
BeginToken(std::pair<int,int>pos):token(Kind::BEGIN,pos){}
};
class EndToken:public token{
public:
EndToken(std::pair<int,int>pos):token(Kind::END,pos){}
};
} //namespace ft
}//namespace fc
#endif | true |
b9721ee9fa4c7d42269c363a167242355dba635d | C++ | guigaoliveira/qtsupervisory | /QtTcpClientConsumer/plotter.cpp | UTF-8 | 2,722 | 3.1875 | 3 | [] | no_license | #include <QPainter>
#include <QBrush>
#include <QPen>
#include <QColor>
#include <cmath>
#include "plotter.h"
#define MAX_ITEMS 30.0
/**
* @brief Plotter::Plotter
* @param parent
*/
Plotter::Plotter(QWidget *parent) : QWidget(parent)
{
times = new vector<float>();
values = new vector<float>();
}
/**
* @brief Plotter::~Plotter
*/
Plotter::~Plotter()
{
delete times;
delete values;
}
/**
* @brief Plotter::paintEvent
* @param event
* @details Evento para atualizar o gráfico
*/
void Plotter::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QBrush brush;
QPen pen;
painter.setRenderHint(QPainter::Antialiasing);
brush.setColor(Qt::white);
brush.setStyle(Qt::SolidPattern);
painter.setBrush(brush);
pen.setColor(QColor(33, 150, 243));
pen.setWidth(1);
painter.setPen(pen);
painter.drawRect(0, 0, this->width(), this->height());
pen.setColor(QColor(210, 210, 210));
pen.setStyle(Qt::SolidLine);
painter.setPen(pen);
int gap = 30;
for (int i = width() / gap; i < width(); i = i + width() / gap)
{
painter.drawLine(i, 0, i, height());
}
for (int i = height() / gap; i < height(); i = i + height() / gap)
{
painter.drawLine(0, i, width(), i);
}
pen.setWidth(2);
pen.setStyle(Qt::SolidLine);
pen.setColor(QColor(33, 150, 243));
painter.setPen(pen);
int data_total = this->times->size();
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = height();
int count = 0;
double max_value = 0.0;
if (this->values->size() > 0)
{
max_value = *std::max_element(values->begin(), values->end());
}
for (vector<float>::iterator i = values->begin(); i != values->end(); i++)
{
x1 = x2;
y1 = y2;
x2 = (count++ / (float)data_total) * width();
y2 = height() - ((*i / max_value) * height());
painter.drawLine(x1, y1, x2, y2);
}
}
/**
* @brief Plotter::setPlot
* @param time
* @param values
* @details Plota o valores no gráfico
*/
void Plotter::setPlot(vector<float> time, vector<float> values)
{
if (time.size() != values.size())
{
return;
}
this->times->clear();
this->values->clear();
for (vector<float>::iterator i = time.begin(); i != time.end(); i++)
{
this->times->push_back(*i);
}
for (vector<float>::iterator i = values.begin(); i != values.end(); i++)
{
this->values->push_back(*i);
}
this->repaint();
}
/**
* @brief Plotter::clear
* @details limpa os valores plotados no gráfico
*/
void Plotter::clear()
{
this->times->clear();
this->values->clear();
this->repaint();
}
| true |
b5a254de3c1ba11334707c6bcc51339b4f45a066 | C++ | meduag/Projetos-Arduino-Proteus-Simulation | /inos/PWM.ino | UTF-8 | 292 | 2.65625 | 3 | [] | no_license | const int PWM_Pin = 3;
void setup() {
// put your setup code here, to run once:
pinMode(PWM_Pin, OUTPUT);
analogWriteFrequency(PWM_Pin, 750000); // Teensy 3.0 pin 3 also changes to 375 kHz
}
void loop() {
// put your main code here, to run repeatedly:
analogWrite(PWM_Pin, 4);
}
| true |
94e57ef28d8e17c0c61915afaadf82b9afbf11dc | C++ | simdjson/simdjson | /include/simdjson/generic/ondemand/json_iterator.h | UTF-8 | 12,030 | 2.546875 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSL-1.0"
] | permissive | #ifndef SIMDJSON_GENERIC_ONDEMAND_JSON_ITERATOR_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#define SIMDJSON_GENERIC_ONDEMAND_JSON_ITERATOR_H
#include "simdjson/generic/ondemand/base.h"
#include "simdjson/generic/implementation_simdjson_result_base.h"
#include "simdjson/generic/ondemand/token_iterator.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
namespace ondemand {
/**
* Iterates through JSON tokens, keeping track of depth and string buffer.
*
* @private This is not intended for external use.
*/
class json_iterator {
protected:
token_iterator token{};
ondemand::parser *parser{};
/**
* Next free location in the string buffer.
*
* Used by raw_json_string::unescape() to have a place to unescape strings to.
*/
uint8_t *_string_buf_loc{};
/**
* JSON error, if there is one.
*
* INCORRECT_TYPE and NO_SUCH_FIELD are *not* stored here, ever.
*
* PERF NOTE: we *hope* this will be elided into control flow, as it is only used (a) in the first
* iteration of the loop, or (b) for the final iteration after a missing comma is found in ++. If
* this is not elided, we should make sure it's at least not using up a register. Failing that,
* we should store it in document so there's only one of them.
*/
error_code error{SUCCESS};
/**
* Depth of the current token in the JSON.
*
* - 0 = finished with document
* - 1 = document root value (could be [ or {, not yet known)
* - 2 = , or } inside root array/object
* - 3 = key or value inside root array/object.
*/
depth_t _depth{};
/**
* Beginning of the document indexes.
* Normally we have root == parser->implementation->structural_indexes.get()
* but this may differ, especially in streaming mode (where we have several
* documents);
*/
token_position _root{};
/**
* Normally, a json_iterator operates over a single document, but in
* some cases, we may have a stream of documents. This attribute is meant
* as meta-data: the json_iterator works the same irrespective of the
* value of this attribute.
*/
bool _streaming{false};
public:
simdjson_inline json_iterator() noexcept = default;
simdjson_inline json_iterator(json_iterator &&other) noexcept;
simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept;
simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default;
simdjson_inline json_iterator &operator=(const json_iterator &other) noexcept = default;
/**
* Skips a JSON value, whether it is a scalar, array or object.
*/
simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept;
/**
* Tell whether the iterator is still at the start
*/
simdjson_inline bool at_root() const noexcept;
/**
* Tell whether we should be expected to run in streaming
* mode (iterating over many documents). It is pure metadata
* that does not affect how the iterator works. It is used by
* start_root_array() and start_root_object().
*/
simdjson_inline bool streaming() const noexcept;
/**
* Get the root value iterator
*/
simdjson_inline token_position root_position() const noexcept;
/**
* Assert that we are at the document depth (== 1)
*/
simdjson_inline void assert_at_document_depth() const noexcept;
/**
* Assert that we are at the root of the document
*/
simdjson_inline void assert_at_root() const noexcept;
/**
* Tell whether the iterator is at the EOF mark
*/
simdjson_inline bool at_end() const noexcept;
/**
* Tell whether the iterator is live (has not been moved).
*/
simdjson_inline bool is_alive() const noexcept;
/**
* Abandon this iterator, setting depth to 0 (as if the document is finished).
*/
simdjson_inline void abandon() noexcept;
/**
* Advance the current token without modifying depth.
*/
simdjson_inline const uint8_t *return_current_and_advance() noexcept;
/**
* Returns true if there is a single token in the index (i.e., it is
* a JSON with a scalar value such as a single number).
*
* @return whether there is a single token
*/
simdjson_inline bool is_single_token() const noexcept;
/**
* Assert that there are at least the given number of tokens left.
*
* Has no effect in release builds.
*/
simdjson_inline void assert_more_tokens(uint32_t required_tokens=1) const noexcept;
/**
* Assert that the given position addresses an actual token (is within bounds).
*
* Has no effect in release builds.
*/
simdjson_inline void assert_valid_position(token_position position) const noexcept;
/**
* Get the JSON text for a given token (relative).
*
* This is not null-terminated; it is a view into the JSON.
*
* @param delta The relative position of the token to retrieve. e.g. 0 = next token, -1 = prev token.
*
* TODO consider a string_view, assuming the length will get stripped out by the optimizer when
* it isn't used ...
*/
simdjson_inline const uint8_t *peek(int32_t delta=0) const noexcept;
/**
* Get the maximum length of the JSON text for the current token (or relative).
*
* The length will include any whitespace at the end of the token.
*
* @param delta The relative position of the token to retrieve. e.g. 0 = next token, -1 = prev token.
*/
simdjson_inline uint32_t peek_length(int32_t delta=0) const noexcept;
/**
* Get a pointer to the current location in the input buffer.
*
* This is not null-terminated; it is a view into the JSON.
*
* You may be pointing outside of the input buffer: it is not generally
* safe to dereference this pointer.
*/
simdjson_inline const uint8_t *unsafe_pointer() const noexcept;
/**
* Get the JSON text for a given token.
*
* This is not null-terminated; it is a view into the JSON.
*
* @param position The position of the token to retrieve.
*
* TODO consider a string_view, assuming the length will get stripped out by the optimizer when
* it isn't used ...
*/
simdjson_inline const uint8_t *peek(token_position position) const noexcept;
/**
* Get the maximum length of the JSON text for the current token (or relative).
*
* The length will include any whitespace at the end of the token.
*
* @param position The position of the token to retrieve.
*/
simdjson_inline uint32_t peek_length(token_position position) const noexcept;
/**
* Get the JSON text for the last token in the document.
*
* This is not null-terminated; it is a view into the JSON.
*
* TODO consider a string_view, assuming the length will get stripped out by the optimizer when
* it isn't used ...
*/
simdjson_inline const uint8_t *peek_last() const noexcept;
/**
* Ascend one level.
*
* Validates that the depth - 1 == parent_depth.
*
* @param parent_depth the expected parent depth.
*/
simdjson_inline void ascend_to(depth_t parent_depth) noexcept;
/**
* Descend one level.
*
* Validates that the new depth == child_depth.
*
* @param child_depth the expected child depth.
*/
simdjson_inline void descend_to(depth_t child_depth) noexcept;
simdjson_inline void descend_to(depth_t child_depth, int32_t delta) noexcept;
/**
* Get current depth.
*/
simdjson_inline depth_t depth() const noexcept;
/**
* Get current (writeable) location in the string buffer.
*/
simdjson_inline uint8_t *&string_buf_loc() noexcept;
/**
* Report an unrecoverable error, preventing further iteration.
*
* @param error The error to report. Must not be SUCCESS, UNINITIALIZED, INCORRECT_TYPE, or NO_SUCH_FIELD.
* @param message An error message to report with the error.
*/
simdjson_inline error_code report_error(error_code error, const char *message) noexcept;
/**
* Log error, but don't stop iteration.
* @param error The error to report. Must be INCORRECT_TYPE, or NO_SUCH_FIELD.
* @param message An error message to report with the error.
*/
simdjson_inline error_code optional_error(error_code error, const char *message) noexcept;
/**
* Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with
* N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero.
* The buffer (tmpbuf) is padded with space characters.
*/
simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept;
simdjson_inline token_position position() const noexcept;
/**
* Write the raw_json_string to the string buffer and return a string_view.
* Each raw_json_string should be unescaped once, or else the string buffer might
* overflow.
*/
simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept;
simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept;
simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept;
simdjson_inline error_code consume_character(char c) noexcept;
#if SIMDJSON_DEVELOPMENT_CHECKS
simdjson_inline token_position start_position(depth_t depth) const noexcept;
simdjson_inline void set_start_position(depth_t depth, token_position position) noexcept;
#endif
/* Useful for debugging and logging purposes. */
inline std::string to_string() const noexcept;
/**
* Returns the current location in the document if in bounds.
*/
inline simdjson_result<const char *> current_location() const noexcept;
/**
* Updates this json iterator so that it is back at the beginning of the document,
* as if it had just been created.
*/
inline void rewind() noexcept;
/**
* This checks whether the {,},[,] are balanced so that the document
* ends with proper zero depth. This requires scanning the whole document
* and it may be expensive. It is expected that it will be rarely called.
* It does not attempt to match { with } and [ with ].
*/
inline bool balanced() const noexcept;
protected:
simdjson_inline json_iterator(const uint8_t *buf, ondemand::parser *parser) noexcept;
/// The last token before the end
simdjson_inline token_position last_position() const noexcept;
/// The token *at* the end. This points at gibberish and should only be used for comparison.
simdjson_inline token_position end_position() const noexcept;
/// The end of the buffer.
simdjson_inline token_position end() const noexcept;
friend class document;
friend class document_stream;
friend class object;
friend class array;
friend class value;
friend class raw_json_string;
friend class parser;
friend class value_iterator;
template <typename... Args>
friend simdjson_inline void logger::log_line(const json_iterator &iter, const char *title_prefix, const char *title, std::string_view detail, int delta, int depth_delta, logger::log_level level, Args&&... args) noexcept;
template <typename... Args>
friend simdjson_inline void logger::log_line(const json_iterator &iter, token_position index, depth_t depth, const char *title_prefix, const char *title, std::string_view detail, logger::log_level level, Args&&... args) noexcept;
}; // json_iterator
} // namespace ondemand
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
namespace simdjson {
template<>
struct simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::json_iterator> : public SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::json_iterator> {
public:
simdjson_inline simdjson_result(SIMDJSON_IMPLEMENTATION::ondemand::json_iterator &&value) noexcept; ///< @private
simdjson_inline simdjson_result(error_code error) noexcept; ///< @private
simdjson_inline simdjson_result() noexcept = default;
};
} // namespace simdjson
#endif // SIMDJSON_GENERIC_ONDEMAND_JSON_ITERATOR_H | true |
a815dca79eadaebf2adcafdb5c67fefc555d143b | C++ | drlongle/leetcode | /algorithms/problem_1230/solution.cpp | UTF-8 | 1,830 | 3.40625 | 3 | [] | no_license | /*
1230. Toss Strange Coins
Medium
You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.
Example 1:
Input: prob = [0.4], target = 1
Output: 0.40000
Example 2:
Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
Output: 0.03125
*/
#include <algorithm>
#include <atomic>
#include <bitset>
#include <cassert>
#include <cmath>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#define ll long long
#define ull unsigned long long
class Solution {
public:
double probabilityOfHeads(vector<double>& prob, int target) {
int n = prob.size();
vector<vector<double>> dp(n, vector<double>(target + 1, 0.0));
if(target) dp[0][1] = prob[0];
dp[0][0] = 1.0 - prob[0];
for(int i = 1; i < n; i ++){
dp[i][0] = dp[i - 1][0] * (1 - prob[i]);
for(int j = 1; j <= target; j ++)
dp[i][j] = dp[i - 1][j] * (1 - prob[i]) + dp[i - 1][j - 1] * prob[i];
}
return dp[n - 1][target];
}
};
int main() {
Solution sol;
vector<double> prob;
int target;
// Output: 0.40000
prob = {0.4}, target = 1;
// Output: 0.03125
prob = {0.5,0.5,0.5,0.5,0.5}, target = 0;
// Output: 0
prob = {1,1,1,1,1,1,1,1,1,1}, target = 9;
// Output: 0.182
prob = {0.2,0.8,0,0.3,0.5}, target = 3;
cout << "Result: " << sol.probabilityOfHeads(prob, target) << endl;
return 0;
}
| true |
189daa53b1936185c114c3650b32a40d0717687a | C++ | Remi-Coulom/joedb | /test/Readonly_File_Connection_Test.cpp | UTF-8 | 2,841 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "joedb/concurrency/Readonly_File_Connection.h"
#include "joedb/concurrency/Interpreted_Client.h"
#include "joedb/journal/Test_File.h"
#include "gtest/gtest.h"
namespace joedb
{
////////////////////////////////////////////////////////////////////////////
TEST(Readonly_Connection, pull)
////////////////////////////////////////////////////////////////////////////
{
Test_File server_file;
Writable_Journal server_journal(server_file);
Readonly_File_Connection connection(server_file);
Test_File client_file;
Interpreted_Client client(connection, client_file);
EXPECT_EQ(0, int(client.get_database().get_tables().size()));
server_journal.create_table("person");
client.pull();
EXPECT_EQ(0, int(client.get_database().get_tables().size()));
server_journal.flush();
client.pull();
EXPECT_EQ(0, int(client.get_database().get_tables().size()));
server_journal.checkpoint(Commit_Level::no_commit);
client.pull();
EXPECT_EQ(1, int(client.get_database().get_tables().size()));
}
////////////////////////////////////////////////////////////////////////////
TEST(Readonly_Connection, no_write)
////////////////////////////////////////////////////////////////////////////
{
Test_File server_file;
Writable_Journal server_journal(server_file);
Readonly_File_Connection connection(server_file);
Test_File client_file;
Interpreted_Client client(connection, client_file);
EXPECT_ANY_THROW
(
client.transaction([](const Readable &readable, Writable &writable){});
);
}
////////////////////////////////////////////////////////////////////////////
TEST(Readonly_Connection, mismatch)
////////////////////////////////////////////////////////////////////////////
{
Test_File server_file;
{
Writable_Journal server_journal(server_file);
server_journal.create_table("person");
server_journal.checkpoint(Commit_Level::no_commit);
}
Test_File client_file;
{
Writable_Journal client_journal(client_file);
client_journal.create_table("city");
client_journal.checkpoint(Commit_Level::no_commit);
}
Readonly_File_Connection connection(server_file);
EXPECT_ANY_THROW
(
Interpreted_Client client(connection, client_file);
);
}
////////////////////////////////////////////////////////////////////////////
TEST(Readonly_Connection, push)
////////////////////////////////////////////////////////////////////////////
{
Test_File server_file;
Writable_Journal server_journal(server_file);
Test_File client_file;
{
Writable_Journal client_journal(client_file);
client_journal.create_table("city");
client_journal.checkpoint(Commit_Level::no_commit);
}
Readonly_File_Connection connection(server_file);
Interpreted_Client client(connection, client_file);
EXPECT_ANY_THROW
(
client.push_unlock();
);
}
}
| true |
009a2771af1b5e5d890c2ba847ece58d2d9f382d | C++ | zxx43/Tiny3D | /Win32Project1/node/staticNode.cpp | UTF-8 | 2,222 | 2.515625 | 3 | [] | no_license | #include "staticNode.h"
#include "../render/staticDrawcall.h"
#include "../render/terrainDrawcall.h"
#include "../render/waterDrawcall.h"
#include "../util/util.h"
#include "../scene/scene.h"
StaticNode::StaticNode(const vec3& position):Node(position, vec3(0, 0, 0)) {
batch = NULL;
dynamicBatch = true;
fullStatic = false;
type = TYPE_STATIC;
}
StaticNode::~StaticNode() {
if(batch)
delete batch;
batch=NULL;
}
void StaticNode::addObjects(Scene* scene,Object** objectArray,int count) {
for(int i=0;i<count;i++)
addObject(scene,objectArray[i]);
}
void StaticNode::createBatch() {
if (batch) delete batch;
batch = new Batch();
int vertCount = 0, indCount = 0;
for (uint i = 0; i < objects.size(); i++) {
vertCount += objects[i]->mesh->vertexCount;
indCount += objects[i]->mesh->indexCount;
}
batch->initBatchBuffers(vertCount, indCount);
batch->setDynamic(false);
for(uint i=0;i<objects.size();i++) {
Object* object=objects[i];
batch->pushMeshToBuffers(object->mesh,object->material,fullStatic,object->transformMatrix,object->normalMatrix);
}
if (drawcall) delete drawcall;
if (!batch->hasTerrain && !batch->hasWater)
drawcall = new StaticDrawcall(batch);
else if (batch->hasTerrain)
drawcall = new TerrainDrawcall((Terrain*)(objects[0]->mesh), batch);
else if (batch->hasWater)
drawcall = new WaterDrawcall((Water*)(objects[0]->mesh), batch);
}
void StaticNode::prepareDrawcall() {
if (!dynamicBatch) createBatch();
needCreateDrawcall = false;
}
void StaticNode::updateRenderData() {
if (dynamicBatch) return;
for (unsigned int i = 0; i < objects.size(); i++) {
Object* object = objects[i];
batch->updateMatrices(i, object->transformMatrix, NULL);
}
}
void StaticNode::updateDrawcall() {
if (!dynamicBatch && drawcall && !batch->hasTerrain && !batch->hasWater)
((StaticDrawcall*)drawcall)->updateMatrices();
needUpdateDrawcall = false;
}
bool StaticNode::isFullStatic() {
return fullStatic;
}
void StaticNode::setFullStatic(bool fullStatic) {
this->fullStatic = fullStatic;
if(fullStatic) setDynamicBatch(false);
}
bool StaticNode::isDynamicBatch() {
return dynamicBatch;
}
void StaticNode::setDynamicBatch(bool dynamic) {
dynamicBatch = dynamic;
}
| true |
9cc50e1845f92e777f3d0173c796e8e56ca77e8b | C++ | Lujie1996/Leetcode | /42. Trapping Rain Water/42. Trapping Rain Water/main.cpp | UTF-8 | 1,228 | 3.234375 | 3 | [] | no_license | //
// main.cpp
// 42. Trapping Rain Water
//
// Created by Jie Lu on 2018/4/3.
// Copyright © 2018 Jie Lu. All rights reserved.
//
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int trap(vector<int>& height) {
if (height.size() <= 2) {
return 0;
}
int i, maxHeight, maxHeightIndex;
maxHeight = maxHeightIndex = 0;
for (i = 0; i < height.size(); i++) {
if(height[i] > maxHeight) {
maxHeightIndex = i;
maxHeight = height[i];
}
}
int root = height[0], res = 0;
for (i = 0; i < maxHeightIndex; i++) {
if (height[i] > root) {
root = height[i];
}
else {
res += (root - height[i]);
}
}
root = height[height.size() - 1];
for (i = (int)height.size() - 1; i > maxHeightIndex; i--) {
if (height[i] > root) {
root = height[i];
}
else {
res += (root - height[i]);
}
}
return res;
}
int main(int argc, const char * argv[]) {
// int nums[] = {0,1,0,2,1,0,1,3,2,1,2,1};
int nums[] = {5,2,1,2,1,5};
vector<int> height(nums, nums + 6);
cout<<trap(height)<<endl;
return 0;
}
| true |
2e71bbe7739e75b0886f66c4dd2157684217e147 | C++ | hyunbingil/OpenCV_lecture | /week4/we04_ex01.cpp | UHC | 840 | 3.09375 | 3 | [] | no_license | #include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
// Scalar Ŭ? ϳ ȼ Ÿ Ŭ̴.
// Scalar 4 .(rgb )
int functionn() {
Scalar_<uchar> red(0, 0, 255);
Scalar_<int> blue(255, 0, 0);
Scalar_<double> color1(500);
Scalar_<float> color2(100.f, 200.f, 125.9f);
Vec3d green(0, 0, 300.5);
Scalar green1 = color1 + (Scalar)green; // Scalar double ⺻̴.
Scalar green2 = color2 + (Scalar_<float>)green;
cout << "blue = " << blue[0] << ", " << blue[1];
cout << ", " << blue[1] << ", " << blue[2] << endl;
cout << "red = " << red << endl;
cout << "green = " << green << endl << endl;
cout << "green1 = " << green1 << endl;
cout << "green2 = " << green2 << endl;
system("pause");
return 0;
}
| true |
663a58095186b7640f9ce964f4e2e6f84bcf8dea | C++ | morikoh/io_library | /inputDevice/lib_photoReflector/lib_photoReflector.ino | UTF-8 | 346 | 2.515625 | 3 | [] | no_license | /*
インプットライブラリ_フォトリフレクタ
フォトリフレクタからのアナログ入力値をシリアルモニタに表示する
*/
void setup() {
Serial.begin(9600); // シリアル通信速度
}
void loop() {
float photoReflectorValue = analogRead(A0);
Serial.println(photoReflectorValue);
}
| true |
dd09f0d00d05f1e1ed0ee15adf30774483a65689 | C++ | Bolodya1997/Proxy | /cache/cache.cpp | UTF-8 | 1,755 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include "cache.h"
#include "../logging.h"
using namespace std;
using namespace chrono;
cache_entry *cache::get_entry(string &absolute_url) {
auto it = entry_map.find(absolute_url);
if (it == entry_map.end())
return NULL;
if (!it->second->is_valid()) {
remove_entry(it);
return NULL;
}
return it->second;
}
cache_entry *cache::add_entry(string &absolute_url, unsigned long size,
pollable *server) {
if (size > CACHE_PAGE_SIZE)
throw (no_place_exception());
millis cur = duration_cast<millis>(system_clock::now().time_since_epoch());
while (this->size + size > CACHE_CAPACITY)
remove_last_used_entry(cur);
entry_map.insert({ absolute_url, new cache_entry(size) });
this->size += size;
cache_entry *entry = entry_map[absolute_url];
logging::store(absolute_url);
sessions.insert(new cache_loader(server, entry));
return entry;
}
void cache::remove_last_used_entry(millis min_time) {
auto min_it = entry_map.end();
for (auto it = entry_map.begin(); it != entry_map.end(); it++) {
cache_entry *entry = it->second;
if (entry->is_in_use() || !entry->is_complete())
continue;
millis entry_time = entry->get_last_access_time();
if (entry_time < min_time) {
min_time = entry_time;
min_it = it;
}
}
if (min_it == entry_map.end())
throw (no_place_exception());
remove_entry(min_it);
}
void cache::remove_entry(map<string, cache_entry *>::iterator it) {
logging::remove(it->first);
cache_entry *to_del = it->second;
entry_map.erase(it);
size -= to_del->get_size();
delete to_del;
}
| true |
2dfa9e6f3aa4e4b3b5145d7d9b44afb86fcbf114 | C++ | mtreviso/university | /Programming Languages/C e C++/Avancado/Aula5/codigos/ex1.cpp | UTF-8 | 6,128 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <typeinfo>
using namespace std;
/////////////////////////////////////
// EMPREGADO
/////////////////////////////////////
class Empregado{
private:
static unsigned int id;
string nome, email, celular;
float salario;
int departamento;
public:
Empregado(){
this->id++;
};
Empregado(string nome, string email, string celular, float salario, int departamento);
string getNome(){
return this->nome;
}
void setNome(string nome){
this->nome = nome;
}
string getEmail(){
return this->email;
}
void setEmail(string email){
this->email = email;
}
string getCelular() {
return this->celular;
}
void setCelular(string celular) {
this->celular = celular;
}
float getSalario() {
return this->salario;
}
void setSalario(float salario) {
if (salario > 0.0f)
this->salario = salario;
}
int getDepartamento() {
return this->departamento;
}
void setDepartamento(int departamento) {
this->departamento = departamento;
}
int getId(){
return this->id;
}
};
unsigned int Empregado::id = 0;
Empregado::Empregado(string nome, string email, string celular, float salario, int departamento){
this->id++;
this->setNome(nome);
this->setEmail(email);
this->setCelular(celular);
this->setSalario(salario);
this->setDepartamento(departamento);
}
std::ostream& operator<<(std::ostream &output, Empregado &e){
cout << typeid(e).name() << endl;
output << "Nome: " << e.getNome() << endl;
output << "Email: " << e.getEmail() << endl;
output << "Celular: " << e.getCelular() << endl;
output << "Salario: " << e.getSalario() << endl;
output << "Departamento: " << e.getDepartamento() << endl << endl;
return output;
}
/////////////////////////////////////
// GERENTE <- Empregado
/////////////////////////////////////
class Gerente: public Empregado{
private:
Empregado *gerenciados;
int numGerenciados;
public:
Gerente(string nome, string email, string celular, float salario, int departamento, Empregado *gerenciados, int numGerenciados);
Empregado *getGerenciados(){
return this->gerenciados;
}
void setGerenciados(Empregado *gerenciados){
this->gerenciados = gerenciados;
}
int getNumGerenciados(){
return this->numGerenciados;
}
void setNumGerenciados(int numGerenciados){
this->numGerenciados = numGerenciados;
}
};
Gerente::Gerente(string nome, string email, string celular, float salario, int departamento, Empregado *gerenciados, int numGerenciados):
Empregado(nome, email, celular, salario, departamento){
this->setGerenciados(gerenciados);
this->setNumGerenciados(numGerenciados);
};
/////////////////////////////////////
// SECRETARIA <- Empregado
/////////////////////////////////////
class Secretaria: public Empregado{
private:
Empregado chefe;
public:
Secretaria(string nome, string email, string celular, float salario, int departamento, Empregado chefe);
Empregado getChefe(){
return this->chefe;
}
void setChefe(Empregado chefe){
this->chefe = chefe;
}
};
Secretaria::Secretaria(string nome, string email, string celular, float salario, int departamento, Empregado chefe):
Empregado(nome, email, celular, salario, departamento){
this->setChefe(chefe);
}
/////////////////////////////////////
// TEMPORARIO
/////////////////////////////////////
class Temporario{
private:
string dataContrato;
int numMeses;
public:
Temporario(string dataContrato, int numMeses){
this->setDataContrario(dataContrato);
this->setNumMeses(numMeses);
};
string getDataContrato(){
return this->dataContrato;
}
void setDataContrario(string dataContrato){
this->dataContrato = dataContrato;
}
int getNumMeses(){
return this->numMeses;
}
void setNumMeses(int numMeses){
this->numMeses = numMeses;
}
};
/////////////////////////////////////
// SECRETARIA TEMPORARIA
/////////////////////////////////////
class SecretariaTemporaria: public Temporario, public Secretaria{
public:
SecretariaTemporaria(string dataContrato, int numMeses, string nome, string email, string celular, float salario, int departamento, Empregado chefe);
};
SecretariaTemporaria::SecretariaTemporaria(string dataContrato, int numMeses, string nome, string email, string celular, float salario, int departamento, Empregado chefe):
Temporario(dataContrato, numMeses),
Secretaria(nome, email, celular, salario, departamento, chefe){
}
/////////////////////////////////////
// CONSULTOR
/////////////////////////////////////
class Consultor: public Temporario, public Empregado{
private:
string areaConsutoria;
public:
string getAreaconsultoria() {
return this->areaConsutoria;
}
void setAreaConsultoria(string areaConsultoria) {
this->areaConsutoria = areaConsutoria;
}
};
int main(int argc, char const *argv[]){
cout << "MINHA EMPRESA\n=======================\n" << endl;
Empregado *e1 = new Empregado();
cout << e1->getId() << endl;
e1->setNome("Marcos");
e1->setEmail("marcos@gmail.com");
e1->setCelular("84132621");
e1->setSalario(450.75);
e1->setDepartamento(1);
cout << *e1;
Empregado *e2 = new Empregado("Jesus", "jesus@gmail.com", "99669966", 55.55, 1);
cout << e2->getId() << endl;
cout << *e2;
int qtdEmpregados = 2;
Empregado *arr = new Empregado[qtdEmpregados];
arr[0] = *e1;
arr[1] = *e2;
Gerente *g1 = new Gerente("Satanas", "satan@gmail.com", "66666666", 66.66, 2, arr, qtdEmpregados);
Empregado *temp = g1->getGerenciados();
cout << endl << "USUARIOS MINISTRADOS PELO GERENTE:" << endl;
cout << g1->getId() << endl;
cout << *g1 << endl;
for(int i=0; i<g1->getNumGerenciados(); i++)
cout << temp[i] << endl;
SecretariaTemporaria *st1 = new SecretariaTemporaria("08/09/2014", 8, "Juliana", "ju@gmail.com", "99556677", 69.69, 4, *e1);
cout << *st1 << endl;
cout << st1->getNumMeses() << "meses" << endl;
cout << st1->getDataContrato() << endl;
delete e1;
delete e2;
delete[] arr; //ja deleta o temp tbm, nao fez clone do objeto, apenas o referenciou (partilham a mesma instancia (like others languages))
delete g1;
delete st1;
return 0;
} | true |
8e66d7c70b3502932242a1d0e716ac7c9fab236c | C++ | rdffg/bcaa_importer | /model/propertyclassvaluetype.cpp | UTF-8 | 1,721 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include "propertyclassvaluetype.h"
#include "saveerror.h"
#include <QMetaEnum>
#include "QDjangoQuerySet.h"
using namespace model;
PropertyClassValueType::PropertyClassValueType(QObject *parent) : QDjangoModel(parent)
{
}
PropertyClassValueType::ValueType PropertyClassValueType::type() const
{
return m_type;
}
void PropertyClassValueType::setType(const PropertyClassValueType::ValueType &type)
{
m_type = type;
}
QString PropertyClassValueType::description() const
{
return m_description;
}
void PropertyClassValueType::setDescription(const QString &description)
{
m_description = description;
}
void PropertyClassValueType::populate()
{
const QMetaObject &mo = PropertyClassValueType::staticMetaObject;
int index = mo.indexOfEnumerator("ValueType");
QMetaEnum metaEnum = mo.enumerator(index);
QDjangoQuerySet<PropertyClassValueType> query;
if (query.count() < metaEnum.keyCount())
{
for (int i = 1; i < metaEnum.keyCount(); i++)
{
PropertyClassValueType prop;
prop.setType(static_cast<ValueType>(metaEnum.value(i)));
prop.setDescription(metaEnum.valueToKey(metaEnum.value(i)));
if (!prop.save())
throw SaveError(prop.lastError().text());
}
}
}
std::unique_ptr<model::PropertyClassValueType> PropertyClassValueType::getModel(ValueType type)
{
auto model = std::make_unique<model::PropertyClassValueType>();
const QMetaObject &mo = PropertyClassValueType::staticMetaObject;
int index = mo.indexOfEnumerator("ValueType");
QMetaEnum metaEnum = mo.enumerator(index);
model->setType(type);
model->setDescription(metaEnum.valueToKey(type));
return model;
}
| true |
0ec01ecc8f995730cd386ef30ebc03956f9b3be0 | C++ | DanielSlavov/FMI-OOP-HW-TaskManager | /BusinessTask.cpp | UTF-8 | 2,855 | 3.59375 | 4 | [] | no_license | #include"BusinessTask.h"
Time BusinessTask::Duration()
{
return Time(this->End().Hour() - this->Start().Hour(), this->End().Min() - this->Start().Min(), this->End().Sec() - this->Start().Sec());
}
void BusinessTask::AddPerson(char * firstName, char * lastName)
{
people.push_back( Person(firstName, lastName));
}
BusinessTask::BusinessTask() :Task::Task()
{
this->host = nullptr;
this->location = nullptr;
}
BusinessTask::BusinessTask(const char * name, const char * description, Time start, Time end,const char * location,const char * host) : Task::Task(name, description, start, end, Business)
{
size_t hostSize = strlen(host) + 1;
this->host = new char[hostSize];
strcpy_s(this->host, hostSize, host);
size_t locSize = strlen(location) + 1;
this->location = new char[locSize];
strcpy_s(this->location, locSize, location);
}
BusinessTask::BusinessTask(const char * name, const char * description, Time start, Time end, const char* location , const char* host,List<Person>* people) : Task::Task(name, description, start, end, Business)
{
size_t hostSize = strlen(host) + 1;
this->host = new char[hostSize];
strcpy_s(this->host, hostSize, host);
size_t locSize = strlen(location) + 1;
this->location = new char[locSize];
strcpy_s(this->location, locSize, location);
this->people = *people;
}
BusinessTask::~BusinessTask()
{
delete []this->host;
delete []this->location;
}
BusinessTask::BusinessTask(const BusinessTask & other):Task::Task(other)
{
size_t hostSize = strlen(other.host) + 1;
this->host = new char[hostSize];
strcpy_s(this->host, hostSize, other.host);
size_t locSize = strlen(other.location) + 1;
this->location = new char[locSize];
strcpy_s(this->location, locSize, other.location);
this->people = other.people;
}
BusinessTask & BusinessTask::operator=(const BusinessTask & other)
{
if (this != &other)
{
Task::operator=(other);
delete[]this->host;
delete[]this->location;
size_t hostSize = strlen(other.host) + 1;
this->host = new char[hostSize];
strcpy_s(this->host, hostSize, other.host);
size_t locSize = strlen(other.location) + 1;
this->location = new char[locSize];
strcpy_s(this->location, locSize, other.location);
this->people = other.people;
}
return*this;
}
void BusinessTask::PrintPeople()
{
for (int i = 0; i < this->people.Size(); i++)
std::cout << this->people.get(i) << "\n";
}
const List<Person> BusinessTask::People()
{
return this->people;
}
const char * BusinessTask::Host()
{
return this->host;
}
void BusinessTask::print(std::ostream & os) const
{
os << this->number << ". Business Task: " << this->name << "\n";
os << this->description << "\n";
os << this->start << " - " << this->end << "\n";
os << "Host: " << this->host << "\n";
os << "People : " << this->people.Size() << "\n";
os << "Location: " << this->location << "\n";
}
| true |