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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dcf152a07d2224017e5f7743c87f89316ff016e3 | C++ | ravikjay/Steganographer | /Compressor.cpp | UTF-8 | 6,534 | 3.25 | 3 | [] | no_license | #include "provided.h"
#include "HashTable.h"
//#include "anotherHashTable.h"
//#include "substituteHashTable.h"
//#include "saveMyHashTable.h"
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
// ComputeHash function
unsigned int computeHash (string x)
{
int hash = 9;
for (size_t i = 0; i < x.size(); i++)
{
hash = hash * 131 + x[i];
}
return hash;
}
unsigned int computeHash (unsigned short x){
return x % 10;
}
void Compressor::compress(const string& s, vector<unsigned short>& numbers)
{
// Make sure the vector we're working with is empty
numbers.clear();
unsigned int n = s.size();
unsigned int myCapacity = 0;
// Calculate the capacity as defined by the algorithm
if ((n/2)+512 < 16384)
{
myCapacity = (n/2)+512;
}
else {
myCapacity = 16384;
}
// Create a hash table based on the capacity we defined earlier
HashTable<string, unsigned short> myHash ((myCapacity/0.5), myCapacity);
// For the first 256 buckets, we will make their permanence true (can't be altered) and place in our characters
for (int j = 0; j < 256; j++)
{
string str2(1, static_cast<char>(j)); // static_cast so that the char can be converted and inputted in as a string
myHash.set(str2, j, true);
}
int nextFreeID = 256; // This is where we begin when we start adding new values later
string runSoFar = "";
vector<unsigned short> v;
for (int i = 0; i < s.size(); i++) // Loop through each character in the string
{
string str(1, static_cast<char>(s[i])); // convert each char to a one value string
string expandedRun = runSoFar + str; // append this string with our running total to create our appended total
unsigned short val = 0;
if (myHash.get(expandedRun, val)) // See if the value of expandedRun exists in our hash table
{
runSoFar = expandedRun; // If so, make our running total the appended total (current char added)
continue;
}
myHash.get(runSoFar, val); // otherwise, see if the non-appended string exists and then push it
unsigned short x = val;
v.push_back(x);
myHash.touch(runSoFar); // make this the most recently added
runSoFar = ""; // reset our running total string
myHash.get(str, val); // Look for a specific string
unsigned short cv = val;
v.push_back(cv);
if (!myHash.isFull()) // if the hash table is not full, add this appended total
{
myHash.set(expandedRun, nextFreeID);
nextFreeID++; // move our current location
}
else // get rid of the least recently added value to make room for this
{
string discardKey = "";
unsigned short discardVal = 0;
myHash.discard(discardKey, discardVal);
myHash.set(expandedRun, discardVal);
}
}
if (runSoFar != "") // if the current string question is not empty
{
unsigned short checkVal = 0;
myHash.get(runSoFar, checkVal);
unsigned short x = checkVal;
v.push_back(x); // find the current string's value in the hash table and push it
}
v.push_back(myCapacity);
numbers = v; // all our compressed numbers that represent string combinations are saved into a vector
}
bool Compressor::decompress(const vector<unsigned short>& numbers, string& s)
{
//unsigned short myCapacity = *(numbers.size()-1);
unsigned short myCapacity = numbers[numbers.size()-1];
HashTable<unsigned short, string> myHash ((myCapacity/0.5), myCapacity); // Create another hash table with the specified capacity
// loop through all the 256 values and set the characters
for (int j = 0; j < 256; j++)
{
// static_cast so that each character can be used as a one value string
string str(1, static_cast<char>(j));
// set each char with a permanence of true
myHash.set(j, str, true);
}
// start creating new values in the hash table at a position at 256
int nextFreeID = 256;
string runSoFar = "";
string output = "";
// loop through all of the numbers in the passed in vector
for (int i = 0; i < numbers.size()-1; i++)
{
// If the value we're looking at in the numbers array has a value that already exists in the hash table
if (numbers[i] <= 255)
{
// get that value thats been compressed and append it to the string being examined
string tempString = "";
myHash.get(numbers[i], tempString);
output.append(tempString);
// after being appended, if the string being examined is empty
if (runSoFar == "")
{
// make the running total string equal to the recovered value
runSoFar = tempString;
continue; // Will this enter the next iteration of the for loop and not run the rest of the code??
}
// now create another running total string that will be appended to the expanded string
string expandedRun = runSoFar + tempString;
// as long as the hashtable is not full
if (!myHash.isFull())
{
// add or update the value into the next free spot
myHash.set(nextFreeID, expandedRun);
nextFreeID++;
}
else // if its full, discard a key -- value and then set the expanded run
{
string discardKey = "";
unsigned short discardVal = 0;
myHash.discard(discardVal, discardKey);
myHash.set(discardVal, expandedRun);
}
runSoFar = "";
continue;
}
else // if this value we're examining does not already exist in the hash table
{
string tempString = "";
// if the value of tempstring does not exist in the table at that bucket
if (!myHash.get(numbers[i], tempString))
return false;
// make it the most recent in history
myHash.touch(numbers[i]);
// and add it to the final output
output.append(tempString);
runSoFar = tempString;
continue;
}
}
// finally, set the output equal to the value by const reference
s = output;
return true;
}
| true |
09a993906c0432ed215663a7b554af90215e179d | C++ | SurlySilverback/rshell | /src/TestProcess.h | UTF-8 | 1,873 | 3.25 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <string>
#include "Command.h"
class TestProcess : public Command {
private:
char* flag;
char* path;
public:
TestProcess(char* path)
{
std::string default_flag = "-e";
this->flag = new char;
strcpy(this->flag, default_flag.c_str());
this->path = path;
}
TestProcess(char* flag, char* path)
{
this->flag = flag;
this->path = path;
}
bool execute()
{
struct stat statbuf;
if (static_cast<std::string>(this->flag) == "-d") {
if ( stat( path, &statbuf ) != -1 )
{
if ( S_ISDIR( statbuf.st_mode ) == true )
{
std::cout << "(True)" << std::endl;
return true;
}
else
{
std::cout << "(False)" << std::endl;
return true;
}
}
return false;
}
else if (static_cast<std::string>(this->flag) == "-f") {
if ( stat( path, &statbuf ) != -1 )
{
if ( S_ISREG( statbuf.st_mode ) == true )
{
std::cout << "(True)" << std::endl;
return true;
}
else
{
std::cout << "(False)" << std::endl;
return true;
}
}
return false;
}
else {
if ( stat( path, &statbuf ) != -1 )
{
std::cout << "(True)" << std::endl;
return true;
}
else
{
std::cout << "(False)" << std::endl;
return true;
}
}
}
};
| true |
5a1596c9795522599bed240cbf8e06df48aef36d | C++ | RomMarie/open_rm | /src/Graphe/robotvirtuel.cpp | UTF-8 | 1,948 | 2.875 | 3 | [] | no_license | #include <open_rm/Graphe/robotvirtuel.h>
namespace rm{
namespace Graphe{
/*!
* \brief Constructeur principal d'un robot virtuel
* \param posCur Pose courante
* \param posPrec Pose précédente
* \param d distance parcourue
* \param n Indice du noeud de départ
* \param b Indice de la branche de départ
*/
RobotVirtuel::RobotVirtuel(cv::Point posCur, cv::Point posPrec, float d,int n,int b):
m_posCur(posCur),m_posPrec(posPrec),m_posInit(posPrec),m_distTraveled(d),m_indNoeudDepart(n),
m_brancheDepart(b)
{
}
/*!
* \brief Accesseur de la pose initiale
* \return Position initiale du robot virtuel
*/
cv::Point RobotVirtuel::getPosInit()
{
return m_posInit;
}
/*!
* \brief Accesseur de la pose courante
* \return Position courante du robot virtuel
*/
cv::Point RobotVirtuel::getPosCur()
{
return m_posCur;
}
/*!
* \brief Accesseur de la pose précédente
* \return Position précédente du robot virtuel
*/
cv::Point RobotVirtuel::getPosPrec()
{
return m_posPrec;
}
/*!
* \brief Accesseur du noeud de départ
* \return Indice du noeud de départ
*/
int RobotVirtuel::getIndNoeudDepart()
{
return m_indNoeudDepart;
}
/*!
* \brief Accesseur de la branche de départ
* \return Indice de la branche de départ
*/
int RobotVirtuel::getBrancheDepart()
{
return m_brancheDepart;
}
/*!
* \brief Accesseur de la distance parcourue
* \return Distance parcourue par le robot virtuel
*/
float RobotVirtuel::getDistTraveled()
{
return m_distTraveled;
}
/*!
* \brief Déplace le robot
* \param posNext Position à destination du mouvement
* \param dist Amplitude du mouvement
*/
void RobotVirtuel::move(cv::Point posNext, float dist)
{
m_posPrec=m_posCur;
m_posCur=posNext;
m_distTraveled+=dist;
}
/*!
* \brief Destructeur de la classe
*/
RobotVirtuel::~RobotVirtuel()
{
}
}
}
| true |
88bfa790f66494eb1af3e8298289d56b4f54b12a | C++ | KasperOmari/Problems | /SPOJ/TEST - Life, the Universe, and Everything.cpp | UTF-8 | 685 | 2.53125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<cmath>
#include<math.h>
#include<memory.h>
#include<cctype>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<utility>
#include<iomanip>
#include<vector>
#include<cassert>
#include<cstdio>
#include<cstdlib>
#include<sstream>
#include<cstring>
using namespace std;
int main()
{
int n;
vector<int>v;
while(cin >>n){
if(n==42)
break;
v.push_back(n);
}
for(int i=0;i<v.size();i++){
cout <<v[i]<<endl;
}
return 0;
}
| true |
a0d3e1ff4439b2cd965968d1fb8be4f72cb2980b | C++ | michealchen17/cmd_vel | /src/cmd_vel.cpp | UTF-8 | 2,104 | 2.546875 | 3 | [] | no_license | /** 2017-12-17
* michealchen michealchen17@163.com
*
* this node can subsrcibe topic teleop published from kb_teleop node.
* and it can publish geometry_msgs::twistStamped msg as topic cmd_vel.
* this is velocity command publish node used to drive a mobile robot to move!
* only for x linear velocity and z angular velocity
* goodluck!
* */
#include <ros/ros.h>
#include <geometry_msgs/TwistStamped.h>
#include <sensor_msgs/Joy.h>
//system configure. this will be set as param,so it can be asinged through launch file
const double vel_l_max = 1; //maxmum linear velocity m/s
const double vel_a_max = 1; //maxmum angular velocity rad/s
const double vel_l_acc = 0.01; //linear velocity acceleration
const double vel_a_acc = 0.01; //angular velocity acceleration
ros::Publisher pub;
geometry_msgs::TwistStamped lastVel;
unsigned int msg_seq = 0;
void teleopCallback(const sensor_msgs::Joy &msg)
{
if( (msg.buttons[0]==1) && (lastVel.twist.linear.x<vel_l_max))
{
lastVel.twist.linear.x += vel_l_acc;
}
if( (msg.buttons[1]==1) && (lastVel.twist.linear.x>-vel_l_max))
{
lastVel.twist.linear.x -= vel_l_acc;
}
if( (msg.buttons[2]==1) && (lastVel.twist.angular.z<vel_a_max))
{
lastVel.twist.angular.z += vel_a_acc;
}
if( (msg.buttons[3]==1) && (lastVel.twist.angular.z>-vel_a_max))
{
lastVel.twist.angular.z -= vel_a_acc;
}
pub.publish(lastVel);
msg_seq++;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "cmd_vel");
ros::NodeHandle nh;
pub = nh.advertise<geometry_msgs::TwistStamped>("/cmd_vel",1);
lastVel.header.frame_id = "base_link";
lastVel.header.seq = msg_seq;
lastVel.header.stamp = ros::Time::now();
lastVel.twist.linear.x = 0;
lastVel.twist.linear.y = 0;
lastVel.twist.linear.z = 0;
lastVel.twist.angular.x = 0;
lastVel.twist.angular.y = 0;
lastVel.twist.angular.z = 0;
ros::Subscriber sub = nh.subscribe("kb_teleop", 1, teleopCallback);
ros::spin();
return 0;
}
| true |
f6cbee69279790c8bf45579dad52ec307384c78d | C++ | ybouret/upsylon | /src/main/y/code/utils.hpp | UTF-8 | 1,546 | 2.765625 | 3 | [] | no_license | //! \file
#ifndef Y_CODE_UTILS_INCLUDED
#define Y_CODE_UTILS_INCLUDED 1
#include "y/os/platform.hpp"
namespace upsylon
{
//! hexadecimal helpers
struct hexadecimal
{
static const char *lowercase_word[16]; //!< "0".."f"
static const char *uppercase_word[16]; //!< "0".."F"
static const char *lowercase[256]; //!< "00".."ff"
static const char *uppercase[256]; //!< "00".."FF"
//! internal formatting of an address to a C-string
static const char *address( const void *addr ) throw();
//! return the decimal value, -1 on error
static int to_decimal(const char h) throw();
//! get the xdigit from last fourbits
static char digit(const unsigned fourBits);
};
//! detecting case
enum case_type
{
lowercase, //!< islower
uppercase, //!< isupper
case_none //!< neutral
};
//! some different translation tables
struct cchars
{
static const char *visible[256]; //!< human readable chars
static const char *printable[256]; //!< for external programs/compilation
static const char *encoded[256]; //!< C-string version
static const char *to_visible(const char C) throw(); //!< visible char
static case_type case_of(const char C) throw(); //!< check case
static char to_lower(const char C) throw(); //!< to lowercase
static char to_upper(const char C) throw(); //!< to uppercase
};
}
#endif
| true |
e9275338d49d25ed36ab5be6c4f44e14c55aaaa7 | C++ | yjjfirst/x-sip | /test/CallIdHeaderTest.cpp | UTF-8 | 2,286 | 2.578125 | 3 | [] | no_license | #include "CppUTest/TestHarness.h"
extern "C" {
#include "CallIdHeader.h"
#include "Parser.h"
}
TEST_GROUP(CallIdHeaderTestGroup)
{
};
TEST(CallIdHeaderTestGroup, CallIdHeaderParseTest)
{
struct CallIdHeader *id = CreateEmptyCallIdHeader();
char callidString[] = "Call-ID : 843E@TTT.COM";
Parse(callidString, id, GetCallIdPattern());
STRCMP_EQUAL("Call-ID", CallIdHeaderGetName(id));
STRCMP_EQUAL("843E@TTT.COM", CallIdHeaderGetId(id));
DestroyCallIdHeader((struct Header *)id);
}
TEST(CallIdHeaderTestGroup, CallIdHeader2StringTest)
{
struct CallIdHeader *id = CreateEmptyCallIdHeader();
char callidString[] = "Call-ID:843E@TTT.COM";
char result[128] = {0};
Parse(callidString, id, GetCallIdPattern());
CallIdHeader2String(result, (struct Header *)id);
STRCMP_EQUAL(callidString, result);
DestroyCallIdHeader((struct Header *)id);
}
TEST(CallIdHeaderTestGroup, CallIdHeaderDupTest)
{
struct CallIdHeader *src = CreateEmptyCallIdHeader();
char callidString[] = "Call-ID:843E@TTT.COM";
Parse(callidString, src, GetCallIdPattern());
struct CallIdHeader *dest = CallIdHeaderDup(src);
CHECK_TRUE(CallIdHeaderMatched(src, dest));
DestroyCallIdHeader((struct Header *)dest);
DestroyCallIdHeader((struct Header *)src);
}
TEST(CallIdHeaderTestGroup, CallIdHeaderMatchedTest)
{
struct CallIdHeader *id1 = CreateEmptyCallIdHeader();
struct CallIdHeader *id2 = CreateEmptyCallIdHeader();
char callidString[] = "Call-ID:843E@TTT.COM";
Parse(callidString, id1, GetCallIdPattern());
Parse(callidString, id2, GetCallIdPattern());
CHECK_TRUE(CallIdHeaderMatched(id1, id2));
DestroyCallIdHeader((struct Header *)id1);
DestroyCallIdHeader((struct Header *)id2);
}
TEST(CallIdHeaderTestGroup, CallIdHeaderUnmatchedTest)
{
struct CallIdHeader *id1 = CreateEmptyCallIdHeader();
struct CallIdHeader *id2 = CreateEmptyCallIdHeader();
char callidString1[] = "Call-ID:843E@TTT.COM";
char callidString2[] = "Call-ID:845E@TTT.COM";
Parse(callidString1, id1, GetCallIdPattern());
Parse(callidString2, id2, GetCallIdPattern());
CHECK_FALSE(CallIdHeaderMatched(id1, id2));
DestroyCallIdHeader((struct Header *)id1);
DestroyCallIdHeader((struct Header *)id2);
}
| true |
a57f44e817af709da0e9d496fe3450da2b220203 | C++ | northWindPA/cpp_modules | /Module_03/ex02/FragTrap.cpp | UTF-8 | 1,938 | 3.03125 | 3 | [] | no_license | #include "FragTrap.hpp"
std::string FragTrap::_attack_line[10] =
{
"Spider in da face!",
"Giant tree coming!",
"Bully teenager kicking da ass!",
"Dragon poop coming!",
"Ass blowing!",
"Fat man's fart in da face!",
"Dendi face!",
"Rocky Balboa's motivational speech!",
"Cowabunga!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",
"For the EMPEROR!!! Die heretic!"
};
FragTrap::FragTrap(std::string name): ClapTrap(name)
{
_hit_points = 100;
_max_hit_points = 100;
_energy_points = 100;
_max_energy_points = 100;
_level = 1;
_melee_attack_damage = 30;
_ranged_attack_damage = 20;
_armor_damage_reduction = 5;
_random_damage_tmp = 0;
std::cout << _name << " is here." << std::endl;
}
FragTrap::~FragTrap()
{
std::cout << _name << " is no more." << std::endl;
}
FragTrap::FragTrap(const FragTrap ©): ClapTrap(copy._name)
{
std::cout << "Copy constructor called." << std::endl;
*this = copy;
}
void FragTrap::vaulthunter_dot_exe(std::string const &target)
{
int damage;
unsigned int random_damage;
if (_energy_points >= 25)
{
_energy_points -= 25;
damage = rand () % 40;
if (damage < 0)
damage = 15;
random_damage = (unsigned int)damage;
_random_damage_tmp = random_damage;
std::cout << _name << " " << FragTrap::_attack_line[rand() % 9] <<" attacks " << target << " for " << random_damage << " damage points!" << std::endl;
}
else
std::cout << _name << " not enough energy for special attack!" << std::endl;
}
FragTrap &FragTrap::operator = (const FragTrap ©)
{
_hit_points = copy._hit_points;
_max_hit_points = copy._max_hit_points;
_energy_points = copy._energy_points;
_max_energy_points = copy._max_energy_points;
_level = copy._level;
_name = copy._name;
_melee_attack_damage = copy._melee_attack_damage;
_ranged_attack_damage = copy._ranged_attack_damage;
_armor_damage_reduction = copy._armor_damage_reduction;
_random_damage_tmp = copy._random_damage_tmp;
return (*this);
} | true |
bd2cfc45fe4c15c3b6b88def7dea275831be27e0 | C++ | xuedong/leet-code | /Problems/Algorithms/445. Add Two Numbers II/add-two-numbers-II.cpp | UTF-8 | 1,223 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <stack>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> stack1, stack2;
while (l1 != nullptr) {
stack1.push(l1->val);
l1 = l1->next;
}
while (l2 != nullptr) {
stack2.push(l2->val);
l2 = l2->next;
}
int sum = 0, carry = 0;
ListNode* ans = new ListNode();
while (!stack1.empty() || !stack2.empty()) {
if (!stack1.empty()) {
sum += stack1.top();
stack1.pop();
}
if (!stack2.empty()) {
sum += stack2.top();
stack2.pop();
}
ans->val = sum % 10;
carry = sum / 10;
ListNode* curr = new ListNode(carry);
curr->next = ans;
ans = curr;
sum = carry;
}
return carry == 0 ? ans->next : ans;
}
};
| true |
5b656b9359bbebb996e55d0308830550aa4511c3 | C++ | crystal95/Competetive-Programming-at-different-platforms | /summer_2k15_coding/graphs/dijkstra.cpp | UTF-8 | 1,425 | 2.875 | 3 | [] | no_license | using namespace std;
#include <iostream>
#include <list>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
typedef pair<int ,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vii> vvii;
int *D;
int ver,edges;
void di(int start, vector<vector<ii> > &arr)
{
vii::iterator it;
priority_queue< ii , vector< ii>, greater<ii> > Q;
D[start]=0;
Q.push(ii(0,start));
while(!Q.empty())
{
ii top = Q.top();
Q.pop();
int v=top.second;
int d= top.first;
if(d<=D[v])////////////////////////////////////////////////////////////this to avoid the repetition .......... ////verrrrrry veryyyy importatn step
{
for(it=arr[v].begin();it!=arr[v].end();it++)
{
int v2 = it->first, cost=it->second;
if(D[v]+cost<D[v2])
{
D[v2]=D[v]+cost;
Q.push(ii(D[v2],v2));
}
}
}
}
}
void printgraph(vector< vector <ii> > &arr)
{
vii::iterator it;
for(int i=0;i<ver;i++)
{
for(it=arr[i].begin();it!=arr[i].end();it++)
{
cout<<i<<" "<<it->first<<" "<<it->second<<endl;
}
}
}
int main()
{
int i,j,k,l,m,n,u,v,w,start;
cin>>ver>>edges;
vvii arr(ver);
D = new int[ver*ver]; cout<<endl;
//vii arr[ver];
for(i=0;i<edges;i++)
{
cin>>u>>v>>w;
arr[u].push_back(ii(w,v));
arr[v].push_back(ii(w,u));
D[i] = 99999;
}
printgraph( arr);
cin>>start;
di(start,arr);
for(i=0;i<ver;i++)
cout<<D[i]<<" ";
cout<<endl;
return 0;
}
| true |
ea3985d2a0dac8942f869d8a470b88d3979dd966 | C++ | sekharkaredla/Cpp_Programs | /week2/2.2.cpp | UTF-8 | 195 | 3.15625 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"enter two numbers : ";
cin>>a>>b;
if(a>b)
cout<<"\nthe larger is "<<a;
else
cout<<"\n the larger is "<<b;
return 1;
}
| true |
78f5646ef3b8d54e0d4024a84337d4b960f6e7bb | C++ | rmit-s3536515-jianning-pan/C-Assignment-2 | /model/model.h | UTF-8 | 1,915 | 2.734375 | 3 | [] | no_license | /***********************************************************************
* COSC1254 - Programming Using C++
* Semester 2 2017 Assignment #2
* Full Name : Yixuan Zhang, Jianning Pan
* Student Number : s3380293, s3536515
* Course Code : COSC1254
**********************************************************************/
#include <vector>
#include <memory>
#include <utility>
#include <iostream>
#include <sstream>
#include <map>
#include <thread>
#include <chrono>
#include "player.h"
#include "piece.h"
#include "normalPiece.h"
#include "playerType.h"
#pragma once
namespace draughts
{
namespace model
{
class model
{
static std::unique_ptr<model> instance;
std::vector<std::unique_ptr<player>> players; //store full players
std::vector<std::unique_ptr<player>> selected; // store the selected players
int currentId = 0; //track for the current player
model(void);
bool player_exists(const std::string&);
public:
void setCurrentId(const int& id){currentId=id;} //set the current player number
std::vector<std::unique_ptr<player>>& getSelectedPlayers(){return selected;} //get the selected players
std::vector<std::unique_ptr<player>>& getPlayers(){return players;} // get the players
void start_game(int, int);
char get_token(int,int);
void make_move(int, int, int, int, int);
void add_player(const std::string& );
int get_player_score(int);
int get_current_player(void);
std::string get_player_name(int);
std::map<int, std::string> get_player_list(void) const;
int get_winner();
int get_width();
int get_height();
static model * get_instance(void);
static void delete_instance(void);
virtual ~model(void);
};
}
}
| true |
fa9379bf5f16f613e08f96307a65a06cc866d1b5 | C++ | denisyq/LeeCode | /283_Move_Zeroes.cc | UTF-8 | 543 | 3.53125 | 4 | [] | no_license | /* 283. Move Zeroes
* Description: move 0 to the last position in vector
*/
class Solution {
public:
void moveZeroes(vector<int>& nums){
int num_zero = 0;
vector<int>::iterator it = nums.begin();
while(it != nums.end() ){
if(*it == 0){
it = nums.erase(it);
num_zero++;
}else
it++;
}
if(num_zero){
vector<int> zeroes(num_zero,0);
nums.insert(nums.end(),zeroes.begin(),zeroes.end());
}
}
};
| true |
68cb529d8c2a25ccf6bae7c9d926721f7f5cdd5c | C++ | alexandraback/datacollection | /solutions_5658571765186560_0/C++/Wajeb/probD.cpp | UTF-8 | 861 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream cin("probDsmall.in");
ofstream cout("probDsmall.txt");
int T;
cin >> T;
for(int t = 0; t < T; t++)
{
int X, R, C;
cin >> X >> R >> C;
stringstream casenum;
casenum << t + 1;
string casenumstr = casenum.str();
string possible = "Case #" + casenumstr + ": GABRIEL";
string impossible = "Case #" + casenumstr + ": RICHARD";
if(X == 1) cout << possible << endl;
else if(X == 2)
{
if(R * C % 2 == 0) cout << possible << endl;
else cout << impossible << endl;
}
else if(X == 3)
{
if(R * C % 3 == 0 && R * C != 3) cout << possible << endl;
else cout << impossible << endl;
}
else if(X == 4)
{
if(R * C == 16 || R * C == 12) cout << possible << endl;
else cout << impossible << endl;
}
}
return 0;
}
| true |
f1faff68de2a6bd13d5cb7d91d4c472ebb9fe230 | C++ | FrankieV/Fondamenti-di-Informatica | /(Appello d'esame del 15.11.2011) - Es 1/main.cpp | UTF-8 | 1,058 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
const int dim = 100;
void Elimina_Lettere(char[],char[]);
void print_Frase(char[]);
int main()
{
char Frase[dim];
cin.getline(Frase,dim);
char Elenco_Parole[strlen(Frase)];
cin.getline(Elenco_Parole,strlen(Frase));
Elimina_Lettere(Frase,Elenco_Parole);
print_Frase(Frase);
}
void Elimina_Lettere(char Frase[], char el_Parole[])
{
char *token = strtok(el_Parole," ");
char tmp[strlen(token)];
while(token != NULL)
{
strcpy(tmp,token);
for(int i=0; i < strlen(tmp); i++)
{
for(int j = 0; j < strlen(Frase); j++)
{
if(tmp[i] == Frase[j])
{
Frase[j] = -1;
break;
}
}
}
token = strtok(NULL, " ");
}
}
void print_Frase(char Frase[])
{
for(int i = 0; i < strlen(Frase); i++)
{
if(Frase[i] != -1 && Frase[i] != ' ')
{
cout << Frase[i];
}
}
}
| true |
24f29bad172fae425e44f05329e9cac1c305d1fc | C++ | piranna/asi-iesenlaces | /0607/funciones/digito.cpp | ISO-8859-1 | 1,352 | 3.84375 | 4 | [] | no_license | // $Id$
// Explicacion del programa
#include <stdio.h>
#include <stdlib.h>
int digit(int pos, int num)
/* funcin, Digit(N,num) que devuelva el dgito Nsimo
de un nmero num de tipo entero, teniendo en cuenta que el dgito 0 es el dgito ms a la derecha (el menos significativo).
La funcin devolver -1 si el nmero no tiene suficientes dgitos.
12345
*/
{
int i;
for(i=0; i<pos ; i++)
num = num / 10;
if ( (num <= 9) && (num > 0) )
return num;
else
{ num %= 10;
if (num == 0)
return -1;
else
return num;
}
}
int digit_v2(int pos, int num)
/* funcin, Digit(N,num) que devuelva el dgito Nsimo
de un nmero num de tipo entero, teniendo en cuenta que el dgito 0 es el dgito ms a la derecha (el menos significativo).
La funcin devolver -1 si el nmero no tiene suficientes dgitos.
12345
*/
{
int i;
for(i=0; i<pos ; i++)
{ num = num / 10;
if (num == 0) return -1;
}
if ( (num <= 9) && (num > 0) )
return num;
else
return num %= 10;
}
int main(void)
{
int num=12345678, pos=5;
printf("Posicion %d de %d es %d\n", pos, num, digit(pos, num) );
printf("Posicion %d de %d es %d\n", pos, num, digit_v2(pos, num) );
system("pause"); // Detiene la consola
}
| true |
95cbbe9cc92046b8419aad1a09a630cc2fb81daa | C++ | Hyp-ed/hyped-2018 | /BeagleBone_black/src/demo_gpio.cpp | UTF-8 | 688 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive |
#include <stdio.h>
#include "utils/concurrent/thread.hpp"
#include "utils/io/gpio.hpp"
#include "utils/system.hpp"
using hyped::utils::concurrent::Thread;
using hyped::utils::io::GPIO;
using hyped::utils::System;
namespace io = hyped::utils::io;
int main(int argc, char* argv[]) {
System::parseArgs(argc, argv);
GPIO pin_66(66, io::gpio::kOut); // P8_7
GPIO pin_69(69, io::gpio::kIn); // P8_9
for (int i = 0; i < 5; i++) {
uint8_t val = pin_69.wait();
printf("gpio changed to %d\n", val);
// pin_69.read();
// Thread::sleep(200);
}
pin_66.set();
Thread::sleep(5000);
pin_66.clear();
Thread::sleep(5000);
pin_66.set();
Thread::sleep(5000);
} | true |
38501fa7602a6f63cdf04f66a47f6a781ecbc5e3 | C++ | sunkest/Algorithm | /Baekjoon/9205.cpp | UTF-8 | 368 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Point {
int x;
int y;
};
int t, n;
vector<Point> v;
vector<vector<int>> g;
bool* visited;
bool* ans;
int main(void) {
cin >> t >> n;
ans = new bool[t];
for (int i = 0; i < n + 2; i++) {
visited[i] = false;
}
int x, y;
cin >> x, y;
Point p = { x, y };
v.insert(p);
} | true |
4926b227f3d62da98180215b9e1387ade6fcd931 | C++ | Atrix256/RandomCode | /OneQubit/Source.cpp | UTF-8 | 8,364 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
#include <array>
#include <complex>
typedef std::array<std::complex<float>, 2> TQubit;
typedef std::array<std::complex<float>, 4> TComplexMatrix;
const float c_pi = 3.14159265359f;
//=================================================================================
static const TQubit c_qubit0 = { 1.0f, 0.0f }; // false aka |0>
static const TQubit c_qubit1 = { 0.0f, 1.0f }; // true aka |1>
static const TQubit c_qubit01_0deg = { 1.0f / std::sqrt(2.0f), 1.0f / std::sqrt(2.0f) }; // 50% true. 0 degree phase
static const TQubit c_qubit01_180deg = { 1.0f / std::sqrt(2.0f), -1.0f / std::sqrt(2.0f) }; // 50% true. 180 degree phase
// A not gate AKA Pauli-X gate
// Flips false and true probabilities (amplitudes)
// Maps |0> to |1>, and |1> to |0>
// Rotates PI radians around the x axis of the Bloch Sphere
static const TComplexMatrix c_notGate =
{
{
0.0f, 1.0f,
1.0f, 0.0f
}
};
static const TComplexMatrix c_pauliXGate = c_notGate;
// Pauli-Y gate
// Maps |0> to i|1>, and |1> to -i|0>
// Rotates PI radians around the y axis of the Bloch Sphere
static const TComplexMatrix c_pauliYGate =
{
{
{ 0.0f, 0.0f }, { 0.0f, -1.0f },
{ 0.0f, 1.0f }, { 0.0f, 0.0f }
}
};
// Pauli-Z gate
// Negates the phase of the |1> state
// Rotates PI radians around the z axis of the Bloch Sphere
static const TComplexMatrix c_pauliZGate =
{
{
1.0f, 0.0f,
0.0f, -1.0f
}
};
// Hadamard gate
// Takes a pure |0> or |1> state and makes a 50/50 superposition between |0> and |1>.
// Put a 50/50 superposition through and get the pure |0> or |1> back.
// Encodes the origional value in the phase information as either matching or
// mismatching phase.
static const TComplexMatrix c_hadamardGate =
{
{
1.0f / std::sqrt(2.0f), 1.0f / std::sqrt(2.0f),
1.0f / std::sqrt(2.0f), 1.0f / -std::sqrt(2.0f)
}
};
//=================================================================================
void WaitForEnter ()
{
printf("\nPress Enter to quit");
fflush(stdin);
getchar();
}
//=================================================================================
TQubit ApplyGate (const TQubit& qubit, const TComplexMatrix& gate)
{
// multiply qubit amplitude vector by unitary gate matrix
return
{
qubit[0] * gate[0] + qubit[1] * gate[1],
qubit[0] * gate[2] + qubit[1] * gate[3]
};
}
//=================================================================================
int ProbabilityOfBeingTrue (const TQubit& qubit)
{
float prob = std::round((qubit[1] * std::conj(qubit[1])).real() * 100.0f);
return int(prob);
}
//=================================================================================
TComplexMatrix MakePhaseAdjustmentGate (float radians)
{
// This makes a gate like this:
//
// [ 1 0 ]
// [ 0 e^(i*radians) ]
//
// The gate will adjust the phase of the |1> state by the specified amount.
// A more general version of the pauli-z gate
return
{
{
1.0f, 0.0f,
0.0f, std::exp(std::complex<float>(0.0f,1.0f) * radians)
}
};
}
//=================================================================================
void Print (const TQubit& qubit)
{
printf("[(%0.2f, %0.2fi), (%0.2f, %0.2fi)] %i%% true",
qubit[0].real(), qubit[0].imag(),
qubit[1].real(), qubit[1].imag(),
ProbabilityOfBeingTrue(qubit));
}
//=================================================================================
int main (int argc, char **argv)
{
// Not Gate
{
printf("Not gate:\n ");
// Qubit: false
TQubit v = c_qubit0;
Print(v);
printf("\n ! = ");
v = ApplyGate(v, c_notGate);
Print(v);
printf("\n\n ");
// Qubit: true
v = c_qubit1;
Print(v);
printf("\n ! = ");
v = ApplyGate(v, c_notGate);
Print(v);
printf("\n\n ");
// Qubit: 50% chance, reverse phase
v = c_qubit01_180deg;
Print(v);
printf("\n ! = ");
v = ApplyGate(v, c_notGate);
Print(v);
printf("\n\n");
}
// Pauli-y gate
{
printf("Pauli-y gate:\n ");
// Qubit: false
TQubit v = c_qubit0;
Print(v);
printf("\n Y = ");
v = ApplyGate(v, c_pauliYGate);
Print(v);
printf("\n\n ");
// Qubit: true
v = c_qubit1;
Print(v);
printf("\n Y = ");
v = ApplyGate(v, c_pauliYGate);
Print(v);
printf("\n\n ");
// Qubit: 50% chance, reverse phase
v = c_qubit01_180deg;
Print(v);
printf("\n Y = ");
v = ApplyGate(v, c_pauliYGate);
Print(v);
printf("\n\n");
}
// Pauli-z gate
{
printf("Pauli-z gate:\n ");
// Qubit: false
TQubit v = c_qubit0;
Print(v);
printf("\n Z = ");
v = ApplyGate(v, c_pauliZGate);
Print(v);
printf("\n\n ");
// Qubit: true
v = c_qubit1;
Print(v);
printf("\n Z = ");
v = ApplyGate(v, c_pauliZGate);
Print(v);
printf("\n\n ");
// Qubit: 50% chance, reverse phase
v = c_qubit01_180deg;
Print(v);
printf("\n Z = ");
v = ApplyGate(v, c_pauliZGate);
Print(v);
printf("\n\n");
}
// 45 degree phase adjustment gate
{
printf("45 degree phase gate:\n ");
TComplexMatrix gate = MakePhaseAdjustmentGate(c_pi / 4.0f);
// Qubit: false
TQubit v = c_qubit0;
Print(v);
printf("\n M = ");
v = ApplyGate(v, gate);
Print(v);
printf("\n\n ");
// Qubit: true
v = c_qubit1;
Print(v);
printf("\n M = ");
v = ApplyGate(v, gate);
Print(v);
printf("\n\n ");
// Qubit: 50% chance, reverse phase
v = c_qubit01_180deg;
Print(v);
printf("\n M = ");
v = ApplyGate(v, gate);
Print(v);
printf("\n\n");
}
// Hadamard gate
{
printf("Hadamard gate round trip:\n ");
// Qubit: false
TQubit v = c_qubit0;
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n\n ");
// Qubit: true
v = c_qubit1;
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n\n ");
// Qubit: 50% chance, reverse phase
v = c_qubit01_180deg;
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n\n");
}
// 1 bit circuit
// Hadamard -> Pauli-Z -> Hadamard
{
printf("Circuit Hadamard->Pauli-Z->Hadamard:\n ");
// Qubit: false
TQubit v = c_qubit0;
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n Z = ");
v = ApplyGate(v, c_pauliZGate);
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n\n ");
// Qubit: true
v = c_qubit1;
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n Z = ");
v = ApplyGate(v, c_pauliZGate);
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n\n ");
// Qubit: 50% chance, reverse phase
v = c_qubit01_180deg;
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n Z = ");
v = ApplyGate(v, c_pauliZGate);
Print(v);
printf("\n H = ");
v = ApplyGate(v, c_hadamardGate);
Print(v);
printf("\n");
}
WaitForEnter();
return 0;
} | true |
48bfd9b8a85e8a74105b21fbf13e68dca220c0a9 | C++ | JonnyKong/LeetCode | /388_Longest_Absolute_File_Path.cpp | UTF-8 | 888 | 2.765625 | 3 | [] | no_license | class Solution {
int pos;
int level;
int length;
bool type; // 0 dir, 1 file
bool hasFile;
void getNext(const string& s) {
type = 0;
level = 0;
length = 0;
while (pos < s.length() && s[pos] == '\t') {
++pos;
++level;
}
while (pos < s.length() && s[pos] != '\n') {
if (s[pos++] == '.') type = 1;
++length;
}
++pos;
}
public:
int lengthLongestPath(string input) {
int total = -1;
int max = -1;
hasFile = 0;
pos = 0;
stack<int> s;
while (pos < input.length()) {
getNext(input);
if (type) hasFile = 1;
while (level < s.size()) {
--total;
total -= s.top();
s.pop();
}
s.push(length);
total += length;
total++;
if (max < total && type) {
max = total;
}
}
if (!hasFile) return 0;
return max;
}
}; | true |
05ac2368b8b040d95e25315d29fb284e4293c506 | C++ | 0xCC00FFEE/Unprotect_snippet | /screen_res/main.cpp | UTF-8 | 741 | 2.984375 | 3 | [] | no_license | #include "wtypes.h"
#include <iostream>
using namespace std;
/*
1024x768 can be used for automated Sandbox
800x600 can be used for automated Sandbox
640x480 can be used for automated Sandbox
1024x697
1280x800
1280x960
1680x1050
1916x1066
*/
void GetResolution(int& horiz, int& verti)
{
RECT desktop;
const HWND hDesktop = GetDesktopWindow();
GetWindowRect(hDesktop, &desktop);
horiz = desktop.right;
verti = desktop.bottom;
}
int main()
{
int horiz = 0;
int verti = 0;
GetResolution(horiz, verti);
if(horiz < 1024)
{
cout << "[!] Looks like you run in a sandbox!"<< '\n';
}
cout << "[+] Screen resolution: "<< horiz << "x" << verti << '\n';
return 0;
}
| true |
6e7c449cdc558e959ebfefb78778d09534a3ccea | C++ | kiranarsam/understanding-cpp-step-by-step | /cpp-advanced/complex-user-defined-literals.cpp | UTF-8 | 455 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <complex>
using namespace std;
// imaginary literal
constexpr complex <double> operator"" _i(long double d) {
return complex <double> { 0.0 , static_cast<double>( d )};
}
int main() {
complex<double> z = 3.0 + 4.0_i;
complex<double> y = 2.3 + 5.0_i;
cout << "z + y = " << z + y << endl;
cout << "z * y = " << z * y << endl;
cout << "abs(z) = " << abs(z) << endl;
return 0;
} | true |
aca4b13818876ec27983621a1d7dadfc39ddbe33 | C++ | tcoderwang913/algorithmic_study | /DivideTwoIntegers.cpp | UTF-8 | 526 | 3.34375 | 3 | [
"Apache-2.0"
] | permissive | /**
Divide two integers without using multiplication, division and mod operator.
*/
class Solution {
public:
int divide(int dividend, int divisor) {
long long a = abs((double)dividend);;
long long b = abs((double)divisor);
long long ret = 0;
while (a >= b) {
long long c = b;
for (int i = 0; a >= c; ++i, c <<= 1) {
a -= c;
ret += 1 << i;
}
}
return ((dividend^divisor)>>31) ? (-ret) : (ret);
}
}; | true |
ceaa23fe57c9c212718eb2f5d8ac2128694dd813 | C++ | saitotm/Atrimx | /test/test_arithmetic_operations.cpp | UTF-8 | 1,891 | 3 | 3 | [] | no_license | #include <iostream>
#include "../src/atrimx.hpp"
namespace
{
const int kCols = 100;
const int kRows = 200;
} // namespace
int main()
{
Atrimx::Matrix<float, kRows, kCols> m1, m2;
for (int i = 0; i < m1.rows(); ++i)
{
for (int j = 0; j < m1.cols(); ++j)
{
m1(i, j) = m1.rows() * i + j;
m2(i, j) = -(i * j % 3);
}
}
// 行と列のサイズが一致しなくともエラーが出ない
Atrimx::Matrix<float, kRows, kCols> m_add;
m_add = m1 + m2;
Atrimx::Matrix<float, kRows, kCols> m_sub;
m_sub = m1 - m2;
Atrimx::Matrix<float, kRows, kCols> m_scaled;
m_scaled = m1 * 3.5;
Atrimx::Matrix<float, kRows, kCols> m_scaled2;
m_scaled2 = -3.0 * m2;
for (int i = 0; i < kRows; ++i)
{
for (int j = 0; j < kCols; ++j)
{
float elm1 = m_add.rows() * i + j;
float elm2 = -(i * j % 3);
float elm_add = elm1 + elm2;
float diff = abs(m_add(i, j) - elm_add);
if (diff > 1e-6)
{
std::cout << "error_add " << i << ", " << j << std::endl;
}
float elm_sub = elm1 - elm2;
diff = abs(m_sub(i, j) - elm_sub);
if (diff > 1e-6)
{
std::cout << "error_sub " << i << ", " << j << std::endl;
}
float elm_scaled = elm1 * 3.5;
diff = abs(m_scaled(i, j) - elm_scaled);
if (diff > 1e-6)
{
std::cout << "error_sub " << i << ", " << j << std::endl;
}
float elm_scaled2 = -3.0 * elm2;
diff = abs(m_scaled2(i, j) - elm_scaled2);
if (diff > 1e-6)
{
std::cout << "error " << i << ", " << j << std::endl;
}
}
}
std::cout << "finished" << std::endl;
} | true |
fe186291134afd481ada74b5a8bb0d66f471eb44 | C++ | maojie/hackerrank | /number_theory/closet_number.cc | UTF-8 | 335 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main() {
int t;
long long a, b, x, res;
cin >> t;
while (t--) {
cin >> a >> b >> x;
res = pow(a, b);
cout << (abs(int(res / x) * x - res) <= abs((int(res / x) + 1) * x - res) ?
int(res / x) * x : (int(res / x) + 1) * x) << endl;
}
return 0;
}
| true |
7d8765aa1918fe51ec052022e2a9c6d5d403de2b | C++ | ZombiGik/HomeWork | /Avtomorph.cpp | UTF-8 | 1,261 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
setlocale(0, "");
int n = 0;
cout << "АВТОМОРФНЫЕ ЧИСЛА" << endl << endl;
while (true)
{
int n, m;
cout << "Введите диапазон для поиска автоморфных чисел (\"0 0\" для выхода) \n-> ";
cin >> n;
cin >> m;
if (m == n && m == 0)
{
cout << "Выход" << endl;
return 0;
}
else if (n > m)
{
cout << "Диапазон указан неверно!!!\nПервое число должно быть меньше второго" << endl;
}
else
{
vector<int> output;
for (n ;n <=m;n++)
{
int num = pow(n,2);
int x = 10;
if (num <= m)
{
do
{
if (num % x == n)
{
output.push_back(n);
}
x = x * 10;
} while (num % x != num);
}
}
if (output.size() == 0)
{
cout << "Не найдено автоморфных чисел" << endl;
}
else
{
cout << "Найдено " << output.size() << " автоморфных чисел" << endl;
for (int i = 0; i < output.size(); i++)
{
cout << output[i] << ", " << pow(output[i], 2) << "; ";
}
cout << endl;
}
}
}
}
| true |
26382f4326f82b529eb4a87cbb13512a4bae65cc | C++ | afnan6630/CSE225-Lab | /Lab 04/Task2/StudentInfo.h | UTF-8 | 768 | 3.390625 | 3 | [] | no_license | #ifndef STUDENTINFO_H_INCLUDED
#define STUDENTINFO_H_INCLUDED
using namespace std;
class StudentInfo
{
private:
int id;
string name;
double cgpa;
public:
StudentInfo()
{
}
StudentInfo(int i,string n, double c)
{
id=i;
name= n;
cgpa= c;
}
void printStudent()
{
cout<<"Name: "<<name<<endl<<"Id: "<<id<<endl<<"CGPA: "<<cgpa<<endl;
}
int getId()
{
return id;
}
string getName()
{
return name;
}
double getCgpa()
{
return cgpa;
}
};
#endif // STUDENTINFO_H_INCLUDED
| true |
95857ead9c0bdbe2e0011476cd48a8b94bcc74ec | C++ | zbigos/PGK2020 | /lista_6/maputils.cpp | UTF-8 | 2,149 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <dirent.h>
#define NATIVE_MAP_RESOLUTION 1201
#define SQ(x) ((x) * (x))
using std::vector;
using std::string;
vector<string> gettargets(string path) {
vector<string> targets;
DIR *dir;
struct dirent *ent;
if ((dir = opendir (path.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
if (ent->d_name[0] != '.') {
string mname = ent->d_name;
targets.push_back(path + "/" + mname);
}
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
std::cout << "isn't a valid directory" << std::endl << "terminating" << std::endl;
exit(0);
}
std::cout << "located " << targets.size() << " maps..." << std::endl;
return targets;
}
void readfile(string filename, unsigned short int *mapdump) {
std::ifstream mapdata(filename, std::ios::out | std::ios::binary);
if (!mapdata) {
std::cout << "failed to open file " << filename << std::endl << "terminating...";
exit(1);
}
unsigned char *recvdata = (unsigned char *)malloc(2 * SQ(NATIVE_MAP_RESOLUTION) * sizeof(unsigned char));
mapdata.read((char *)recvdata, 2 * SQ(NATIVE_MAP_RESOLUTION));
for(int i = 0 ; i < NATIVE_MAP_RESOLUTION; i++)
for(int j = 0 ; j < NATIVE_MAP_RESOLUTION; j++) {
int xcoord = i;
int ycoord = (NATIVE_MAP_RESOLUTION + (j-i-1))%NATIVE_MAP_RESOLUTION;
int index = NATIVE_MAP_RESOLUTION * xcoord + ycoord;
int findex = NATIVE_MAP_RESOLUTION * i + j;
if ((recvdata[2 * findex + 0] << 8 | recvdata[2 * findex + 1]) > ((1<<14)-1))
mapdump[i] = 0;
else
mapdump[index] = recvdata[2 * findex + 0] << 8 | recvdata[2 * findex + 1];
}
free(recvdata);
}
unsigned short int * readfile_and_downsample(string filename, int downsample) {
unsigned short int *originalmap = (unsigned short int *)malloc(SQ(NATIVE_MAP_RESOLUTION) * sizeof(unsigned short int));
readfile(filename, originalmap);
return originalmap;
} | true |
d0d2c418835ee7587ced1f99bedfeed73b921b85 | C++ | abhisheksnaik/CS31-Projects | /Project 5/stars.cpp | UTF-8 | 5,979 | 3.375 | 3 | [] | no_license | //
// main.cpp
// stars
//
// Created by Abhishek Naik on 11/13/17.
// Copyright © 2017 AbhishekNaik. All rights reserved.
//
#include "utilities.h"
#include <iostream>
#include <cstring>
#include <cctype>
#include <random>
#include <string>
using namespace std;
//sets the word list to document
const char WORDFILENAME[] = "/Users/abhisheknaik/Desktop/teststars.txt";
//declaration of functions
int runOneRound(const char words[][7], int nWords, int wordnum);
bool hasWord(const char words[][7], const char probeWord[7], int numWords);
bool isValidWord(const char probeWord[7]);
void countStarsPlanets(const char words[][7], const char probeWord[7], int);
int main()
{
//declaration of variables and arrays
const int MAXWORDS = 9000;
const int MAXWORDLEN = 6;
int roundScore = 0;
int arraySize = 7265;
int maxScore = 0;
int minScore = 1000000;
double avgScore = 0;
int totalScore = 0;
int numRounds = 0;
char w[MAXWORDS][MAXWORDLEN + 1];
int n = getWords(w, arraySize, WORDFILENAME);
if(n < 1){//checks that getWords was implemented properly
cout<<"No words were loaded, so I can't play the game.";
return -1;
}
if(n > MAXWORDS)
return -1;
cout<<"How many rounds do you want to play? ";
cin>>numRounds;
cin.ignore(10000, '\n');
if(numRounds<0){
cerr<<"The number of rounds must be positive."<<endl;//terminates program if number of words is negative
return -1;
}
cout<<endl;
//forces doubles to contain two decimal places
cout.setf(ios::fixed);
cout.precision(2);
//runs the number of tries that the user inputs
for(int i = 0; i < numRounds; i++){
int r = randInt(1, n-1);//randomly generates index of secret word between 1 and one less than the number of words in the array
cout<< "Round "<<i+1<<endl;
cout<<"The secret word is "<<strlen(w[r])<<" letters long"<<endl;
roundScore = runOneRound(w, n, r);//calls runOneRound and sets score to roundScore
if(roundScore == -1){//terminates program if runOneRoun encountered an error
cerr<<"There was an error, try again."<<endl;
return -1;
}
totalScore += roundScore;//keeps a running total of score to calculate the average score
if(roundScore > maxScore)
maxScore = roundScore;//sets max score if roundScore is greater than maxScore
if(roundScore < minScore)
minScore = roundScore;//sets min score if roundScore is greater than minScore
avgScore = (double)totalScore/(i+1);//calculates average score
if(roundScore == 1)//writes out the score
cout<<"You got it in 1 try."<<endl;
else
cout<<"You got it in "<<roundScore<<" tries."<<endl;
cout<<"Average: "<<avgScore<<", minimum: "<<minScore<<", maximum: "<<maxScore<<endl; //prints stats for that round
cout<<endl;
}
}
//runs one round of the game with the array of words, the number of words, and the number of the secret word
int runOneRound(const char words[][7], int nWords, int wordnum){
int scoreCounter = 1;
char probeWord[MAXWORDLEN+1];
if(nWords < 0 || wordnum < 0 || wordnum >= nWords)//returns -1 if arguments are incorrect
return -1;
for(;;){
cout<<"Probe word: ";
cin.getline(probeWord, MAXWORDLEN+1);
if(!isValidWord(probeWord)){//checks to make sure that the probe word is between 4 and 6 characters and is lowercase
cout<<"Your probe word must be a word of 4 to 6 lower case letters."<<endl;
continue;
}
if(!hasWord(words, probeWord, nWords)){//checks to make sure that the probe word is a valid word in the word list
cout<<"I don't know that word."<<endl;
continue;
}
if(strcmp(probeWord, words[wordnum]) == 0){//checks to see if the probe word is the secret word
//scoreCounter++;
return scoreCounter;
}
countStarsPlanets(words, probeWord, wordnum);//calculates and prints the planets and stars in the probe word
scoreCounter++;//increments score counter
}
}
//checks that the probe word is in the list
bool hasWord(const char words[][7], const char probeWord[7], int numWords){
for(int j = 0; j< numWords; j++){
if(strcmp(probeWord, words[j]) == 0)
return true;
}
return false;
}
//checks that the probe word is valid by checking its size is valid and that it consists of lower case letters
bool isValidWord(const char probeWord[7]){
if(strlen(probeWord) > 6 || strlen(probeWord) < 4)
return false;
for(int i = 0; i < strlen(probeWord); i++){
if(!isalpha(probeWord[i]) && !islower(probeWord[i]))
return false;
}
return true;
}
//calculates and prints the planets and stars in the porbe word
void countStarsPlanets(const char words[][7], const char probeWord[7], int wordnum){
char copySecret[MAXWORDLEN+1];
char copyProbe[MAXWORDLEN+1];
int stars = 0;
int planets = 0;
//copies the probe word and the secret word into copy ctrings that can be maipulated
strcpy(copySecret, words[wordnum]);
strcpy(copyProbe, probeWord);
for(int i = 0; i < strlen(copyProbe); i++){//finds stars and replaces those letters with spaces
if(copyProbe[i] == copySecret[i]){
copyProbe[i] = ' ';
copySecret[i] = ' ';
stars++;
}
}
for(int i = 0; i < strlen(copyProbe); i++){
for(int j = 0; j < strlen(copySecret); j++){
if((copyProbe[i] == copySecret[j]) && copyProbe[i]!=' '){//finds planets by finding pairs that are not spaces
planets++;
break;//avoids double counting
}
}
}
cout<<"Stars: "<<stars<<", Planets: "<<planets<<endl;//prints the planets and stars
}
| true |
e1c8e5a749b61fa24d19ba9411c3ddbbce395b55 | C++ | brunodea/cg-t3 | /include/GUI/Sidebar/ProjectionRadioButton.h | UTF-8 | 1,169 | 2.734375 | 3 | [] | no_license | /* Classe que faz acoes dependendo de qual RadioButton foi selecionado. Esses radiobuttons sao relativos ao tipo de projecao. */
#ifndef _BRUNODEA_PROJECTION_BUTTON_GROUP_HPP_
#define _BRUNODEA_PROJECTION_BUTTON_GROUP_HPP_
#include <SCV/SCV.h>
#include "Gui/Canvas/Projection.h"
#include <string>
namespace GUI
{
class ProjectionRadioButton : public scv::RadioButton
{
public:
enum Type
{
ORTHO = 0,
PERSP = 1
}; //end of enum Type.
public:
ProjectionRadioButton(Type type, const scv::Point &p, bool state, const std::string &s)
: m_Type(type),scv::RadioButton(p,state,s)
{}
protected:
void onMouseClick(const scv::MouseEvent &evt)
{
switch(m_Type)
{
case ORTHO:
CANVAS::PROJECTION->setType(CANVAS::Projection::ORTHO);
break;
case PERSP:
CANVAS::PROJECTION->setType(CANVAS::Projection::PERSP);
break;
}
}
private:
Type m_Type;
}; //end of class ProjectionRadioButton.
} //end of namespace GUI.
#endif
| true |
ff5a7e25a2769e4b83d9daa4ad306dd38db2116c | C++ | DDUC-CS-Sanjeet/polynomial-implementation-iamkuldeepnath | /Polynomial.cpp | UTF-8 | 3,257 | 4.09375 | 4 | [] | no_license | /*
KULDEEP NATH
19HCS4029
PROGRAM TO IMPLEMENT ADDITION AND SUBSTRACTION ON POLYNOMIALS
*/
#include<iostream>
using namespace std;
class Polynomial
{
private:
// Variables to store information about polynomial
int *arr;
int size;
public:
Polynomial()
{
// Behavior of default constructor
size = 10;
arr = new int [size];
}
Polynomial(int deg)
{
// Behavior of constructor with arguments
size =deg+1;
arr = new int[size];
}
~Polynomial()
{
// Behavior of destructor
}
// Overload copy constructor, +, - and = operators
Polynomial(const Polynomial &p)
{
size = p.size;
for(int i=0;i<size;i++)
{
arr[i] = p.arr[i];
}
}
Polynomial operator + (const Polynomial&);
Polynomial operator - (const Polynomial&);
// = operator overloading
Polynomial &operator = (const Polynomial &p1)
{
size = p1.size;
for(int i=0;i<p1.size;i++)
arr[i] = p1.arr[i];
return *this;
}
void storePolynomial()
{
// Code to enter and store polynomial
cout<<"\n\nEnter polynomial ->";
for(int i=0;i<size;i++)
{
cout<<"\n Co-efficient of x^"<<i<<" : ";
cin>>arr[i];
}
}
void display()
{
// Code to print the polynomial in readable format
cout<<"\n->Polynomial => ";
for(int i=size-1;i>=0;i--)
{
char m= ((i)==0)?' ':'+';
cout<<"( "<<arr[i]<<"x^"<<i<<" ) "<<m;
}
cout<<endl;
}
};
// + operator overloading
Polynomial Polynomial :: operator+ (const Polynomial &p1)
{
int s = (size > p1.size )? size : p1.size;
int m = (size < p1.size )? size : p1.size;
int f = (size > p1.size )? 1 : 0;
Polynomial temp1(s-1);
for(int i=0;i<m;i++)
temp1.arr[i] = arr[i] + p1.arr[i];
if(f)
for(int i=m;i<s;i++)
temp1.arr[i] = arr[i];
else
for(int i=m;i<s;i++)
temp1.arr[i] = p1.arr[i];
return temp1;
}
// - operator overloading
Polynomial Polynomial :: operator- (const Polynomial &p)
{
int s = (size > p.size )? size : p.size;
int m = (size < p.size )? size : p.size;
int f = (size > p.size )? 1 : 0;
Polynomial temp(s-1);
for(int i=0;i<m;i++)
temp.arr[i] = arr[i] - p.arr[i];
if(f)
for(int i=m;i<s;i++)
temp.arr[i] = arr[i];
else
for(int i=m;i<s;i++)
temp.arr[i] = -1*p.arr[i];
return temp;
}
int main()
{
// Ask user to input the values of degFirst and degSecond
int degFirst, degSecond;
cout<<"\nEnter degree of 1st polynomial : ";
cin>>degFirst;
cout<<"\nEnter degree of 2nd polynomial : ";
cin>>degSecond;
Polynomial firstPolynomial(degFirst);
Polynomial secondPolynomial(degSecond);
Polynomial thirdPolynomial;
// Entering values into first and second polynomial
firstPolynomial.storePolynomial();
secondPolynomial.storePolynomial();
// + operator overloading
thirdPolynomial=firstPolynomial+secondPolynomial;
// - operator overloading
Polynomial fourthPolynomial=firstPolynomial-secondPolynomial;
//Displaying all the polynomials
firstPolynomial.display();
secondPolynomial.display();
thirdPolynomial.display();
fourthPolynomial.display();
return 0;
}
| true |
b1e3f1c308ece4f0dde69430daf95d07d8e39750 | C++ | bbockelm/xrootd-tpc | /src/stream.hh | UTF-8 | 3,041 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive |
/**
* The "stream" interface is a simple abstraction of a file handle.
*
* The abstraction layer is necessary to do the necessary buffering
* of multi-stream writes where the underlying filesystem only
* supports single-stream writes.
*/
#include <memory>
#include <vector>
#include <cstring>
struct stat;
class XrdSfsFile;
namespace TPC {
class Stream {
public:
Stream(std::unique_ptr<XrdSfsFile> fh, size_t max_blocks, size_t buffer_size)
: m_avail_count(max_blocks),
m_fh(std::move(fh)),
m_offset(0)
{
//m_buffers.reserve(max_blocks);
for (size_t idx=0; idx < max_blocks; idx++) {
m_buffers.emplace_back(buffer_size);
}
}
~Stream();
int Stat(struct stat *);
int Read(off_t offset, char *buffer, size_t size);
int Write(off_t offset, const char *buffer, size_t size);
size_t AvailableBuffers() const {return m_avail_count;}
private:
class Entry {
public:
Entry(size_t capacity) :
m_capacity(capacity)
{}
Entry(const Entry&) = delete;
Entry(Entry&&) = default;
bool Available() const {return m_offset == -1;}
int Write(Stream &stream) {
if (Available() || !CanWrite(stream)) {return 0;}
// Currently, only full writes are accepted.
int size_desired = m_size;
int retval = stream.Write(m_offset, &m_buffer[0], size_desired);
m_size = 0;
m_offset = -1;
if (retval != size_desired) {
return -1;
}
return retval;
}
bool Accept(off_t offset, const char *buf, size_t size) {
// Validate acceptance criteria.
if ((m_offset != -1) && (offset != m_offset + static_cast<ssize_t>(m_size))) {
return false;
}
if (size > m_capacity - m_size) {
return false;
}
// Inflate the underlying buffer if needed.
ssize_t new_bytes_needed = (m_size + size) - m_buffer.capacity();
if (new_bytes_needed > 0) {
m_buffer.reserve(m_capacity);
}
// Finally, do the copy.
memcpy(&m_buffer[0] + m_size, buf, size);
m_size += size;
if (m_offset == -1) {
m_offset = offset;
}
return true;
}
void ShrinkIfUnused() {
if (!Available()) {return;}
m_buffer.shrink_to_fit();
}
private:
bool CanWrite(Stream &stream) const {
return (m_size > 0) && (m_offset == stream.m_offset);
}
off_t m_offset{-1}; // Offset within file that m_buffer[0] represents.
const size_t m_capacity;
size_t m_size{0}; // Number of bytes held in buffer.
std::vector<char> m_buffer;
};
size_t m_avail_count;
std::unique_ptr<XrdSfsFile> m_fh;
off_t m_offset{0};
std::vector<Entry> m_buffers;
};
}
| true |
8c7f5c0d8182133b99e6f7d84cebfe37cecb7b24 | C++ | cHaO5/data-structure-practicum | /grid-construction-cost-simulation-system/grid_construction_cost_simulation_system.h | UTF-8 | 1,195 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct Edge {
int num; //次顶点序号
float cost; //边的开销
Edge *next; //指向下一个邻接顶点
};
class Node {
public:
int start; //头结点序号
int end; //尾节点序号
float cost; //造价
Node() {} //构造函数
Node(int start, int end, float cost) {
this->start = start;
this->end = end;
this->cost = cost;
}
~Node() {} //析构函数
};
class MinCost {
public:
Node MSTree[100];
int size; //当前的容量值
MinCost() { size = 0; }
void insert(Node *&node) {
MSTree[size].start = node->start;
MSTree[size].end = node->end;
MSTree[size].cost = node->cost;
++size;
}
};
struct Vertex {
int num; //顶点序号
string city; //小区名
Edge *first;
};
class Net {
public:
int size; //顶点个数
Vertex *vertArray; //邻接表顶点表
MinCost MST;
Net() { size = 0; }
~Net() {}
void create();
void add();
int findVertArray(string city);
bool prim();
void operation();
void printMST();
}; | true |
1057bd731e0161563e30ec5eaac6109f393047b4 | C++ | darshan-crypto/darshan_cpp_projects | /netlib/netlib/payload.h | UTF-8 | 891 | 3.28125 | 3 | [] | no_license | #include <string>
typedef std::string string;
class Payload
{
public:
Payload(string);
void getPayload(string *);
string getHeader() { return data; }
private:
string data;
string payload;
void process();
int start;
};
Payload::Payload(string s)
{
data = s;
process();
}
void Payload::getPayload(string *output)
{
*output = payload;
}
void Payload::process()
{
for (int i = 0; i < data.length(); i++)
{
if (data.at(i) == '\r')
{
if (data.at(i + 1) == '\n')
{
if (data.at(i + 2) == '\r')
{
if (data.at(i + 3) == '\n')
{
start = i + 4;
}
}
}
}
}
for (int i = start; i < data.length(); i++)
{
payload.append(1, data.at(i));
}
} | true |
c55400568b820ae0ba02a25b399a8fcc71cf22e7 | C++ | Brightlpf/MY-LEARN | /cpp/C++PrimerPlus/chapter16/PE/bank.cpp | UTF-8 | 2,375 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>
#include "customer.h"
using namespace std;
const int MIN_PER_HR = 60;
bool newcustomer(double x); //is there a new customer
int main()
{
srand(time(NULL));
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs;
queue<Customer> line;
cout << "Enter the number of simulation hours: ";
int hours;
cin >> hours;
//simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours;
cout << "Enter the average number of customers per hours: ";
double perhour;
cin >> perhour;
double min_per_cust;
min_per_cust = MIN_PER_HR / perhour; // 平均循环n次 产生一个顾客
Customer temp; //new customer
long turnaways = 0; //turned away by full queue
long customers = 0; //joined the queue
long served = 0; //served during the simulation
long sum_line = 0; //cumulative line length
int wait_time = 0; //time until autoteller is free
long line_wait = 0; //cumulative time in line
for(int cycle = 0; cycle < cyclelimit; cycle++)
{
//have newcomer
if (newcustomer(min_per_cust))
{
if (line.size() == qs)
turnaways++;
else
{
customers++;
temp.set(cycle);
line.push(temp);
}
}
//处理完成(随机1~3分钟),离开队列
if(wait_time <= 0 && !line.empty())
{
temp = line.front();
line.pop();
//cout << "customer dequeue " << endl;
wait_time = temp.ptime();
line_wait += cycle - temp.when();
served++;
}
//正在处理当中。。。
if(wait_time > 0)
{
//cout <<"wait time is "<< wait_time << endl;
wait_time--;
}
sum_line += line.size();
}
//reporting results
if (customers > 0)
{
cout << "customers accepted: " << customers << endl;
cout << " customers served: " << served << endl;
cout << " turnaways: " << turnaways << endl;
cout << "average queue size: ";
cout.precision(2);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << (double ) sum_line/cyclelimit << endl;
cout << "average wait time: "
<< (double) line_wait / served << "minutes\n";
}
else
cout << "No customers!\n";
cout << "Done!\n";
return 0;
}
bool newcustomer(double x)
{
return (rand() * x /RAND_MAX < 1);
}
void Customer::set(long when)
{
arrivetime = when;
processtime = rand() % 3 + 1;
} | true |
4bfa012b09cacb5739926219bd21a657063b8228 | C++ | Samas1503/EDM | /1ro Info/Pactica de abii/multiplicar sumando.cpp | UTF-8 | 382 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
void ingreso_datos(int &x, int &y);
int division(int x, int y);
using namespace std;
int main(){
int a,b;
ingreso_datos(a,b);
cout<<division(a,b)<<endl;
}
void ingreso_datos (int &x, int &y){
cin>>x>>y;
}
int division (int x, int y){
int r=0;
do{
if (x>=y)r++
x-=y
}
while (x>=y);
return r;
}
| true |
2769eeda2d1a144a31090a7e55a36d8458b4e1a0 | C++ | cedoduarte/QML_QPROPERTY_and_QQuickStyle | /myperson.cpp | UTF-8 | 471 | 3.046875 | 3 | [
"MIT"
] | permissive | #include "myperson.h"
MyPerson::MyPerson(QObject *parent) : QObject(parent)
{
m_age = 0;
}
MyPerson::MyPerson(const QString &name, int age, QObject *parent) : QObject(parent)
{
m_name = name;
m_age = age;
}
void MyPerson::set_name(const QString &name)
{
if (m_name != name) {
m_name = name;
emit name_changed();
}
}
void MyPerson::set_age(int age)
{
if (m_age != age) {
m_age = age;
emit age_changed();
}
}
| true |
e74d47f26ac7605b9085b10e8602d24cc5c5ee7a | C++ | joel-perez/9515Algo2TP2 | /src/Vertice.cpp | UTF-8 | 2,195 | 3.09375 | 3 | [] | no_license | #include "Vertice.h"
using namespace std;
Vertice::Vertice(string nombre, unsigned int indice) {
if (nombre != "" && indice >= 0) {
this->nombre = nombre;
this->adyacentes = new Lista<Arista*>();
this->indice = indice;
this->envios = NULL;
}
}
Lista<Arista*>* Vertice::obtenerAdyacentes() {
return this->adyacentes;
}
string Vertice::obtenerNombre() {
return this->nombre;
}
unsigned int Vertice::obtenerIndice() {
return this->indice;
}
void Vertice::agregarArista(Arista* nuevaArista) {
if (nuevaArista != NULL) {
this->adyacentes->agregar(nuevaArista);
}
}
void Vertice::ingresarDatosEnvio(unsigned int precio, std::string nombre) {
if (precio >= 0 && nombre != "") {
if (this->envios == NULL) {
this->envios = new Lista<Envio*>();
}
Envio* datos = new Envio(nombre, precio);
this->envios->agregar(datos);
}
}
void Vertice::mostrarPosiblesEnvios() {
if (this->envios != NULL) {
this->envios->iniciarCursor();
while (this->envios->avanzarCursor()) {
Envio* actual = this->envios->obtenerCursor();
cout << actual->obtenerNombreCultivo() << ", ";
}
}
}
bool Vertice::aceptaCultivo(string analizado) {
bool encontrado = false;
this->envios->iniciarCursor();
while (this->envios->avanzarCursor() && !encontrado) {
encontrado = (texto.mayusculas(
this->envios->obtenerCursor()->obtenerNombreCultivo())
== texto.mayusculas(analizado));
}
return encontrado;
}
unsigned int Vertice::obtenerCostoDelCultivo(string nombre) {
bool encontrado = false;
unsigned int costo = 0;
this->envios->iniciarCursor();
while (this->envios->avanzarCursor() && !encontrado) {
encontrado = (texto.mayusculas(
this->envios->obtenerCursor()->obtenerNombreCultivo())
== texto.mayusculas(nombre));
if (encontrado) {
costo = this->envios->obtenerCursor()->obtenerPrecioEnvio();
}
}
return costo;
}
Vertice::~Vertice() {
if (this->envios != NULL) {
this->envios->iniciarCursor();
while (this->envios->avanzarCursor()) {
delete this->envios->obtenerCursor();
}
delete envios;
}
this->adyacentes->iniciarCursor();
while (this->adyacentes->avanzarCursor()) {
delete this->adyacentes->obtenerCursor();
}
delete adyacentes;
}
| true |
d2dd8ac7571ed70c01d340bcbb9dd2dde715ea63 | C++ | Denis-chen/iot-client-sdk | /tests/iot_client/flags.cpp | UTF-8 | 3,358 | 3.203125 | 3 | [] | no_license | #include "flags.h"
#include <iostream>
#include <string.h>
#include <algorithm>
using std::cout;
using std::endl;
namespace
{
const char whiteSpaces[] = " \t\r\n";
std::string TrimRight(const std::string& s, const char *chars = whiteSpaces)
{
std::string res = s;
res.erase(s.find_last_not_of(chars) + 1);
return res;
}
std::string TrimLeft(const std::string& s, const char *chars = whiteSpaces)
{
std::string res = s;
res.erase(0, s.find_first_not_of(chars));
return res;
}
std::string Trim(const std::string& s, const char *chars = whiteSpaces)
{
return TrimLeft(TrimRight(s, chars), chars);
}
}
Flags::Flags(int argc, char * argv[], const Options & options) : m_options(options)
{
ParseArgs(argc, argv);
ApplyDefaults();
}
const Flags::StringMap & Flags::GetAll() const
{
return m_args;
}
std::string Flags::Get(const std::string & name) const
{
StringMap::const_iterator arg = m_args.find(name);
return arg != m_args.end() ? arg->second : "";
}
bool Flags::GetBoolean(const std::string & name) const
{
return Get(name) == "true";
}
bool Flags::Exist(const std::string & name) const
{
return m_args.find(name) != m_args.end();
}
void Flags::ParseArgs(int argc, char * argv[])
{
if (argc > 0)
{
SetProgramName(argv[0]);
}
for (int i = 1; i < argc; ++i)
{
ParseArg(argv[i]);
}
}
void Flags::ParseArg(const char * arg)
{
while (*arg == '-' && *arg != '\0')
{
++arg;
}
std::string str = arg;
size_t pos = str.find_first_of("=");
m_args[Trim(str.substr(0, pos))] = (pos != std::string::npos) ? Trim(str.substr(pos + 1)) : "";
}
void Flags::SetProgramName(const std::string & programName)
{
size_t pos = programName.find_last_of("/\\");
m_programName = (pos != std::string::npos) ? programName.substr(pos + 1) : programName;
}
void Flags::ApplyDefaults()
{
for (Options::iterator i = m_options.begin(); i != m_options.end(); ++i)
{
if (!Exist(i->name) && i->defaultValue != NULL && *(i->defaultValue) != '\0')
{
m_args[i->name] = i->defaultValue;
}
}
}
static std::string Align(const std::string& s, size_t len)
{
int diff = static_cast<int>(len - s.length());
if (diff <= 0)
{
return s;
}
std::string res = s;
res.insert(res.end(), diff, ' ');
return res;
}
void Flags::PrintUsage() const
{
size_t maxNameLen = 0;
for (Options::const_iterator i = m_options.begin(); i != m_options.end(); ++i)
{
maxNameLen = std::max(maxNameLen, strlen(i->name));
}
maxNameLen += 3;
cout << "Usage:" << endl;
cout << m_programName << " [<option>=<value>...]" << endl;
cout << "Available options:" << endl;
for (Options::const_iterator i = m_options.begin(); i != m_options.end(); ++i)
{
const char* defVal = (i->defaultValue != NULL && *(i->defaultValue) != '\0') ? i->defaultValue : "<none>";
std::string name = std::string("-") + i->name + ":";
cout << " " << Align(name, maxNameLen) << i->description;
if (i->defaultValue != NULL && *(i->defaultValue) != '\0')
{
cout << ". Default: " << i->defaultValue;
}
cout << endl;
}
cout << endl;
}
| true |
57a66d5c67c6092bd757ec486402c0d7a3819f4e | C++ | renancmonteiro/ils_simulated_annealing_timetabling | /Vizinhancas/TimeMove.cpp | UTF-8 | 6,433 | 2.75 | 3 | [] | no_license | /*
* TimeMove.cpp
*
* Created on: Dec 16, 2015
* Author: renan
*/
#include "TimeMove.h"
#include "Move.h"
#include "RoomMove.h"
#include "../Model/Alocacao.h"
TimeMove::TimeMove(Individuo* piInd, Alocacao* al1, Alocacao* al2){
tipoMovimento = 3;
list<Alocacao*>::iterator it;
ind = piInd;
m = NULL;
a1 = al2;
bool escolheu = false;
/* Seleciona o primeiro TimeSlot disponível ascendente */
for(it = ind->horariosVazios.begin(); it != ind->horariosVazios.end(); it++)
{
if((*(it))->sala->numeroSequencial == al1->sala->numeroSequencial && (*(it))->horario->horario > a1->horario->horario)
{
a2 = *it;
escolheu = true;
break;
}
}
if(!escolheu)
{
/* Seleciona o primeiro TimeSlot disponível descendente */
list<Alocacao*>::reverse_iterator itr;
for(itr = ind->horariosVazios.rbegin(); itr != ind->horariosVazios.rend(); itr++)
{
if((*(itr))->sala->numeroSequencial == al1->sala->numeroSequencial && (*(itr))->horario->horario < a1->horario->horario)
{
a2 = *itr;
escolheu = true;
break;
}
}
}
if(a2 != NULL && escolheu){
a1 = al1;
deltaFit = calculaDeltaFitTimeMove(piInd->p);
} else {
m = new RoomMove(ind, al1, al2);
deltaFit = m->deltaFit;
}
}
TimeMove::TimeMove(Problema* p, Individuo* piInd)
{
tipoMovimento = 3;
ind = piInd;
m = NULL;
/* Escolhe randomicamente uma aula alocada */
int posAulaAlocada = rand() % ind->aulasAlocadas.size();
/* Cria o iterator pra lista de aulas alocadas */
list<Alocacao*>::iterator it = ind->aulasAlocadas.begin();
/* Avança até a posição escolhida */
advance(it, posAulaAlocada);
a1 = *(it);
bool escolheu = false;
/* Seleciona o primeiro TimeSlot disponível ascendente */
for(it = ind->horariosVazios.begin(); it != ind->horariosVazios.end(); it++)
{
if((*(it))->sala->numeroSequencial == a1->sala->numeroSequencial && (*(it))->horario->horario > a1->horario->horario)
{
a2 = *it;
escolheu = true;
break;
}
}
if(!escolheu)
{
/* Seleciona o primeiro TimeSlot disponível descendente */
list<Alocacao*>::reverse_iterator itr;
for(itr = ind->horariosVazios.rbegin(); itr != ind->horariosVazios.rend(); itr++)
{
if((*(itr))->sala->numeroSequencial == a1->sala->numeroSequencial && (*(itr))->horario->horario < a1->horario->horario)
{
a2 = *itr;
escolheu = true;
break;
}
}
}
if(a2 != NULL && escolheu){
deltaFit = calculaDeltaFitTimeMove(p);
} else {
deltaFit = 99999; deltaHard = 99999;
}
}
void TimeMove::aplicaMovimento()
{
if(m == NULL){
/* Remove A1 da lista de aulas alocadas */
ind->aulasAlocadas.remove(a1);
/* Remove a2 da lista de alocações vazias */
ind->horariosVazios.remove(a2);
aplicaTimeMoveSemRecalculoFuncaoObjetivo();
ind->fitness += deltaFit;
ind->hard += deltaHard;
ind->soft1 += deltaSoft1;
ind->soft2 += deltaSoft2;
ind->soft3 += deltaSoft3;
ind->soft4 += deltaSoft4;
/* Insere A1 na lista de aulas alocadas */
ind->aulasAlocadas.push_back(a1);
/* Insere A2 na lista de alocações vazias, de modo ordenado */
list<Alocacao*>::iterator it;
for(it = ind->horariosVazios.begin(); it != ind->horariosVazios.end() && (*it)->sala->numeroSequencial <= a2->sala->numeroSequencial; it++) {
if ( (*it)->sala->numeroSequencial == a2->sala->numeroSequencial && (*it)->horario->horario > a2->horario->horario ) {
break;
}
}
ind->horariosVazios.insert (it, a2);
} else {
m->aplicaMovimento();
}
}
int TimeMove::calculaDeltaFitTimeMove(Problema* p)
{
list<Restricao*>::iterator it;
int deltaFitness;
int violaRestricaoHard;
deltaFitness = -p->CalculaCustoAulaAlocada(ind, a1, this);
deltaHard = 0;
deltaSoft1 = -deltaSoft1;
deltaSoft2 = -deltaSoft2;
deltaSoft3 = -deltaSoft3;
deltaSoft4 = -deltaSoft4;
deltaFitness = deltaSoft1 + deltaSoft2 + deltaSoft3 + deltaSoft4;
aplicaTimeMoveSemRecalculoFuncaoObjetivo();
violaRestricaoHard = p->violaRestricaoGrave(ind, this);
if( ! violaRestricaoHard ){
deltaFitness += p->CalculaCustoAulaAlocada(ind, a1, this);
}
else {deltaFitness = 99999; deltaHard = 99999;}
aplicaTimeMoveSemRecalculoFuncaoObjetivo();
return deltaFitness;
}
void TimeMove::aplicaTimeMoveSemRecalculoFuncaoObjetivo(){
list<Curriculo*>::iterator itCurr;
Timeslot* temp_hora;
int aula1;
aula1 = a1->aula->disciplina->numeroSequencial;
ind->Alocacao_dias_utilizados[aula1][a1->horario->dia]--;
ind->Alocacao_salas_utilizadas[aula1][a1->sala->numeroSequencial]--;
for( itCurr = a1->aula->disciplina->curriculos.begin(); itCurr!=a1->aula->disciplina->curriculos.end(); itCurr++){
ind->Alocacao_horarios_utilizados_por_curriculo[(*itCurr)->numeroSequencial][a1->horario->horario]--;
if( ind->Alocacao_horarios_utilizados_por_curriculo[(*itCurr)->numeroSequencial][a1->horario->horario] == 0)
ind->matrizAlocacaoCurriculoDiasPeriodos[(*itCurr)->numeroSequencial][a1->horario->dia][a1->horario->periodo] = NULL;
}
ind->matrizProfessorHorarioQntd[a1->aula->disciplina->professor->numeroSequencial][a1->horario->horario]--;
if( ind->matrizProfessorHorario[a1->aula->disciplina->professor->numeroSequencial][a1->horario->horario] == a1)
ind->matrizProfessorHorario[a1->aula->disciplina->professor->numeroSequencial][a1->horario->horario] = NULL;
// a1->aula->disciplina->professor->restricaoHorario[a1->horario->horario] = NULL;
temp_hora = a1->horario;
a1->horario = a2->horario;
a2->horario = temp_hora;
ind->matrizProfessorHorarioQntd[a1->aula->disciplina->professor->numeroSequencial][a1->horario->horario]++;
if( ind->matrizProfessorHorario[a1->aula->disciplina->professor->numeroSequencial][a1->horario->horario] == NULL)
ind->matrizProfessorHorario[a1->aula->disciplina->professor->numeroSequencial][a1->horario->horario] = a1;
// a1->aula->disciplina->professor->restricaoHorario[a1->horario->horario] = a1;
ind->Alocacao_dias_utilizados[aula1][a1->horario->dia]++;
ind->Alocacao_salas_utilizadas[aula1][a1->sala->numeroSequencial]++;
for( itCurr = a1->aula->disciplina->curriculos.begin(); itCurr!=a1->aula->disciplina->curriculos.end(); itCurr++){
ind->Alocacao_horarios_utilizados_por_curriculo[(*itCurr)->numeroSequencial][a1->horario->horario]++;
if( ind->matrizAlocacaoCurriculoDiasPeriodos[(*itCurr)->numeroSequencial][a1->horario->dia][a1->horario->periodo] == NULL )
ind->matrizAlocacaoCurriculoDiasPeriodos[(*itCurr)->numeroSequencial][a1->horario->dia][a1->horario->periodo] = a1;
}
}
| true |
3d735ff61b9b0ba8f5147a61fb1c6b8efb580793 | C++ | thedeepestreality/lectures2019 | /Exceptions/Source.cpp | UTF-8 | 704 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <exception>
int gcd(int x, int y)
{
if (x == 0 || y == 0) throw 1;
if (x < 0) throw "First argument is negative";
if (y < 0) throw std::runtime_error("Second argument is negative");
while (x != y)
x > y ? x -= y : y -= x;
return x;
}
int main()
{
try
{
gcd(1, -1);
int x = gcd(1, 1);
std::cout << x << std::endl;
}
catch (int errNum)
{
std::cout << "Arguments are zero" << std::endl;
system("pause");
return 1;
}
catch (const char* errorMsg)
{
std::cout << errorMsg << std::endl;
system("pause");
return 1;
}
catch (...)
{
std::cout << "Unknown error" << std::endl;
system("pause");
return 1;
}
system("pause");
return 0;
} | true |
a73f1b54688cd5e5655dd8d931c93684d49886fb | C++ | JRProd/SDEngine | /Code/Engine/Core/Math/Primatives/Plane2D.hpp | UTF-8 | 458 | 2.78125 | 3 | [] | no_license | #pragma once
#include "LineSeg2D.hpp"
#include "Vec2.hpp"
struct Plane2D
{
Vec2 normal;
float distance = 0.f;
public:
Plane2D() = default;
Plane2D( const Vec2& direction, float dist );
Plane2D( const Vec2& direction, const Vec2& point );
bool IsOnPositiveSide( const Vec2& point ) const;
bool IsOnPlane( const Vec2& point ) const;
Vec2 GetTangent() const;
LineSeg2D GetClippedEdge( const LineSeg2D& lineSeg ) const;
};
| true |
742613adba784816629ae157b5292597a77fe7b8 | C++ | jashwanth/Advanced-Data-Structures- | /HW1/doubleLinkedList.cpp | UTF-8 | 11,247 | 3.40625 | 3 | [] | no_license | #include "doubleLinkedList.h"
doubleNode::doubleNode(int item, doubleNode* prev, doubleNode* next)
{
this->data = item;
this->prev = prev;
this->next = next;
}
int doubleNode::getNodeData()
{
return this->data;
}
doubleNode* doubleNode::getPrevNode()
{
return this->prev;
}
doubleNode* doubleNode::getNextNode()
{
return this->next;
}
void doubleNode::setNodeData(int item)
{
this->data = item;
}
void doubleNode::setPrevNode(doubleNode* prev)
{
this->prev = prev;
}
void doubleNode::setNextNode(doubleNode* next)
{
this->next = next;
}
void doubleNode::displayData()
{
cout << getNodeData();
}
dll::dll()
{
head = NULL;
}
void dll::createdll(int *arr, int num)
{
int i = 0;
head = NULL;
for ( i = 0; i < num ; i++)
{
InsertAtEnd(arr[i]);
}
}
int dll::ListLength()
{
int length = 0;
if (head == NULL)
{
return length;
}
doubleNode* temp = head;
while(temp != NULL)
{
temp = temp->getNextNode();
length++;
}
return length;
}
/* Return node which is len away from head node
if len is less than zero return null */
doubleNode* dll::ReturnKthNode(int len)
{
int i = 0;
doubleNode* temp = head;
if (len < 0)
{
return NULL;
}
while ((i < len) && (temp != NULL)) temp = temp->getNextNode(),i++;
return temp;
}
/*void dll::sortListByFour()
{
if (head == NULL)
{
return;
}
doubleNode* temp1 = head;
doubleNode* temp2 = NULL;
doubleNode* temp3 = NULL;
doubleNode* temp4 = NULL;
int sortElem[4];
for (int i=0;i<4;i++)sortElem[i] = INT_MAX;
int minIndex = 0;
while (temp1 != NULL)
{
sortElem[0] = temp1->getNodeData();
if ( (temp2 = temp1->getNextNode()) != NULL)
{
sortElem[1] = temp2->getNodeData();
if ((temp3 = temp2->getNextNode()) != NULL)
{
sortElem[2] = temp3->getNodeData();
if ((temp4 = temp3->getNextNode()) != NULL)
{
sortElem[3] = temp4->getNodeData();
}
}
}
for (int i = 0; i < 4; i++)
{
minIndex = i;
for (int j = i+1; j < 4; j++)
{
if (sortElem[j] <= sortElem[minIndex])
{
minIndex = j;
}
}
int swap = sortElem[i];
sortElem[i] = sortElem[minIndex];
sortElem[minIndex] = swap;
}
temp1->setNodeData(sortElem[0]);
if (temp2 != NULL)
{
temp2->setNodeData(sortElem[1]);
}
if (temp3 != NULL)
{
temp3->setNodeData(sortElem[2]);
}
if (temp4 != NULL)
{
temp4->setNodeData(sortElem[3]);
}
for (int i =0; i< 4; i++)sortElem[i] = INT_MAX ;
if (temp4 != NULL)temp1 = temp4->getNextNode();
else
{
if (temp3 != NULL)temp1 = temp3->getNextNode();
else
{
if (temp2 != NULL)temp1 = temp2->getNextNode();
else break;
}
}
temp2 = NULL;
temp3 = NULL;
temp4 = NULL;
}
}*/
void dll::mySort(int pos, int len)
{
doubleNode* cur = ReturnKthNode(pos);
if(cur == NULL)return;
int i, j, index;
doubleNode *temp1 = NULL;
doubleNode *temp2 = NULL;
doubleNode *temp3 = NULL;
doubleNode *temp4 = NULL;
doubleNode *temp5 = NULL;
doubleNode *temp6 = NULL;
for(i = 0; i < len; i++)
{
temp1 = ReturnKthNode(i+pos);
index = i;
for ( j = i+1; j < len; j++)
{
temp2 = ReturnKthNode(j+pos);
if ((temp1 != NULL) && (temp2 != NULL) && (temp2->getNodeData() < temp1->getNodeData()))
{
index = j;
temp1 = ReturnKthNode(index+pos);
}
}
/* swap at i and index */
temp1 = ReturnKthNode(i+pos);
temp2 = ReturnKthNode(index+pos);
temp3 = temp4 = temp5 = temp6 = NULL;
if (temp2 != NULL)temp3 = temp2->getPrevNode();
if (temp1 != NULL)temp4 = temp1->getPrevNode();
if (temp2 != NULL)temp5 = temp2->getNextNode();
if (temp1 != NULL)temp6 = temp1->getNextNode();
/*-------currentNode---------------------SwapNode--------
^ ^
| |
temp4 <=> temp1 <=> temp6 <=>.....temp3 <=> temp2 <=> temp5 <=>..... */
/*Make the previous of index node next as current Node
and prev of current node resp */
if (temp3 != NULL)
{
/*To prevent pointing back to same node causing loop */
if ((temp3 != temp1) && (temp1 != NULL))
temp3->setNextNode(temp1);
}
if (temp1 != NULL)
{
if (temp1 != temp3)
temp1->setPrevNode(temp3);
temp1->setNextNode(temp5);
}
/*Make the next of current node as next of index Node */
if (temp5 != NULL)temp5->setPrevNode(temp1);
/*Make the next of previous Node of current as index Node */
if (temp4 != NULL)
{
temp4->setNextNode(temp2);
}
/*Make the next of index Node as next of current Node */
if (temp2 != NULL)
{
temp2->setPrevNode(temp4);
/*To prevent pointing back to same node causing loop */
if (temp2 != temp6)
{
temp2->setNextNode(temp6);
}
}
if (temp6 != NULL)
{
if (temp2 != temp6)
{
temp6->setPrevNode(temp2);
}
}
if ((temp1 != NULL) && (temp2 != NULL))
{
/* Special case when temp1= temp3 and temp2= temp6 this logic is
needed to not break the chain */
if ((temp1 == temp3) && (temp2 == temp6))
{
temp2->setNextNode(temp1);
temp1->setPrevNode(temp2);
}
}
if (i == 0)
{
cur = temp2;
if (pos == 0)head = cur;
}
}
/* We always mantain start of list
so if this is the first time sort is called
modify head to the sorted list */
if (pos == 0)
{
head = cur;
}
}
void dll::shuffleDll()
{
if (head == NULL)return;
int len = ListLength();
if (len == 1)return;
int k = ((len%2) == 0) ? len/2: (len+1)/2, i = 0, j = 0;
doubleNode *temp1 = head;
doubleNode *temp2 = head;
doubleNode *temp3 = head; /* Contains head after which kth elem is to be inserted */
doubleNode *temp4 = head;
while ((i < k) && (temp1 != NULL))
{
temp1 = temp1->getNextNode();
i++;
}
/* Store prev and next of kth element */
temp2 = temp1->getPrevNode();
temp4 = temp1->getNextNode();
// cout << "kth elem is " << temp1->getNodeData() << " " << endl;
while ((temp1 != NULL) && (temp2 != NULL) &&
(temp3 != NULL))
{
/* Remove the kth element from current position */
/* Point the prev of kth elem to next of Kth elem */
temp2->setNextNode(temp4);
/* Point the next of kth elem to prev of kth elem */
if (temp4 != NULL)temp4->setPrevNode(temp2);
/* Point the kth elem Next to the next of current head */
temp1->setNextNode(temp3->getNextNode());
/* Point the prev of next of current head to kth elem */
if (temp3->getNextNode())temp3->getNextNode()->setPrevNode(temp1);
/* Point the kth elem Previous to the current head */
temp1->setPrevNode(temp3);
/* Point the next of current head to its kth elem */
temp3->setNextNode(temp1);
/* Update the current head to insert next Kth elem */
temp3 = temp1->getNextNode();
/* Update the next kth elem for current head */
temp1 = temp2->getNextNode();
/* Update next elem of current Kth elem */
if (temp1 != NULL)temp4 = temp1->getNextNode();
}
}
void dll::reverseDll()
{
if (head == NULL)return;
int len = ListLength();
if (len == 1)return;
doubleNode *temp1 = head;
doubleNode *temp2 = head;
while (temp1 != NULL)
{
temp2 = temp1->getPrevNode();
temp1->setPrevNode(temp1->getNextNode());
temp1->setNextNode(temp2);
temp1 = temp1->getPrevNode();
}
head = temp2->getPrevNode();
}
void dll::InsertAtStart(int data)
{
doubleNode *newNode = new doubleNode(data, NULL, NULL);
if (head == NULL)
{
head = newNode;
return;
}
else
{
newNode->setNextNode(head);
head->setPrevNode(newNode);
head = newNode;
}
}
void dll::InsertAtEnd(int data)
{
doubleNode* newNode = new doubleNode(data, NULL, NULL);
doubleNode* temp = head;
if (temp == NULL)
{
head = newNode;
return;
}
while (temp->getNextNode() != NULL)
{
temp = temp->getNextNode();
}
temp->setNextNode(newNode);
newNode->setPrevNode(temp);
}
void dll::printList()
{
doubleNode* temp = head;
if (temp == NULL)
{
cout << "==============" << endl;
cout << "Empty list...." << endl;
cout << "==============" << endl;
}
cout << "Head --> ";
while (temp != NULL)
{
temp->displayData();
cout << " --> ";
temp = temp->getNextNode();
if (temp == NULL)
{
cout << "NULL" << endl;
}
}
cout << endl;
}
void dll::printListByFour()
{
doubleNode *temp = head;
int fourElemCount = 0;
if (temp == NULL)
{
cout << "==============" << endl;
cout << "Empty list...." << endl;
cout << "==============" << endl;
}
while (temp != NULL)
{
temp->displayData();
cout << ",";
fourElemCount++;
if (fourElemCount == 4)
{
fourElemCount = 0;
cout << endl;
}
temp = temp->getNextNode();
}
}
void dll::printFirstHalfByFour()
{
doubleNode *temp = head;
if (temp == NULL)
{
cout << "==============" << endl;
cout << "Empty list...." << endl;
cout << "==============" << endl;
}
int len = ListLength(), i = 0, fourElemCount = 0;
int firsthalf = ( (len%2)==0 ? (len/2) : (len+1)/2 );
while( (i < firsthalf))
{
temp->displayData();
cout << ",";
fourElemCount++;
i++;
if (fourElemCount == 4)
{
fourElemCount = 0;
cout << endl;
}
temp = temp->getNextNode();
}
}
void dll::printSecondHalfByFour()
{
doubleNode *temp = head;
if (head == NULL)return;
int len = ListLength(), i = 0, fourElemCount = 0;
int firsthalf = ( (len%2)==0 ? (len/2) : (len+1)/2 );
int secondhalf = len - firsthalf;
while ( i < firsthalf)i++, temp = temp->getNextNode();
i = 0;
while ( (i < secondhalf) && (temp != NULL))
{
temp->displayData();
cout << ",";
fourElemCount++;
i++;
if (fourElemCount == 4)
{
fourElemCount = 0;
cout << endl;
}
temp = temp->getNextNode();
}
}
/*int main()
{
int tc, data, i =0;
dll mydll;
cin >> tc;
while(tc -- )
{
cin >> data;
mydll.InsertAtEnd(data);
// mysll.printList();
}
cout << "****Before Double linkedlist Reverse operation ********" << endl;
mydll.printListByFour();
cout << endl << endl;
cout << "****After Double linkedlist Reverse operation********" << endl;
mydll.reverseDll();
mydll.printListByFour();
cout << endl << endl;
cout << "****Before Double linkedlist Shuffle operation*****" << endl;
mydll.printListByFour();
cout << endl << endl;
cout << "****After Double linkedlist Shuffle operation*****" << endl;
mydll.shuffleDll();
mydll.printListByFour();
cout << endl << endl;
cout << "****Before single linked list Four Operation*****" << endl;
mydll.printListByFour();
cout << endl << endl;
cout << "****After single linked list Four Operation*****" << endl;
int len = mydll.ListLength();
while (i < len)
{
mydll.mySort(i, 4);
i+=4;
}
mydll.printListByFour();
cout << endl << endl;
return 0;
} */
| true |
2de66ea1cc1bb6b490c828201cd4c11476ed9159 | C++ | godforename/1 | /VopesMath/test/include/complex.h | UTF-8 | 2,035 | 3.015625 | 3 | [] | no_license | #ifndef _COMPLEX_H
#define _COMPLEX_H
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <stdbool.h>
#define PI 3.141592654
#define EXP 2.718281828
using namespace std;
class Complex
{
friend ostream & operator <<(ostream &o, const Complex& x);
private:
double real;
double imag;
public:
Complex():real(0), imag(0) {};
Complex(double re, double im):real(re), imag(im) {};
Complex(double x)
{
this->real = x;
this->imag = 0;
}
Complex(const Complex& x)
{
this->real = x.real;
this->imag = x.imag;
}
Complex& operator =(const Complex& x)
{
this->real = x.real;
this->imag = x.imag;
return *this;
}
Complex& operator =(double k)
{
this->real = k;
this->imag = 0;
return *this;
}
Complex operator -()const
{
return Complex(-this->real, -this->imag);
}
bool isZero()const;
double Re()const;
double Im()const;
double module()const;
double arg()const;
Complex conj()const;
friend bool operator ==(const Complex& x, const Complex& y);
friend bool operator !=(const Complex& x, const Complex& y);
friend Complex operator +(const Complex& x, const Complex& y);
friend Complex operator +(double k, const Complex& x);
friend Complex operator +(const Complex& x, double k);
friend Complex operator -(const Complex& x, const Complex& y);
friend Complex operator -(double k, const Complex& x);
friend Complex operator -(const Complex& x, double k);
friend Complex operator *(const Complex& x, const Complex& y);
friend Complex operator *(double k, const Complex& x);
friend Complex operator *(const Complex& x, double k);
friend Complex operator /(const Complex& x, const Complex& y);
friend Complex operator /(double k, const Complex& x);
friend Complex operator /(const Complex& x, double k);
friend Complex operator ^(const Complex& x, double n);
friend Complex operator ^(double a, const Complex& z);
};
Complex pow(const Complex& x, double n);
Complex exp(const Complex& x);
Complex R2C(double x);
bool isZero(double x);
#endif | true |
a7f8a2619b819b010272031646e60ebfca17ac27 | C++ | scse-l/MyCompiler | /lex.cpp | UTF-8 | 3,871 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <map>
#include <limits>
#include "global.h"
#include "support.h"
#pragma warning(disable:4996)
extern unsigned int numMax;
extern char ch;
extern long long value;
extern std::string ident;
extern int lineNo;
extern std::map<std::string, int> keywordTable;
int lex()
{
std::map<std::string, int>::iterator res;
ident.clear();
while (true)
{
//跳过所有空白符
while (isspace(ch))
{
if (ch == '\n')
{
lineNo++;
}
ch = getchar();
}
if (isalpha(ch))
{
//字母开头
ident.clear(); //清除上一个ident留下的内容
ident.append(sizeof(char), ch); //将当前字符添加至ident中
while (isalnum(ch = getchar()))
{
//如果当前是字母或者数字,则其应该是当前标识符中的一部分
ident.append(sizeof(char), ch); //将当前字符添加至ident中
}
//标识符结束
res = keywordTable.find(ident);
if (res != keywordTable.end())
{
//当前标识符是保留字
print("Keyword", "Name", ident.c_str());
return res->second;
}
return IDENT;
}
else if (isdigit(ch))
{
//数字
ungetc(ch, stdin);
scanf("%d", &value);
scanf("%c", &ch);
if (value > INT_MAX)
{
value = 0;
error("The Number Is Too Big!");
}
return NUM;
}
else if (match(':'))
{
if (match('='))
{
//赋值号:=
print("Sign", "Name", "BECOMES");
return BECOMES;
}
else
{
//冒号':'
print("Sign", "Name", "COLON");
return COLON;
}
}
else if (match('<'))
{
if (match('>'))
{
//不等号'<>'
print("Sign", "Name", "NOT EQUAL");
return NEQ;
}
else if (match('='))
{
//小于等于'<='
print("Sign", "Name", "LESS OR EQUAL");
return LEQ;
}
else
{
//小于号'<'
print("Sign", "Name", "LESS");
return LESS;
}
}
else if (match('>'))
{
if (match('='))
{
//大于等于号'>='
print("Sign", "Name", "GREATER OR EQUAL");
return GEQ;
}
else
{
//大于号'>'
print("Sign", "Name", "GREATER");
return GREATER;
}
}
else if (match('\''))
{
//字符处理
ident.clear();
while (isalnum(ch))
{
ident.append(sizeof(char), ch);
ch = getchar();
}
if (match('\''))
{
ident.erase(ident.end()-1);
}else
{
error("The Single Quotes don't match");
//需要错误恢复吗?
}
if (ident.length() > 1)
{
error("There are too many characters in single quotes");
ident.clear();
}
return CH;
}
else if (match('"'))
{
ident.clear();
while (ch == 32 || ch == 33 || 35 <= ch && ch <= 126)
{
//引号内的字符
ident.append(sizeof(char), ch);
ch = getchar();
}
if (!match('"'))
{
//在字符串内出现了非法字符
error("There is an illegal character in the string");
ident.clear();
while (!match('"'))
{
ch = getchar();
if (ch == EOF)
{
error("The Quotes don't match");
return EOF;
}
}
}
ident.erase(--(ident.end())); //去掉末尾的双引号
return STRING;
}
else if (ch == EOF)
{
return EOF;
}
else
{
//其他符号
ident.clear();
ident.append(sizeof(char), ch);
res = keywordTable.find(ident);
if (res != keywordTable.end() && res->second != 0)
{
//找到当前符号
print("Sign", "Name", ident);
ch = getchar();
return res->second;
}
//当前符号为不可识别的符号
//跳到下一个标识符或者数字开始的位置
while (!isalnum(ch) && ch != EOF && keywordTable[std::string(1,ch)] == 0)
{
ch = getchar();
ident.append(sizeof(char), ch);
}
ident.erase(--(ident.end())); //去掉下一个标识符的开始字符
if (ch == EOF)
{
return EOF;
}
return NUL;
}
}
} | true |
1ffd33bc8f9eb2df1a72c17e905d7c23b45575be | C++ | JellyWellyBelly/Comp-2018 | /ast/null_node.h | UTF-8 | 518 | 2.59375 | 3 | [] | no_license | // $Id: null_node.h,v 1.2 2018/03/23 16:45:23 ist426009 Exp $ -*- c++ -*-
#ifndef __GR8_NULLNODE_H__
#define __GR8_NULLNODE_H__
#include <cstddef>
namespace gr8 {
/**
* Class for describing null nodes.
*/
class null_node: public cdk::literal_node<std::nullptr_t> {
public:
inline null_node(int lineno) :
cdk::literal_node<std::nullptr_t>(lineno, NULL) {
}
public:
void accept(basic_ast_visitor *sp, int level) {
sp->do_null_node(this, level);
}
};
} // gr8
#endif
| true |
ec5bf37909757e9321482b18a1a308091d8a5ee7 | C++ | adithya-tp/leet_code | /0377_combination_sum_IV/solution_push_dp.cpp | UTF-8 | 422 | 2.8125 | 3 | [] | no_license | class Solution {
public:
// using the forward / push dynamic programming method
int combinationSum4(vector<int>& nums, int target) {
vector<unsigned long long> dp(target+1, 0);
dp[0] = 1;
for(int i = 0; i < target + 1; i++){
for(int x: nums){
if(i+x < target + 1)
dp[i+x] += dp[i];
}
}
return dp[target];
}
};
| true |
666b2a7d924ab443f64d3624b57930722bd696ea | C++ | abaddon201/qzxsqualpel | /memory/segment.h | UTF-8 | 2,240 | 3.28125 | 3 | [] | no_license | #ifndef SEGMENT_H
#define SEGMENT_H
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <memory>
#include <string>
namespace dasm {
namespace memory {
///@brief Описание сегмента памяти
class Segment {
public:
using IdType = unsigned long long;
using size_type = size_t;
enum class Type {
///@brief Неопознаный тип
RAW,
///@brief Кодовый сегмент
CODE,
///@brief Сегмент данных
DATA
};
Segment() : _size{ 0 }, _dataSize{ 0 }, _id{ 0 }, _type{ Type::RAW } {}
Segment(IdType id, size_type sz) : _size{ sz }, _dataSize{ 0 }, _id{ id }, _type{ Type::RAW } {}
void fill(unsigned char buff[], size_type size);
inline IdType id() const { return _id; }
inline void setId(IdType id) { _id = id; }
inline size_type dataSize() const { return _dataSize; }
inline void setDataSize(size_type sz) { _dataSize = sz; }
inline size_type size() const { return _size; }
inline void setSize(size_type sz) { _size = sz; }
inline Type type() const { return _type; }
inline void setType(Type type) { _type = type; }
const std::vector<uint8_t>& bytes() const { return _mem; }
std::vector<uint8_t>& bytes() { return _mem; }
inline uint8_t getByte(size_type offset) const {
if (offset < _dataSize) {
return _mem[offset];
} else {
throw std::out_of_range("offset:" + std::to_string(offset) + ", max:" + std::to_string(_dataSize));
}
}
inline void setByte(size_type offset, uint8_t b) {
if (offset < _dataSize) {
_mem[offset] = b;
} else {
throw std::out_of_range("offset:" + std::to_string(offset) + ", max:" + std::to_string(_dataSize));
}
}
private:
///@brief размер сегмента в байтах
size_type _size;
///@brief размер данных в сегменте в байтах
size_type _dataSize;
///@brief идентификатор сегмента (дескриптор/номер/адрес в памяти)
IdType _id;
///@brief Тип сегмента
Type _type;
///@brief Содержимое сегмента
std::vector<uint8_t> _mem;
};
using SegmentPtr = std::shared_ptr<Segment>;
}
}
#endif // SEGMENT_H
| true |
7cda0198f4c86b172eab49e34628687cfc578085 | C++ | JLMPL/Ship | /src/Visual/Trail.hpp | UTF-8 | 594 | 2.8125 | 3 | [
"MIT",
"Bitstream-Vera",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | #pragma once
#include "Core/Math.hpp"
#include <SFML/System/Time.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <vector>
class Trail
{
public:
Trail() = default;
void update();
void draw();
void setPosition(const vec2& pos);
void setColor(const sf::Color& color);
void setInterval(float interval);
void setLength(int length);
private:
vec2 m_pos;
std::vector<vec2> m_points;
std::vector<sf::Vertex> m_verts;
sf::Time m_timer = sf::seconds(1);
sf::Color m_color = {255,255,255,255};
float m_interval = 0.1;
int m_length = 100;
}; | true |
0510fc1de5b9efc5d2be2cec3c3105f70266fe2a | C++ | juan-zh/Euler | /EP38.cpp | UTF-8 | 1,091 | 2.765625 | 3 | [] | no_license | /*************************************************************************
> File Name: EP38.cpp
> Author: meng
> Mail: 2206084014@qq.com
> Created Time: 2019年06月16日 星期日 15时00分11秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<cmath>
using namespace std;
int digits(long long num) {
return floor(log10(num)) + 1;
}
long long calc(int x) {
long long ans = 0;
int n = 1;
while (digits(ans) < 9) {
ans *= pow(10, digits(n * x));
ans += n * x;
n += 1;
}
if (digits(ans) != 9) return -1;
int num[10] = {0};
num[0] = 1;
long long temp = ans;
while (temp) {
if (num[temp % 10]) return -1;
num[temp % 10] += 1;
temp /= 10;
}
return ans;
}
int main() {
long long temp, ans = 0;
for (int i = 1; i < 10000; i++) {
temp = calc(i);
if (temp > ans) ans = temp;
}
cout << ans << endl;
return 0;
}
| true |
7a2e962f34bbfc2b2b6607800fca65cfc52c08e8 | C++ | radioation/eyesDx | /MAPPSNativeIO/MAPPSNativeIO/niot.cpp | UTF-8 | 3,837 | 2.65625 | 3 | [] | no_license | #include "native_io_test.h"
inline bool ok(const char* s) { return strcmp(s, "ok") == 0; }
int main(int argc, char** argv)
{
char msg[512];
//////////////////////////////////////////////////////////////////////////
// Connect to the server.
//////////////////////////////////////////////////////////////////////////
EdxState state = EdxNativeIo::Connect(EDX_NATIVE_IO_VERSION_KEY, "native_io.1", 0, msg);
if (!ok(msg))
{
printf("Unable to connect to server [%s]. \n", msg);
return -1;
}
//////////////////////////////////////////////////////////////////////////
// Get the name of the currently running project.
//////////////////////////////////////////////////////////////////////////
char projectName[256];
EdxNativeIo::GetProjectName(state, projectName, msg);
printf("Project currently loaded: [%s]. \n", projectName);
//////////////////////////////////////////////////////////////////////////
// Get a list of bus data.
//////////////////////////////////////////////////////////////////////////
auto listData = make_unique<EdxNativeIo::ListBusData>();
EdxNativeIo::ListBuses(state, listData.get(), msg);
if (ok(msg))
{
printf("\n------------------------------- \n");
printf("There are %d buses. \n", listData->BusCount);
for (int i = 0; i < listData->BusCount; i++)
{
printf(" [%d] %s (%d elements). \n",
i, listData->Buses[i].BusName, listData->Buses[i].ElementCount);
}
printf("\n------------------------------- \n\n");
}
//////////////////////////////////////////////////////////////////////////
// Get and set time.
//////////////////////////////////////////////////////////////////////////
float timeInSec = 0;
int64_t utcTime = 0L;
EdxNativeIo::GetCurrentProjectTime(state, &timeInSec, &utcTime, msg);
printf("Current time is %1.2f sec, UTC: %I64d. \n", timeInSec, utcTime);
EdxNativeIo::SetCurrentProjectTime(state, 60.0f, msg);
//////////////////////////////////////////////////////////////////////////
// Get some data.
//////////////////////////////////////////////////////////////////////////
// Create a big storage buffer.
const int maxLen = 100'000'000; // 100MB
auto payload = make_unique<unsigned char[]>(maxLen);
auto timestamps = make_unique<int64_t[]>(3600 * 1000);
EdxNativeIo::ElementOutput elements[256];
for (int i = 0; i < listData->BusCount; i++)
{
int frameCount = 0;
int elCnt = EdxNativeIo::GetBusDataAllElements(
state, // State pointer
listData->Buses[i].BusName, // Name of bus to get
0, 0, // Get data for ALL time
payload.get(), maxLen, // Buffer to populate
elements, 256, // Elements to populate
timestamps.get(), // Timestamps to populate
&frameCount, // The number of frames produced
msg); // Status message
if (ok(msg))
{
printf("Bus [%s] has %d elements, %d frames. \n",
listData->Buses[i].BusName, elCnt, frameCount);
printf(" Runs from %I64dms to %I64dms (%I64d total milliseconds). \n",
timestamps[0], timestamps[size_t(frameCount) - 1],
timestamps[size_t(frameCount) - 1] - timestamps[0]);
if (strcmp(listData->Buses[i].BusName, "Subject_1") == 0)
{
float* objX = elements[3].Payload.AsFloat;
float* objY = elements[4].Payload.AsFloat;
int maxElems = 10;
if (maxElems > frameCount) {
maxElems = frameCount;
}
for (int fr = 0; fr < maxElems; fr++)
{
printf("%s - X: %1.3f Y: %1.3f \n",
listData->Buses[i].BusName,
objX[fr],
objY[fr]);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
// Disconnect.
//////////////////////////////////////////////////////////////////////////
EdxNativeIo::Disconnect(state, msg);
return 0;
}
| true |
04c2c3073d2aca500e665adf23e11304a7d63779 | C++ | RaduSzasz/PhotoEditor | /src/color.cpp | UTF-8 | 8,616 | 3.125 | 3 | [] | no_license | #include "color.h"
#include <math.h>
float minim(float a, float b, float c)
{
if(a<b&&a<c)
{
return a;
}
else
{
if(b<c)
return b;
}
return c;
}
float minimum(float a, float b)
{
if(a < b)
return a;
return b;
}
float maxim(float a, float b, float c)
{
if(a>b&&a>c)
{
return a;
}
else
{
if(b>c)
return b;
}
return c;
}
Color::Color()
{
argb=0;
}
Color::Color(int setargb)
{
argb = setargb;
}
Color::Color(int r, int g, int b)
{
argb = 0;
argb = argb | r;
argb = argb << 8;
argb= argb | g;
argb = argb << 8;
argb = argb | b;
}
int Color::HsvToRgb(int _H, float _S, float _V)
{
float R = 0, G = 0, B = 0;
if(_H > 360)
_H -= 360;
float h = (1.0 * _H) / 60.0;
float s = _S / 100.0;
float v = _V / 100.0;
int inti = (int)floor(h);
float int1, int2, int3;
int1 = v * (1.0 - s);
int2 = v * (1.0 - s * (h - inti));
int3 = v * (1.0 - s * (1.0 - (h - inti)));
if (s < 0.01)
{
R = v;
G = v;
B = v;
}
else
{
switch (inti)
{
case 0:
R = v;
G = int3;
B = int1;
break;
case 1:
R = int2;
G = v;
B = int1;
break;
case 2:
R = int1;
G = v;
B = int3;
break;
case 3:
R = int1;
G = int2;
B = v;
break;
case 4:
R = int3;
G = int1;
B = v;
break;
default:
R = v;
G = int1;
B = int2;
break;
}
}
R = (int)floor(255 * R);
G = (int)floor(255 * G);
B = (int)floor(255 * B);
return RgbToArgb(R ,G ,B);
}
int Color::RgbToArgb(int R, int G, int B)
{
int argb = 0;
argb = argb | R;
argb = argb << 8;
argb= argb | G;
argb = argb << 8;
argb = argb | B;
return argb;
}
void Color::RgbToHsv(int R, int G, int B, int& H, float& S, float& V)
{
float r =(float)R/255;
float g =(float)G/255;
float b =(float)B/255;
float h = 0,s = 0,v = 0;
float minVal = minim(r, g, b);
float maxVal = maxim(r, g, b);
float delta = maxVal - minVal;
v = maxVal;
if (fabs(delta) < 0.001)
{
h = 0;
s = 0;
}
else
{
s = delta / maxVal;
float del_R = (((maxVal - r) / 6) + (delta / 2)) / delta;
float del_G = (((maxVal - g) / 6) + (delta / 2)) / delta;
float del_B = (((maxVal - b) / 6) + (delta / 2)) / delta;
if (fabs(r - maxVal) < 0.001)
{
h = del_B - del_G;
}
else
if (fabs(g - maxVal) < 0.001)
{
h = (1.0 / 3.0) + del_R - del_B;
}
else
{
if (fabs(b - maxVal) < 0.001)
{
h = (2.0 / 3.0) + del_G - del_R;
}
if (h < 0)
{
h += 1;
}
if (h > 1)
{
h -= 1;
}
}
}
H=h*360;
if (H < 0) {H = 360-H;}
S=s;
V=v;
}
void Color::RgbToCmyk(int R, int G, int B, int &C, int &M, int &Y, int &K)
{
float newC = 0;
float newM = 0;
float newY = 0;
float newK = 0;
if (R<0 || G<0 || B<0)
{
if(R < 0)
R = 0;
if (G < 0)
G = 0;
if(B < 0)
B = 0;
}
if(R > 255 || G > 255 || B > 255)
{
if(R > 255)
R = 255;
if(G > 255)
G = 255;
if(B > 255)
B = 255;
}
if (R==0 && G==0 && B==0)
{
K = 1;
return;
}
newC = 1 - (float)((float)R/255);
newM = 1 - (float)((float)G/255);
newY = 1 - (float)((float)B/255);
float minCMY = minimum(newC, minimum(newM,newY));
newC = (newC - minCMY) / (1 - minCMY) ;
newM = (newM - minCMY) / (1 - minCMY) ;
newY = (newY - minCMY) / (1 - minCMY) ;
newK = minCMY;
C = (int)floor(newC * 255);
M = (int)floor(newM * 255);
Y = (int)floor(newY * 255);
K = (int)floor(newK * 255);
}
int Color::CmykToRgb(int C, int M, int Y, int K)
{
int R, G, B;
C = minim(255, C + K, 255);
M = minim(255, 255, M + K);
Y = minim(255, 255, Y + K);
R = 255 - C;
G = 255 - M;
B = 255 - Y;
return RgbToArgb(R, G, B);
}
Color::Color(int h, float s, float v)
{
if(s>1)
{
s/=100;
}
if(v>1)
{
v/=100;
}
argb=HsvToRgb(h,s,v);
}
int Color::getB()
{
int B=argb;
B=B&0xFF;
return B;
}
int Color::getR()
{
int R=argb;
R=R>>16;
R=R&0xFF;
return R;
}
int Color::getG()
{
int G=argb;
G=G>>8;
G=G&0xFF;
return G;
}
Color& Color::setR(int R)
{
int B = getB();
int G = getG();
if(R > 255) R = 255;
if(R < 0) R = 0;
argb = RgbToArgb(R ,G ,B);
return *this;
}
Color& Color::setB(int B)
{
int R = getR();
int G = getG();
if(B > 255) B = 255;
if(B < 0) B = 0;
argb = RgbToArgb(R ,G ,B);
return *this;
}
Color& Color::setG(int G)
{
int R = getR();
int B = getB();
if(G > 255) G = 255;
if(G < 0) G = 0;
argb = RgbToArgb(R ,G ,B);
return *this;
}
int Color::getH()
{
int R = getR();
int G = getG();
int B = getB();
int H = 0;
float S, V;
RgbToHsv(R, G, B, H, S, V);
return H;
}
int Color::getS()
{
int R = getR();
int G = getG();
int B = getB();
int H = 0;
float S, V;
RgbToHsv(R, G, B, H, S, V);
return (int)(S*100);
}
int Color::getV()
{
int R = getR();
int G = getG();
int B = getB();
int H = 0;
float S, V;
RgbToHsv(R, G, B, H, S, V);
return (int)(V*100);
}
int Color::getC()
{
int R = getR();
int G = getG();
int B = getB();
int C = 0,M, Y, K;
RgbToCmyk(R, G, B, C, M, Y, K);
return C;
}
int Color::getM()
{
int R = getR();
int G = getG();
int B = getB();
int C,M = 0, Y, K;
RgbToCmyk(R, G, B, C, M, Y, K);
return M;
}
int Color::getY()
{
int R = getR();
int G = getG();
int B = getB();
int C ,M , Y = 0, K;
RgbToCmyk(R, G, B, C, M, Y, K);
return Y;
}
int Color::getK()
{
int R = getR();
int G = getG();
int B = getB();
int C ,M , Y , K = 0;
RgbToCmyk(R, G, B, C, M, Y, K);
return K;
}
Color& Color::setC(int C)
{
int M = getM();
int Y = getY();
int K = getK();
argb = CmykToRgb(C, M, Y, K);
return *this;
}
Color& Color::setM(int M)
{
int C = getC();
int Y = getY();
int K = getK();
argb = CmykToRgb(C, M, Y, K);
return *this;
}
Color& Color::setY(int Y)
{
int C = getC();
int M = getM();
int K = getK();
argb = CmykToRgb(C, M, Y, K);
return *this;
}
Color& Color::setK(int K)
{
int C = getC();
int M = getM();
int Y = getY();
argb = CmykToRgb(C, M, Y, K);
return *this;
}
Color& Color::setH(int _H)
{
_H = _H % 360;
int H;
float S,V;
int R = getR();
int G = getG();
int B = getB();
RgbToHsv(R, G, B, H, S, V);
argb = HsvToRgb(_H,S*100,V*100);
return *this;
}
Color& Color::setS(int _S)
{
if (_S < 0) {_S = 0;}
if (_S > 100) {_S = 100;}
int H;
float S,V;
int R = getR();
int G = getG();
int B = getB();
RgbToHsv(R, G, B, H, S, V);
argb = HsvToRgb(H,_S,V * 100);
return *this;
}
Color& Color::setV(int _V)
{
if (_V < 0) {_V = 0;}
if (_V > 100) {_V = 100;}
int H;
float S,V;
int R = getR();
int G = getG();
int B = getB();
RgbToHsv(R, G, B, H, S, V);
argb = HsvToRgb(H,S*100,_V);
return *this;
}
int Color::getArgb()
{
return this->argb;
}
| true |
5cb392afe888085bf9919c181cded68bac0c5882 | C++ | umaatgithub/ImageProcessingOpenCV | /imageedgefiltertool.cpp | UTF-8 | 3,847 | 2.890625 | 3 | [] | no_license | #include "imageedgefiltertool.h"
/***************************************************************************
* Input argument(s) : QObject *parent - Passed to base class constructor
* Return type : NIL
* Functionality : Constructor to initialize all the member variables
* of the class, setup the UI
*
**************************************************************************/
ImageEdgeFilterTool::ImageEdgeFilterTool(QString name): ImageProcessingToolWidget(name), layout(new QGridLayout),
edgeDetectorLabel(new QLabel), edgeDetectorComboBox(new QComboBox),
applyButton(new QPushButton)
{
setupWidget();
connect(applyButton, SIGNAL(clicked(bool)), this, SLOT(applyButtonClicked()));
}
/***************************************************************************
* Input argument(s) : NIL
* Return type : NIL
* Functionality : Destructor to delete all the pointer variables
*
**************************************************************************/
ImageEdgeFilterTool::~ImageEdgeFilterTool()
{
delete applyButton;
delete edgeDetectorComboBox;
delete edgeDetectorLabel;
delete layout;
}
/***************************************************************************
* Input argument(s) : void
* Return type : void
* Functionality : Function to setup the UI for the edge filter tool
*
**************************************************************************/
void ImageEdgeFilterTool::setupWidget()
{
edgeDetectorLabel->setText(QString("Edge Detector : "));
edgeDetectorLabel->setFixedHeight(25);
edgeDetectorComboBox->addItem(QString("Canny"), CANNY);
edgeDetectorComboBox->addItem(QString("Scharr"), SCHARR);
edgeDetectorComboBox->addItem(QString("Sobel"), SOBEL);
edgeDetectorComboBox->setFixedHeight(25);
applyButton->setText(QString("Apply Changes"));
applyButton->setFixedHeight(25);
layout->addWidget(edgeDetectorLabel, 0, 0);
layout->addWidget(edgeDetectorComboBox, 0, 1);
layout->addWidget(applyButton, 2, 0, 2, 3);
layout->setRowMinimumHeight(0, 30);
layout->setRowMinimumHeight(1, 30);
setLayout(layout);
}
/***************************************************************************
* Input argument(s) : void
* Return type : void
* Functionality : Slot to handle apply button click. It calls the
* edge filter function corresponding to the user
* selection
*
**************************************************************************/
void ImageEdgeFilterTool::applyButtonClicked()
{
try{
emit statusChanged(QString(" Processing image..."), Qt::blue);
if(!getInputImage()->isNull()){
if(edgeDetectorComboBox->currentData() == CANNY){
setOutputImage(edgeDetectionImage.applyCannysEdgeDetector(getInputImage()));
emit statusChanged(QString(" Done."), Qt::green);
}
else if(edgeDetectorComboBox->currentData() == SCHARR){
setOutputImage(edgeDetectionImage.applyScharrEdgeDetector(getInputImage()));
emit statusChanged(QString(" Done."), Qt::green);
}
else if(edgeDetectorComboBox->currentData() == SOBEL){
setOutputImage(edgeDetectionImage.applySobelEdgeDetector(getInputImage()));
emit statusChanged(QString(" Done."), Qt::green);
}
}
else{
emit statusChanged(QString(" Image not set."), Qt::black);
}
}
catch (const char* msg) {
emit statusChanged(QString(msg), Qt::red);
}
catch(std::exception exp){
emit statusChanged(QString(" Error."), Qt::red);
}
}
| true |
cc56227b4bd8b340ef05df5f55cd8476d2689f74 | C++ | luiz734/Jogo-VS | /ListaEntidade.cpp | UTF-8 | 687 | 2.859375 | 3 | [] | no_license | #include "ListaEntidade.h"
ListaEntidade::ListaEntidade()
{
}
ListaEntidade::~ListaEntidade()
{
limpar();
}
ListaEntidade* ListaEntidade::instancia = NULL;
ListaEntidade* ListaEntidade::getInstancia()
{
if (instancia == NULL)
{
instancia = new ListaEntidade;
}
return instancia;
}
void ListaEntidade::addEntidade(Entidade *eA)
{
lista.addData(eA);
}
void ListaEntidade::delEntidade(Entidade *serDeletada)
{
lista.delData(serDeletada);
}
Entidade* ListaEntidade::getEntidade(int pos)
{
return lista.getData(pos);
}
void ListaEntidade::limpar()
{
lista.limpar();
}
int ListaEntidade::getTamanho()
{
return lista.getTamanho();
}
| true |
91b64befaa8ac524c4c2a74c9e0a38e0f3c000a0 | C++ | ailyanlu1/ACM-10 | /图论/拓扑排序/拓扑排序.cpp | GB18030 | 1,261 | 2.734375 | 3 | [] | no_license | // ACMdata.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include<cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <map>
#include <vector>
#include <queue>
using namespace std;
const int N = 510;
int n, m, s[N], a, b;
int head[N], cnt;
struct edge {
int to, next;
}e[N*N];
void add(int u, int v) {
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt++;
}
void init() {
cnt = 0;
memset(head, -1, sizeof(head));
memset(s, 0, sizeof(s));
}
int getm(int *t) { //ҵǰСĵ㷵
int res = 10000, pos;
for (int i = 1; i <= n; i++) {
if (t[i] == -1)
continue;
if (res > t[i]) {
pos = i;
res = t[i];
}
}
return pos;
}
void solve() {
while (~scanf("%d%d", &n, &m)) {
init();
for (int i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
add(a, b);
s[b]++;
}
for (int i = 0; i < n; i++) {
int pos = getm(s);
printf("%d", pos);
if (i != n - 1)
printf(" ");
else
break;
for (int j = head[pos]; j != -1; j = e[j].next) { //ݵǰСĵĵ
s[e[j].to]--;
}
s[pos] --;
}
printf("\n");
}
return;
}
int main()
{
solve();
return 0;
}
| true |
9a5fdeab6a6f169267026b5a2401d46c97715951 | C++ | shortthirdman/code-eval-challenges | /quickstart/ArrayAbsurdity.cc | UTF-8 | 1,608 | 3.578125 | 4 | [
"MIT"
] | permissive | /*
Array Absurdity Share on LinkedIn
Description:
Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2, inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears exactly twice. Find the duplicated entry. (For bonus points, ensure your solution has constant space and time proportional to N)
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Ignore all empty lines. Each line begins with a positive integer(N) i.e. the size of the array, then a semicolon followed by a comma separated list of positive numbers ranging from 0 to N-2, inclusive. i.e eg.
5;0,1,2,3,0
20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14
Output sample:
Print out the duplicated entry, each one on a new line eg
0
4
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
int main(int argc, char *argv[]) {
ifstream ifs(argv[1]);
string line;
set<int> table;
while (getline(ifs, line)) {
string remain = line.substr(line.find(';')+1);
replace(remain.begin(), remain.end(), ',', ' ');
istringstream iss(remain);
int temp;
table.clear();
while (iss >> temp) {
if (table.find(temp) != table.end()) {
cout << temp << endl;
break;
} else {
table.insert(temp);
}
}
}
return 0;
} | true |
a28452bd08a98b3db6666464a2ad3a749196e393 | C++ | nos8160/AlgosWithCPlusPlsu | /OneFileToRuleThemAll.cpp | UTF-8 | 317 | 2.65625 | 3 | [] | no_license | #include<iostream>
#include<time.h>
#include "TemplateCollection.cpp"
using namespace std;
int main(){
double start = clock();
int array[] = {-89,0,-32,789,0,1,45};
int size = sizeof(array)/sizeof(array[0]);
sortWithSelection(array,size);
printArray(array,size);
cout<< clock()-start<<endl;
}
| true |
7a45f740235a686f15a917cec9ed044bb38a8778 | C++ | luqian2017/Algorithm | /LintCode/707_Optimal-Account-Balancing/707_Optimal-Account-Balancing-V2.cpp | UTF-8 | 1,307 | 3 | 3 | [] | no_license | class Solution {
public:
/*
* @param edges: a directed graph where each edge is represented by a tuple
* @return: the number of edges
*/
int balanceGraph(vector<vector<int>> &edges) {
int nRow = edges.size();
int nCol = edges[0].size();
unordered_map<int, int> um; //<i, j> Node i has balance j
for (auto e : edges) {
um[e[0]] -= e[2];
um[e[1]] += e[2];
}
vector<int> account;
for (auto u : um) {
if (u.second != 0) account.push_back(u.second);
}
if(account.size() == 0) return 0;
vector<int> dp(1 << account.size(), INT_MAX / 2); //???
for (int i = 1; i < dp.size(); ++i) {
int sum = 0, count = 0;
for (int j = 0; j < account.size(); ++j) {
if ((1 << j) & i) {
sum += account[j];
count++;
}
}
if (sum == 0) {
dp[i] = count - 1;
for (int j = 1; j < i ; ++j) {
if ((i & j) == j) {
dp[i] = min(dp[i], dp[j] + dp[i - j]);
}
}
}
}
return dp.back(); //dp[dp.size() - 1];
}
}; | true |
0e5b339d5f81f204bd90606fd5f10cab48df51ff | C++ | danykim57/c-study | /quiz/54.cpp | UTF-8 | 493 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
int main(int argc, char** argv){
//freopen("input.txt", "rt", stdin);
stack<char> s;
char a[50];
int i, flag=1;
scanf("%s", &a);
for(i=0; a[i]!='\0'; i++){
if(a[i]=='(') s.push(a[i]);
else{
if(s.empty()){
printf("NO\n");
flag=0;
break;
}
else s.pop();
}
}
if(s.empty() && flag==1) printf("YES\n");
else printf("NO\n");
return 0;
}
| true |
ae3357a683a7342d4ce04fadddbcfe70a3de5168 | C++ | tatevbarseghyan/shape_class | /inc/CircleClass.hpp | UTF-8 | 284 | 2.71875 | 3 | [] | no_license | #ifndef CIRCLE_H
#define CIRCLE_H
#include <string>
#include "ShapeClass.hpp"
class Circle : public Shape
{
private:
double m_radius;
public:
Circle(std::string name, std::string color, double radius);
double get_area();
~Circle();
};
#endif
| true |
f7357639ba805b567f02d7c64dd31b7d07474a96 | C++ | chenxinjizhe/dynasoar | /allocator/soa_defrag.inc | UTF-8 | 38,498 | 2.5625 | 3 | [] | no_license | // Textual header.
static const BlockIndexT kInvalidBlockIndex =
std::numeric_limits<BlockIndexT>::max();
template<int NumBuckets, typename IndexT>
__DEV__ IndexT block_idx_hash(IndexT block_idx) {
return block_idx % NumBuckets;
}
template<typename ClassIteratorT, typename AllocatorT>
__global__ void kernel_iterate_rewrite_objects(AllocatorT* allocator) {
ClassIteratorT::iterate_rewrite_objects(allocator);
}
template<typename AllocatorT>
struct AllocatorWrapperDefrag {
template<typename T>
using BlockHelper = typename AllocatorT::template BlockHelper<T>;
using BlockBitmapT = typename AllocatorT::BlockBitmapT;
static const int kCudaBlockSize = 256;
// Select fields of type DefragT* and rewrite pointers if necessary.
// DefragT: Type that was defragmented.
// ScanClassT: Class which is being scanned for affected fields.
// SoaFieldHelperT: SoaFieldHelper of potentially affected field.
template<typename DefragT, int NumRecords>
struct SoaPointerUpdater {
template<typename ScanClassT>
struct ClassIterator {
using ThisClass = ClassIterator<ScanClassT>;
static const int kScanBlockSize = BlockHelper<ScanClassT>::kSize;
static const int kScanTypeIndex = BlockHelper<ScanClassT>::kIndex;
// Checks if this field should be rewritten.
template<typename SoaFieldHelperT>
struct FieldChecker {
using FieldType = typename SoaFieldHelperT::type;
bool operator()() {
// Stop iterating if at least one field must be rewritten.
return !FieldUpdater<SoaFieldHelperT>::kSelected;
}
};
__DEV__ static void iterate_rewrite_objects(AllocatorT* allocator) {
#ifndef OPTION_DEFRAG_FORWARDING_POINTER
allocator->template load_records_to_shared_mem<NumRecords>();
#endif // OPTION_DEFRAG_FORWARDING_POINTER
const auto N_alloc =
allocator->allocated_[kScanTypeIndex].scan_num_bits();
// Round to multiple of kScanBlockSize.
int num_threads = ((blockDim.x * gridDim.x)/kScanBlockSize)*kScanBlockSize;
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if (tid < num_threads) {
for (int j = tid/kScanBlockSize; j < N_alloc; j += num_threads/kScanBlockSize) {
// i is the index of in the scan array.
auto block_idx = allocator->allocated_[kScanTypeIndex].scan_get_index(j);
// TODO: Consider doing a scan over "allocated" bitmap.
auto* block = allocator->template get_block<ScanClassT>(block_idx);
const auto allocation_bitmap = block->allocation_bitmap();
int thread_offset = tid % kScanBlockSize;
if ((allocation_bitmap & (1ULL << thread_offset)) != 0ULL) {
SoaClassHelper<ScanClassT>
::template dev_for_all<FieldUpdater, /*IterateBase=*/ true>(
allocator, block, thread_offset);
}
}
}
}
// Scan and rewrite field.
template<typename SoaFieldHelperT>
struct FieldUpdater {
using FieldType = typename SoaFieldHelperT::type;
using SoaFieldType = SoaField<typename SoaFieldHelperT::OwnerClass,
SoaFieldHelperT::kIndex>;
// Scan this field.
template<bool Check, int Dummy>
struct FieldSelector {
template<typename BlockT>
__DEV__ static void call(AllocatorT* allocator,
BlockT* block, ObjectIndexT object_id) {
// Location of field value to be scanned/rewritten.
auto* block_char_p = reinterpret_cast<char*>(block);
FieldType* scan_location =
SoaFieldType::template data_ptr_from_location<BlockT::kN>(
block_char_p, object_id);
// Rewrite value at address.
allocator->template maybe_rewrite_pointer<
DefragT, NumRecords, ScanClassT, FieldType>(scan_location);
}
};
// Check array base type.
template<bool Check, int Dummy>
struct ArrayFieldSelector {
using ArrayBaseT = typename FieldType::BaseType;
static const bool kSelected =
std::is_pointer<ArrayBaseT>::value
&& std::is_base_of<typename std::remove_pointer<ArrayBaseT>::type,
DefragT>::value;
// Base type macthes. Scan this array.
template<bool Check2, int Dummy2>
struct FieldSelector {
template<typename BlockT>
__DEV__ static void call(AllocatorT* allocator,
BlockT* block, ObjectIndexT object_id) {
// Location of field value to be scanned/rewritten.
auto* block_char_p = reinterpret_cast<char*>(block);
FieldType& array =
*SoaFieldType::template data_ptr_from_location<BlockT::kN>(
block_char_p, object_id);
for (int i = 0; i < FieldType::kN; ++i) {
// Rewrite value at address.
allocator->template maybe_rewrite_pointer<
DefragT, NumRecords, ScanClassT, ArrayBaseT>(&array[i]);
}
}
};
// Do not scan this array.
template<int Dummy2>
struct FieldSelector<false, Dummy2> {
template<typename BlockT>
__DEV__ static void call(AllocatorT* allocator,
BlockT* block, ObjectIndexT object_id) {}
};
template<typename... Args>
__DEV__ static void call(Args&&... args) {
// Rewrite base type is a super class (or exact class)
// of DefragT.
FieldSelector<kSelected, 0>::call(std::forward<Args>(args)...);
}
};
// Do not scan this field.
template<int Dummy>
struct FieldSelector<false, Dummy> {
template<typename BlockT>
__DEV__ static void call(AllocatorT* allocator,
BlockT* block, ObjectIndexT object_id) {}
};
// Not an array.
template<int Dummy>
struct ArrayFieldSelector<false, Dummy> {
static const bool kSelected = false;
template<typename BlockT>
__DEV__ static void call(AllocatorT* allocator,
BlockT* block, ObjectIndexT object_id) {}
};
static const bool kFieldSelected =
std::is_pointer<FieldType>::value
&& std::is_base_of<typename std::remove_pointer<FieldType>::type,
DefragT>::value;
static const bool kArraySelected =
ArrayFieldSelector<is_device_array<FieldType>::value, 0>::kSelected;
static const bool kSelected = kFieldSelected || kArraySelected;
template<typename... Args>
__DEV__ bool operator()(Args&&... args) {
// Rewrite field if field type is a super class (or exact class)
// of DefragT.
FieldSelector<kFieldSelected, 0>::call(std::forward<Args>(args)...);
// For array types: Check base type.
ArrayFieldSelector<is_device_array<FieldType>::value, 0>
::call(std::forward<Args>(args)...);
return true; // Continue processing.
}
};
bool operator()(AllocatorT* allocator, bool first_iteration) {
static_assert(NumRecords <= kMaxDefragRecords,
"Too many defragmentation records requested.");
bool process_class = SoaClassHelper<ScanClassT>::template for_all<
FieldChecker, /*IterateBase=*/ true>();
if (process_class) {
// Initialized during first iteration.
static BlockIndexT num_soa_blocks;
if (first_iteration) {
// Initialize iteration: Perform scan operation on bitmap.
allocator->allocated_[kScanTypeIndex].scan();
auto* d_num_soa_blocks_ptr =
&allocator->allocated_[kScanTypeIndex]
.data_.scan_data.enumeration_result_size;
num_soa_blocks = copy_from_device(d_num_soa_blocks_ptr);
}
if (num_soa_blocks > 0) {
auto total_threads = num_soa_blocks * kScanBlockSize;
kernel_iterate_rewrite_objects<ThisClass>
<<<(total_threads + kCudaBlockSize - 1)/kCudaBlockSize,
kCudaBlockSize,
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
/* No shared memory */
0
#else
NumRecords*sizeof(DefragRecord<BlockBitmapT>)
#endif // OPTION_DEFRAG_FORWARDING_POINTER
>>>(allocator);
gpuErrchk(cudaDeviceSynchronize());
}
}
return true; // Continue processing.
}
};
};
template<typename T>
struct SoaObjectCopier {
// Copies a single field value from one block to another one.
template<typename SoaFieldHelperT>
struct ObjectCopyHelper {
using SoaFieldType = SoaField<typename SoaFieldHelperT::OwnerClass,
SoaFieldHelperT::kIndex>;
__DEV__ bool operator()(char* source_block_base, char* target_block_base,
ObjectIndexT source_slot, ObjectIndexT target_slot) {
assert(source_slot < BlockHelper<T>::kSize);
assert(target_slot < BlockHelper<T>::kSize);
// TODO: Optimize copy routine for single value. Should not use the
// assignment operator here.
typename SoaFieldHelperT::type* source_ptr =
SoaFieldType::template data_ptr_from_location<BlockHelper<T>::kSize>(
source_block_base, source_slot);
typename SoaFieldHelperT::type* target_ptr =
SoaFieldType::template data_ptr_from_location<BlockHelper<T>::kSize>(
target_block_base, target_slot);
*target_ptr = *source_ptr;
#ifndef NDEBUG
// Reset value for debugging purposes.
memset(source_ptr, 0, sizeof(typename SoaFieldHelperT::type));
#endif // NDEBUG
return true; // Continue processing.
}
};
};
};
// Select a source block for fragmentation. Will not bring the number of
// defragmentation candidates under min_remaining_records.
template<BlockIndexT N_Objects, class... Types>
template<typename T, int NumRecords>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_choose_source_block(
int min_remaining_records) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
for (; tid < NumRecords; tid += blockDim.x * gridDim.x) {
auto bid = kInvalidBlockIndex;
// Assuming 64-bit bitmaps.
for (auto bit = tid; bit < kN; bit += NumRecords) {
auto container = leq_50_[BlockHelper<T>::kIndex].get_container(bit/64);
if (container & (1ULL << (bit % 64))) {
assert(leq_50_[BlockHelper<T>::kIndex][bit]);
bid = bit;
assert(block_idx_hash<NumRecords>(bid) == tid);
break;
}
}
defrag_records_.source_block_idx[tid] = bid;
if (bid != kInvalidBlockIndex) {
// This block would be suitable. Check if we still need more blocks
if (atomicSub(&num_leq_50_[BlockHelper<T>::kIndex], 1)
> min_remaining_records) {
defrag_records_.source_bitmap[tid] =
~get_block<T>(bid)->free_bitmap
& BlockHelper<T>::BlockType::kBitmapInitState;
// Remove from leq_50 to avoid block from being selected as target.
ASSERT_SUCCESS(leq_50_[BlockHelper<T>::kIndex].deallocate<true>(bid));
} else {
atomicAdd(&num_leq_50_[BlockHelper<T>::kIndex], 1);
defrag_records_.source_block_idx[tid] = kInvalidBlockIndex;
break;
}
}
}
// We got enough blocks. Fill up the rest with invalid markers.
for (tid += blockDim.x * gridDim.x; tid < NumRecords;
tid += blockDim.x * gridDim.x) {
defrag_records_.source_block_idx[tid] = kInvalidBlockIndex;
}
}
// TODO: Allow a block to be a target multiple times.
template<BlockIndexT N_Objects, class... Types>
template<typename T, int NumRecords>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_choose_target_blocks() {
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < NumRecords; tid += blockDim.x * gridDim.x) {
if (defrag_records_.source_block_idx[tid] != kInvalidBlockIndex) {
int remaining_slots = __popcll(defrag_records_.source_bitmap[tid]);
// Find target blocks.
for (int i = 0; i < kDefragFactor; ++i) {
// Note: May have to turn on these bits again later.
// But not for now, since block should not be chosen again.
auto bid = leq_50_[BlockHelper<T>::kIndex].deallocate_seed(tid + i);
defrag_records_.target_block_idx[i][tid] = bid;
const auto target_bitmap = get_block<T>(bid)->free_bitmap;
defrag_records_.target_bitmap[i][tid] = target_bitmap;
remaining_slots -= __popcll(target_bitmap);
if (remaining_slots <= 0) break;
}
assert(remaining_slots <= 0);
}
}
}
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
template<BlockIndexT N_Objects, class... Types>
template<typename T>
__DEV__ BlockIndexT SoaAllocator<N_Objects, Types...>::get_num_defrag_compactions() {
// Note: scan_num_bits() is different from num_leq_50 here! The latter one
// was already decreased.
return (leq_50_[BlockHelper<T>::kIndex].scan_num_bits() - kMinDefragRetainBlocks)
/ (kDefragFactor + 1);
}
template<BlockIndexT N_Objects, class... Types>
template<typename T>
__DEV__ BlockIndexT SoaAllocator<N_Objects, Types...>::get_defrag_candidate_index(
int did, int idx) {
assert(idx < get_num_defrag_compactions<T>());
const auto num_blocks = get_num_defrag_compactions<T>();
return leq_50_[BlockHelper<T>::kIndex].scan_get_index(did*num_blocks + idx);
}
template<BlockIndexT N_Objects, class... Types>
template<typename T>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_clear_source_leq_50() {
const int num_compactions = get_num_defrag_compactions<T>();
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < num_compactions; tid += blockDim.x * gridDim.x) {
ASSERT_SUCCESS(leq_50_[BlockHelper<T>::kIndex].deallocate<true>(
get_defrag_candidate_index<T>(0, tid)));
atomicSub(&num_leq_50_[BlockHelper<T>::kIndex], 1);
}
}
template<BlockIndexT N_Objects, class... Types>
template<typename T>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_move() {
// Use 64 threads per SOA block.
assert(blockDim.x % 64 == 0);
const int num_compactions = get_num_defrag_compactions<T>();
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < 64 * num_compactions; tid += blockDim.x * gridDim.x) {
const int source_pos = tid % 64;
const int record_id = tid / 64;
const auto source_block_idx = get_defrag_candidate_index<T>(0, record_id);
BlockBitmapT source_bitmap =
~get_block<T>(source_block_idx)->free_bitmap
& BlockHelper<T>::BlockType::kBitmapInitState;
// This thread should move the source_pos-th object (if it exists).
if (source_pos < __popcll(source_bitmap)) {
// Determine positition in source bitmap: Find index of source_pos-th set bit.
for (int i = 0; i < source_pos; ++i) {
source_bitmap &= source_bitmap - 1;
}
int source_object_id = __ffsll(source_bitmap) - 1;
assert(source_object_id >= 0);
// Determine target block and target position.
int target_pos = source_pos;
auto target_block_idx = kInvalidBlockIndex;
BlockBitmapT target_bitmap;
for (int i = 0; i < kDefragFactor; ++i) {
target_block_idx = get_defrag_candidate_index<T>(i + 1, record_id);
target_bitmap = get_block<T>(target_block_idx)->free_bitmap;
const auto num_slots = __popcll(target_bitmap);
if (target_pos < num_slots) {
// This object goes in here.
break;
} else {
target_pos -= num_slots;
}
}
assert(target_block_idx != kInvalidBlockIndex);
// Determine target object ID: Find index of target_pos-th set bit.
for (int i = 0; i < target_pos; ++i) {
target_bitmap &= target_bitmap - 1;
}
int target_object_id = __ffsll(target_bitmap) - 1;
assert(target_object_id >= 0);
auto* source_block = get_block<T>(source_block_idx);
auto* target_block = get_block<T>(target_block_idx);
SoaClassHelper<T>::template dev_for_all<AllocatorWrapperDefrag<ThisAllocator>
::template SoaObjectCopier<T>::ObjectCopyHelper, true>(
reinterpret_cast<char*>(source_block),
reinterpret_cast<char*>(target_block),
source_object_id, target_object_id);
}
}
}
#else
template<BlockIndexT N_Objects, class... Types>
template<typename T, int NumRecords>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_move() {
// Use 64 threads per SOA block.
assert(blockDim.x % 64 == 0);
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < 64 * NumRecords; tid += blockDim.x * gridDim.x) {
const int source_pos = tid % 64;
const int record_id = tid / 64;
const auto source_block_idx = defrag_records_.source_block_idx[record_id];
if (source_block_idx != kInvalidBlockIndex) {
BlockBitmapT source_bitmap = defrag_records_.source_bitmap[record_id];
// This thread should move the source_pos-th object (if it exists).
if (source_pos < __popcll(source_bitmap)) {
// Determine positition in source bitmap: Find index of source_pos-th set bit.
for (int i = 0; i < source_pos; ++i) {
source_bitmap &= source_bitmap - 1;
}
int source_object_id = __ffsll(source_bitmap) - 1;
assert(source_object_id >= 0);
// Determine target block and target position.
int target_pos = source_pos;
auto target_block_idx = kInvalidBlockIndex;
BlockBitmapT target_bitmap;
for (int i = 0; i < kDefragFactor; ++i) {
target_bitmap = defrag_records_.target_bitmap[i][record_id];
const auto num_slots = __popcll(target_bitmap);
if (target_pos < num_slots) {
// This object goes in here.
target_block_idx = defrag_records_.target_block_idx[i][record_id];
break;
} else {
target_pos -= num_slots;
}
}
assert(target_block_idx != kInvalidBlockIndex);
// Determine target object ID: Find index of target_pos-th set bit.
for (int i = 0; i < target_pos; ++i) {
target_bitmap &= target_bitmap - 1;
}
int target_object_id = __ffsll(target_bitmap) - 1;
assert(target_object_id >= 0);
auto* source_block = get_block<T>(source_block_idx);
auto* target_block = get_block<T>(target_block_idx);
SoaClassHelper<T>::template dev_for_all<AllocatorWrapperDefrag<ThisAllocator>
::template SoaObjectCopier<T>::ObjectCopyHelper, true>(
reinterpret_cast<char*>(source_block),
reinterpret_cast<char*>(target_block),
source_object_id, target_object_id);
}
}
}
}
#endif // OPTION_DEFRAG_FORWARDING_POINTER
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
// TODO: Remove code duplication.
template<BlockIndexT N_Objects, class... Types>
template<typename T>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_store_forwarding_ptr() {
// Use 64 threads per SOA block.
assert(blockDim.x % 64 == 0);
const int num_compactions = get_num_defrag_compactions<T>();
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < 64 * num_compactions; tid += blockDim.x * gridDim.x) {
const int source_pos = tid % 64;
const int record_id = tid / 64;
const auto source_block_idx = get_defrag_candidate_index<T>(0, record_id);
BlockBitmapT source_bitmap =
~get_block<T>(source_block_idx)->free_bitmap
& BlockHelper<T>::BlockType::kBitmapInitState;
// This thread should move the source_pos-th object (if it exists).
if (source_pos < __popcll(source_bitmap)) {
// Determine positition in source bitmap: Find index of source_pos-th set bit.
for (int i = 0; i < source_pos; ++i) {
source_bitmap &= source_bitmap - 1;
}
int source_object_id = __ffsll(source_bitmap) - 1;
assert(source_object_id >= 0);
// Determine target block and target position.
int target_pos = source_pos;
auto target_block_idx = kInvalidBlockIndex;
BlockBitmapT target_bitmap;
for (int i = 0; i < kDefragFactor; ++i) {
target_block_idx = get_defrag_candidate_index<T>(i + 1, record_id);
target_bitmap = get_block<T>(target_block_idx)->free_bitmap;
const auto num_slots = __popcll(target_bitmap);
if (target_pos < num_slots) {
// This object goes in here.
break;
} else {
target_pos -= num_slots;
}
}
assert(target_block_idx != kInvalidBlockIndex);
// Determine target object ID: Find index of target_pos-th set bit.
for (int i = 0; i < target_pos; ++i) {
target_bitmap &= target_bitmap - 1;
}
int target_object_id = __ffsll(target_bitmap) - 1;
assert(target_object_id >= 0);
auto* source_block = get_block<T>(source_block_idx);
auto* target_block = get_block<T>(target_block_idx);
// Store forwarding pointer.
auto* target_obj_ptr = target_block->make_pointer(target_object_id);
assert(target_obj_ptr->get_type() == BlockHelper<T>::kIndex);
assert(target_obj_ptr->get_type() == source_block->get_type());
source_block->set_forwarding_pointer(source_object_id, target_obj_ptr);
}
}
}
#endif // OPTION_DEFRAG_FORWARDING_POINTER
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
template<BlockIndexT N_Objects, class... Types>
template<typename T>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_update_block_state() {
const int num_compactions = get_num_defrag_compactions<T>();
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < num_compactions; tid += blockDim.x * gridDim.x) {
const auto source_block_idx = get_defrag_candidate_index<T>(0, tid);
BlockBitmapT source_bitmap =
~get_block<T>(source_block_idx)->free_bitmap
& BlockHelper<T>::BlockType::kBitmapInitState;
// Delete source block.
// Invalidate block.
get_block<T>(source_block_idx)->free_bitmap = 0ULL;
// Precond.: Block is active and allocated. Block was already
// removed from leq_50_ above.
deallocate_block<T>(source_block_idx, /*dealloc_leq_50=*/ false);
// Update state of target blocks.
int remaining_objs = __popcll(source_bitmap);
for (int i = 0; i < kDefragFactor; ++i) {
const auto target_block_idx = get_defrag_candidate_index<T>(i + 1, tid);
auto target_bitmap = get_block<T>(target_block_idx)->free_bitmap;
const auto num_target_slots = __popcll(target_bitmap);
if (num_target_slots <= remaining_objs) {
// This target block is now full.
ASSERT_SUCCESS(active_[BlockHelper<T>::kIndex].deallocate<true>(target_block_idx));
ASSERT_SUCCESS(leq_50_[BlockHelper<T>::kIndex].deallocate<true>(target_block_idx));
atomicSub(&num_leq_50_[BlockHelper<T>::kIndex], 1);
get_block<T>(target_block_idx)->free_bitmap = 0ULL;
// leq_50 is already cleared.
} else {
// Check leq_50 status of target block.
int num_target_after = BlockHelper<T>::kSize - num_target_slots + remaining_objs;
if (num_target_after <= BlockHelper<T>::kLeq50Threshold) {
// This block is still leq_50.
} else {
ASSERT_SUCCESS(leq_50_[BlockHelper<T>::kIndex].deallocate<true>(target_block_idx));
atomicSub(&num_leq_50_[BlockHelper<T>::kIndex], 1);
}
// Clear now allocated bits.
for (int j = 0; j < remaining_objs; ++j) {
target_bitmap &= target_bitmap - 1;
}
get_block<T>(target_block_idx)->free_bitmap = target_bitmap;
}
remaining_objs -= num_target_slots;
if (remaining_objs <= 0) {
// This is the last target block.
break;
}
}
assert(remaining_objs <= 0);
}
}
#else
template<BlockIndexT N_Objects, class... Types>
template<typename T, int NumRecords>
__DEV__ void SoaAllocator<N_Objects, Types...>::defrag_update_block_state() {
for (int tid = threadIdx.x + blockIdx.x * blockDim.x;
tid < NumRecords; tid += blockDim.x * gridDim.x) {
if (defrag_records_.source_block_idx[tid] != kInvalidBlockIndex) {
// Delete source block.
// Invalidate block.
get_block<T>(defrag_records_.source_block_idx[tid])->free_bitmap = 0ULL;
// Precond.: Block is active and allocated. Block was already
// removed from leq_50_ above.
deallocate_block<T>(defrag_records_.source_block_idx[tid],
/*dealloc_leq_50=*/ false);
// Update state of target blocks.
int remaining_objs = __popcll(defrag_records_.source_bitmap[tid]);
for (int i = 0; i < kDefragFactor; ++i) {
auto target_bitmap = defrag_records_.target_bitmap[i][tid];
const auto target_block_idx = defrag_records_.target_block_idx[i][tid];
const auto num_target_slots = __popcll(target_bitmap);
if (num_target_slots <= remaining_objs) {
// This target block is now full.
ASSERT_SUCCESS(active_[BlockHelper<T>::kIndex].deallocate<true>(target_block_idx));
atomicSub(&num_leq_50_[BlockHelper<T>::kIndex], 1);
get_block<T>(target_block_idx)->free_bitmap = 0ULL;
// leq_50 is already cleared.
} else {
// Check leq_50 status of target block.
int num_target_after = BlockHelper<T>::kSize - num_target_slots + remaining_objs;
if (num_target_after <= BlockHelper<T>::kLeq50Threshold) {
// This block is still leq_50.
ASSERT_SUCCESS(leq_50_[BlockHelper<T>::kIndex].allocate<true>(target_block_idx));
} else {
atomicSub(&num_leq_50_[BlockHelper<T>::kIndex], 1);
}
// Clear now allocated bits.
for (int j = 0; j < remaining_objs; ++j) {
target_bitmap &= target_bitmap - 1;
}
get_block<T>(target_block_idx)->free_bitmap = target_bitmap;
}
remaining_objs -= num_target_slots;
if (remaining_objs <= 0) {
// This is the last target block.
break;
}
}
assert(remaining_objs <= 0);
}
}
}
#endif // OPTION_DEFRAG_FORWARDING_POINTER
template<BlockIndexT N_Objects, class... Types>
template<int NumRecords>
__DEV__ void SoaAllocator<N_Objects, Types...>
::load_records_to_shared_mem() {
extern __shared__ DefragRecord<BlockBitmapT> records[];
// Every block loads records into shared memory.
for (int i = threadIdx.x; i < NumRecords; i += blockDim.x) {
records[i].copy_from(defrag_records_, i);
}
__syncthreads();
}
// For benchmarks: Measure time spent outside of parallel sections.
// Measure time in microseconds because numbers are small.
long unsigned int bench_init_leq_time = 0;
long unsigned int bench_defrag_move_time = 0;
long unsigned int bench_rewrite_time = 0;
long unsigned int bench_total_defrag_time = 0;
long unsigned int bench_num_passes = 0;
// Should be invoked from host side. Perform defragmentation only if there are
// enough blocks so that at least min_num_compactions many defragmentation
// candidates can be elimated. (Not taking into account collisions.)
template<BlockIndexT N_Objects, class... Types>
template<typename T, int NumRecords>
void SoaAllocator<N_Objects, Types...>::parallel_defrag(int min_num_compactions) {
static_assert(NumRecords <= kMaxDefragRecords, "Too many records requested.");
assert(min_num_compactions >= 1);
auto time_0 = std::chrono::system_clock::now();
// Determine number of records.
auto num_leq_blocks =
copy_from_device(&num_leq_50_[BlockHelper<T>::kIndex]);
for (bool first_iteration = true; ; first_iteration = false) {
#ifdef OPTION_DEFRAG_BENCH
printf("%i, %f\n", (int) num_leq_blocks, DBG_host_calculate_fragmentation());
#endif // OPTION_DEFRAG_BENCH
// E.g.: n = 3: Retain 3/4 = 75% of blocks. Round up.
const int max_num_source_blocks =
(num_leq_blocks - kMinDefragRetainBlocks) / (kDefragFactor + 1);
if (max_num_source_blocks <= min_num_compactions) break;
++bench_num_passes;
auto time_1 = std::chrono::system_clock::now();
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
leq_50_[BlockHelper<T>::kIndex].scan();
#else
const int min_remaining_records = num_leq_blocks - max_num_source_blocks;
assert(min_remaining_records >= (num_leq_blocks - min_remaining_records)
* kDefragFactor);
#ifndef NDEBUG
printf("[DEFRAG] min_remaining: %i / %i\n",
(int) min_remaining_records, (int) num_leq_blocks);
#endif // NDEBUG
// TODO: Assign one warp per defrag record.
// Step 1: Choose source blocks.
member_func_kernel<
ThisAllocator, int,
&ThisAllocator::template defrag_choose_source_block<T, NumRecords>>
<<<512, (NumRecords + 512 - 1) / 512>>>(this, min_remaining_records);
gpuErrchk(cudaDeviceSynchronize());
// Step 2: Choose target blocks.
member_func_kernel<
ThisAllocator,
&ThisAllocator::defrag_choose_target_blocks<T, NumRecords>>
<<<512, (NumRecords + 512 - 1) / 512>>>(this);
gpuErrchk(cudaDeviceSynchronize());
#endif // OPTION_DEFRAG_FORWARDING_POINTER
auto time_2 = std::chrono::system_clock::now();
bench_init_leq_time += std::chrono::duration_cast<std::chrono::microseconds>(
time_2 - time_1).count();
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
// Move objects. 64 threads per block.
const int num_move_threads = 64*max_num_source_blocks;
#else
const int num_move_threads = 64*NumRecords;
#endif // OPTION_DEFRAG_FORWARDING_POINTER
member_func_kernel<
ThisAllocator,
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
&ThisAllocator::defrag_move<T>>
#else
&ThisAllocator::defrag_move<T, NumRecords>>
#endif // OPTION_DEFRAG_FORWARDING_POINTER
<<<(num_move_threads + 256 - 1) / 256, 256>>>(this);
gpuErrchk(cudaDeviceSynchronize());
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
member_func_kernel<
ThisAllocator,
&ThisAllocator::defrag_store_forwarding_ptr<T>>
<<<(num_move_threads + 256 - 1) / 256, 256>>>(this);
gpuErrchk(cudaDeviceSynchronize());
#endif // OPTION_DEFRAG_FORWARDING_POINTER
// Update block states.
member_func_kernel<
ThisAllocator,
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
&ThisAllocator::defrag_update_block_state<T>>
<<<512, (max_num_source_blocks + 512 - 1) / 512>>>(this);
#else
&ThisAllocator::defrag_update_block_state<T, NumRecords>>
<<<512, (NumRecords + 512 - 1) / 512>>>(this);
#endif // OPTION_DEFRAG_FORWARDING_POINTER
gpuErrchk(cudaDeviceSynchronize());
auto time_3 = std::chrono::system_clock::now();
bench_defrag_move_time += std::chrono::duration_cast<std::chrono::microseconds>(
time_3 - time_2).count();
// Scan and rewrite pointers.
TupleHelper<Types...>
::template for_all<AllocatorWrapperDefrag<ThisAllocator>
::template SoaPointerUpdater<T, NumRecords>
::template ClassIterator>(this, first_iteration);
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
// Clear leq_50 of source blocks.
member_func_kernel<
ThisAllocator,
&ThisAllocator::template defrag_clear_source_leq_50<T>>
<<<512, (max_num_source_blocks + 512 - 1) / 512>>>(this);
gpuErrchk(cudaDeviceSynchronize());
#endif // OPTION_DEFRAG_FORWARDING_POINTER
auto time_4 = std::chrono::system_clock::now();
bench_rewrite_time += std::chrono::duration_cast<std::chrono::microseconds>(
time_4 - time_3).count();
// Determine new number of defragmentation candidates.
#ifndef NDEBUG
auto num_leq_blocks_before = num_leq_blocks;
#endif // NDEBUG
num_leq_blocks = copy_from_device(&num_leq_50_[BlockHelper<T>::kIndex]);
#ifndef NDEBUG
printf("[DEFRAG] Completed pass<%i> [%s]: %i --> %i (%i)\n",
NumRecords, typeid(T).name(),
num_leq_blocks_before, num_leq_blocks, num_leq_blocks_before - num_leq_blocks);
#endif // NDEBUG
}
auto time_5 = std::chrono::system_clock::now();
bench_total_defrag_time += std::chrono::duration_cast<std::chrono::microseconds>(
time_5 - time_0).count();
}
template<BlockIndexT N_Objects, class... Types>
template<typename T>
void SoaAllocator<N_Objects, Types...>::parallel_defrag(int min_num_compactions) {
this->template parallel_defrag<T, kMaxDefragRecords>(min_num_compactions);
}
template<BlockIndexT N_Objects, class... Types>
void SoaAllocator<N_Objects, Types...>::DBG_print_defrag_time() {
printf("%lu, %lu, %lu, %lu\n",
bench_init_leq_time / 1000,
bench_defrag_move_time / 1000,
bench_rewrite_time / 1000,
bench_total_defrag_time / 1000);
}
template<BlockIndexT N_Objects, class... Types>
template<typename DefragT, int NumRecords, typename ScanClassT,
typename FieldT>
__DEV__ void SoaAllocator<N_Objects, Types...>::maybe_rewrite_pointer(
FieldT* scan_location) {
#ifndef OPTION_DEFRAG_FORWARDING_POINTER
extern __shared__ DefragRecord<BlockBitmapT> records[];
#endif // OPTION_DEFRAG_FORWARDING_POINTER
assert(reinterpret_cast<char*>(scan_location) >= data_
&& reinterpret_cast<char*>(scan_location) < data_ + kDataBufferSize);
FieldT scan_value = *scan_location;
if (scan_value == nullptr) return;
// Check if value points to an object of type DefragT.
if (scan_value->get_type() != BlockHelper<DefragT>::kIndex) return;
// Calculate block index of scan_value.
char* block_base =
PointerHelper::block_base_from_obj_ptr(scan_value);
assert(block_base >= data_ && block_base < data_ + kDataBufferSize);
assert((block_base - data_) % kBlockSizeBytes == 0);
// Get block index of scan value.
auto scan_block_idx = (block_base - data_) / kBlockSizeBytes;
assert(scan_block_idx < N);
#ifdef OPTION_DEFRAG_FORWARDING_POINTER
if (leq_50_[BlockHelper<DefragT>::kIndex][scan_block_idx]
&& scan_block_idx <= get_defrag_candidate_index<DefragT>(
0, get_num_defrag_compactions<DefragT>() - 1)) {
// Rewrite this pointer.
auto* source_block = reinterpret_cast<
typename BlockHelper<DefragT>::BlockType*>(block_base);
auto src_obj_id = PointerHelper::obj_id_from_obj_ptr(scan_value);
bool valid_pointer = (source_block->allocation_bitmap() & (1ULL << src_obj_id)) != 0;
if (valid_pointer) {
auto* forwarding_ptr = reinterpret_cast<FieldT>(
source_block->get_forwarding_pointer(src_obj_id));
assert(forwarding_ptr->get_type() == scan_value->get_type());
*scan_location = forwarding_ptr;
}
}
#else
// Look for defrag record for this block.
const auto record_id = block_idx_hash<NumRecords>(scan_block_idx);
assert(record_id < NumRecords);
const auto& record = records[record_id];
if (record.source_block_idx == scan_block_idx) {
// This pointer must be rewritten.
auto src_obj_id = PointerHelper::obj_id_from_obj_ptr(scan_value);
// ... but this pointer could contain garbage data.
// In that case, we do not want need to rewrite.
#ifdef OPTION_DEFRAG_USE_GLOBAL
bool valid_pointer =
defrag_records_.source_bitmap[record_id] & (1ULL << src_obj_id);
#else
bool valid_pointer = record.source_bitmap & (1ULL << src_obj_id);
#endif // OPTION_DEFRAG_USE_GLOBAL
if (!valid_pointer) return;
// First src_obj_id bits are set to 1.
BlockBitmapT cnt_mask = src_obj_id ==
63 ? (~0ULL) : ((1ULL << (src_obj_id + 1)) - 1);
assert(__popcll(cnt_mask) == src_obj_id + 1);
#ifdef OPTION_DEFRAG_USE_GLOBAL
int src_bit_idx =
__popcll(cnt_mask & defrag_records_.source_bitmap[record_id]) - 1;
#else
int src_bit_idx = __popcll(cnt_mask & record.source_bitmap) - 1;
#endif // OPTION_DEFRAG_USE_GLOBAL
// Find correct target block and bit in target bitmaps.
BlockBitmapT target_bitmap;
auto target_block_idx = kInvalidBlockIndex;
for (int i = 0; i < kDefragFactor; ++i) {
#ifdef OPTION_DEFRAG_USE_GLOBAL
target_bitmap = defrag_records_.target_bitmap[i][record_id];
#else
target_bitmap = record.target_bitmap[i];
#endif // OPTION_DEFRAG_USE_GLOBAL
if (__popcll(target_bitmap) > src_bit_idx) {
// Target block found.
#ifdef OPTION_DEFRAG_USE_GLOBAL
target_block_idx = defrag_records_.target_block_idx[i][record_id];
#else
target_block_idx = record.target_block_idx[i];
#endif // OPTION_DEFRAG_USE_GLOBAL
break;
} else {
src_bit_idx -= __popcll(target_bitmap);
}
}
// Assert that target block was found.
assert(target_block_idx < N);
// Find src_bit_idx-th bit in target bitmap.
for (int j = 0; j < src_bit_idx; ++j) {
target_bitmap &= target_bitmap - 1;
}
int target_obj_id = __ffsll(target_bitmap) - 1;
assert(target_obj_id < BlockHelper<DefragT>::kSize);
assert(target_obj_id >= 0);
assert((get_block<DefragT>(target_block_idx)->free_bitmap
& (1ULL << target_obj_id)) == 0);
// Rewrite pointer.
auto* target_block = get_block<
typename std::remove_pointer<FieldT>::type>(target_block_idx);
*scan_location = PointerHelper::rewrite_pointer(
scan_value, target_block, target_obj_id);
#ifndef NDEBUG
// Sanity checks.
assert(PointerHelper::block_base_from_obj_ptr(*scan_location)
== reinterpret_cast<char*>(target_block));
assert((*scan_location)->get_type()
== BlockHelper<DefragT>::kIndex);
auto* loc_block = reinterpret_cast<typename BlockHelper<DefragT>::BlockType*>(
PointerHelper::block_base_from_obj_ptr(*scan_location));
assert(loc_block->type_id == BlockHelper<DefragT>::kIndex);
assert((loc_block->free_bitmap & (1ULL << target_obj_id)) == 0);
#endif // NDEBUG
}
#endif // OPTION_DEFRAG_FORWARDING_POINTER
}
| true |
b63f0c7c8c835717b73e2e93b783884bf0693f57 | C++ | ShreyaTarwey/OOM-Project | /display_students.cpp | UTF-8 | 2,745 | 3.515625 | 4 | [] | no_license | #include"main.hpp"
//using namespace comp;
void display(student s){
cout << "Name: " << s.get_name() << endl;
date a = s.getDOB(), b=s.getDOJ();
cout << "Year of study: " << s.get_year() << endl;
cout << "DOB: "<<a.day<<"/"<<a.month<<"/"<<a.year<<endl;
cout << "DOJ: "<<b.day<<"/"<<b.month<<"/"<<b.year<<endl;
cout << "Enrollment: " << s.get_enrollment() << endl;
cout << "Grade: " << s.get_grade() << endl;
auto opt = s.get_opt();
cout << "Phone Number: " << opt.phone_number << endl;
cout << "Blood Group: " << opt.blood_group << endl;
cout << "Address: "<<opt.address << endl << endl << endl;
}
void displayAll(vector<student>& v, string mode = ""){
if(mode == "DOB_ASC") DOB_sort(v);
else if(mode == "DOB_DSC") DOBrev_sort(v);
else if(mode == "NAME_ASC") alpha_sort(v);
else if(mode == "NAME_DSC") alpharev_sort(v);
else if(mode == "DOJ_ASC") DOJ_sort(v);
else if(mode == "DOJ_DSC") DOJrev_sort(v);
else if(mode == "ENROLL_ASC") enroll_sort(v);
else if(mode == "ENROLL_DSC") enrollrev_sort(v);
else return void(cout << "Invalid Input.\n");
for(student s:v){
display(s);
}
}
void interface(){
string mode;
auto s_list = d.get_student_list();
cout << "How would you like to arrange the student list?\n";
cout << "Kindly give input in the format A_B, where: \n";
cout <<"A can be : DOB, NAME, DOJ, ENROLL. \n";
cout <<"B can be : ASC (Ascending Order) or DSC (Descending Order).\n\n";
cout << "Your Input: ";
cin >> mode;
cout << endl;
if(mode == "YEAR"){
int year;
cout << "Enter year: ";
cin >> year;
showBy(s_list,year);
}
else if(mode == "RANGE_DOB"){
date from, to;
cout << "Enter dates from and to: ";
cin >> from.day >> from.month >> from.year;
cin >> to.day >> to.month >> to.year;
showBy(s_list, "DOB", from, to);
}
else if(mode == "RANGE_DOJ"){
date from, to;
cout << "Enter dates from and to: ";
cin >> from.day >> from.month >> from.year;
cin >> to.day >> to.month >> to.year;
showBy(s_list, "DOJ", from, to);
}
else displayAll(s_list, mode);
}
void showBy(vector<student>& v, string type, date a, date b){
if(type == "DOB") {
DOB_sort(v);
for(auto st:v){
if(a <= st.getDOB() and st.getDOB() <= b) display(st);
}
}
else if(type == "DOJ"){
DOJ_sort(v);
for(auto st:v){
if(a <= st.getDOJ() and st.getDOJ() <= b) display(st);
}
}
}
void showBy(vector<student> &v, int year){
alpha_sort(v);
for(auto st:v){
if(st.get_year() == year) display(st);
}
} | true |
d4eaee52bdb08ae432c0a299a7edf5df219476a4 | C++ | OscarFredriksson/DT064G | /Labb2/sorts.h | UTF-8 | 2,732 | 3.578125 | 4 | [] | no_license | #include <algorithm>
int& find_min(int* begin, int* end)
{
int* min = begin;
while(begin++ != end)
{
if(*begin < *min) min = begin;
}
return *min;
}
void selection_sort(int* begin, int* end)
{
std::for_each(begin, end, [&end](int& iter)
{
int& min = find_min(&iter, end);
std::swap(iter, min);
});
}
void insertion_sort(int* begin, int* end)
{
for(int* i = begin; i != end + 1; i++)
{
for(int* j = i; j != begin && *(j - 1) > *j; j--)
{
std::swap(*j, *(j - 1));
}
}
}
int* partition(int* begin, int* end, int pivot = -1)
{
if(pivot == -1) pivot = *end;
int* i = begin;
for(int* j = begin; j != end; j++)
{
if(*j < pivot)
{
i++;
std::swap(*i, *j);
}
}
std::swap(*i, *end);
return i;
}
int medianOfThree(int* begin, int* end)
{
int* mid = begin + (end - begin) /2;
if(*end < *begin) std::swap(*end, *begin);
if(*mid < *begin) std::swap(*mid, *begin);
if(*end < *mid) std::swap(*end, *mid);
return *end;
}
void partition_quick_sort(int* begin, int* end)
{
if(begin >= end) return;
auto pivot = partition(begin, end);
partition_quick_sort(begin, pivot - 1);
partition_quick_sort(pivot + 1, end);
}
void median_quick_sort(int* begin, int* end)
{
if(begin >= end) return;
auto pivot = partition(begin, end, medianOfThree(begin, end));
median_quick_sort(begin, pivot - 1);
median_quick_sort(pivot + 1, end);
}
struct Median_Quick_Sort
{
void operator()(int* begin, int* end)
{
median_quick_sort(begin, end);
}
const std::string path = "benchmarks/median_quick_sort/";
const std::string name = "Median quick sort";
};
struct Partition_Quick_Sort
{
void operator()(int* begin, int* end)
{
partition_quick_sort(begin, end);
}
const std::string path = "benchmarks/partition_quick_sort/";
const std::string name = "Partition quick sort";
};
struct Insertion_Sort
{
void operator()(int* begin, int* end)
{
insertion_sort(begin, end);
}
const std::string path = "benchmarks/insertion_sort/";
const std::string name = "Insertion sort";
};
struct Selection_Sort
{
void operator()(int* begin, int* end)
{
selection_sort(begin, end);
}
const std::string path = "benchmarks/selection_sort/";
const std::string name = "Selection sort";
};
struct Std_Sort
{
void operator()(int* begin, int* end)
{
std::sort(begin, end);
}
const std::string path = "benchmarks/std_sort/";
const std::string name = "std::sort";
}; | true |
1853012f4ad56ad58a092db8824ed7674fc17f63 | C++ | olitvinenko/sound-engine | /common/impl/openal/OalUtils.hpp | UTF-8 | 2,259 | 2.5625 | 3 | [] | no_license | #pragma once
#ifdef SOUND_OPENAL
#include <OpenAL/OpenAL.h>
#include <string>
#include <type_traits>
namespace details
{
bool check_al_errors(const std::string& filename, const std::uint_fast32_t line);
bool check_alc_errors(const std::string& filename, const std::uint_fast32_t line, ALCdevice* device);
}
template<typename T>
struct OpenALCallResult
{
T value;
bool isError;
OpenALCallResult(const T& v, bool error):value(v), isError(error)
{ }
operator T() const { return value; }
operator bool() const { return !isError; }
};
template<typename T>
constexpr ALCdevice* get_device(T arg)
{
if constexpr(std::is_same<T, ALCdevice*>::value)
{
return arg;
}
else
{
return nullptr;
}
}
template<typename T, typename ... Args>
constexpr ALCdevice* get_device(T arg, Args&& ... args)
{
if constexpr (std::is_same<T, ALCdevice*>::value)
return arg;
return get_device(args...);
}
template<typename alFunction, typename... Params>
auto alCallImpl(const char* filename,
const std::uint_fast32_t line,
alFunction function,
Params ... params)
->typename std::enable_if<!std::is_same<void,decltype(function(params...))>::value, OpenALCallResult<decltype(function(params...))>>::type
{
ALCdevice* device = get_device(params...);
using namespace details;
return OpenALCallResult<decltype(function(params...))>
{
function(std::forward<Params>(params)...),
device ? check_alc_errors(filename,line,device) : check_al_errors(filename,line)
};
}
template<typename alFunction, typename... Params>
auto alCallImpl(const char* filename,
const std::uint_fast32_t line,
alFunction function,
Params ... params)
->typename std::enable_if<std::is_same<void,decltype(function(params...))>::value, bool>::type
{
ALCdevice* device = get_device(params...);
using namespace details;
function(std::forward<Params>(params)...);
return device ? check_alc_errors(filename,line,device) : check_al_errors(filename,line);
}
#define alCall(function, ...) alCallImpl(__FILE__, __LINE__, function, __VA_ARGS__)
#endif
| true |
ba3a873f8a7b21f1cb59a165f2b4f331c2c5bb2c | C++ | yeahzdx/Leetcode | /模拟-Spiral Image.cpp | GB18030 | 1,944 | 3.171875 | 3 | [] | no_license | #include"stage2.h"
vector<int> spiralOrder(vector<vector<int> > &matrix){
vector<int> ret;
int m=matrix.size();//ﲻͬʱжmnm=0matrix[0]ڣʲ
if(m>0){
int n=matrix[0].size();
if(n>0){
for(int i=0;i<min(m,n)/2;++i){
for(int j=i;j<n-i-1;++j)
ret.push_back(matrix[i][j]);
for(int j=i;j<m-i-1;++j)
ret.push_back(matrix[j][n-i-1]);
for(int j=n-i-1;j>i;--j)// ҪעDzȥҪƽ
ret.push_back(matrix[m-i-1][j]);
for(int j=m-i-1;j>i;--j)
ret.push_back(matrix[j][i]);
}
int layer=min(m,n)/2;
if(min(m,n)%2==1){
if(m>n)//ҪԪʲô
for(int i=layer;i<=m-layer-1;++i)
ret.push_back(matrix[i][layer]);
else
for(int i=layer;i<=n-layer-1;++i)
ret.push_back(matrix[layer][i]);
}
}
}
return ret;
}
void spiralPrint(int m,int n){
if(m<=0 || n<=0)return;
int **ret=new int*[m];
for(int i=0;i<m;++i){
ret[i]=new int[n];
memset(ret[i],0,sizeof(int)*n);//memset÷עԲκvoid *memset(void *dest,char c,size_t count);
}
//memset(ret,0,sizeof(int)*m*n);
int cnt=1;
for(int layer=0;layer<min(m,n)/2;++layer){
for(int j=layer;j<n-layer-1;++j,++cnt)
ret[layer][j]=cnt;
for(int j=layer;j<m-1-layer;++j,++cnt)
ret[j][n-layer-1]=cnt;
for(int j=n-layer-1;j>layer;--j,++cnt)
ret[m-layer-1][j]=cnt;
for(int j=m-layer-1;j>layer;--j,++cnt)
ret[j][layer]=cnt;
}
int layer=min(m,n)/2;
if(1==min(m,n)%2){
if(m>n)
for(int i=layer;i<=m-layer-1;++i,++cnt)
ret[i][layer]=cnt;
else
for(int i=layer;i<=n-layer-1;++i,++cnt)
ret[layer][i]=cnt;
}
for(int i=0;i<m;++i){
for(int j=0;j<n;++j)
cout<<ret[i][j]<<'\t';
cout<<endl;
}
for(int i=0;i<m;++i)
delete [] ret[i];
delete [] ret;
}
| true |
5cb7d43663854b02f9ef78c8a71c8cd434d8a09c | C++ | jtcullen/compiler | /src/ast/statements/Continue.h | UTF-8 | 437 | 2.625 | 3 | [] | no_license | #ifndef COMPILER_CONTINUE_H
#define COMPILER_CONTINUE_H
#include <iostream>
#include "Statement.h"
#include "Expression.h"
#include "AssemblyProgram.h"
class Continue : public Statement
{
public:
Continue();
~Continue();
void print(std::ostream &os, int indent) const;
void generate(AssemblyProgram &ap) const;
friend std::ostream &operator<<(std::ostream &os, const Continue &ret);
};
#endif //COMPILER_CONTINUE_H | true |
17940b4fe00282e55b7e6b24162f5c25315107de | C++ | herob4u/Velocity | /Velocity/src/Engine/Renderer/Camera.h | UTF-8 | 2,499 | 2.703125 | 3 | [] | no_license | #pragma once
#include "Engine/Math/Rotator.h"
namespace Vct
{
class Camera
{
public:
static const float WORLD_Z_MAX;
struct Frustum
{
float FOV;
float Aspect;
float NearZ;
float FarZ;
Frustum()
: FOV(45.f)
, Aspect(16.f/9.f)
, NearZ(0.1f)
, FarZ(WORLD_Z_MAX)
{
}
Frustum(float fov, float aspect, float nearz, float farz)
: FOV(fov)
, Aspect(aspect)
, NearZ(nearz)
, FarZ(farz)
{
}
};
Camera(const Frustum& frustum = Frustum());
Camera(float fov, float aspect, float nearz = 0.001f, float farz = WORLD_Z_MAX);
void SetFOV(float fov);
void SetAspect(float aspect);
void SetNearZ(float nearz);
void SetFarZ(float farz);
void SetFrustum(const Frustum& frustum);
FORCEINLINE float GetFOV() const { return m_Frustum.FOV; }
FORCEINLINE float GetAspect() const { return m_Frustum.Aspect; }
FORCEINLINE float GetNearZ() const { return m_Frustum.NearZ; }
FORCEINLINE float GetFarZ() const { return m_Frustum.FarZ; }
FORCEINLINE const Frustum& GetFrustum() const { return m_Frustum;}
/* Updates the aspect the ratio to match the screen/window */
void NotifyScreenResized(int newWidth, int newHeight);
const glm::vec3& GetPosition() const { return m_Position; }
const Rotator& GetRotation() const { return m_Rotation; }
void SetPosition(const glm::vec3& pos);
void Offset(const glm::vec3& offset);
void SetRotation(const Rotator& rotation);
void AddRotation(const Rotator& rotation);
void LookAt(const glm::vec3 target);
const glm::mat4& GetViewProjection() const { return m_ViewProjection; }
const glm::mat4& GetView() const { return m_View; }
const glm::mat4& GetProjection() const { return m_Projection; }
protected:
void RecomputeProjection();
void RecomputeView();
void RecomputeViewProjection();
private:
Frustum m_Frustum;
Rotator m_Rotation;
glm::vec3 m_Position;
glm::mat4 m_Projection;
glm::mat4 m_View;
glm::mat4 m_ViewProjection;
};
} | true |
2c562e21be4e8664f9bc3c7f6589ed46a4d7c2a2 | C++ | MarioHsiao/bup-log-analizer | /filesystemmodel.cpp | UTF-8 | 4,069 | 2.75 | 3 | [] | no_license | #include "filesystemmodel.h"
#include <QDebug>
#include <QStorageInfo>
FileSystemModel::FileSystemModel(QObject *parent)
: QAbstractListModel(parent),
dir(QDir("/"))
{
updateDirInfo();
}
void FileSystemModel::updateDirInfo (void){
beginResetModel();
items.clear();
if(dir.isRoot()){
items.append(Item({cdItemName, "drives", Back}));
QFileInfoList currentDir = dir.entryInfoList(QStringList("*.log"),
QDir::NoDotAndDotDot | QDir::Dirs |
QDir::AllDirs | QDir::Files,
QDir::DirsFirst | QDir::Name);
for(int i = 0; i < currentDir.count(); i++){
items.append(Item({currentDir.at(i).fileName(),
currentDir.at(i).absoluteFilePath(),
currentDir.at(i).isFile() ? File : Dir}));
}
}
else {
QString currentPath = dir.absolutePath();
dir.cdUp();
items.append(Item({cdItemName, dir.absolutePath(), Back}));
dir.cd(currentPath);
QFileInfoList currentDir = dir.entryInfoList(QStringList("*.log"),
QDir::NoDotAndDotDot | QDir::Dirs |
QDir::AllDirs | QDir::Files,
QDir::DirsFirst | QDir::Name);
for(int i = 0; i < currentDir.count(); i++){
items.append(Item({currentDir.at(i).fileName(),
currentDir.at(i).absoluteFilePath(),
currentDir.at(i).isFile() ? File : Dir}));
}
}
endResetModel();
emit currentPathChanged(currentPath());
}
void FileSystemModel::updateDrivesInfo(void){ // This fills items list of drives names as normal files/folders
beginResetModel(); // but without "back" item
items.clear();
QFileInfoList drives = dir.drives();
for(int i = 0; i < drives.count(); i++){
QString driveName = QStorageInfo(drives.at(i).absoluteFilePath()).name();
driveName += " (" + drives.at(i).absoluteFilePath() + ")";
items.append(Item({driveName, drives.at(i).absoluteFilePath(), Drive}));
}
endResetModel();
emit currentPathChanged(currentPath());
}
QString FileSystemModel::currentPath(void) const{
return dir.absolutePath();
}
void FileSystemModel::setCurrentPath(QString){
}
int FileSystemModel::rowCount(const QModelIndex &parent) const{
Q_UNUSED(parent)
return items.count();
}
QHash<int, QByteArray> FileSystemModel::roleNames(void) const{
static QHash<int, QByteArray> roles = {
{NAME, "name"},
{DIR, "dir"},
{DIR_UP, "dir_up"},
{DRIVE, "drive"},
{FULL_PATH, "fullPath"}
};
return roles;
}
QVariant FileSystemModel::data(const QModelIndex &index, int role) const{
const int row = index.row();
if(items.count() < row)
return QVariant();
const auto& item = items.at(row);
switch (role) {
case NAME:
return item.name;
case DIR:
return (item.type == Dir ? true : false);
case DIR_UP:
return (item.type == Back ? true : false);
case DRIVE:
return (item.type == Drive ? true : false);
case FULL_PATH:
return item.fullPath;
default:
return QVariant();
}
}
void FileSystemModel::cdUp(void){
if(dir.isRoot()) // When user want to move up from current directory, but it's root directory
updateDrivesInfo(); // we introduce an abstraction to show drives as folders with special role
else {
dir.cdUp();
updateDirInfo();
}
}
void FileSystemModel::cd(const QString& path){
if(path == "drives") // path "drives" is abstraction level to show drives as folders
updateDrivesInfo();
else {
dir = QDir(path);
updateDirInfo();
}
}
| true |
0be96e7925b4d0a18a5b6bc6f5862f3c36a87f56 | C++ | XRabell13/NewRep | /1curs/Laba13_Dop/Source.cpp | WINDOWS-1251 | 2,263 | 3.109375 | 3 | [] | no_license | // 4
/*#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <ctime>
using namespace std;
int main() {
setlocale(LC_ALL, "Russian");
int n;
cout << " ";
cin >> n;
int Mass[17][17], d = n, k, count = 1, i, j, p;
for (p = 0; count <= pow(n, 2); p++) {
for (k = p; k < d; k++)
Mass[p][k] = count++;
for (k = p + 1; k < d - 1; k++)
Mass[k][n - (p + 1)] = count++;
for (k = n - (p + 1); k >= p; k--)
Mass[n - (p + 1)][k] = count++;
for (k = n - (p + 2); k > p; k--)
Mass[k][p] = count++;
d--;
}
if (n % 2 == 1)
Mass[n / 2][n / 2] = pow(n, 2);
cout << endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout << Mass[i][j] << " ";
}
cout << endl;
}
}*/
// 2
/*#include <iostream>
using namespace std;
int main()
{
int const n=5;
int sq[n][n];
for (int i = 0; i < n; i++)
{
int a = i + 1;
for (int j = 0; j < n; j++)
{
sq[i][j] = a;
a++;
if (a > n) a = 1;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << sq[i][j] << ' ';
cout << endl;
}
return 0;
}*/
// 5
#include <iostream>
#include <iomanip>
int main()
{
setlocale(LC_CTYPE, "Rus");
int n;
std::cout << " : ";
std::cin >> n;
float** arr = new float* [n];
float max;
int i_max, j_max;
std::cout << " : ";
for (int i = 0; i < n; ++i)
{
arr[i] = new float[n];
for (int j = 0; j < n; ++j)
{
std::cin >> arr[i][j];
if (((!i) && (!j)) || (arr[i][j] > max))
{
max = arr[i][j];
i_max = i;
j_max = j;
}
}
}
arr[i_max][j_max] = arr[0][0];
arr[0][0] = max;
for (int count = 1; count < n; ++count)
{
max = arr[0][1];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (((i != j) || ((i >= count) && (j >= count))) && (arr[i][j] > max))
{
max = arr[i][j];
i_max = i;
j_max = j;
}
arr[i_max][j_max] = arr[count][count];
arr[count][count] = max;
}
std::cout << " : \n";
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
std::cout << std::setw(5) << arr[i][j];
std::cout << std::endl;
}
} | true |
6f2aa519486a24592a7f4045dc4a3c380f795b8c | C++ | assassin945/The-Summary-of-ACM | /基础算法——高精度计算/例1.3-高精度乘法/例1.3-高精度乘法.cpp | UTF-8 | 972 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main() {
char a1[101], b1[101];
int a[101], b[101], c[10001];
int lena, lenb, lenc;
int x;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
memset(c, 0, sizeof(c));
cin >> a1;
cin >> b1;
lena = strlen(a1);
lenb = strlen(b1);
for (int i = 0; i < lena; i++)
{
a[lena - i] = a1[i] - 48;
}
for (int j = 0; j < lenb; j++)
{
b[lenb - j] = b1[j] - 48;
}
for (int m = 1; m <= lena; m++)
{
x = 0; //用于存放进位
for (int n = 1; n <= lenb; n++) //对乘数的每一位进行处理
{
c[m + n - 1] = a[m] * b[n] + x + c[m + n - 1]; //当前乘积+上次乘积进位+原数
x = c[m + n - 1] / 10;
c[m + n - 1] %= 10;
}
c[m + lenb] = x; //进位
}
lenc = lena + lenb;
while (c[lenc] == 0 && lenc > 1) //删除前导0
{
lenc--;
}
for (int k = lenc; k >= 1 ; k--) //输出结果
{
cout << c[k];
}
cout << endl;
return 0;
} | true |
d7c9c4d154dd8219352489ecd9538031a06d3a0d | C++ | jiyahan/moon | /moon/moon/logic/units/doerUnit/doerEquip.h | UTF-8 | 1,219 | 2.640625 | 3 | [] | no_license | #ifndef __ACTOR_EQUIP_H__
#define __ACTOR_EQUIP_H__
class CPlayer;
/*******************************************
* 玩家装备模块
******************************************/
class CPlayerEquip :
public CDoerUnit
{
public:
typedef CDoerUnit super;
//角色装备位置定义
enum EquipPosition
{
epHat = 0,//头盔(左侧第一格)
epDress = 1,//衣服(左侧第二格)
epPants = 2,//裤子(右侧第一格)
epBoot = 3,//靴子(右侧第二格)
EquipCount,//装备数量
};
public:
CPlayerEquip();
~CPlayerEquip();
virtual bool init();
virtual bool loadData(CDataPacketReader &data);
virtual void saveData(CDataPacket &data);
virtual void dispatchRecvPacket(int btCmd, CDataPacketReader &inPacket);
//获取装备穿戴位置
int getEquipPos(int btItemType);
//通过物品系列号获取装备位置索引
int findEquipItem(common::ItemSeries series);
//向客户端发送装备列表
void sendEquipItems();
private:
void HandleTakeOnItem(CDataPacketReader &inPacket);
void HandleTakeOffItem(CDataPacketReader &inPacket);
void TakeOffItem(int nEquipPos);
public:
UserItem* m_ItemList[EquipCount];//装备物品列表,wItemId为0表示没有装备
};
#endif
| true |
1280def72c63fa7e393b8718b705c0b3c883921b | C++ | JiatuYan/NumericalAnalysis | /project1/code/problemB/test.cpp | UTF-8 | 736 | 2.875 | 3 | [] | no_license | /**
* @file test.cpp
* @brief
* @author XDDD
* @version
* @date 2020-03-20
*/
#include "function.h"
#include "NewtonMethod.h"
int main(int argc, char *argv[])
{
std::ifstream my_in("input.txt"); //input from input.txt
std::ofstream my_out("output.txt"); //output to output.txt
function f;
functiond fd;
NewtonMethod N;
double e, x_0;
int t;
for(int i=0; i!=20; i++) { //calculate 10 times with different range of postconditions
my_in >> e >> t >> x_0;
N.set(e, t); //set the postconditions.
my_out << std::fixed << std::setprecision(15) << N.solve(f, fd, x_0) << "\t" << N.num() << std::endl;
//output the root and the iterating times.
}
my_in.close();
my_out.close();
return 0;
}
| true |
a66c4c494a966ee0bc0ccd6ed1585d143aa8191a | C++ | fraigo/arduino-sketches | /step_motor_direction/step_motor_direction.ino | UTF-8 | 663 | 3.15625 | 3 | [] | no_license | /**
* Step motor - direction control
* Author: Francisco Igor
* Email : franciscoigor@gmail.com
*
*
*/
#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// initialize the stepper library on pins 2 through 5:
Stepper myStepper(stepsPerRevolution, 2, 4, 3, 5);
void setup() {
// nothing to do inside the setup
}
void loop() {
// read the potentiometer value:
int sensorReading = analogRead(A0);
// Map it to a range from -2 to 2
int direction = map(sensorReading, 0, 1023, -2, 2);
// set the motor speed and step direction
myStepper.setSpeed(50);
myStepper.step(direction);
delay(10);
}
| true |
a9ce5cf811835d548056fcfd376efef7c94dcca6 | C++ | aplqo/exercises | /loj/3045-Switch.cpp | UTF-8 | 3,203 | 2.6875 | 3 | [] | no_license | #ifdef APTEST
#include "debug_tools/judge.h"
#endif
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <iterator>
#include <numeric>
const int maxn = 100, maxsp = 5e4;
constexpr unsigned int mod = 998244353, inv2 = 499122177;
struct Number {
inline friend Number operator+(const Number l, const Number r)
{
const unsigned int ret = l.val + r.val;
return Number{ret >= mod ? ret - mod : ret};
}
inline void operator+=(const Number r)
{
val += r.val;
if (val >= mod) val -= mod;
}
inline friend Number operator-(const Number l, const Number r)
{
return Number{l.val >= r.val ? l.val - r.val : l.val + mod - r.val};
}
inline void operator-=(const Number r)
{
val = val >= r.val ? val - r.val : val + mod - r.val;
}
inline friend Number operator*(const Number l, const Number r)
{
return Number{
static_cast<unsigned int>(((unsigned long long)l.val * r.val) % mod)};
}
inline void operator*=(const Number r)
{
val = (static_cast<unsigned long long>(val) * r.val) % mod;
}
unsigned int val;
};
Number quickPow(Number a, unsigned int e)
{
Number ret{1};
for (; e; e >>= 1) {
if (e & 0x01) ret *= a;
a *= a;
}
return ret;
}
inline Number inverse(const Number x) { return quickPow(x, mod - 2); }
Number fMem[maxsp * 2 + 10], gMem[maxsp * 2 + 10];
Number *const f = fMem + maxsp + 5, *const g = gMem + maxsp + 5;
int p[maxn + 10], s[maxn + 10];
template <bool negitive>
inline void shift(const Number src[], Number dest[], const int n,
const int offset)
{
if (!negitive) {
std::memcpy(dest + offset, src, sizeof(src[0]) * (n - offset));
std::memset(dest, 0, sizeof(dest[0]) * offset);
}
else {
std::memcpy(dest, src + offset, sizeof(src[0]) * (n - offset));
std::memset(dest + (n - offset), 0, sizeof(dest[0]) * offset);
}
}
/// @brief dest*x^v +\- dest*x^{-v}
template <bool neg>
void multiply(Number dest[], const int sumP, const int v)
{
static Number mema[maxsp * 2 + 10], memb[maxsp * 2 + 10];
static Number *const tmpa = mema + maxsp + 5, *const tmpb = memb + maxsp + 5;
const int n = sumP * 2 + 1;
shift<false>(dest - sumP, tmpa - sumP, n, v);
shift<true>(dest - sumP, tmpb - sumP, n, v);
for (int i = -sumP; i <= sumP; ++i)
if constexpr (neg)
dest[i] = (tmpa[i] - tmpb[i]) * Number{inv2};
else
dest[i] = (tmpa[i] + tmpb[i]) * Number{inv2};
}
Number solve(const int n)
{
const int sumP = std::accumulate(p, p + n, 0);
f[0].val = g[0].val = 1;
for (int i = 0; i < n; ++i) {
if (s[i])
multiply<true>(f, sumP, p[i]);
else
multiply<false>(f, sumP, p[i]);
multiply<false>(g, sumP, p[i]);
}
Number acc{0};
for (int i = -sumP; i <= sumP; ++i)
acc += (f[i] - g[i]) *
inverse(Number{(i + static_cast<int>(mod) - sumP) % mod});
return acc * quickPow(Number{2}, n) * Number{static_cast<unsigned int>(sumP)};
}
int main()
{
std::ios::sync_with_stdio(false);
int n;
std::cin >> n;
std::copy_n(std::istream_iterator<int>(std::cin), n, s);
std::copy_n(std::istream_iterator<int>(std::cin), n, p);
std::cout << solve(n).val << "\n";
return 0;
} | true |
28ce4693626f9e422090f81bf78e06557bb75155 | C++ | lixiang2017/leetcode | /cpp/5894.0_Two_Out_of_Three.cpp | UTF-8 | 1,985 | 3.25 | 3 | [] | no_license | /*
执行用时:24 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:27.3 MB, 在所有 C++ 提交中击败了100.00% 的用户
通过测试用例:288 / 288
*/
class Solution {
public:
vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) {
unordered_set<int> us1 (nums1.begin(), nums1.end());
unordered_set<int> us2 (nums2.begin(), nums2.end());
unordered_set<int> us3 (nums3.begin(), nums3.end());
unordered_set<int> us;
us.insert(us1.begin(), us1.end());
us.insert(us2.begin(), us2.end());
us.insert(us3.begin(), us3.end());
vector<int> ans;
for (int x: us) {
int f1 = us1.find(x) != us1.end() ? 1 : 0;
int f2 = us2.find(x) != us2.end() ? 1 : 0;
int f3 = us3.find(x) != us3.end() ? 1 : 0;
if (f1 + f2 + f3 >= 2) {
ans.push_back(x);
}
}
return ans;
}
};
/*
执行用时:20 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:27.2 MB, 在所有 C++ 提交中击败了100.00% 的用户
通过测试用例:288 / 288
*/
class Solution {
public:
vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) {
unordered_set<int> us1 (nums1.begin(), nums1.end());
unordered_set<int> us2 (nums2.begin(), nums2.end());
unordered_set<int> us3 (nums3.begin(), nums3.end());
unordered_set<int> us;
us.insert(nums1.begin(), nums1.end());
us.insert(nums2.begin(), nums2.end());
us.insert(nums3.begin(), nums3.end());
vector<int> ans;
for (int x: us) {
int f1 = us1.find(x) != us1.end() ? 1 : 0;
int f2 = us2.find(x) != us2.end() ? 1 : 0;
int f3 = us3.find(x) != us3.end() ? 1 : 0;
if (f1 + f2 + f3 >= 2) {
ans.push_back(x);
}
}
return ans;
}
};
| true |
8c7d0bb57590a78e2204ddddbccf2efc124d1986 | C++ | asahi7/UNIST-data-structure-assignments | /assignment1/polynomial.h | UTF-8 | 8,736 | 3.609375 | 4 | [] | no_license | // Aibek Smagulov 20142028
// CSE221 Assignment 1
#ifndef polynomial_h
#define polynomial_h
#include <typeinfo>
#include <iostream>
#include <math.h>
using namespace std;
template <typename T>
class Polynomial
{
public:
// Default constructor p(x) = 0
Polynomial();
// Copy constructor
Polynomial(const Polynomial& source);
// Destructor
~Polynomial();
// Assignment operator
Polynomial& operator = (const Polynomial& source);
// Sum of *this->and source polynomials
Polynomial operator+(const Polynomial& source);
// Subtract of source polynomials from *this
Polynomial operator-(const Polynomial& source);
// Product of *this->and source polynomials
Polynomial operator*(const Polynomial& source);
// Evaluate polynomial *this->at x and return the result
T Eval(T x);
// Print polynomial
void Print();
// Create a new term. If the term exists, overwrite its coefficient.
void CreateTerm(const T coef, const int exp);
T* coefs;
int* exps;
int size;
void deleteZeros();
int getNewSize(const Polynomial& left, const Polynomial& right);
};
//
// Implementation
//
template<typename T>
Polynomial<T>::Polynomial()
{
size = 0;
coefs = NULL;
exps = NULL;
}
// Copy constructor
template <typename T>
Polynomial<T>::Polynomial(const Polynomial& source)
{
this->size = source.size;
this->coefs = new T[this->size];
this->exps = new int[this->size];
for(int i = 0; i < this->size; i++)
{
this->coefs[i] = source.coefs[i];
this->exps[i] = source.exps[i];
}
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator = (const Polynomial& source)
{
if(this != &source){
delete[] this->coefs;
delete[] this->exps;
this->size = 0;
this->size = source.size;
this->coefs = new T[this->size];
this->exps = new int[this->size];
for(int i = 0; i < this->size; i++){
this->coefs[i] = source.coefs[i];
this->exps[i] = source.exps[i];
}
}
return *this;
}
template <typename T>
Polynomial<T>::~Polynomial()
{
delete[] this->coefs;
delete[] this->exps;
}
template <typename T>
void Polynomial<T>::Print()
{
for(int i = 0; i < this->size; i++){
if(i != 0 && coefs[i] > 0) cout << '+';
cout << coefs[i]; // ??
if(exps[i] > 0) cout << "x^" << exps[i];
}
cout << endl;
}
template <typename T>
int Polynomial<T>::getNewSize(const Polynomial & left, const Polynomial & right){
int newSize = left.size + right.size;
for(int l = 0, r = 0; l < left.size || r < right.size;){
if(l >= left.size){
r++;
continue;
}
if(r >= right.size){
l++;
continue;
}
if(left.exps[l] == right.exps[r]){
newSize--;
l++;
r++;
}
else if(left.exps[l] > right.exps[r]){
l++;
}
else if(left.exps[l] < right.exps[r]){
r++;
}
}
return newSize;
}
template <typename T>
void Polynomial<T>::deleteZeros(){
bool* checker = new bool[this->size];
for(int i = 0; i < this->size; i++) checker[i] = 0;
int newSize = this->size;
for(int i = 0; i < this->size; i++){
if(is_same<T, double>::value && fabs(this->coefs[i]) < pow(10, -15)){
checker[i] = 1;
newSize--;
}
else if(is_same<T, int>::value && this->coefs[i] == 0){
checker[i] = 1;
newSize--;
}
}
Polynomial<T> temp;
temp.size = newSize;
temp.coefs = new T[newSize];
temp.exps = new int[newSize];
for(int i = 0, j = 0; i < this->size; i++){
if(checker[i] == 0){
temp.coefs[j] = this->coefs[i];
temp.exps[j] = this->exps[i];
j++;
}
}
*this = temp;
}
// Sum of *this->and source polynomials
template <typename T>
Polynomial<T>
Polynomial<T>::operator+(const Polynomial& source)
{
Polynomial<T> newPolynomial;
int newSize = getNewSize(*this, source);
newPolynomial.size = newSize;
newPolynomial.exps = new int[newSize];
newPolynomial.coefs = new T[newSize];
for(int l = 0, r = 0, i = 0; l < this->size || r < source.size;){
if(l >= this->size){
newPolynomial.coefs[i] = source.coefs[r];
newPolynomial.exps[i] = source.exps[r];
i++;
r++;
continue;
}
if(r >= source.size){
newPolynomial.coefs[i] = this->coefs[l];
newPolynomial.exps[i] = this->exps[l];
l++;
i++;
continue;
}
if(this->exps[l] == source.exps[r]){
newPolynomial.exps[i] = this->exps[l];
newPolynomial.coefs[i] = this->coefs[l] + source.coefs[r];
//cout << newPolynomial.coefs[i] << "---------" << this->exps[l] << endl;
l++;
r++;
i++;
}
else if(this->exps[l] > source.exps[r]){
newPolynomial.exps[i] = this->exps[l];
newPolynomial.coefs[i] = this->coefs[i];
i++;
l++;
}
else{
newPolynomial.exps[i] = source.exps[r];
newPolynomial.coefs[i] = source.coefs[r];
i++;
r++;
}
}
newPolynomial.deleteZeros();
return newPolynomial;
}
template <typename T>
Polynomial<T>
Polynomial<T>::operator-(const Polynomial& source)
{
Polynomial<T> newPolynomial;
int newSize = getNewSize(*this, source);
newPolynomial.size = newSize;
newPolynomial.exps = new int[newSize];
newPolynomial.coefs = new T[newSize];
for(int l = 0, r = 0, i = 0; l < this->size || r < source.size;){
if(l >= this->size){
newPolynomial.coefs[i] = source.coefs[r];
newPolynomial.exps[i] = -source.exps[r];
i++;
r++;
continue;
}
if(r >= source.size){
newPolynomial.coefs[i] = this->coefs[l];
newPolynomial.exps[i] = this->exps[l];
l++;
i++;
continue;
}
if(this->exps[l] == source.exps[r]){
newPolynomial.exps[i] = this->exps[l];
newPolynomial.coefs[i] = this->coefs[l] - source.coefs[r];
l++;
r++;
i++;
}
else if(this->exps[l] > source.exps[r]){
newPolynomial.exps[i] = this->exps[l];
newPolynomial.coefs[i] = this->coefs[i];
i++;
l++;
}
else{
newPolynomial.exps[i] = source.exps[r];
newPolynomial.coefs[i] = -source.coefs[r];
i++;
r++;
}
}
newPolynomial.deleteZeros();
return newPolynomial;
}
template <typename T>
Polynomial<T>
Polynomial<T>::operator*(const Polynomial& source)
{
Polynomial<T> newPolynomial;
for(int i = 0; i < this->size; i++){
Polynomial<T> mul;
mul.size = source.size;
mul.exps = new int[mul.size];
mul.coefs = new T[mul.size];
for(int j = 0; j < source.size; j++){
mul.exps[j] = source.exps[j] + this->exps[i];
mul.coefs[j] = source.coefs[j] * this->coefs[i];
}
newPolynomial = newPolynomial + mul;
}
newPolynomial.deleteZeros();
return newPolynomial;
}
template <typename T>
T Polynomial<T>::Eval(T x)
{
T result = 0;
for(int i = 0; i < this->size; i++){
result += this->coefs[i] * pow(x, this->exps[i]);
}
return result;
}
template <typename T>
void Polynomial<T>::CreateTerm(const T coef, const int exp)
{
for(int i = 0; i < this->size; i++){
if(this->exps[i] == exp){
this->coefs[i] = coef;
return;
}
}
if(this->size == 0){
this->size = 1;
this->exps = new int[1];
this->coefs = new T[1];
this->exps[0] = exp;
this->coefs[0] = coef;
return;
}
Polynomial<T> temp(*this); // Copy constructor, makes equal all the fields
delete[] this->coefs;
delete[] this->exps;
this->coefs = new T[this->size + 1];
this->exps = new int[this->size + 1];
for(int i = 0; i < this->size; i++){
this->coefs[i] = temp.coefs[i];
this->exps[i] = temp.exps[i];
}
this->coefs[this->size] = coef;
this->exps[this->size] = exp;
this->size++;
for(int i = this->size - 1; i > 0; i--){
if(this->exps[i] > this->exps[i - 1]){
swap(this->coefs[i], this->coefs[i - 1]);
swap(this->exps[i], this->exps[i - 1]);
}
}
}
#endif
| true |
bd70aaf6ee2ae75d07c16e08f898992ee68e6717 | C++ | WIAS-BERLIN/dti | /src/Vector.h | UTF-8 | 1,278 | 2.984375 | 3 | [] | no_license | #ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
#include <R.h>
#include <R_ext/Utils.h>
#include <Rinternals.h>
/*
* The class 'Vector' offers typical vector operations.
*/
class Vector
{
private:
// length of Vector
int n;
// components of Vector
double* components;
// LinkedList-Variables
Vector* next;
Vector* prev;
public:
/** constructors & destructor **/
Vector() {};
Vector(int);
Vector(double, double, double);
Vector(double*, int);
// ~Vector();
// print-method
void print();
/** getters **/
double* getComponents();
int getN();
Vector* getNext();
Vector* getPrev();
/** setters **/
void setNext(Vector*);
void setPrev(Vector*);
/** mathematical functions **/
// norm of a vector
static double norm(Vector&);
// divide vector with scalar
Vector& operator/(double);
// multiply vector with scalar
Vector& operator*(double);
// multiply vector with vector
double operator*(Vector&);
// add vector to vector
Vector& operator+(Vector&);
// subtract vector from vector
Vector& operator-(Vector&);
// cross product of two vectors
Vector& cross(Vector&);
};
#endif /*VECTOR_H_*/
| true |
c6226c74e94aa4cfdb1c267561aa601339512fb1 | C++ | spsbstn/ProjectWatchlist | /src/cursorshapearea.h | UTF-8 | 592 | 2.53125 | 3 | [] | no_license | #ifndef CURSORSHAPEAREA_H
#define CURSORSHAPEAREA_H
#include <QDeclarativeItem>
/*
* Class for setting different CursorShapes in GUI
*/
class QsltCursorShapeArea : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY(Qt::CursorShape cursorShape READ cursorShape WRITE setCursorShape NOTIFY cursorShapeChanged)
public:
explicit QsltCursorShapeArea(QDeclarativeItem *parent = 0);
Qt::CursorShape cursorShape() const;
Q_INVOKABLE void setCursorShape(Qt::CursorShape cursorShape);
private:
int m_currentShape;
signals:
void cursorShapeChanged();
};
#endif // CURSORSHAPEAREA_H
| true |
d320675852ccec9fdaad72f5d9f51d92d84b950a | C++ | SayaUrobuchi/uvachan | /Kattis/nimionese.cpp | UTF-8 | 1,357 | 2.59375 | 3 | [] | no_license | #include <iostream>
using namespace std;
const char *tk = "bcdgknpt";
const char *tt = "aou";
int tbl[128], tail[128];
int main()
{
int i, j, mod;
char last, better;
bool ws, ss;
string s;
for (i=0; tk[i]; i++)
{
tbl[tk[i]] = 1;
}
for (i=0; tt[i]; i++)
{
tail[tt[i]] = 1;
}
while (getline(cin, s))
{
for (i=0, ws=true, ss=false, last=0; i<=s.size(); i++)
{
if (i == s.size() || s[i] == ' ')
{
if (tbl[last])
{
for (j=1; ; j++)
{
if (last-j >= 'a' && tail[last-j])
{
last -= j;
break;
}
if (last+j <= 'z' && tail[last+j])
{
last += j;
break;
}
}
cout << last << 'h';
}
ws = true;
ss = false;
if (i < s.size())
{
cout << " ";
}
}
else if (s[i] == '-')
{
ss = true;
}
else
{
last = (s[i] | 32);
mod = ((s[i] & 32) ? ~0 : ~32);
if (ws)
{
if (!tbl[last])
{
for (j=1; ; j++)
{
if (last-j >= 'a' && tbl[last-j])
{
last -= j;
break;
}
if (last+j <= 'z' && tbl[last+j])
{
last += j;
break;
}
}
}
better = last;
}
else if (ss && tbl[last])
{
last = better;
}
ws = false;
cout << (char)(last&mod);
}
}
cout << "\n";
}
return 0;
}
| true |
72a243971d304bb7a76b6bd5f8029553e4174b2a | C++ | antikrem/mg_ultra | /mg_ultra/movement_polar_turn.h | UTF-8 | 654 | 2.84375 | 3 | [] | no_license | #ifndef __MOVEMENT_POLAR_TURN__
#define __MOVEMENT_POLAR_TURN__
#include "movement_quanta.h"
class MovementPolarTurn : public MovementQuanta {
float rate;
int duration;
public:
MovementPolarTurn(float rate, int duration) {
this->rate = rate;
this->duration = duration;
}
~MovementPolarTurn() {
}
bool isExecuting() override {
return cycle <= duration;
}
Point3 updateExecution(shared_ptr<ComponentMovement> componentMovement, const Point3& position) override {
if (!cycle) {
componentMovement->setAngleChange(rate);
}
else if (cycle == duration) {
componentMovement->setAngleChange(0);
}
return position;
}
};
#endif | true |
48976a38466546b97b6eb980ab307cf27bf3fde3 | C++ | dumel7/MyGame | /IcyTower/IcyTower/PointBanner.cpp | UTF-8 | 483 | 2.5625 | 3 | [] | no_license | #include "PointBanner.h"
PointBanner::PointBanner(Resource &resource)
{
resource.setFont(font);
resource.setPointsBanner(sprite);
points.setFont(font);
points.setCharacterSize(30);
points.setPosition(BANNER_POSITION);
sprite.setPosition(BANNER_POSITION);
}
void PointBanner::drawNow(sf::RenderWindow & Window, int point)
{
points.setString(std::to_string(point));
Window.draw(sprite);
Window.draw(points);
}
PointBanner::~PointBanner()
{
}
| true |
404e0440c27d6aaa3adbeaf35867d9987e50cbba | C++ | mqaaa/algorithmmic | /1129. Recommendation System (25).cpp | UTF-8 | 931 | 2.625 | 3 | [] | no_license |
/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ : 1163306125
Blog : http://blog.csdn.net/Mq_Go/
Create : 2018-03-17 18:49:35
Version: 1.0
**************************************************************/
#include <set>
#include <cstdio>
using namespace std;
struct node{
int value,cnt;
node(int a,int b):value(a),cnt(b){};
bool operator <(const node &c) const{
return cnt != c.cnt ? cnt>c.cnt : value < c.value;
}
};
set<node>::iterator it;
int book[50005] = {0};
int main(){
int n,k,num;
scanf("%d %d",&n,&k);
set<node> s;
for(int i = 0 ; i < n ; i++){
scanf("%d",&num);
if(i!=0){
printf("%d:",num);
int i = 0;
for(it = s.begin();i < k && it!=s.end() ; i++,it++){
printf(" %d",it->value);
}
printf("\n");
}
it = s.find(node(num,book[num]));
if(it!=s.end())s.erase(it);
book[num]++;
s.insert(node(num,book[num]));
}
return 0;
}
| true |
7de750edb14cb7faa0a159afa160c0b66076e1a7 | C++ | AndreyG/watermarking | /src/algorithms/median.h | UTF-8 | 3,767 | 3.1875 | 3 | [] | no_license | #ifndef _MEDIAN_H_
#define _MEDIAN_H_
#include <algorithm>
#include <boost/utility.hpp>
#include "../utility/stopwatch.h"
#include "../utility/debug_stream.h"
namespace algorithm
{
namespace
{
template< class Iter >
struct default_comparator_f
{
typedef std::less< typename std::iterator_traits< Iter >::value_type > type;
};
template< class Iter, class Comparator, class ValueType >
bool sequence_is_valid( Iter p, Iter q, Iter m, ValueType const & value, Comparator comp )
{
if ( comp( *m, value ) )
{
return false;
}
for ( ; p != m; ++p )
{
if ( !comp( *p, value ) )
{
return false;
}
}
for ( ; m != q; ++m )
{
if ( comp( *m, value ) )
{
return false;
}
}
return true;
}
template< class T, class Comparator >
struct operator_binder
{
operator_binder( T const & value, Comparator const & comp )
: value_( value )
, comp_( comp )
{}
bool operator() ( T const & t ) const
{
return comp_( t, value_ );
}
private :
T const & value_;
Comparator const & comp_;
};
template< class Iter, class Comparator >
Iter part( Iter p, Iter q, Comparator const & comp )
{
typedef typename std::iterator_traits< Iter >::value_type value_type;
const typename std::iterator_traits< Iter >::difference_type size = std::distance( p, q );
value_type middle = *( p + (size / 2) );
typedef operator_binder< value_type, Comparator > predicate;
Iter bound = std::partition( p, q, predicate( middle, comp ) );
std::swap( *bound, *std::find( bound, q, middle ) );
assert( sequence_is_valid( p, q, bound, middle, comp ) );
return bound;
}
template< class Iter, class Comparator >
Iter kth( Iter p, Iter q, typename std::iterator_traits< Iter >::difference_type k, Comparator const & comp )
{
typename std::iterator_traits< Iter >::difference_type dist = std::distance( p, q );
assert(k <= dist);
if ( dist == 1 )
return p;
if ( dist == 2 )
{
if ( comp( *next( p ), *p ) )
std::swap( *p, *next( p ) );
return p + k;
}
Iter m = part( p, q, comp );
dist = std::distance( p, m );
if ( k < dist )
return kth( p, m, k, comp );
else if ( k == dist )
return m;
else
return kth( m + 1, q, k - (dist + 1), comp );
}
}
template< class Iter, class Comparator >
Iter median( Iter p, Iter q, Comparator comp )
{
Iter res = kth( p, q, std::distance( p, q ) / 2, comp );
assert( ::abs( std::distance( p, res ) - std::distance( res, q ) ) <= 1 );
for ( ; p != res; ++p )
{
assert( !comp( *res, *p ) );
}
--q;
for ( ; q != res; --q )
{
assert( !comp( *q, *res ) );
}
return res;
}
template< class Iter >
Iter median( Iter p, Iter q )
{
typedef typename default_comparator_f< Iter >::type comp_t;
return median( p, q, comp_t() );
}
}
#endif /* _MEDIAN_H */
| true |
73c31b27eb210551f92342d7658d877838ce27e0 | C++ | jbji/Programming-Method-and-Practice---2019-CS | /2020ad-p14-crystal/main.cpp | UTF-8 | 2,764 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
class Block{
public:
int a;
int b;
int c;
int index;
int min;
Block(int _a,int _b, int _c,int _index):a(_a),b(_b),c(_c),index(_index){
if(a < b) swap(a, b);
if(a < c) swap(a,c);
if(b < c) swap(b,c);
min = a < b ? a : b;
min = min < c ? min : c;
}
static bool cmpab(Block *i,Block *j){
if (i->a != j->a) return i->a < j->a;
if (i->b != j->b) return i->b < j->b;
return i->c < j->c;
}
static bool cmpbc(Block *i,Block *j){
if (i->b != j->b) return i->b < j->b;
if (i->c != j->c) return i->c < j->c;
return i->a < j->a;
}
static bool cmpca(Block *i,Block *j){
if (i->c != j->c) return i->c < j->c;
if (i->a != j->a) return i->a < j->a;
return i->b < j->b;
}
static bool cmpmin(Block *i,Block *j){
return i->min < j->min;
}
};
int main() {
int n;
cin >> n;
Block * bl[n];
int a,b,c,maxBlock;
for(int i=0;i<n;i++){
scanf("%d %d %d",&a,&b,&c);
bl[i] = new Block(a,b,c,i);
}
//mode single
sort(bl,bl+n,Block::cmpmin);
Block * p1 = NULL,* p2 = NULL;
p1 = bl[n-1];
maxBlock = p1->min;
//mode multiple
sort(bl,bl+n,Block::cmpab);
for(int i=0;i<n-1;i++){
if(bl[i]->a == bl[i+1]->a && bl[i]->b == bl[i+1]->b){
int min = bl[i]->a < bl[i]->b ? bl[i]->a : bl[i]->b;
min = min < bl[i]->c + bl[i+1]->c ? min : bl[i]->c + bl[i+1]->c;
if(maxBlock < min){
maxBlock = min;
p1 = bl[i];
p2 = bl[i+1];
}
}
}
sort(bl,bl+n,Block::cmpbc);
for(int i=0;i<n-1;i++){
if(bl[i]->b == bl[i+1]->b && bl[i]->c == bl[i+1]->c){
int min = bl[i]->b < bl[i]->c ? bl[i]->b : bl[i]->c;
min = min < bl[i]->a + bl[i+1]->a ? min : bl[i]->a + bl[i+1]->a;
if(maxBlock < min){
maxBlock = min;
p1 = bl[i];
p2 = bl[i+1];
}
}
}
sort(bl,bl+n,Block::cmpca);
for(int i=0;i<n-1;i++){
if(bl[i]->c == bl[i+1]->c && bl[i]->a == bl[i+1]->a){
int min = bl[i]->c < bl[i]->a ? bl[i]->c : bl[i]->a;
min = min < bl[i]->b + bl[i+1]->b ? min : bl[i]->b + bl[i+1]->b;
if(maxBlock < min){
maxBlock = min;
p1 = bl[i];
p2 = bl[i+1];
}
}
}
if(p2){
int i1=p1->index,i2=p2->index;
cout << "2" << endl << (i1<i2?i1:i2)+1 << " " << (i1>i2?i1:i2)+1 <<endl;
}else{
cout << "1" << endl << p1->index+1 <<endl;
}
return 0;
} | true |
707abaf9def83fbc57dcdc8700b40dbcf1b5d3af | C++ | patilaarti15/CorJava | /anjali cpp prog/e1.cpp | UTF-8 | 696 | 3.375 | 3 | [] | no_license | /*#include<iostream>
using namespace std;
class demo
{
int a;
public:
void show()
{
cout<<"In Constructor"<<a<<endl;
}
demo()
{
cout<<"Enter number";
cin>>a;
}
demo(int i)
{
a=i;
}
~demo()
{
cout<<"In destructor";
}
};
int main()
{
demo d1;
d1.show();
}
*/
#include<iostream>
using namespace std;
class cal
{
int a,b;
public:
int get()
{
cout<<"Enter two number";
cin>>a>>b;
}
int show()
{
cout<<"addition="<<a+b;
cout<<"substraction="<<a-b;
cout<<"multiplication="<<a*b;
cout<<"division="<<a/b;
}
};
int main()
{
cal c1;
c1.get();
c1.show();
}
| true |
2fbfdce6e11eb7552dca45725d1868f5d3131652 | C++ | Rahul-D78/DS_and_Algo | /array/maxLengthSubString.cpp | UTF-8 | 1,374 | 3.65625 | 4 | [] | no_license | // C++ program to find maximum length equal
// character string with k changes
#include <iostream>
using namespace std;
// function to find the maximum length of
// substring having character ch
int findLen(string& A, int n, int k, char ch)
{
int maxlen = 1;
int cnt = 0;
int l = 0, r = 0;
// traverse the whole string
while (r < n) {
/* if character is not same as ch
increase count */
if (A[r] != ch)
++cnt;
/* While count > k traverse the string
again until count becomes less than k
and decrease the count when characters
are not same */
while (cnt > k) {
if (A[l] != ch)
--cnt;
++l;
}
/* length of substring will be rightIndex -
leftIndex + 1. Compare this with the maximum
length and return maximum length */
maxlen = max(maxlen, r - l + 1);
++r;
}
return maxlen;
}
// function which returns maximum length of substring
int answer(string& A, int n, int k)
{
int maxlen = 1;
for (int i = 0; i < 26; ++i) {
maxlen = max(maxlen, findLen(A, n, k, i+'A'));
maxlen = max(maxlen, findLen(A, n, k, i+'a'));
}
return maxlen;
}
// Driver code
int main()
{
int n = 5, k = 2;
string A = "ABABA";
cout << "Maximum length = " << answer(A, n, k) << endl;
n = 6, k = 4;
string B = "HHHHHH";
cout << "Maximum length = " << answer(B, n, k) << endl;
return 0;
}
| true |
25ad444a2251c6417a2cf2e86fed9dbb34243bbe | C++ | jayoswald/sparse | /src/vector.h | UTF-8 | 442 | 2.71875 | 3 | [] | no_license | #pragma once
class SparseMatrix;
// Very simple vector class.
class Vector {
friend Vector *sym_spmv(const SparseMatrix&, const Vector&, int);
public:
Vector(int len) : _data(new double[len]), _len(len) {}
~Vector() { delete _data; }
double &operator()(int i) { return _data[i]; }
double operator()(int i) const { return _data[i]; }
int size() const { return _len; }
private:
double *_data;
int _len;
};
| true |
839a2ec96dc39f6cbf90e78aad0a1f892a0aaeb1 | C++ | ipetrovanton/C-lab-4 | /src/main3.cpp | UTF-8 | 1,227 | 3.453125 | 3 | [] | no_license | /*Задача №3
Написать программу, которая запрашивает строку и определяет, не является
ли строка палиндромом (одинаково читается и слева направо и справа налево)
Пояснение
Цель задачи - применить указатели для быстрого сканирования строки с двух концов
Состав
Программа должна состоять из функций:
- int isPalindrome(char * str) - функция, проверяющая str (ответ либо 0, либо 1)
- main() - организация ввода строки
Создаются три файла: task3.h,task3.cpp,main3.cpp.
*/
#include <stdio.h>
#include <string.h>
#include "task3.h"
#define N 256
int main (void) {
char str [N] = { 0 };
printf("Enter a string:\n");
fgets(str, N, stdin);
if (str[strlen(str) - 1] == '\n')
str[strlen(str) - 1] = '\0';
if(isPalindrome(str) == 1)
printf("%s is Palindrom\n", str);
else if (isPalindrome(str) == 0)
printf("%s is not Palindrom\n", str);
return 0;
}
| true |
ab9b2557dfc03ba80a5dd28da33af658b94b4723 | C++ | vlongle/Neurosimulation | /feb/learn/main.cpp | UTF-8 | 383 | 3.03125 | 3 | [] | no_license | #include "Vector.h"
#include <iostream>
using namespace std;
int main(){
Vector<double> test;
test.reserve(10);
cout << "main" << endl;
cout << test.size() << endl;
for (int i=0; i < 10; i++){
// cout << "loop" << endl;
test.put(i, i*2);
cout << "test[" << i << "]: " << test[i] << endl;
}
cout << "end" << endl;
}
| true |
fc232421134c1cd80c8ea8e1d004398ae22a961e | C++ | HectorIGH/Competitive-Programming | /Leetcode Challenge/09_September_2020/C++/Week 3/5_Sequential Digits.cpp | UTF-8 | 1,198 | 3.671875 | 4 | [] | no_license | //An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
//
//Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
//
//
//
//Example 1:
//
//Input: low = 100, high = 300
//Output: [123,234]
//Example 2:
//
//Input: low = 1000, high = 13000
//Output: [1234,2345,3456,4567,5678,6789,12345]
//
//
//Constraints:
//
//10 <= low <= high <= 10^9
// Hide Hint #1
//Generate all numbers with sequential digits and check if they are in the given range.
// Hide Hint #2
//Fix the starting digit then do a recursion that tries to append all valid digits.
class Solution {
public:
vector<int> sequentialDigits(int low, int high) {
string s = "123456789";
string sub;
int ans;
vector<int> v;
for(int i = 0; i < s.length(); i++) {
for(int j = i; j < s.length(); j++) {
sub = s.substr(i, j - i + 1);
ans = stoi(sub);
if(ans >= low and ans <= high) {
v.push_back(ans);
}
}
}
sort(v.begin(), v.end());
return v;
}
}; | true |
af5e20b96b770f38fa15d93cd4318960d642feb6 | C++ | Steelbadger/OpenGLThreading | /Windows Framework/Lab6c/terrain.cpp | UTF-8 | 1,526 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "Terrain.h"
#include "myvector4.h"
#include "my4x4matrix.h"
#include "noisegenerator.h"
#include <time.h>
#include <string>
#include <iostream>
#include <algorithm>
Terrain::Terrain()
{
}
Terrain::Terrain(float s, float r):
squareSize(s),
resolution(r)
{
Create();
}
Terrain::Terrain(Mesh &m) :
Mesh(m)
{
std::vector<Vector3>::iterator it1 = verts.begin();
std::vector<Vector3>::iterator it2 = verts.end();
it2--;
float lower = (*it1).x;
float higher = (*it2).x;
squareSize = higher - lower;
float size = sqrt(float(verts.size()));
step = squareSize/(size - 1);
resolution = squareSize / size;
}
Terrain::~Terrain(void)
{
}
void Terrain::Create()
{
float height = 0;
int size = squareSize/resolution;
step = squareSize/(size-1);
// double myTime = clock();
for (float i = 0; i < size; i++) {
for (float j = 0; j < size; j++) {
verts.push_back(Vector3(i*step, 0, j*step));
Vector3 normalA = Vector3(0,0,0);
normals.push_back(normalA);
uvs.push_back(Vector2(i*step/4, j*step/4));
}
}
for (int i = 0; i < size-1; i++) {
for (int j = 0; j < size-1; j++) {
index.push_back(i+j*size);
index.push_back(1+i+(1+j)*size);
index.push_back(i+(1+j)*size);
index.push_back(1+i+(1+j)*size);
index.push_back(i+j*size);
index.push_back(1+i+j*size);
}
}
// myTime = clock()-myTime;
// std::cout << "Number of Triangles in Terrain Mesh: " << index.size()/3 << std::endl;
// std::cout << "Generation Time: " << myTime/CLOCKS_PER_SEC << "s" << std::endl;
}
| true |
eee572966fb2c462b8793fa266a2e7d8e2f01138 | C++ | chinawch007/LeetCode | /221.cpp | UTF-8 | 1,548 | 3.09375 | 3 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.size() == 0)return 0;
int n = matrix.size();
int o = matrix[0].size();
vector< vector<int> > e;
e.resize(n);
for(int i = 0; i < n; ++i)
{
e[i].resize(o);
}
int ma = 0;
for(int i = 0; i < o; ++i)
{
e[0][i] = matrix[0][i] - '0';
if(e[0][i] == 1)ma = 1;
}
for(int i = 0; i < n; ++i)
{
e[i][0] = matrix[i][0] - '0';
if(e[i][0] == 1)ma = 1;
}
int l = 0, k = 0, m = 0;
for(int i = 1; i < n; ++i)
{
for(int j = 1; j < o; ++j)
{
if(matrix[i][j] != '1')continue;
l = e[i-1][j-1];
for(k = i - 1; k > i - 1 - l; --k)
{
if(matrix[k][j] != '1')break;
}
for(m = j - 1; m > j - 1 - l; --m)
{
if(matrix[i][m] != '1')break;
}
e[i][j] = i - k < j - m ? i - k : j - m;
if(e[i][j] > ma)ma = e[i][j];
}
}
return ma * ma;
}
};
int main()
{
Solution s;
/*
int n, t;
vector<int> vi;
cin >> n;
for(int i = 0; i < n; ++i)
{
cin >> t;
vi.push_back(t);
}
cout << s.maxProfit(vi) << endl;
*/
return 0;
} | true |
73d45add50416a9fb937fd1d7a0f309e683f88fe | C++ | hello-starry/ML4KP | /src/prx/simulation/playback/plan.cpp | UTF-8 | 6,582 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "prx/simulation/playback/plan.hpp"
namespace prx
{
plan_t::plan_t(const space_t* new_space)
{
control_space = new_space;
steps.push_back(plan_step_t(control_space->make_point(), 0));
num_steps = 0;
max_num_steps = 1;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
}
plan_t::plan_t(const plan_t& other)
{
control_space = other.control_space;
num_steps = 0;
max_num_steps = 0;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
(*this) = other;
}
plan_t::~plan_t()
{
steps.clear();
}
void plan_t::resize(unsigned num_size)
{
while( max_num_steps < num_size )
{
increase_buffer();
}
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
plan_t& plan_t::operator=(const plan_t& t)
{
prx_assert(control_space->get_space_name()==t.control_space->get_space_name(),"Assigning a plan that doesn't have a matching control space.");
if( this != &t )
{
//check the size of the two plans
while( max_num_steps < t.num_steps )
{
increase_buffer();
}
//clear the plan
clear();
for(auto&& step: t)
{
control_space->copy_point((*end_iterator).control, step.control);
(*end_iterator).duration = step.duration;
++num_steps;
++end_iterator;
++const_end_iterator;
}
}
return *this;
}
plan_t& plan_t::operator+=(const plan_t& t)
{
unsigned new_size = t.num_steps + num_steps;
//check the size of the two plans
while( max_num_steps < new_size )
{
increase_buffer();
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
for(auto&& step: t)
{
control_space->copy_point((*end_iterator).control, step.control);
(*end_iterator).duration = step.duration;
++num_steps;
++end_iterator;
++const_end_iterator;
}
return *this;
}
void plan_t::clear()
{
end_iterator = steps.begin();
const_end_iterator = steps.begin();
num_steps = 0;
}
void plan_t::copy_to(const double start_time, const double duration, plan_t& t)
{
prx_assert(control_space->get_space_name()==t.control_space->get_space_name(),"Copying a plan that doesn't have a matching control space.");
double s = start_time;
double d = duration;
auto step = steps.begin();
while (s > step->duration)
{
s -= step->duration;
step++;
if (step == steps.end())
prx_throw("Indexed into plan with time outside the plan's full duration.");
}
if (d < step->duration)
{
t.copy_onto_back(step->control, d);
// std::cout<<duration<<" Copy to: "<<t.duration()<<std::endl;
return;
}
t.copy_onto_back(step->control, step->duration-s);
d -= (step->duration-s);
step++;
while (step != steps.end())
{
if (d < step->duration)
{
t.copy_onto_back(step->control, d);
break;
}
t.copy_onto_back(step->control, step->duration);
d -= step->duration;
step++;
}
// std::cout<<duration<<" Copy to: "<<t.duration()<<std::endl;
}
void plan_t::copy_onto_back(space_point_t control, double time)
{
if( (num_steps + 1) >= max_num_steps )
{
increase_buffer();
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
control_space->copy_point((*end_iterator).control, control);
(*end_iterator).duration = time;
++end_iterator;
++const_end_iterator;
++num_steps;
}
void plan_t::copy_onto_front(space_point_t control, double time)
{
if( (num_steps + 1) >= max_num_steps )
increase_buffer();
plan_step_t new_step = steps.back();
steps.pop_back();
steps.push_front(new_step);
control_space->copy_point((*steps.begin()).control, control);
(*steps.begin()).duration = time;
++num_steps;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
void plan_t::append_onto_front(double time)
{
if( (num_steps + 1) >= max_num_steps )
increase_buffer();
plan_step_t new_step = steps.back();
steps.pop_back();
steps.push_front(new_step);
(*steps.begin()).duration = time;
++num_steps;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
void plan_t::append_onto_back(double time)
{
if( (num_steps + 1) >= max_num_steps )
{
increase_buffer();
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
(*end_iterator).duration = time;
++end_iterator;
++const_end_iterator;
++num_steps;
}
void plan_t::extend_last_control(double time)
{
prx_assert(num_steps>0,"Can't extend the last control if a plan has no controls");
this->back().duration+=time;
}
void plan_t::pop_front()
{
if( num_steps == 0 )
prx_throw("Trying to pop the front off an empty plan.");
plan_step_t popped = steps[0];
for( unsigned i = 0; i < num_steps - 1; ++i )
{
steps[i] = steps[i + 1];
}
num_steps--;
steps[num_steps] = popped;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
void plan_t::pop_back()
{
if( num_steps == 0 )
prx_throw("Trying to pop the backs off an empty plan.");
num_steps--;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
std::advance(end_iterator, num_steps);
std::advance(const_end_iterator, num_steps);
}
std::string plan_t::print( unsigned precision ) const
{
std::stringstream out(std::stringstream::out);
out << "\n";
for(const plan_step_t& step : *this)
{
out << "[" << control_space->print_point(step.control, precision)
<< " , " << step.duration << "s]" << std::endl;
}
return out.str();
}
void plan_t::increase_buffer()
{
if( max_num_steps != 0 )
{
for( unsigned i = 0; i < max_num_steps; i++ )
{
steps.push_back(plan_step_t(control_space->make_point(), 0));
}
max_num_steps *= 2;
}
else
{
steps.push_back(plan_step_t(control_space->make_point(), 0));
max_num_steps = 1;
num_steps = 0;
end_iterator = steps.begin();
const_end_iterator = steps.begin();
}
}
}
| true |
36c856f5ba1967e12782908d17312a91679787f6 | C++ | akkybm/Leetcode_July-21 | /Day11_Find Median from Data Stream.cpp | UTF-8 | 820 | 2.59375 | 3 | [] | no_license | #include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
class MedianFinder {
public:
vector<int> median;
ordered_set s;
MedianFinder() {
}
void addNum(int num) {
median.push_back(num);
s.insert(num);
}
double findMedian() {
double med = 0.0;
int n=median.size();
if(n%2==0){
med = ((double)(*(s.find_by_order(n/2))+(*(s.find_by_order(n/2-1)))))/2.0;
}else{
med = (*(s.find_by_order(n/2)))*1.0;
}
return med;
}
};
| true |
0d79297cb05655da55ae937df01cc8e63fb4e13b | C++ | Luke2336/EDA_2021_Spring | /lab2/Code/Timer.hpp | UTF-8 | 931 | 2.921875 | 3 | [] | no_license | #pragma once
#include<bits/stdc++.h>
using namespace std;
class GlobalTimer {
static unique_ptr<GlobalTimer> uniqueGlobalTimer;
chrono::seconds timeLimit;
chrono::high_resolution_clock::time_point startTime;
GlobalTimer() {}
void restart(chrono::seconds seconds) {
timeLimit = seconds;
startTime = chrono::high_resolution_clock::now();
}
public:
static void initialTimerAndSetTimeLimit(chrono::seconds seconds) {
if (uniqueGlobalTimer == nullptr)
uniqueGlobalTimer = unique_ptr<GlobalTimer>(new GlobalTimer);
uniqueGlobalTimer->restart(seconds);
}
static GlobalTimer *getInstance() { return uniqueGlobalTimer.get(); }
template <class ToDuration = chrono::nanoseconds>
ToDuration getDuration() {
auto endTime = chrono::high_resolution_clock::now();
return chrono::duration_cast<ToDuration>(endTime - startTime);
}
bool overTime() { return getDuration<>() >= timeLimit; }
}; | true |
edd2aff942e90a605a603e43d390bd29fff34604 | C++ | el-bart/ACARM-ng | /src/datafacades/DataFacades/StrAccess/ErrorThrower.t.cpp | UTF-8 | 3,234 | 2.640625 | 3 | [] | no_license | /*
* ErrorThrower.t.cpp
*
*/
#include <tut.h>
#include "DataFacades/StrAccess/ErrorThrower.hpp"
#include "DataFacades/StrAccess/DefaultHandleMap.hpp"
#include "DataFacades/StrAccess/TestParams.t.hpp"
using namespace DataFacades::StrAccess;
namespace
{
struct TestClass
{
TestClass(void):
pLast_(Path("a.b"), cb_),
p_(Path("a.b"), cb_)
{
while(pLast_.hasNext())
++pLast_;
}
TestParams::ResultCallback cb_;
TestParams pLast_;
TestParams p_;
};
typedef tut::test_group<TestClass> factory;
typedef factory::object testObj;
factory tf("DataFacades/StrAccess/ErrorThrower");
} // unnamed namespace
namespace tut
{
// test exception when end is found
template<>
template<>
void testObj::test<1>(void)
{
try
{
ErrorThrower::throwOnLast(SYSTEM_SAVE_LOCATION, pLast_);
fail("throwOnLast() didn't throw on end");
}
catch(const ExceptionInvalidPath &)
{
// this is expected
}
}
// test if non-end does not throw
template<>
template<>
void testObj::test<2>(void)
{
ErrorThrower::throwOnLast(SYSTEM_SAVE_LOCATION, p_);
}
// test throwing on non-end
template<>
template<>
void testObj::test<3>(void)
{
try
{
ErrorThrower::throwOnNotLast(SYSTEM_SAVE_LOCATION, p_);
fail("throwOnNotLast() didn't throw on non-end path");
}
catch(const ExceptionInvalidPath &)
{
// this is expected
}
}
// test if end does not throw
template<>
template<>
void testObj::test<4>(void)
{
ErrorThrower::throwOnNotLast(SYSTEM_SAVE_LOCATION, pLast_);
}
// test thwoing on unexpected path token
template<>
template<>
void testObj::test<5>(void)
{
try
{
ErrorThrower::throwOnInvalidPath(SYSTEM_SAVE_LOCATION, p_);
fail("throwOnInvalidPath() didn't throw");
}
catch(const ExceptionInvalidPath &)
{
// this is expected
}
}
// test if end does not throw when not reached
template<>
template<>
void testObj::test<6>(void)
{
ErrorThrower::throwOnEnd(SYSTEM_SAVE_LOCATION, pLast_);
}
// test thwoing on end()
template<>
template<>
void testObj::test<7>(void)
{
++pLast_;
try
{
ErrorThrower::throwOnEnd(SYSTEM_SAVE_LOCATION, pLast_);
fail("throwOnEnd() didn't throw on end");
}
catch(const ExceptionInvalidPath &)
{
// this is expected
}
}
// test throwing on invalid index
template<>
template<>
void testObj::test<8>(void)
{
try
{
ErrorThrower::throwOnInvalidIndex(SYSTEM_SAVE_LOCATION, pLast_);
fail("throwOnInvalidIndex() didn't throw");
}
catch(const ExceptionInvalidPath &)
{
// this is expected
}
}
// test throwing on invalid name
template<>
template<>
void testObj::test<9>(void)
{
try
{
ErrorThrower::throwOnInvalidName(SYSTEM_SAVE_LOCATION, p_, "invalidname");
fail("throwOnInvalidName() didn't throw");
}
catch(const ExceptionInvalidPath &)
{
// this is expected
}
}
// test no-throwing on valid name
template<>
template<>
void testObj::test<10>(void)
{
ErrorThrower::throwOnInvalidName(SYSTEM_SAVE_LOCATION, p_, "a");
}
// test no-throwing on index
template<>
template<>
void testObj::test<11>(void)
{
TestParams p(Path("42.xyz"), cb_);
ErrorThrower::throwOnInvalidName(SYSTEM_SAVE_LOCATION, p, "thething");
}
} // namespace tut
| true |
5b467cf877bbc6e52d652c7891748af2fb39e669 | C++ | fastbuild/fastbuild | /Code/Core/CoreTest/Tests/TestThread.cpp | UTF-8 | 1,843 | 2.859375 | 3 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // TestThread.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
// TestFramework
#include "TestFramework/TestGroup.h"
// Core
#include "Core/Process/Thread.h"
// TestThread
//------------------------------------------------------------------------------
class TestThread : public TestGroup
{
private:
DECLARE_TESTS
// Tests
void Unused() const;
void StartAndJoin() const;
// Helpers
static uint32_t ThreadFunc( void * userData )
{
const size_t returnValue = reinterpret_cast<size_t>( userData );
return static_cast<uint32_t>( returnValue );
}
};
// Register Tests
//------------------------------------------------------------------------------
REGISTER_TESTS_BEGIN( TestThread )
REGISTER_TEST( Unused )
REGISTER_TEST( StartAndJoin )
REGISTER_TESTS_END
// Unused
//------------------------------------------------------------------------------
void TestThread::Unused() const
{
// A thread object never used to create a thread
Thread t;
TEST_ASSERT( t.IsRunning() == false );
}
// StartAndJoin
//------------------------------------------------------------------------------
void TestThread::StartAndJoin() const
{
// Test thread will return user data as return value
const uint32_t userData = 99;
// Start thread
Thread t;
t.Start( ThreadFunc,
"StartAndJoin",
reinterpret_cast<void *>( static_cast<size_t>( userData ) ) );
TEST_ASSERT( t.IsRunning() );
// Join and check result
const uint32_t result = t.Join();
TEST_ASSERT( result == userData );
TEST_ASSERT( t.IsRunning() == false );
}
//------------------------------------------------------------------------------
| true |
f78a89ef744ff3fea0509d78e79948bb714c5409 | C++ | lisnayk/oop | /lec9/Ex1.cpp | UTF-8 | 1,456 | 3 | 3 | [] | no_license | //---------------------------------------------------------------------------
#pragma hdrstop
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
using namespace std;
class TestConst {
public:
int data;
//const int data2 = 10; -- error
const int data2;
const int data3;
mutable int editable;
int getData2() const {
editable++;
cout << "Const getData2" << editable << endl;
}
int getData() const {
this->editable++;
cout << "Const getData" << this->editable << endl;
// this->getData2(); // ++
// this->editable = 1;
// dataChange(); - error compile time
}
int getData() {
cout << "getData" << endl;
this->data = 1;
cout << "getData = " <<this->data << endl;
}
int dataChange (){
cout << "dataChange" << endl;
this->data = 10;
}
void Print(){
cout << "";
}
TestConst():data2(10),data3(100){
editable = 0;
//data3 = 100; -- error compile time
//data2 = 10; -- error compile time
data = 0;
}
};
int main(int argc, char *argv[])
{
TestConst t;
t.getData();
//t.dataChange();
t.data = 10;
const TestConst ct;
ct.getData();
ct.getData();
ct.getData();
ct.getData();
//ct.data = 100; -- error compile time
//ct.dataChange(); -- error compile time
system("PAUSE");
return EXIT_SUCCESS;
}
| true |
d6f362ced98f961fb38aaa09a48dd82af6727a0a | C++ | Kionte/ProcessSimulation | /OS_Simulation/OS_Simulation/Source.cpp | UTF-8 | 5,369 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include "Core.h"
#include "Process.h"
#include "GlobalQueue.h"
using namespace std;
// randomly created representation of user
queue<Process> user;
// queue that the processes will be pulling from
queue<Process> ready;
void createUser() {
srand((unsigned int)time(NULL));
for (int i = 0; i < 100; i++) // generates 100 random processes
{
int PID = i, priority = rand() % (5) + 1, arrivalTime = 0, cpuBurst = rand() % (10) + 1,
ioBurst = rand() % (11) + 5, ifIO = rand() % 2, contextSwitch = rand() % 3 + 1,
tProcessTime = cpuBurst + ioBurst + contextSwitch;
if (ifIO == 0) ioBurst = 1; // randomly decide if process is io-bound/heavy or not
Process *process = NULL;
process = new Process(PID, priority, arrivalTime, cpuBurst, ioBurst, 0, 0, 0, contextSwitch, 0, tProcessTime);
user.push(*process);
}
}
void computeAvg(vector<Core> cores, int clock, int wasted);
bool check(vector<Core> cores);
int main(){
vector<Core> cores;
int wasted = 0; // total time wasted waiting
int clock = 0; // global clock variable
int totalProcessTime = 0;
int quantum = 0;
bool quantum_set = false;
createUser();
cout << "Please enter the desired number of cores for the simulation (*4 or 8).\n\n";
int num_cores;
cin >> num_cores;
while ((num_cores != 4 && num_cores != 8) || cin.fail()){
cout << "Invalid input\n";
cin.clear();
cout << "Please enter your desired number of cores for the simulation (*4 or 8).\n\n";
cin.ignore(std::numeric_limits<int>::max(), '\n');
cin >> num_cores;
}
cout << "\nPlease enter the desired run time for the simulation (*Range: 100-1000000).\n\n";
int run;
cin >> run;
while (!(run >= 100 && run <= 1000000) || cin.fail()){
cout << "Invalid input\n";
cin.clear();
cout << "Please enter the desired run time for the simulation (*Range: 100-1000000).\n\n";
cin.ignore(std::numeric_limits<int>::max(), '\n');
cin >> run;
}
cout << "\nPlease enter the desired algorithm for the simulation.\n\n";
int alg;
cout << "First Come First Serve = 1\n";
cout << "Round Robin = 2\n";
cout << "Shortest Process Next = 3\n";
cin >> alg;
while (!(alg >= 1 && alg <= 4) || cin.fail())
{
cout << "Invalid input\n";
cin.clear();
cout << "Please enter the desired algorithm for the simulation.\n\n";
cin.ignore(std::numeric_limits<int>::max(), '\n');
cin >> alg;
}
for (int i = 0; i < num_cores; i++) // creats "num_cores" cores to work with
{
Core* temp = NULL;
temp = new Core(&ready, quantum);
cores.push_back(*temp);
}
while (clock < run)
{
for (int i = 0; i < 15; i++)
{
if ((!user.empty() && (ready.size() < 20))) {
int entry = 1;
if (entry == 1) {
Process process = user.front();
process.arrivalTime = clock;
ready.push(process);
user.pop();
}
}
}
switch (alg) {
case 1:
for (auto &c : cores) {
c.FCFS(clock, &totalProcessTime);
} break;
case 2:
if (quantum_set == false) {
cout << "\nPlease enter the desired quantum for the simulation (max 20).\n\n";
cin >> quantum;
while (!(quantum >= 1 && quantum <= 20) || cin.fail()) {
cout << "Invalid input\n";
cin.clear();
cout << "Please enter the desired quantum for the simulation (max 20).\n\n";
cin.ignore(std::numeric_limits<int>::max(), '\n');
cin >> quantum;
}
quantum_set = true;
for (auto &c : cores) {
c.setQuantum(quantum);
}
}
for (auto &c : cores) {
c.RR(clock, &totalProcessTime);
} break;
//case 3:
// for (auto &c : cores) {
// c.SPN(clock, &totalProcessTime);
// } break;
//case 4:
// for (auto &c : cores) {
// c.MLFB(clock, &totalProcessTime);
// } break;
}
clock++;
}
system("CLS"); // clears screen
computeAvg(cores, clock, wasted);
return 0;
}
void computeAvg(vector<Core> cores, int clock, int wasted)
{
// stat you want find
double avgWait = 0;
double avgResponse = 0;
double avgTurnaround = 0;
double avgConSwitch = 0;
double wastedTime = 0;
double utilization = 0;
int throughput = 0;
// go through cores and get total for stat
for (auto &c : cores)
{
avgWait += c.getTotalWait();
avgResponse += c.getTotalResponse();
avgTurnaround += c.getTotalTurnAround();
avgConSwitch += c.getConSwitch();
throughput += c.getThroughput();
}
// calculate avg of stat
utilization = (((double)clock - (double)wasted) / (double)clock) * 100;
avgWait = (double)avgWait / (double)throughput;
avgResponse = (double)avgResponse / (double)throughput;
avgTurnaround = (double)avgTurnaround / (double)throughput;
avgConSwitch = (double)avgConSwitch / (double)throughput;
// output stat
cout << "Throughput: " << throughput << endl;
cout << "Avg. Wait: " << avgWait << endl;
cout << "Avg. Response: " << avgResponse << endl;
cout << "Avg. Turnaround: " << avgTurnaround << endl;
cout << "Avg. Context Switch Time: " << avgConSwitch << endl;
cout << "CPU Utilization Percentage: %" << utilization << endl;
}
//bool check(vector<Core> cores) {
// for (auto &c : cores){
// if (c.getBusy()){
// return true;}
// else { return false; }
// }
//
//}
| true |
2685143773b7447c97682867233c311b88c2e145 | C++ | BizShuk/code_sandbox | /c_cpp/test.cpp | UTF-8 | 1,431 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string.h>
#include <list>
using namespace std;
void test1()
{
char b = 'a';
char *a = &b;
char w[] = "aaaaaa";
char *x = w;
cout << "x:" << strlen(x) << endl;
cout << sizeof(*a) << endl;
char d[] = "eeee";
char *c[] = {d};
cout << c[0] << strlen(c[0]) << endl;
}
void test2()
{
int a;
a++;
cout << a << endl;
}
void continue_memory_array()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
/*
int* tmp;
int* tmp1 = &a[5];
int* tmp2 = &a[3];
*tmp = *tmp1;
*tmp1 = *tmp2;
*tmp2 = *tmp;
*/
int tmp;
tmp = a[5];
a[3] = a[5];
a[5] = tmp;
for (int i = 0; i < 8; ++i)
{
cout << a[i] << endl;
}
}
class A
{
public:
A ();
~A ();
int num;
};
A::A()
{
}
A::~A()
{
}
A test_scope()
{
A a;
a.num = 4;
return a;
}
int main(int argc, char *argv[])
{
// test1();
// test2();
//continue_memory_array();
A *b;
if (!b)
{
cout << "123" << endl;
}
else
{
cout << "456";
}
A c = test_scope();
cout << "t" << c.num << endl;
list<int> _list;
list<int>::iterator _list_it = _list.begin();
cout << "begin:" << *_list_it << endl;
_list_it++;
cout << "begin++:" << *_list_it << endl;
_list_it++;
cout << "begin++:" << *_list_it << endl;
return 0;
}
| true |