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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4028c8013a15cc0af6cbadfc1243580337cfa339 | C++ | sailesh2/CompetitiveCode | /2020/cf539C.cpp | UTF-8 | 1,045 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
map<int,long long int> even;
map<int,long long int>::iterator evenIt;
map<int,long long int> odd;
map<int,long long int>::iterator oddIt;
even.insert(make_pair(0,1));
int x=0;
long long int c,sm=0;
for(int i=0;i<n;i++){
x=x^arr[i];
if((i+1)%2==0){
evenIt=even.find(x);
c=0;
if(evenIt!=even.end()){
c=evenIt->second;
even.erase(evenIt);
}
sm=sm+c;
c++;
even.insert(make_pair(x,c));
}else{
oddIt=odd.find(x);
c=0;
if(oddIt!=odd.end()){
c=oddIt->second;
odd.erase(oddIt);
}
sm=sm+c;
c++;
odd.insert(make_pair(x,c));
}
}
cout<<sm;
return 0;
}
| true |
3058308605695cd9ef3e31dda355935db691a7d5 | C++ | vadera11jeet/DataStructure-And-Algorihtm | /trees/binary search tree/check bst has dead end or not.cpp | UTF-8 | 1,500 | 3.59375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *right;
Node *left;
Node(int data = INT_MIN, Node *right = NULL, Node *left = NULL)
{
this->data = data;
this->right = right;
this->left = left;
}
};
class BinarySearchTree
{
public:
Node *root;
vector<int> v;
BinarySearchTree()
{
root = NULL;
}
void insertNode(int value)
{
Node * newNode = new Node(value);
if(!root)
root = newNode;
else
{
Node *temp = root;
Node *par;
while(temp)
{
par = temp;
if(temp->data >= value)
temp = temp->left;
else
temp = temp->right;
}
if(par->data >= value)
par->left = newNode;
else
par->right = newNode;
}
}
bool isDeadEnd(Node *root, int start = 1, int end_ = INT_MAX)
{
if(!root)
return false;
if(start == end_)
return true;
return isDeadEnd(root->left, start, root->data-1) || isDeadEnd(root->right, root->data +1, end_);
}
};
int main()
{
BinarySearchTree b;
b.insertNode(8);
b.insertNode(5);
b.insertNode(2);
b.insertNode(3);
b.insertNode(7);
b.insertNode(11);
b.insertNode(4);
cout<<b.isDeadEnd(b.root);
return 0;
}
| true |
3d575045fedf0992ac98edd27535c342ce9f0634 | C++ | Tosi/wadutil | /src/ArgParser.cpp | UTF-8 | 4,182 | 3.046875 | 3 | [
"MIT"
] | permissive | #include "ArgParser.h"
#include <iostream>
#include <cstdlib>
using std::vector;
using std::string;
using std::map;
using std::pair;
using std::cout;
using std::endl;
ArgParser::ArgParser(const int argc, const char** argv)
{
conf = new ArgParserConf();
callback = nullptr;
this->argc = argc;
args = new vector<string>();
//Convert to array of strings for easier handling
for(int i = 1; i < argc; i++) {
args->push_back(string(argv[i]));
}
//These structures will be built when parse is called
for(int i = 0; i < 256; i++) {
shortargs[i] = nullptr;
}
longargs = nullptr;
}
ArgParser::~ArgParser()
{
delete conf;
delete args;
if(longargs) {
delete longargs;
}
}
//Build lookup table for short arguments and hash map for long arguments
bool ArgParser::buildLookups() {
const std::vector<CmdLineArgument*>& opts = conf->getArguments();
if(longargs != nullptr) {
delete longargs;
longargs = nullptr;
}
longargs = new map<string, CmdLineArgument*>();
for(vector<CmdLineArgument*>::const_iterator i = opts.begin(); i != opts.end(); i++) {
CmdLineArgument* arg = *i;
if(arg->shortname != '\0') {
shortargs[(unsigned int)arg->shortname] = arg;
}
longargs->insert(pair<string, CmdLineArgument*>(arg->longname, arg));
}
return true;
}
//Display help for the arguments in the current configuration
void ArgParser::showHelp(std::ostream& os)
{
if(!conf)
return;
vector<CmdLineArgument*> opts = conf->getArguments();
for(vector<CmdLineArgument*>::const_iterator i = opts.begin(); i != opts.end(); i++) {
CmdLineArgument* arg = *i;
string param = arg->has_argument ? " [param]" : "";
os << "--" << arg->longname << param;
if(arg->shortname != '\0') {
os << " \t-" << arg->shortname << param;
}
os << "\t\t" << arg->description << endl;
}
}
//Parse the command line arguments, calling the callback function for each argument that exists
//If exit on unrecognized is true, will show the list of valid commands before exiting
bool ArgParser::parse(bool exit_on_unrecognized)
{
if(!buildLookups()) {
return false;
}
for(vector<string>::iterator i = args->begin(); i != args->end(); i++) {
const string& arg = *i;
bool has_argument = false;
//Check for a short argument
if(arg.length() == 2 && arg[0] == '-' && arg[1] != '-') {
CmdLineArgument* opt = shortargs[(unsigned int)arg[1]];
if(opt) {
has_argument = true;
//Set the flag if it was given to us
if(opt->flag) {
*opt->flag = true;
}
//Call the callback if it is given
if(callback) {
callback(opt, ""); //TODO: handle case of an argument
}
} else {
cout << "Unrecognized argument: " << arg << endl;
if(exit_on_unrecognized)
exit(EXIT_FAILURE);
}
} else if(arg.length() > 2 && arg[0] == '-' && arg[1] == '-') {
//Lookup the long argument in the map (will be case sensitive)
map<string, CmdLineArgument*>::const_iterator e
= longargs->find(arg.substr(2));
if(e != longargs->end()) {
CmdLineArgument* opt = e->second;
has_argument = true;
if(opt->flag) {
*opt->flag = true;
}
if(callback) {
callback(opt, "");
}
} else {
cout << "Unrecognized argument: " << arg << endl;
if(exit_on_unrecognized)
exit(EXIT_FAILURE);
}
}
//Remove the argument from the list if it was recognized
if(has_argument) {
i = args->erase(i);
i--; //Since erase() returns an iterator after this one
}
}
return true;
}
| true |
8faf327bfe884e5bdfa2431781535bac4b666d47 | C++ | CSDNSampleGroup/CSDNQA4VS | /Q185912/Source.cpp | UTF-8 | 562 | 3.109375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main()
{
double sum_2diagonal(double arry_2d[][100], unsigned int m, unsigned int n);
int i, j;
double summ;
unsigned int x, y;
double arry[100][100];
cin >> x >> y;
for (i = 0; i < x; i++)
for (j = 0; j < y; j++)
{
cin >> arry[i][j];
}
summ = sum_2diagonal(arry, x, y);
cout << summ;
return 0;
}
double sum_2diagonal(double arry_2d[][100], unsigned int m, unsigned int n)
{
int n0 = (m>n) ? n : m;
int i;
double sum = 0, t = 0;
for (i = 0; i < n0; i++)
sum += (arry_2d[i][i]);
return sum;
} | true |
abe1c3dc8c4550b6d11e919c4280384566a6aa6c | C++ | kunalsharmaks/DS-Algorithmic-Questions | /Data Structure/Stack/Stack using Array.cpp | UTF-8 | 1,494 | 3.84375 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include <limits.h>
#define SIZE 100
int stack[SIZE];
int top = -1;
void push(int element);
int pop();
int main()
{
int choice, data;
while(1){
printf("------------------------------------\n");
printf(" STACK IMPLEMENTATION PROGRAM \n");
printf("------------------------------------\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Size\n");
printf("4. Exit\n");
printf("------------------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter Data to Push into stack: ");
scanf("%d",&data);
push(data);
break;
case 2:
data = pop();
if (data != INT_MIN)
printf("Data => %d\n", data);
break;
case 3:
printf("Stack Size: %d\n",top+1);
break;
case 4:
printf("Exiting!\n");
exit(0);
break;
default:
printf("Invalid Choice\n");
}
printf("\n\n");
}
}
void push(int element)
{
if(top >= SIZE)
{
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = element;
printf("Data Pushed\n");
}
int pop()
{
if (top < 0)
{
printf("Stack is empty.\n");
return INT_MIN;
}
return stack[top--];
}
| true |
198e9cf6d72fd37523b05d6b1fbe522ca182bafc | C++ | Abrham-CISCO/Problem-Solving-With-Programming-II | /Day1/Lab5_Functions.cpp | UTF-8 | 505 | 3.71875 | 4 | [] | no_license | #include <iostream>
//passing arguements to function can be done in two ways by value and by reference.
//by default we are passing by value. by reference means using memory address and usually done using a pointer variable
//for example int sum(int *x, int *y) here by reference method is used.
using namespace std;
int sum(int,int);
int main()
{
int a = 10, b = 20;
cout << "The sum of a and b is \t"<<sum(a,b);
return 0;
}
int sum (int x, int y) {
return (x + y);
}
function_X(x=0,y=1)
| true |
95d0d8c9bdc7f54d3fa7ca9a41ccb5cf7b53447c | C++ | davidcorne/cpp-sandbox | /VirtualFunctions.cpp | UTF-8 | 1,113 | 3.5625 | 4 | [] | no_license | //=============================================================================
// How virtual functions work in constructors and destructors
#include <iostream>
//=============================================================================
class Base {
public:
Base()
{
print("Base::Base()");
function();
}
virtual void function() const
{
print("Base::function()");
}
virtual ~Base()
{
print("Base::~Base()");
function();
}
protected:
void print(const char* to_print) const
{
std::cout << to_print << std::endl;
}
};
//=============================================================================
class Derived : public Base {
public:
Derived()
: Base()
{
print("Derived::Derived()");
function();
}
virtual void function() const override
{
print("Derived::function()");
}
virtual ~Derived()
{
print("Derived::~Derived()");
function();
}
};
//=============================================================================
int main()
{
Derived d;
return 0;
}
| true |
983ffe536e921a988c65da6674b08b34c1160d76 | C++ | meakambut/Snake | /Snake/Snake/Point.cpp | WINDOWS-1251 | 852 | 3.234375 | 3 | [] | no_license | #include "stdafx.h"
#include "Point.h"
#include "Direction.h"
#include "stdio.h"
#include "conio.h"
using namespace std;
void Point::Draw()
{
COORD position = { x, y };
HANDLE hconsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hconsole, position);
cout << sym;
}
Point::Point(int _x, int _y, char _sym)
{
x = _x;
y = _y;
sym = _sym;
}
Point::Point(int _x)
{
x = _x;
y = _x;
sym = ' ';
}
void Point::Move(int offset, Direction direction)
{
if (direction == RIGHT)
{
x += offset;
}
else if (direction == LEFT)
{
x -= offset;
}
else if (direction == UP)
{
y -= offset;
}
else if (direction == DOWN)
{
y += offset;
}
}
void Point::Clear()
{
sym = ' ';
Draw();
}
bool Point::match(Point p) // =
{
return p.x == this->x && p.y == this->y;
}
Point::~Point()
{
}
| true |
8ebe37209cc9571b4787514e42fb2925f8765e73 | C++ | arkrde/foundations_of_qt_development | /ch1/ch1-14/main.cpp | UTF-8 | 1,372 | 2.90625 | 3 | [] | no_license | /*
* Foundations of Qt Development
* Ch 1-14
* STL-style iterator and Java-style iterator side by side
* Copyright (C) 2021 Arnab De <arkrde@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QDebug>
#include <QList>
typedef QList<int>::const_iterator ConstIntListIterator;
int
main() {
QList<int> list;
list << 23 << 27 << 52 << 52;
qDebug() << "Java iterator:";
QListIterator<int> javaIter(list);
while (javaIter.hasNext()) {
qDebug() << javaIter.next();
}
qDebug() << "C++ STL iterator:";
ConstIntListIterator b, e;
for (b = list.begin(), e = list.end(); b != e; ++b) {
qDebug() << *b;
}
qDebug() << "C++ range-based for loop:";
for (auto &e : list) {
qDebug() << e;
}
}
| true |
53c25225c0e201b420e307d4c5269c07a74845ab | C++ | simple-user/cpp | /tempik26 Car/tempik26 Car/lib.cpp | UTF-8 | 2,426 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include "Menu.h"
#include "lib.h"
bool odInit(Odometr *&od)
{
if (od)
{
gotoxy(0, 9, 7);
cout << "Parameters are cleared!" << endl;
delete od;
}
int kmpl = 0;
int cap = 0;
int vol = 0;
gotoxy(0, 10, 7);
cout << "Input km per liter: "; cin >> kmpl;
cout << "Input capacity of fuel gauge: "; cin >> cap;
cout << "Input volume of fuel gauge: "; cin >> vol;
od = new Odometr(0, kmpl, cap, vol);
cout << "OK!" << endl;
system("pause");
system("cls");
return 1;
}
void goOneKm(Odometr *od)
{
gotoxy(0, 10, 7);
if (!od)
cout << "Parameters are not initialized!" << endl;
else
{
goKM(od, 1);
}
system("pause");
system("cls");
}
void goXKm(Odometr *od)
{
gotoxy(0, 10, 7);
if (!od)
cout << "Parameters are not initialized!" << endl;
else
{
int t = 0;
gotoxy(0, 10, 7);
cout << "Input count kilometers to move: "; cin >> t;
goKM(od, t);
}
system("pause");
system("cls");
}
void putOneLiter(Odometr *od)
{
gotoxy(0, 10, 7);
if (!od)
cout << "Parameters are not initialized!" << endl;
else
putLiter(od, 1);
system("pause");
system("cls");
}
void putXLiters(Odometr *od)
{
gotoxy(0, 10, 7);
if (!od)
cout << "Parameters are not initialized!" << endl;
else
{
int t = 0;
cout << "input count of liters to fuel: "; cin >> t;
putLiter(od, t);
}
system("pause");
system("cls");
}
void printInfa(Odometr *od)
{
gotoxy(0, 10, 7);
if (!od)
cout << "Parameters are not initialized!" << endl;
else
{
char odometrText[7] = {};
od->getKiloMetrage(odometrText);
cout << odometrText << " kilometers" << " " << endl;
cout << od->fgPtr()->GetReaminingFuel() << " liters left" << " " << endl;
cout << od->leftKilometers() << " kilometrs left by liter" << " " << endl;
}
}
void goKM(Odometr *od, int km)
{
printInfa(od);
Sleep(500);
for (int a(0); a < km; a++)
{
if (od->goOneKm())
{
printInfa(od);
Sleep(500);
}
else
{
gotoxy(0, 14, 15);
cout << "we can't go any more!" << endl;
break;
}
}
}
void putLiter(Odometr *od, int l)
{
for (int a(0); a < l; a++)
if (od->fgPtr()->toFuel())
{
gotoxy(0, 10, 7);
cout << a + 1 << " liter of fuel got to the fuel gauge " << endl;
Sleep(500);
}
else
{
gotoxy(0, 11, 7);
cout << "fuel gauge is full!" << endl;
break;
}
} | true |
25e2804b18c532472fd48e53414ee63042f842a0 | C++ | green-fox-academy/dodoo86 | /Week5/Day-3/GFOpractice/Sponsor.h | UTF-8 | 384 | 2.625 | 3 | [] | no_license | #ifndef GFOPRACTICE_SPONSOR_H
#define GFOPRACTICE_SPONSOR_H
#include "Person.h"
class Sponsor : public Person {
public:
Sponsor();
Sponsor(const string &name, int age, const string &gender, const string &company);
void introduce();
void hire();
void getGoal();
protected:
string _company;
int _hiredStudents;
};
#endif //GFOPRACTICE_SPONSOR_H
| true |
b4639ab4b22ee70cab471b4e6cbf59c3a9a279be | C++ | JoTaeYang/Study | /Profile.cpp | UHC | 5,525 | 2.5625 | 3 | [] | no_license | #include <Windows.h>
#include <stdio.h>
#include <wchar.h>
#include "Profile.h"
//PROFILE_SAMPLE profile[MAX_PROFILE];
THREAD_SAMPLE g_profile[MAX_PROFILE];
int IsCheckName(int index, const WCHAR* szName)
{
for (int iCnt = 0; iCnt < MAX_SAMPLE; iCnt++)
{
if (g_profile[index].samples[iCnt].lFlag == 1)
{
if (wcscmp(g_profile[index].samples[iCnt].szName, szName) == 0)
{
return iCnt;
}
}
}
return -1;
}
int IsCheckThread(int id)
{
for (int iCnt = 0; iCnt < MAX_PROFILE; iCnt++)
{
if (g_profile[iCnt].id == id)
{
return iCnt;
}
}
int index = AddThread(id);
return index;
}
int AddThread(int id)
{
for (int iCnt = 0; iCnt < MAX_PROFILE; iCnt++)
{
if (g_profile[iCnt].flag == 0)
{
if (InterlockedIncrement((long*)&g_profile[iCnt].flag) == 1)
{
g_profile[iCnt].id = id;
return iCnt;
}
}
}
return -1; // 迭 .
}
void AddProfile(int id, int index, const WCHAR* szName)
{
if (*szName == L'\0')
return;
g_profile[id].samples[index].lFlag = 1;
wcscpy_s(g_profile[id].samples[index].szName, szName);
QueryPerformanceCounter(&g_profile[id].samples[index].lStartTime);
g_profile[id].samples[index].iTotalTime = 0;
g_profile[id].samples[index].iCall = 1;
memset(g_profile[id].samples[index].iMin, 0, sizeof(g_profile[id].samples[index].iMin) / sizeof(_int64));
memset(g_profile[id].samples[index].iMax, 0, sizeof(g_profile[id].samples[index].iMax) / sizeof(_int64));
return;
}
void StartProfile(int id, int index)
{
QueryPerformanceCounter(&g_profile[id].samples[index].lStartTime);
g_profile[id].samples[index].iCall += 1;
}
void ProfileBegin(const WCHAR* szName)
{
int index = -1;
int tIndex;
tIndex = IsCheckThread(GetCurrentThreadId());
index = IsCheckName(tIndex, szName);
if (index == -1) // ̸
{
for (int iCnt = 0; iCnt < MAX_SAMPLE; iCnt++)
{
if (g_profile[tIndex].samples[iCnt].lFlag == 0)
{
//AddProfile(iCnt, szName);
return;
}
}
}
else
{
StartProfile(tIndex, index);
}
}
void CheckMinMax(int id, int index, double time)
{
double tmp = 0;
if (g_profile[id].samples[index].iMin[0] == 0)
{
g_profile[id].samples[index].iMin[0] = time;
return;
}
for (int iCnt = 0; iCnt < 2; iCnt++)
{
if (g_profile[id].samples[index].iMin[iCnt] > time)
{
tmp = time;
time = g_profile[id].samples[index].iMin[iCnt];
g_profile[id].samples[index].iMin[iCnt] = tmp;
}
}
for (int iCnt = 0; iCnt < 2; iCnt++)
{
if (g_profile[id].samples[index].iMax[iCnt] < time)
{
tmp = time;
time = g_profile[id].samples[index].iMax[iCnt];
g_profile[id].samples[index].iMax[iCnt] = tmp;
}
}
}
void ProfileEnd(const WCHAR* szName)
{
LARGE_INTEGER End;
LARGE_INTEGER Freq;
LONGLONG timeDiff;
double microFreq = 0.0;
double usingTime;
int index;
int tIndex;
if (!QueryPerformanceFrequency(&Freq))
return;
QueryPerformanceCounter(&End);
tIndex = IsCheckThread(GetCurrentThreadId());
index = IsCheckName(tIndex, szName); // üũϴ ̸ ε
timeDiff = End.QuadPart - g_profile[tIndex].samples[index].lStartTime.QuadPart;//Լ ð
usingTime = (timeDiff) / (Freq.QuadPart / 1000000.0); //Լ ð, ũ 100
g_profile[tIndex].samples[index].iTotalTime += usingTime; // ð 踦 ϱ
CheckMinMax(tIndex, index, usingTime); //Min Max
}
void ProfileDataOutText(const WCHAR* szFileName)
{
FILE* fp;
LPCTSTR columns = L"Id | Name | Average | Min | Ma x | Call |\n";
WCHAR outbuffer[1024];
char te[1024];
_wfopen_s(&fp, szFileName, L"w, ccs = UTF-8");
wmemset(outbuffer, 0, 1024);
wcsncat_s(outbuffer, columns, wcslen(columns));
for (int tiCnt = 0; tiCnt < MAX_PROFILE; tiCnt++)
{
WCHAR tbuf[100];
swprintf_s(tbuf, L"-----------------------------------------------\n");
wcsncat_s(outbuffer, tbuf, wcslen(tbuf));
for (int iCnt = 0; iCnt < MAX_SAMPLE; iCnt++)
{
if (g_profile[tiCnt].samples[iCnt].lFlag == 1)
{
WCHAR tmpbuf[250];
swprintf_s(tmpbuf, L"%2d | %10s | %10.4lf | %10.4lf | %10.4lf | %lld\n", g_profile[tiCnt].id, g_profile[tiCnt].samples[iCnt].szName,
(g_profile[tiCnt].samples[iCnt].iTotalTime / g_profile[tiCnt].samples[iCnt].iCall) / 1.0,
g_profile[tiCnt].samples[iCnt].iMin[0] / 1.0, g_profile[tiCnt].samples[iCnt].iMax[0] / 1.0, g_profile[tiCnt].samples[iCnt].iCall);
wcsncat_s(outbuffer, tmpbuf, wcslen(tmpbuf));
}
}
fwrite(outbuffer, 1, wcslen(outbuffer) * 2, fp);
}
fclose(fp);
} | true |
fa72073d7a4821798f912be68a61037f89c58a31 | C++ | KaraJ/conpenguum | /Core/comm/udpConnection.cpp | UTF-8 | 3,689 | 2.90625 | 3 | [] | no_license | /*----------------------------------------------------------------------------------------------------------
-- SOURCE FILE: udpConnection.cpp
--
-- PROGRAM: TuxSpace
--
-- METHODS:
-- UDPConnection(int port)
-- ~UDPConnection()
-- void sendMessage(struct sockaddr* to, const void* data, size_t dataLen)
-- ssize_t recvMessage(BYTE** buffer)
--
-- PROGRAMMER: Kara Martens
--
-- REVISIONS (date and description):
--
-- DATE: 2010-02-18
--
-- NOTES: UDPClient and UDPServer both have a UDPConnection for common functions.
----------------------------------------------------------------------------------------------------------*/
#include "udpConnection.h"
#include "unistd.h"
/*----------------------------------------------------------------------------------------------------------
-- FUNCTION: UDPConnection::UDPConnection
--
-- DATE: 2010-02-18
--
-- INTERFACE:
-- int port: the UDP port
--
----------------------------------------------------------------------------------------------------------*/
UDPConnection::UDPConnection(int port)
{
struct sockaddr_in servaddr;
this->sockfd_ = SocketWrapper::Socket(AF_INET, SOCK_DGRAM, 0);
// set up the address structure
bzero(&servaddr, sizeof(struct sockaddr_in));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
//We can remove this if we used different ports for client and server
SocketWrapper::Bind(this->sockfd_, &servaddr, sizeof(sockaddr_in));
}
/*----------------------------------------------------------------------------------------------------------
-- FUNCTION: UDPConnection::~UDPConnection
--
-- DATE: 2010-02-18
--
-- NOTES: Close the socket when the object is deleted.
----------------------------------------------------------------------------------------------------------*/
UDPConnection::~UDPConnection()
{
close(sockfd_);
}
/*----------------------------------------------------------------------------------------------------------
-- FUNCTION: UDPConnection::sendMessage
--
-- DATE: 2010-02-18
--
-- INTERFACE:
-- struct sockaddr* to: The address to send the data to
-- const void* data: The data to send
-- size_t datalen: The length of the data
--
-- RETURN: void
--
-- NOTES: The error handling is done in the Sendto function.
----------------------------------------------------------------------------------------------------------*/
void UDPConnection::sendMessage(struct sockaddr* to, const void* data, size_t dataLen)
{
BYTE* buffer = (BYTE*)malloc(sizeof(BYTE) * (dataLen + 1));
memcpy(buffer, data, dataLen);
buffer[dataLen] = CRC::makeCRC((BYTE*)data, dataLen);
SocketWrapper::Sendto(this->sockfd_, buffer, dataLen + 1, 0, to, sizeof(struct sockaddr));
free(buffer);
}
/*----------------------------------------------------------------------------------------------------------
-- FUNCTION: UDPConnection::recvMessage
--
-- DATE: 2010-02-25
--
-- INTERFACE:
-- BYTE** buffer: Should be null when passed in. Will be filled with the incoming data.
-- size_t* bufSize: The amount of data in buffer.
--
-- RETURN: -1 on error. -2 on bad CRC
--
-- NOTES:
----------------------------------------------------------------------------------------------------------*/
ssize_t UDPConnection::recvMessage(BYTE** buffer)
{
sockaddr_in from;
socklen_t socklen = sizeof(from);
(*buffer) = (BYTE*)malloc(UDP_MAXMSG * sizeof(BYTE));
ssize_t len = SocketWrapper::Recvfrom(this->sockfd_, *buffer, UDP_MAXMSG, NULL, (sockaddr*)&from, &socklen);
if (len == -1)
return -1;
if (!CRC::checkCRC((*buffer), len))
return -2;
return len - 1;
}
| true |
6624db4c160b0265e8dda439c0e976e9ad318ab4 | C++ | zungybungy/Codility | /L3_PermMissingElem.cpp | UTF-8 | 599 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> &A) {
// write your code in C++11 (g++ 4.8.2)
int res = 0;
for (int i = 0; i < int(A.size()); i++) {
res += (i + 1 - A[i]);
}
res += int(A.size() + 1);
return res;
}
int main(int argc, char **argv)
{
vector<int> A;
A.push_back(2);
A.push_back(3);
A.push_back(1);
A.push_back(5);
cout << solution(A) << " ";
/*
vector<int> S = solution(A);
for (vector<int>::iterator it = S.begin(); it != S.end(); it++) {
cout << *it << " ";
}*/
}
| true |
c8a5afbcb5cc81147e70cd711f28f0b1c810f57c | C++ | tianzhuwei/Algorithm | /Introduction to Algorithms/StringMatching/StringMatching-Read/StringMatching-Read/main.cpp | WINDOWS-1252 | 1,439 | 2.765625 | 3 | [] | no_license | #include"general.h"
void PuSu_match(char* buffer,char* p);
void KMP(char* buffer, char* p);
void BM(char* buffer, char* p);
void Sunday(char* buffer, char * p);
#include<string>
int main() {
clock_t time = clock();
ifstream DNA("E:\\ݼ\\DNA.txt");
//ifstream DNA("E:\\test.txt");
if (!DNA)
{
cout << "Can not open the file!" << endl;
system("pause");
return 1;
}
DNA.seekg(0,DNA.end);
unsigned length = DNA.tellg();
DNA.seekg(0,DNA.beg);
cout << "string length is "<<length << endl;
char* buffer = new char[length+1];
memset(buffer, 0, length+1);
DNA.read(buffer, length+1);
//cout << "the string is " << endl;
//cout << buffer << endl;
if (DNA.eof())
{
cout << "all chacter readed!" << endl;
}
else
{
cout << "error: only " <<DNA.gcount() << " could be read";
}
DNA.close();
time = clock() - time;
cout << "Read Use time is " << time <<" ms"<< endl;
// char* a ;
// string a;
// getline(DNA, a);
time = clock();
//char* p = "11";
//buffer = "aaaaa";
//char* p="aa";
char* p = "GTGCTGACACATCCA";
PuSu_match(buffer, p);
KMP(buffer, p);
cout << "KMP Matched use time " << time << "ms" << endl;
time = clock();
BM(buffer, p);
time = clock() - time;
cout << "BM Matched use time " << time << "ms" << endl;
time = clock();
Sunday(buffer, p);
time = clock() - time;
cout << "Sunday Matched use time " << time << "ms" << endl;
delete[] buffer;
system("pause");
return 0;
} | true |
0df0ff22ce10fdc6d3e834512952a79f70080689 | C++ | EPAC-Saxon/environment-map-JuliePreperier | /ShaderGLLib/Texture.cpp | UTF-8 | 4,392 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "Texture.h"
#include <GL/glew.h>
#include "Image.h"
namespace sgl {
Texture::Texture(
const std::string& file,
const PixelElementSize pixel_element_size /*= PixelElementSize::BYTE*/,
const PixelStructure pixel_structure /*= PixelStructure::RGB_ALPHA*/) :
pixel_element_size_(pixel_element_size),
pixel_structure_(pixel_structure)
{
sgl::Image img(file,pixel_element_size_,pixel_structure_);
size_ = img.GetSize();
glGenTextures(1, &texture_id_);
glBindTexture(GL_TEXTURE_2D, texture_id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(
GL_TEXTURE_2D,
0,
ConvertToGLType(pixel_element_size_, pixel_structure_),
static_cast<GLsizei>(size_.first),
static_cast<GLsizei>(size_.second),
0,
ConvertToGLType(pixel_structure_),
ConvertToGLType(pixel_element_size_),
img.Data());
glGenerateMipmap(GL_TEXTURE_2D);
}
Texture::~Texture()
{
glDeleteTextures(1, &texture_id_);
}
void Texture::Bind(const unsigned int slot /*= 0*/) const
{
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, texture_id_);
}
void Texture::UnBind() const
{
glBindTexture(GL_TEXTURE_2D, 0);
}
TextureManager::~TextureManager()
{
DisableAll();
}
bool TextureManager::AddTexture(
const std::string& name,
const std::shared_ptr<sgl::Texture>& texture)
{
auto ret = name_texture_map_.insert({ name, texture });
return ret.second;
}
bool TextureManager::RemoveTexture(const std::string& name)
{
auto it = name_texture_map_.find(name);
if (it == name_texture_map_.end())
{
return false;
}
name_texture_map_.erase(it);
return true;
}
const int TextureManager::EnableTexture(const std::string& name) const
{
auto it1 = name_texture_map_.find(name);
if (it1 == name_texture_map_.end())
{
throw std::runtime_error("try to enable a texture: " + name);
}
for (int i = 0; i < name_array_.size(); ++i)
{
if (name_array_[i].empty())
{
name_array_[i] = name;
it1->second->Bind(i);
return i;
}
}
throw std::runtime_error("No free slots!");
}
void TextureManager::DisableTexture(const std::string& name) const
{
auto it1 = name_texture_map_.find(name);
if (it1 == name_texture_map_.end())
{
throw std::runtime_error("no texture named: " + name);
}
auto it2 = std::find_if(
name_array_.begin(),
name_array_.end(),
[name](const std::string& value)
{
return value == name;
});
if (it2 != name_array_.end())
{
*it2 = "";
it1->second->UnBind();
}
else
{
throw std::runtime_error("No slot bind to: " + name);
}
}
void TextureManager::DisableAll() const
{
for (int i = 0; i < 32; ++i)
{
if (!name_array_[i].empty())
{
DisableTexture(name_array_[i]);
}
}
}
TextureCubeMap::TextureCubeMap(
const std::array<std::string, 6>& cube_file,
const PixelElementSize pixel_element_size /*= PixelElementSize::BYTE*/,
const PixelStructure pixel_structure /*= PixelStructure::RGB_ALPHA*/) :
Texture(pixel_element_size, pixel_structure)
{
CreateCubeMap();
int i = 0;
for(std::string str : cube_file)
{
sgl::Image img(str, pixel_element_size_, pixel_structure_);
size_ = img.GetSize();
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X+i,
0,
ConvertToGLType(pixel_element_size_, pixel_structure_),
static_cast<GLsizei>(size_.first),
static_cast<GLsizei>(size_.second),
0,
ConvertToGLType(pixel_structure_),
ConvertToGLType(pixel_element_size_),
img.Data());
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
i++;
}
}
void TextureCubeMap::CreateCubeMap()
{
glGenTextures(1, &texture_id_);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
} // End namespace sgl.
| true |
522368d4c03b005eb5c3a30cb4aac8e4f909d789 | C++ | PeterZhouSZ/Boundary_Sampled_Halfspaces | /src/Cone_sImplicit.h | UTF-8 | 4,881 | 2.71875 | 3 | [] | no_license | //
// Created by Charles Du on 10/9/20.
//
#ifndef PSI_CONE_SIMPLICIT_H
#define PSI_CONE_SIMPLICIT_H
#include "Sampled_Implicit.h"
#include <Eigen/Dense>
#include <iostream>
class Cone_sImplicit : public Sampled_Implicit
{
public:
// standard cone
Cone_sImplicit()
: Sampled_Implicit()
, apex(0, 0, 0)
, axis_unit_vector(0, 0, -1)
, apex_angle(M_PI / 4)
, is_flipped(false){};
Cone_sImplicit(const Point &p, const Eigen::Vector3d &v, double a, bool flip)
: Sampled_Implicit()
, apex(p)
, axis_unit_vector(v.normalized())
, apex_angle(fmod(a, M_PI))
, is_flipped(flip){};
~Cone_sImplicit() override = default;
std::string get_type() const override { return "cone"; }
double function_at(const Point &x) const override;
Eigen::Vector3d gradient_at(const Point &x) const override;
void flip() override { is_flipped = !is_flipped; }
bool has_control_points() const override { return true; }
const std::vector<Point> &get_control_points() const override
{
if (m_control_pts.empty()) {
m_control_pts.push_back(apex);
m_control_pts.push_back(apex + m_reference_length * axis_unit_vector);
if (std::abs(axis_unit_vector[1]) < 0.9) {
Point dir =
(Eigen::Vector3d(0, 1, 0).cross(axis_unit_vector.transpose())).transpose();
m_control_pts.push_back(
apex + m_reference_length * (axis_unit_vector + dir * std::sin(apex_angle)));
} else {
Point dir =
(Eigen::Vector3d(0, 0, 1).cross(axis_unit_vector.transpose())).transpose();
m_control_pts.push_back(
apex + m_reference_length * (axis_unit_vector + dir * std::sin(apex_angle)));
}
}
return m_control_pts;
}
void set_control_points(const std::vector<Point> &pts) override
{
if (pts.size() != 3) {
std::cerr << "Cone primitive expects 3 control points";
return;
}
Eigen::Transform<double, 3, Eigen::AffineCompact> transform;
transform.setIdentity();
m_control_pts = pts;
if ((pts[0] - apex).norm() < 1e-6) {
Point dir = (pts[1] - pts[0]).normalized();
if ((dir - axis_unit_vector).norm() < 1e-6) {
dir = pts[2] - pts[0];
apex_angle =
std::atan2(dir.cross(axis_unit_vector).norm(), dir.dot(axis_unit_vector));
} else {
Point axis = axis_unit_vector.cross(dir);
double theta = std::atan2(axis.norm(), axis_unit_vector.dot(dir));
transform.rotate(Eigen::AngleAxis<double>(theta, axis));
axis_unit_vector = dir;
}
} else {
transform.translate(pts[0] - apex);
apex = pts[0];
}
// Reproject samples points
for (auto &p : Sampled_Implicit::sample_points) {
p = transform * p;
Point d = p - apex;
Point q = apex + d.dot(axis_unit_vector) * axis_unit_vector;
double r = (q - apex).norm() * std::tan(apex_angle);
p = q + (p - q).normalized() * r;
}
m_control_pts[1] = apex + m_reference_length * axis_unit_vector;
if (std::abs(axis_unit_vector[1]) < 0.9) {
Point dir = (Eigen::Vector3d(0, 1, 0).cross(axis_unit_vector.transpose())).transpose();
m_control_pts[2] =
apex + m_reference_length * (axis_unit_vector + dir * std::sin(apex_angle));
} else {
Point dir = (Eigen::Vector3d(0, 0, 1).cross(axis_unit_vector.transpose())).transpose();
m_control_pts[2] =
apex + m_reference_length * (axis_unit_vector + dir * std::sin(apex_angle));
}
}
void get_apex(Point &p) const override { p = apex; };
void get_axis_unit_vector(Eigen::Vector3d &vec) const override { vec = axis_unit_vector; };
void get_apex_angle(double &a) const override { a = apex_angle; };
void get_is_flipped(bool &flip) const override { flip = is_flipped; };
bool save(
const std::string &dir, const std::string &name, nlohmann::json &json_obj) const override;
void translate(const Point &t) override
{
Sampled_Implicit::translate(t);
apex += t;
}
private:
// p: cone apex
Point apex;
// v: unit vector along cone axis
Eigen::Vector3d axis_unit_vector;
// a: angle between generatrix and axis vector (range [0,pi))
double apex_angle;
// is_flipped = false: f(x) = cos(a) ||x-p|| - dot(x-p,v)
// is_flipped = true : f(x) = dot(x-p,v) - cos(a) ||x-p||
bool is_flipped;
mutable std::vector<Point> m_control_pts;
};
#endif // PSI_CONE_SIMPLICIT_H
| true |
002be08fcadac9b405cb3070d093ece0494f74a1 | C++ | souzag/training | /456.cpp | UTF-8 | 1,021 | 3.203125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int qtdP, rooms;
string city;
cin >> qtdP >> city >> rooms;
transform(city.begin(), city.end(), city.begin(), ::tolower); //transforma a palavra toda em minusculo
double value = 0;
if(city == "pipa")
{
int passeio = 75 * qtdP;
value += passeio;
if(rooms == 3)
{
value += 900;
}
else
{
value += 600;
}
cout << fixed << setprecision(2) << value << endl;
cout << fixed << setprecision(2) << value/qtdP << endl;
}
else if(city == "fortaleza")
{
int passeio = 60 * qtdP;
value += passeio;
if(rooms == 3)
{
value += 950;
}
else
{
value += 1120;
}
cout << fixed << setprecision(2) << value << endl;
cout << fixed << setprecision(2) << value/qtdP << endl;
}
} | true |
b107a358cd9a5e57433a6986015b49da23c68c07 | C++ | DeclanRussell/WhatTheFlock | /src/openglwidget.cpp | UTF-8 | 2,726 | 2.765625 | 3 | [] | no_license | #include <QGuiApplication>
#include <ngl/NGLInit.h>
#include <ngl/Vec3.h>
#include "openglwidget.h"
#include <iostream>
OpenGLWidget::OpenGLWidget(const QGLFormat _format, QWidget *_parent) : QGLWidget(_format,_parent)
{
// set this widget to have the initial keyboard focus
setFocus();
// re-size the widget to that of the parent (in this case the GLFrame passed in on construction)
this->resize(_parent->size());
}
//----------------------------------------------------------------------------------------------------------------------
OpenGLWidget::~OpenGLWidget(){
//destructor to clear everything
ngl::NGLInit *Init = ngl::NGLInit::instance();
std::cout<<"Shutting down NGL, removing VAO's and Shaders\n";
Init->NGLQuit();
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWidget::initializeGL(){
// we must call this first before any other GL commands to load and link the
// gl commands from the lib, if this is not done program will crash
ngl::NGLInit::instance();
// ngl::NGLInit::instance();
glClearColor(0.4f, 0.4f, 0.7f, 1.0f); // Cyan Background :3
// enable depth testing for drawing
glEnable(GL_DEPTH_TEST);
// enable multisampling for smoother drawing
glEnable(GL_MULTISAMPLE);
// Now we will create a basic Camera from the graphics library
// This is a static camera so it only needs to be set once
// First create Values for the camera position
ngl::Vec3 from(0,0,7);
ngl::Vec3 to(0,0,0);
ngl::Vec3 up(0,1,0);
m_cam= new ngl::Camera(from,to,up);
// set the shape using FOV 45 Aspect Ratio based on Width and Height
// The final two are near and far clipping planes of 0.5 and 10
m_cam->setShape(45,(float)width()/height(),0.5,150);
// create our transform stack
m_transformStack = new ngl::TransformStack();
// as re-size is not explicitly called we need to do this.
glViewport(0,0,width(),height());
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWidget::resizeGL(const int _w, const int _h){
// set the viewport for openGL
glViewport(0,0,_w,_h);
// now set the camera size values as the screen size has changed
m_cam->setShape(45,(float)_w/_h,0.05,350);
}
//----------------------------------------------------------------------------------------------------------------------
void OpenGLWidget::paintGL(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
//----------------------------------------------------------------------------------------------------------------------
| true |
77b9c6759d712c51e3bc57dddb6b2bcfe5c9c5b2 | C++ | kakabori/nfit12.16 | /inc/fileTools.h | UTF-8 | 2,547 | 3.125 | 3 | [] | no_license | #ifndef GUARD_FILETOOLS_H
#define GUARD_FILETOOLS_H
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <assert.h>
#include <stdexcept>
using std::vector; using std::string; using std::ifstream;
using std::getline; using std::istringstream; using std::ofstream;
using std::cout; using std::endl; using std::cerr;
void appendStringToFile(const char *, const std::string&);
void appendStringToFile(const char *, const char *);
void saveDoubleColumns(std::vector<double>&, std::vector<double>&, const char *);
void saveMatrix(std::vector<double>&, std::vector<double>&,
std::vector<double>&, const char *);
void saveMatrix(unsigned int, unsigned int, std::vector<double>&, const char *);
void saveThreeVectorsToFile(std::vector<double>&, std::vector<double>&,
std::vector<double>&, const char *);
void saveAsColumnVectors(std::vector<double>&, std::vector<double>&,
std::vector<double>&, const char *);
void saveAsRowVectors(std::vector<double>&, std::vector<double>&, const char *);
void saveRowVector(std::vector<double>&, const char *);
/******************************************************************************
Read an ASCII formatted matrix into the input 1D vector, vec.
Returns the total number of columns. The total number of rows
can be calculated via vec.size() divided by the function's
returned value.
vec[i*width + j] returns the matrix element in ith row and
jth column
******************************************************************************/
template <class T>
int readMatrixFromFile(const char *filename, vector<T>& vec)
{
T tmp;
string line;
int count = 0, width = 0;
ifstream infile;
infile.open(filename);
if (!infile) {
cerr << filename << ": not found" << endl;
//throw domain_error("ERROR: could not open the file");
}
// Go through the first line and determine the width
getline(infile, line);
istringstream iss(line);
while (iss >> tmp) {
vec.push_back(tmp);
width++;
}
// Go through the rest of the file
while (getline(infile, line)) {
istringstream iss2(line);
count = 0;
while (iss2 >> tmp) {
vec.push_back(tmp);
count++;
}
// Complain if the width is not constant
if (count != width) {
cout << count << " " << width << endl;
cerr << "what the heck!?" << endl;
//throw domain_error("the input file was not formatted correctly");
}
}
return width;
}
#endif
| true |
d699e2d75f90949152ccce8cba3764b4a6b00152 | C++ | magnusl/SwfEngine | /src/glrenderer/vertex_buffer.cpp | UTF-8 | 922 | 2.8125 | 3 | [] | no_license | #include "stdafx.h"
#include "vertex_buffer.h"
#include <GL\glew.h>
namespace ogl
{
/**
* \brief Constructor for oglVertexBuffer
* \param [in] a_VertexData The vertex data.
* \param [in] a_DataSize The size fo the data.
*/
VertexBuffer::VertexBuffer(const void * a_VertexData, size_t a_DataSize, GLenum a_Usage) : _usage(a_Usage)
{
glGenBuffers(1, &_buffer_id);
glBindBuffer(GL_ARRAY_BUFFER, _buffer_id);
glBufferData(GL_ARRAY_BUFFER, a_DataSize, a_VertexData, _usage);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexBuffer::Update(const void * a_VertexData, size_t a_DataSize)
{
glBindBuffer(GL_ARRAY_BUFFER, _buffer_id);
glBufferData(GL_ARRAY_BUFFER, a_DataSize, a_VertexData, _usage);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
/**
* \brief Destructor. Performs the required cleanup.
*/
VertexBuffer::~VertexBuffer()
{
glDeleteBuffers(1, &_buffer_id);
}
} // namespace ogl | true |
f21ffa314f5d58bf1e203e233d30e61aa233cc74 | C++ | Wonki4/coding-practice | /codingStudy/2001_swea.cpp | UTF-8 | 1,106 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int arr[15][15] ={0};
int M, N;
//정사각형내부에 있는 파리의 총 개수를 세어주는 함수
int getArea(int y, int x) {
int area = 0;
for(int i = 0; i<M;i++) {
for(int j = 0; j<M; j++) {
area+=arr[y+i][x+j];
}
}
return area;
}
int main(void) {
ifstream cin;
cin.open("./input.txt");
int iter;
cin>>iter;
//Case만큼 loop를 돈다.
for(int test_case = 1; test_case<=iter; test_case++) {
int max = 0;
int value = 0;
cin>>N>>M;
memset(arr, 0, 15*15*sizeof(int));
for(int i = 0 ;i<N;i++) {
for(int j = 0; j<N; j++) {
cin>>arr[i][j];
}
}
//가로 세로 N-M+1까지 첫꼭지점으로 잡고 쭉 돈다.
for(int i = 0 ;i<N-M+1;i++) {
for(int j = 0; j<N-M+1; j++) {
value = getArea(i, j);
max = max > value ? max : value;
}
}
cout<<"#"<<test_case<<" "<<max<<"\n";
}
} | true |
12b230784c008d2b97c2dfd056e6fce630a14510 | C++ | sudoDavi/cpp-study | /chapter8/Point2d.cpp | UTF-8 | 720 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include <cmath>
class Point2d {
private:
double m_x{};
double m_y{};
public:
Point2d(double x = 0.0, double y = 0.0) : m_x{x}, m_y{y} {}
void print() const {
std::cout << "Point2d(" << m_x << ", " << m_y << ")\n";
}
friend double distanceFrom(const Point2d& point1, const Point2d& point2);
};
double distanceFrom(const Point2d& point1, const Point2d& point2) {
return std::sqrt((point1.m_x - point2.m_x) * (point1.m_x - point2.m_x) + (point1.m_y - point2.m_y) * (point1.m_y - point2.m_y));
}
int main() {
Point2d first{};
Point2d second{ 3.0, 4.0 };
first.print();
second.print();
std::cout << "Distance between two points: " << distanceFrom(first, second) << "\n";
return 0;
}
| true |
18a5706892b960ff722eeade9779ec6408facf22 | C++ | abicorios/MyCppExercises | /c7e19date/c7e19date/c7e19date.cpp | WINDOWS-1251 | 3,131 | 2.671875 | 3 | [
"Unlicense"
] | permissive | // c7e19date.cpp: .
//
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <regex>
using namespace std;
struct Date
{
short day;
short month;
short year;
short wday;
};
int what_day(Date*);
void dprint(Date);
void wdpp(short& wd)
{
short x = (wd++) % 7;
wd = (x == 0) ? 7 : x;
}
void dincr(Date&);
void dincr(Date& d)
{
//dprint(d);
d.wday = what_day(&d);
//dprint(d);
if (d.day >= 1 && d.day <= 27)
{
d.day++;
d.wday = what_day(&d);
return;
}
if (d.day == 28 && d.month != 2)
{
d.day++;
d.wday = what_day(&d);
return;
}
if (((d.year % 4 == 0 && d.year % 100 != 0) || d.year % 400 == 0) && d.day == 28 && d.month == 2)
{
d.day++;
d.wday = what_day(&d);
return;
}
if ((d.year % 4 != 0 || (d.year % 100 == 0 && d.year % 400 != 0))&& d.day == 28 && d.month == 2)
{
d.day = 1;
d.month++;
d.wday = what_day(&d);
return;
}
/*else
{
d.day = 1;
d.month++;
d.wday = what_day(&d);
return;
}*/
if (d.day == 28 && d.month == 2)
{
d.day = 1;
d.month++;
d.wday = what_day(&d);
return;
}
if (d.day == 28 && d.month != 2)
{
d.day++;
d.wday = what_day(&d);
return;
}
if (d.day == 29 && d.month != 2)
{
d.day++;
d.wday = what_day(&d);
return;
}
if (d.day == 29 && d.month == 2)
{
d.day = 1;
d.month++;
d.wday = what_day(&d);
return;
}
if (d.day == 30)
{
switch (d.month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
d.day++;
d.wday = what_day(&d);
//return;
break;
default:
d.day = 1;
d.month++;
d.wday = what_day(&d);
//return;
break;
}
return;
}
if (d.day == 31)
{
if (d.month != 12)
{
d.day = 1;
d.month++;
d.wday = what_day(&d);
return;
}
else
{
d.day = 1;
d.month = 1;
d.year++;
d.wday = what_day(&d);
return;
}
}
}
short s_to_sh(string);
short s_to_sh(string sz)
{
istringstream mybufer;
mybufer.str(sz);
short sh;
mybufer >> sh;
return sh;
}
Date string_to_date(string);
Date string_to_date(string s)
{
smatch sm;
regex_match(s, sm, regex("(\\d{2})\\.(\\d{2})\\.(\\d{4})"));
Date d;
d.day = s_to_sh(sm[1]);
d.month = s_to_sh(sm[2]);
d.year = s_to_sh(sm[3]);
return d;
}
int what_day(Date* date)
{
int a = (14 - date->month) / 12;
int y = date->year - a;
int m = date->month + 12 * a - 2;
return (7000 + (date->day + y + y / 4 - y / 100 + y / 400 + (31 * m) / 12)) % 7;
}
Date find_date_for_next_monday(Date);
Date find_date_for_next_monday(Date d)
{
dprint(d);
dincr(d);
d.wday = what_day(&d);
dprint(d);
while (d.wday != 1)
{
dincr(d);
d.wday = what_day(&d);
dprint(d);
}
return d;
}
void dprint(Date d1)
{
cout << d1.day << '.' << d1.month << '.' << d1.year << " day "<<d1.wday<< '\n';
}
int main()
{
/*Date date = string_to_date("26.07.2017");
cout << what_day(&date)<<'\n';*/
Date d0 = string_to_date("26.07.2017");
d0.wday = what_day(&d0);
Date d1 = find_date_for_next_monday(d0);
dprint(d1);
/*for (int i = 0; i < 10; i++)
{
dincr(date);
dprint(date);
}*/
}
| true |
77d70fc8638e8fd8051adbd9ae5f003184379d78 | C++ | XuChongBo/cxxdemo | /opencv_cxx_to_py_demo/examples.cpp | UTF-8 | 1,916 | 3.109375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <boost/python.hpp>
#include "conversion.h"
namespace py = boost::python;
typedef unsigned char uchar_t;
//http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/python/exposing.html
/**
* Displays an image, passed in from python as an ndarray.
*/
void
display(PyObject *img)
{
NDArrayConverter cvt;
cv::Mat mat { cvt.toMat(img) };
cv::namedWindow("display", CV_WINDOW_NORMAL);
cv::imshow("display", mat);
cv::waitKey(0);
}
/**
* Converts a grayscale image to a bilevel image.
*/
PyObject*
binarize(PyObject *grayImg, short threshold)
{
NDArrayConverter cvt;
cv::Mat img { cvt.toMat(grayImg) };
for (int i = 0; i < img.rows; ++i)
{
uchar_t *ptr = img.ptr<uchar_t>(i);
for (int j = 0; j < img.cols; ++j)
{
ptr[j] = ptr[j] < threshold ? 0 : 255;
}
}
return cvt.toNDArray(img);
}
/**
* Multiplies two ndarrays by first converting them to cv::Mat and returns
* an ndarray containing the result back.
*/
PyObject*
mul(PyObject *left, PyObject *right)
{
NDArrayConverter cvt;
cv::Mat leftMat, rightMat;
leftMat = cvt.toMat(left);
rightMat = cvt.toMat(right);
auto r1 = leftMat.rows, c1 = leftMat.cols, r2 = rightMat.rows,
c2 = rightMat.cols;
// Work only with 2-D matrices that can be legally multiplied.
if (c1 != r2)
{
PyErr_SetString(PyExc_TypeError,
"Incompatible sizes for matrix multiplication.");
py::throw_error_already_set();
}
cv::Mat result = leftMat * rightMat;
PyObject* ret = cvt.toNDArray(result);
return ret;
}
static void init()
{
Py_Initialize();
import_array();
}
BOOST_PYTHON_MODULE(examples)
{
init();
py::def("display", display);
py::def("binarize", binarize);
py::def("mul", mul);
}
| true |
0e289091c6dbd081024e467fdbe0fa1e6c9d3752 | C++ | icepic/bass | /src/functions.cpp | UTF-8 | 3,788 | 2.953125 | 3 | [] | no_license | #include "assembler.h"
#include <cmath>
#include <coreutils/file.h>
static uint8_t translate(uint8_t c)
{
if (c >= 'a' && c <= 'z') return c - 'a' + 1;
if (c >= 'A' && c <= 'Z') return c - 'A' + 0x41;
return c;
}
void initFunctions(Assembler& a)
{
auto& syms = a.getSymbols();
syms.set("Math.Pi", M_PI);
// Allowed data types:
// * Any arithmetic type, but they will always be converted to/from double
// * `std::vector<uint8_t>` for binary data
// * `AnyMap` for returning struct like things
// * `std::vector<std::any> const&` as single argument.
a.registerFunction("sqrt", [](double f) { return std::sqrt(f); });
a.registerFunction("sin", [](double f) { return std::sin(f); });
a.registerFunction("cos", [](double f) { return std::cos(f); });
a.registerFunction("tan", [](double f) { return std::tan(f); });
a.registerFunction("asin", [](double f) { return std::asin(f); });
a.registerFunction("acos", [](double f) { return std::acos(f); });
a.registerFunction("atan", [](double f) { return std::atan(f); });
a.registerFunction("min",
[](double a, double b) { return std::min(a, b); });
a.registerFunction("max",
[](double a, double b) { return std::max(a, b); });
a.registerFunction("pow",
[](double a, double b) { return std::pow(a, b); });
a.registerFunction("len",
[](std::vector<uint8_t> const& v) { return v.size(); });
a.registerFunction("round", [](double a) { return std::round(a); });
a.registerFunction("compare",
[](std::vector<uint8_t> const& v0,
std::vector<uint8_t> const& v1) { return v0 == v1; });
a.registerFunction("load", [&](std::string_view name) {
auto p = utils::path(name);
if (p.is_relative()) {
p = a.getCurrentPath() / p;
}
try {
utils::File f{p};
return f.readAll();
} catch (utils::io_exception&) {
throw parse_error(fmt::format("Could not load {}", name));
}
});
a.registerFunction("word", [](std::vector<uint8_t> const& data) {
Check(data.size() >= 2, "Need at least 2 bytes");
return data[0] | (data[1] << 8);
});
a.registerFunction("big_word", [](std::vector<uint8_t> const& data) {
Check(data.size() >= 2, "Need at least 2 bytes");
return data[1] | (data[0] << 8);
});
a.registerFunction("to_cbm", [](std::vector<uint8_t> const& data) {
std::vector<uint8_t> res;
res.reserve(data.size());
for (auto d : data) {
res.push_back(translate(d));
}
return res;
});
a.registerFunction("zeroes", [](int32_t sz) {
std::vector<uint8_t> res(sz);
std::fill(res.begin(), res.end(), 0);
return res;
});
a.registerFunction("bytes", [](std::vector<std::any> const& args) {
std::vector<uint8_t> res;
res.reserve(args.size());
for (auto const& a : args) {
res.push_back(number<uint8_t>(a));
}
return res;
});
a.registerFunction("to_lower", [](std::string_view sv) {
auto s = std::string(sv);
for (auto& c : s) {
c = tolower(c);
}
return persist(s);
});
a.registerFunction("str", [](double n) {
auto s = std::to_string(static_cast<int64_t>(n));
std::string_view sv = s;
persist(sv);
return sv;
});
a.registerFunction("load_png", [&](std::string_view name) {
auto p = utils::path(name);
if (p.is_relative()) {
p = a.getCurrentPath() / p;
}
return loadPng(p.string());
});
}
| true |
0f5869d11597925d43eeb24ce09a7e5e167a19e7 | C++ | Kirby-Vong/FinalProject | /main.cpp | UTF-8 | 3,354 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include "UserClass.hpp"
#include "Warrior.hpp"
#include "Ranger.hpp"
#include "State.hpp"
#include "UnlockedState.hpp"
#include "LockedState.hpp"
#include "Armors.hpp"
#include "LightArmor.hpp"
#include "HeavyArmor.hpp"
#include "Weapons.hpp"
#include "Melee.hpp"
#include "Ranged.hpp"
#include "Interface.hpp"
#include "ItemOrder.hpp"
#include "HighestAttack.hpp"
#include "HighestDefense.hpp"
int main() {
// return 0;
int userClass;
bool validInput = false;
UserClass* playerClass;
Interface* controlPanel;
std::string myClass = "";
while (validInput == false) {
std::cout << "Enter user Class (Ranger = 1, Warrior = 2) : ";
std::cin >> userClass;
if (userClass == 1) {
myClass = "******* Ranger";
validInput = true;
playerClass = new Ranger();
controlPanel = new Interface(playerClass);
}
else if (userClass == 2) {
myClass = "******* Warrior";
validInput = true;
playerClass = new Warrior();
controlPanel = new Interface(playerClass);
}
else {
std::cout << "invalid class";
validInput = false;
}
}
int opt = 0;
std::string name;
int stat;
while (opt != 7) {
std::cout << std::endl << myClass << " Inventory Menu *******\n 1.Add an armor\n 2.Add a weapon\n 3.Remove an item\n 4.Favorite an item\n 5.Unfavorite an item\n 6.Display\n 7.Close Inventory\nEnter option to select operation:\n";
std::cin >> opt;
switch (opt) { /* menu options*/
case 1:{
std::cout << "Enter armor name :" << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
std::cout << "Enter armor defense stat :" << std::endl;
std::cin >> stat;
controlPanel->AddArmor(stat, name);
break;
}
case 2:{
std::cout << "Enter weapon name :" << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
std::cout << "Enter weapon attack stat :" << std::endl;
std::cin >> stat;
controlPanel->AddWeapon(stat, name);
break;
}
case 3: {
std::cout << " Enter name of item to remove : " << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
controlPanel->remove(name);
break;
}
case 4:{
std::cout << " Enter name of item to favorite :" << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
controlPanel->Favorite(name);
break;
}
case 5:{
std::cout << " Enter name of item to Unfavorite :" << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
controlPanel->Unfavorite(name);
break;
}
case 6:{
bool canDo = false;
while (canDo == false) {
std::cout << " Display order :\n1. Highest -> lowest ATK \n2. Highest -> lowest DEF \n3.Back to Inventory Menu" << std::endl;
int displayOrder;
std::cin >> displayOrder;
if (displayOrder == 1 || displayOrder == 2) {
controlPanel->Display(displayOrder);
canDo = true;
}
else if (displayOrder == 3) {
canDo = true;
}
else {
std::cout << "invalid input" << std::endl;
}
}
break;
}
case 7:{
std::cout << "Closing " << myClass << " Inventory Menu *******" << std::endl;
std::cout << "please give us full credit" << std::endl;
/*return 0;*/
break;
}
default:{
std::cout << "Invalid option" << std::endl;
}
}
}
delete playerClass;
delete controlPanel;
return 0;
}
| true |
0758690c9334f0bc44d854e883daa300898496db | C++ | jt-taylor/42-cpp-piscine | /d03/ex00/main.cpp | UTF-8 | 495 | 2.8125 | 3 | [] | no_license | #include "FragTrap.hpp"
int main(void)
{
FragTrap not_claptrap("'a good name'");
not_claptrap.beRepaired(10);
not_claptrap.takeDamage(10);
not_claptrap.takeDamage(100);
not_claptrap.beRepaired(30);
not_claptrap.beRepaired(3);
for (int i = 0;i < 5;i++)
not_claptrap.vaulthunder_dot_exe("also not claptrap");
std::cout << "\n\n";
FragTrap tmp1(not_claptrap);
tmp1.beRepaired(50);
std::cout << "\n\n";
FragTrap& tmp2 = tmp1;
tmp2.takeDamage(105);
not_claptrap.takeDamage(0);
}
| true |
e3102e8aa4229b12733d33bad770c7ec511cec7e | C++ | nikhilyadv/UVA | /Mathematics/10407 - Simple Division.cpp | UTF-8 | 553 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int gcd(int a , int b){ return b == 0 ? a : gcd(b , a%b);}
int main(){
int a[1001];
while(1){
cin>>a[0];
if(a[0] == 0)
break;
int size =1;
while(1){
cin>>a[size];
if(a[size] == 0)
break;
size++;
}
int ans;
ans = abs(a[1] - a[0]);
for(int i = 2 ; i < size ; i++){
ans = gcd(ans , abs(a[i] - a[i-1]));
}
cout<<ans<<endl;
}
return 0;
}
| true |
a0c5eeb56e44313e04b2c36a975667fd21d0d1b6 | C++ | alexey-roienko/Cpp-courses | /task2_1/Bicycle.cpp | UTF-8 | 6,056 | 3.0625 | 3 | [] | no_license | // Task 2.1 - Realization of Bicycle-class which describes Bicycle entity
// Created by Alexey Roienko, 2017
#include <iostream>
#include <iomanip>
#include "Bicycle.h"
std::array<std::string, static_cast<unsigned int>(BicycleTypes::COUNT)> Bicycle::bTypesDescr{
"Road bicycles are designed for traveling at speed on paved roads.",
"Touring bicycles are designed for bicycle touring and long journeys.",
"Hybrid bicycles are a compromise between the mountain and racing style bicycles which replaced European-style utility bikes in North America in the early 1990s.",
"Mountain bicycles are designed for off-road cycling. All mountain bicycles feature sturdy, highly durable frames and wheels, wide-gauge treaded tires, and cross-wise handlebars to help the rider resist sudden jolts",
"Racing bicycles are designed for speed, and the sport of competitive road racing.",
"BMX bikes are designed for stunts, tricks, and racing on dirt BMX tracks.",
"Cruiser bicycles are heavy framed bicycles designed for comfort, with curved back handlebars, padded seats, and balloon tires."
};
/*
char* Bicycle::bTypesDescr[]={
"Road bicycles are designed for traveling at speed on paved roads.",
"Touring bicycles are designed for bicycle touring and long journeys.",
"Hybrid bicycles are a compromise between the mountain and racing style bicycles which replaced European-style utility bikes in North America in the early 1990s.",
"Mountain bicycles are designed for off-road cycling. All mountain bicycles feature sturdy, highly durable frames and wheels, wide-gauge treaded tires, and cross-wise handlebars to help the rider resist sudden jolts",
"Racing bicycles are designed for speed, and the sport of competitive road racing.",
"BMX bikes are designed for stunts, tricks, and racing on dirt BMX tracks.",
"Cruiser bicycles are heavy framed bicycles designed for comfort, with curved back handlebars, padded seats, and balloon tires."
};
*/
// initialization of class static variable
unsigned int Bicycle::createdBicyclesN = 0;
// implementation of static method
unsigned int Bicycle::getCreatedBicyclesN() {
return Bicycle::createdBicyclesN;
}
// Default constructor
Bicycle::Bicycle() {
frameSize = 19.5;
wheelsDiameter = 26.0;
price = 10'000.0;
createdBicyclesN++;
hasBought = false;
std::cout << "\tDefault constructor is being run..." << std::endl;
}
// Explicit constructor with parameters
Bicycle::Bicycle(const BicycleTypes type_, const BicycleProducers producer_,
const double frameSize_, const double wheelsDiameter_,
const double price_):
type(type_),
producer(producer_),
frameSize(frameSize_),
wheelsDiameter(wheelsDiameter_),
price(price_)
{
createdBicyclesN++;
hasBought = false;
std::cout << "\tExplicit constructor was run..." << std::endl;
}
// Destructor
Bicycle::~Bicycle(){
std::cout << "\tDestructor is being run...\n" << std::endl;
}
// 'Getter' for 'type' field is implemented in header
// 'Setter' for 'type' field
void Bicycle::setType(const BicycleTypes newType){
type = newType;
}
// 'Getter' for 'producer' field is implemented in header
// 'Setter' for 'producer' field
void Bicycle::setProducer(const BicycleProducers newProducer){
producer = newProducer;
}
// 'Getter' for 'frameSize' field is implemented in header
// 'Setter' for 'frameSize' field
void Bicycle::setFrameSize(const double newFrameSize){
frameSize = newFrameSize;
}
// 'Getter' for 'wheelsDiameter' field is implemented in header
// 'Setter' for 'wheelsDiameter' field
void Bicycle::setWheelsDiameter(const double newWheelsDiameter){
wheelsDiameter = newWheelsDiameter;
}
// 'Getter' for 'price' field
double Bicycle::getPrice(){
std::cout << "Object method 'getPrice()' is being run." << std::endl;
return price;
}
// 'Setter' for 'price' field
void Bicycle::setPrice(const double newPrice){
std::cout << "Object method 'setPrice()' is being run." << std::endl;
price = newPrice;
}
// 'Getter' for 'hasBought' field is implemented in header
// 'Setter' for 'hasBought' field
void Bicycle::buyBicycle() {
hasBought = true;
}
// 'toString' object method
std::string Bicycle::toString(){
using namespace std;
string s = "This bicycle is of ";
switch (type){
case BicycleTypes::Road:
s += "Road";
break;
case BicycleTypes::Touring:
s += "Touring";
break;
case BicycleTypes::Hybrid:
s += "Hybrid";
break;
case BicycleTypes::Mountain:
s += "Mountain";
break;
case BicycleTypes::Racing:
s += "Racing";
break;
case BicycleTypes::BMX:
s += "BMX";
break;
case BicycleTypes::Cruiser:
s += "Cruiser";
break;
default:
s += "Unknown";
}
s += " type, produced by ";
switch (producer){
case BicycleProducers::TrekSport:
s += "TrekSport";
break;
case BicycleProducers::Cannondale:
s += "Cannondale";
break;
case BicycleProducers::Bianchi:
s += "Bianchi";
break;
case BicycleProducers::Skott:
s += "Skott";
break;
case BicycleProducers::AIST:
s += "AIST";
break;
case BicycleProducers::GT:
s += "GT";
break;
case BicycleProducers::Mongoose:
s += "Mongoose";
break;
case BicycleProducers::GaryFisher:
s += "GaryFisher";
break;
default:
s += "Unknown";
}
char temp[8];
sprintf(temp, "%.1f", frameSize);
string s1 = string(temp);
s += (",\nhas FrameSize = " + s1 + " inches,\n" + "WheelsDiameter = ");
sprintf(temp, "%.1f", wheelsDiameter);
s1 = string(temp);
s += (s1 + " inches,\n" + "price = ");
sprintf(temp, "%.1f", price);
s1 = string(temp);
s += (s1 + " grn. and " + (hasBought ? "has already bought." : "is free."));
return s;
}
// static method
void Bicycle::infoAboutBicycleType(const BicycleTypes type){
std::cout << bTypesDescr[static_cast<unsigned int>(type)] << std::endl;
}
void setPrice(const double newPrice, Bicycle& obj){
obj.price = newPrice;
std::cout << "Friend function 'setPrice()' is being run." << std::endl;
}
double getPrice(Bicycle& obj) {
std::cout << "Friend function 'getPrice()' is being run." << std::endl;
return obj.price;
}
| true |
5507ec4927d887bb38a8b61c962b2013103a2ea8 | C++ | AsamiSato9/Asami | /PR1/P_20/P_8.cpp | UTF-8 | 347 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a,half1,half2;
cin >> a;
if (a>9999||a<1000) {cout << "fail" << endl;}
else {
half1 = a%100;
half2 = (a-half1)/100;
half2 = (half2%10)*10 + (half2-half2%10)/10;
if (half1==half2) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
| true |
db9e2e1c492e7e026efb8fa280c54c767acceda2 | C++ | MalcevStepan/Snake | /Snake/Delegate.h | UTF-8 | 196 | 2.96875 | 3 | [] | no_license | #pragma once
#include <functional>
template <class T>
class Delegate {
public:
Delegate(std::function<T(T)>& fn) : fn(fn) {}
void invoke(T t) {
fn(t);
}
private:
std::function<T(T)> fn;
};
| true |
b8617027b46128430112388130368c8bca800464 | C++ | KDSBest/service-fabric | /src/prod/src/ServiceModel/ConfigPackageSettingDescription.cpp | UTF-8 | 3,639 | 2.671875 | 3 | [
"MIT"
] | permissive | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
ConfigPackageSettingDescription::ConfigPackageSettingDescription() :
Name(),
SectionName(),
MountPoint(L""),
EnvironmentVariableName(L"")
{
}
bool ConfigPackageSettingDescription::operator == (ConfigPackageSettingDescription const & other) const
{
bool equals = true;
equals = StringUtility::AreEqualCaseInsensitive(this->Name, other.Name);
if (!equals) { return equals; }
equals = StringUtility::AreEqualCaseInsensitive(this->SectionName, other.SectionName);
if (!equals) { return equals; }
equals = StringUtility::AreEqualCaseInsensitive(this->MountPoint, other.MountPoint);
if (!equals) { return equals; }
equals = StringUtility::AreEqualCaseInsensitive(this->EnvironmentVariableName, other.EnvironmentVariableName);
if (!equals) { return equals; }
return equals;
}
bool ConfigPackageSettingDescription::operator != (ConfigPackageSettingDescription const & other) const
{
return !(*this == other);
}
void ConfigPackageSettingDescription::WriteTo(TextWriter & w, FormatOptions const &) const
{
w.Write("ConfigPackageSettingDescription { ");
w.Write("Name = {0}, ", Name);
w.Write("SectionName = {0}", SectionName);
w.Write("MountPoint = {0}", MountPoint);
w.Write("EnvironmentVariableName = {0}", EnvironmentVariableName);
w.Write("}");
}
void ConfigPackageSettingDescription::ReadFromXml(XmlReaderUPtr const & xmlReader)
{
// ensure that we are on <ConfigPackage
xmlReader->StartElement(
*SchemaNames::Element_ConfigPackage,
*SchemaNames::Namespace);
this->Name = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_Name);
this->SectionName = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_SectionName);
if (xmlReader->HasAttribute(*SchemaNames::Attribute_MountPoint))
{
this->MountPoint = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_MountPoint);
}
if (xmlReader->HasAttribute(*SchemaNames::Attribute_EnvironmentVariableName))
{
this->EnvironmentVariableName = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_EnvironmentVariableName);
}
xmlReader->ReadElement();
}
ErrorCode ConfigPackageSettingDescription::WriteToXml(XmlWriterUPtr const & xmlWriter)
{
ErrorCode er = xmlWriter->WriteStartElement(*SchemaNames::Element_ConfigPackage, L"", *SchemaNames::Namespace);
if (!er.IsSuccess())
{
return er;
}
er = xmlWriter->WriteAttribute(*SchemaNames::Attribute_Name, this->Name);
if (!er.IsSuccess())
{
return er;
}
er = xmlWriter->WriteAttribute(*SchemaNames::Attribute_SectionName, this->SectionName);
if (!er.IsSuccess())
{
return er;
}
er = xmlWriter->WriteAttribute(*SchemaNames::Attribute_MountPoint, this->MountPoint);
if (!er.IsSuccess())
{
return er;
}
er = xmlWriter->WriteAttribute(*SchemaNames::Attribute_EnvironmentVariableName, this->EnvironmentVariableName);
if (!er.IsSuccess())
{
return er;
}
return xmlWriter->WriteEndElement();
}
void ConfigPackageSettingDescription::clear()
{
this->Name.clear();
this->SectionName.clear();
this->MountPoint.clear();
this->EnvironmentVariableName.clear();
}
| true |
0542c52d84ebeea00e25ca612677456ece90b6da | C++ | zeta0134/1gam-runner | /arm9/source/state_machine.h | UTF-8 | 2,968 | 3.265625 | 3 | [] | no_license | #ifndef STATE_MACHINE_H_
#define STATE_MACHINE_H_
#include <functional>
#include "drawable_entity.h"
class Game;
template<typename T>
using GuardFunction = std::function<bool(T const&)>;
template<typename T>
using ActionFunction = std::function<void(T &)>;
struct ObjectState {
DrawableEntity* entity = nullptr;
Game* game = nullptr;
int current_node = 0;
int frames_alive = 0;
int frames_at_this_node = 0;
bool dead = false;
};
enum Trigger {
kAlways = 0,
kGuardOnly, // same as always? state logic is run per-frame
kFirstFrame, //ie, framecount for the state == 0
kLastFrame, //framecount for the state == duration - 1
};
struct Node {
const char* name;
bool can_rest;
int begin_edge;
int end_edge;
const char* animation;
int duration;
};
template<typename T>
struct Edge {
Trigger trigger;
GuardFunction<T> guard;
ActionFunction<T> action;
int destination;
};
template <typename T>
class StateMachine {
public:
StateMachine(Node* node_list, Edge<T>* edge_list) {
this->edge_list = edge_list;
this->node_list = node_list;
}
~StateMachine() {};
void RunLogic(T& state) {
auto current_node = node_list[state.current_node];
for (int i = current_node.begin_edge; i <= current_node.end_edge; i++) {
auto edge = edge_list[i];
// Make sure we pass this edge's trigger condition
if (edge.trigger == kAlways or edge.trigger == kGuardOnly or
(edge.trigger == kFirstFrame and state.frames_at_this_node == 0) or
(edge.trigger == kLastFrame and state.frames_at_this_node == current_node.duration - 1)) {
// If this edge has a guard function, only continue if the guard
// passes its condition. If not, always continue.
if (edge.guard == nullptr or edge.guard(state)) {
// this edge will now be traversed! First, if the edge has an
// action, run it (this logic typically sets up the next state)
if (edge.action != nullptr) {
edge.action(state);
}
// update our animation if needed; ie, the new state has animation
// set, and it's not the animation we're already playing
if (node_list[edge.destination].animation != nullptr and
node_list[edge.destination].animation != current_node.animation) {
state.entity->SetAnimation(node_list[edge.destination].animation);
}
// now set our new destination, and reset our counters
state.current_node = edge.destination;
state.frames_at_this_node = 0;
//finally, break out so we stop processing edges
break;
}
}
}
//increment counters, to track actions and lifetimes
state.frames_alive++;
state.frames_at_this_node++;
}
private:
Edge<T>* edge_list;
Node* node_list;
};
#endif // STATE_MACHINE_H_ | true |
64a4b919db10ee70e76b768924e4862cd00d4a4a | C++ | ankitwagadre/My-Competitive-Programming-Code | /hackerrank/Art.cpp | UTF-8 | 693 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
int main() {
ll t;
cin >> t;
while (t--) {
ll n;
cin >> n;
ll a[n];
for(ll i = 0; i < n; i++) {
cin>>a[i];
}
bool possible = false;
ll i = 0;
for (i = 0; i < n - 2;i++)
{
if (a[i] == a[i+1] && a[i] == a[i+2])
{
possible = true;
break;
}
}
if (possible)
cout << "Yes"<<endl;
else
cout << "No" <<endl;
}
return 0;
}
| true |
f0b6cde56c6b6b9a30c7eedf7f8a6d1eb717b42e | C++ | SashaMazurProger/AcademyTasks | /C++ Homeworks/Solutions/17.03.26/4.cpp | UTF-8 | 2,492 | 2.96875 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<iomanip>
#include<string.h>
using namespace std;
struct Auto
{
char Model[20];
char Kolir[20];
char Nomer[9];
};
void Print(Auto a)
{
cout << "\n\tModel:" << a.Model;
cout << "\n\tKolir:" << a.Kolir;
cout << "\n\tNomer:" << a.Nomer;
}
void Print(Auto a[],int size)
{
for (int i = 0; i < size; ++i)
{
if (atoi(a[i].Nomer)==0)
continue;
cout << i + 1 << " avto";
cout << "\n\tModel:" << a[i].Model;
cout << "\n\tKolir:" << a[i].Kolir;
cout << "\n\tNomer:" << a[i].Nomer;
cout << endl;
}
}
void Detali(Auto &a)
{
int key = 1;
do
{
cout << "Vkazhit harakterystyky auto";
cout << "\n\tModel avto";
do
{
gets_s(a.Model);
} while (!isalpha(a.Model[0]));
cout << "\n\tKolir";
do
{
gets_s(a.Kolir);
} while (!isalpha(a.Kolir[0]));
cout << "\n\tNomer";
do
{
gets_s(a.Nomer);
} while (!isdigit(a.Nomer[0]));
Print(a);
cout << "\n\nZberehty?(1-Tak,0-Ni)\n\n";
do
{
cin >> key;
} while (key != 0 && key != 1);
} while (!key);
}
void PoshukN(Auto m[], int size, char s[])
{
int count = 0;
for (int i = 0; i < size; ++i)
{
count = 0;
for (int e = 0; e < strlen(s); ++e)
{
if (m[i].Nomer[e] != s[e])
break;
else
++count;
}
if (count == strlen(s))
{
cout << "\nTakyy nomer maye " << i + 1 << "-te avto";
Print(m[i]);
return;
}
}
cout << "\nAvto z takym nomerom ne znaydeno";
}
int main()
{
char arr[2];
cout <<atoi(arr);
const int size = 10;
char masN[9];
Auto myCar = {};
Auto myCars[size];
int key,nAvto;
cout << "\t\t***Avto***";
do
{
cout << "\n--------------------------"
<< "\n \\\\\\Menu///"
<< "\n1 - Dodaty avto"
<< "\n2 - Druk avto"
<< "\n ***"
<< "\n3 - Redahuvaty avto"
<< "\n4 - Druk vsih avto"
<< "\n5 - Poshuk avto po nomerom"
<<"\n\n0 - Vyhid"
<<"\n--------------------------\n";
do
{
cout << "\nZrobit vash vybir";
cin >> key;
} while (key<0||key>5);
switch (key)
{
case 1:
Detali(myCar);
break;
case 2:
Print(myCar);
break;
case 3:
do
{
cout << "\nVkazhit poryadkovyy nomer avto(<=10)";
cin >> nAvto;
} while (nAvto <= 0 || nAvto > 10);
Detali(myCars[nAvto -1]);
break;
case 4:
Print(myCars, size);
break;
case 5:
cout << "\nVkazhit nomer avto(8 tsyfr)";
do
{
gets_s(masN);
} while (!atoi(masN));
PoshukN(myCars, size, masN);
break;
}
} while (key);
system("pause");
return 0;
}
| true |
c8749928412bb8ed6143445b67ecca5191ae30f2 | C++ | longnguyen1997/adv_comp_photography | /problem_sets/ps1/Image.h | UTF-8 | 5,531 | 3.34375 | 3 | [] | no_license | /* -----------------------------------------------------------------
* File: Image.h
* Created: 2015-08-29
* Updated: 2019-08-10
* -----------------------------------------------------------------
*
* The 6.815/6.865 Image class
*
* ---------------------------------------------------------------*/
#ifndef __IMAGE__H
#define __IMAGE__H
#include <cfloat>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "ImageException.h"
#include "lodepng.h"
class Image {
public:
// Constructor to initialize an image of size width*height*channels
// Input Requirements:
// width : a positive integer (>0) for the image width in pixels
// height : positive integer for the image height in pixels
// if not specified will default to 1
// channels: a value of either 1 or 3 for the image channels
// if not specified will default to 1
// name : string name for the image
Image(int width, int height = 1, int channels = 1,
const std::string &name = "");
// Constructor to create an image from a file.
// The file MUST to be in the PNG format
Image(const std::string &filename);
// Image Class Destructor. Because there is no explicit memory management
// here, this doesn't do anything
~Image();
// Returns the image's name, should you specify one
const std::string &name() const { return image_name; }
// The distance between adjacent values in image_data in a given dimension
// where width is dimension 0, height is dimension 1 and channel is
// dimension 2. The dim input must be a value between 0 and 2
int stride(int dim) const { return stride_[dim]; }
int extent(int dim) const { return dim_values[dim]; } // Size of dimension
int width() const { return dim_values[0]; } // Extent of dimension 0
int height() const { return dim_values[1]; } // Extent of dimension 1
int channels() const { return dim_values[2]; } // Extent of dimension 2
// Write an image to a file.
void write(const std::string &filename) const;
// Write image to Output directory with automatically chosen name
void debug_write() const;
static int debugWriteNumber; // Image number for debug write
// --------- HANDOUT PS01 ------------------------------
// set image pixels to corresponding values (only if channel is valid)
void set_color(float r = 0.0f, float g = 0.0f, float b = 0.0f);
// set the rectangle bounded by [xstart, ystart] -> [xend, yend]
// (inclusive) to specified color
void create_rectangle(int xstart, int ystart, int xend, int yend,
float r = 0.0f, float g = 0.0f, float b = 0.0f);
// create a line segment from [xstart, ystart] to [xend, yend] with
// specified color
void create_line(int xstart, int ystart, int xend, int yend, float r = 0.0f,
float g = 0.0f, float b = 0.0f);
// The total number of elements.
// Should be equal to width()*height()*channels()
// That is, a 200x100x3 image has 60000 pixels not 20000 pixels
long long number_of_elements() const;
// Getters for the pixel values
const float &operator()(int x) const;
const float &operator()(int x, int y) const;
const float &operator()(int x, int y, int z) const;
// Setters for the pixel values.
// A reference to the value in image_data is returned
float &operator()(int x);
float &operator()(int x, int y);
float &operator()(int x, int y, int z);
// ------------------------------------------------------
// The "private" section contains functions and variables that cannot be
// accessed from outside the class.
private:
static unsigned int const DIMS = 3; // Number of dimensions
unsigned int dim_values[DIMS]; // Size of each dimension
unsigned int stride_[DIMS]; // strides
std::string image_name; // Image name (filename if read from file)
// This vector stores the values of the pixels. A vector in C++ is an array
// that manages its own memory
std::vector<float> image_data;
// Helper functions for reading and writing
// Conversion Policy:
// uint8 float
// 0 0.f
// 255 1.f
static float uint8_to_float(const unsigned char &in);
static unsigned char float_to_uint8(const float &in);
// Common code shared between constructors
// This does not allocate the image; it only initializes image metadata -
// image name, width, height, number of channels and number of pixels
void initialize_image_metadata(int w, int h, int c, const std::string &name_);
};
// --------- HANDOUT PS01 ------------------------------
void compareDimensions(const Image &im1, const Image &im2);
// Image/Image element-wise operations
Image operator+(const Image &im1, const Image &im2);
Image operator-(const Image &im1, const Image &im2);
Image operator*(const Image &im1, const Image &im2);
Image operator/(const Image &im1, const Image &im2);
// Image/scalar operations
Image operator+(const Image &im1, const float &c);
Image operator-(const Image &im1, const float &c);
Image operator*(const Image &im1, const float &c);
Image operator/(const Image &im1, const float &c);
// scalar/Image operations
Image operator+(const float &c, const Image &im1);
Image operator-(const float &c, const Image &im1);
Image operator*(const float &c, const Image &im1);
Image operator/(const float &c, const Image &im1);
// ------------------------------------------------------
#endif
| true |
b49d8a5d4040234a1bbe7778e26e18c4a9210bb7 | C++ | jakobfrederikson/Homework | /QuadraticEquation_JakobFrederikson/QuadraticEquation_JakobFrederikson.cpp | UTF-8 | 1,156 | 4.125 | 4 | [] | no_license | #include <iostream>
#include <cmath> // including <cmath> for the future use of sqrt()
using namespace std;
// this program gathers user input to calculate a quadratic equation in C++
int main()
{
float a, b, c, x1, x2; // declaring variables used for quadratic equation
cout << "Enter a, b , c ";
cin >> a >> b >> c; // getting inputs for variables a, b and c
// calculating with the input from the user into variables x1 and x2 with the quadratic equation
x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
// outputting solution of x1 and x2 to the user
// endl; is used to help with readibility
if ((b * b - 4 * a * c) == 0) {
cout << "\n Roots are real and equal" << endl;
cout << "\n x1 = " << x1 << ";" << " x2 = " << x2;
}
else if ((b * b - 4 * a * c) > 0) {
cout << "\n Roots are real and unequal" << endl;
cout << "\n x1 = " << x1 << ";" << " x2 = " << x2;
}
else {
cout << "\nRoots are imaginary";
cout << "\n x1 = nan;" << " x2 = nan";
}
return 0;
} | true |
418dab63fbaa4c36f365f36fb8aa65ac53b9785a | C++ | Louis5499/leetcode-practice | /636/solution.cpp | UTF-8 | 936 | 2.71875 | 3 | [] | no_license | class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
stack<pair<int, int>> stk;
vector<int> output(n, 0);
int beingOccupied = 0;
for (string &log: logs) {
stringstream ss(log);
string temp, temp2, temp3;
getline(ss, temp, ':');
getline(ss, temp2, ':');
getline(ss, temp3, ':');
pair<int, int> item = make_pair(stoi(temp), stoi(temp3));
if (temp2 == "start") {
stk.push(item);
} else {
pair<int, int> lastItem = stk.top(); stk.pop();
int timeOccpuied = item.second - lastItem.second + 1;
output[item.first] += timeOccpuied;
if (!stk.empty()) {
output[stk.top().first] -= timeOccpuied;
}
}
}
return output;
}
}; | true |
65609744dbbf144236a0f18cb8b8a9d025047ae9 | C++ | anil-adepu/OS_lab | /2_fork/perfectno.cpp | UTF-8 | 662 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int isPerfectNumber(int n)
{
int sum = 0;
for(int i=1;i<=n-1;i++)
{
if(n%i==0)
sum += i;
}
if(sum==n)
return 1;
return 0;
}
int main()
{
pid_t pid;
pid = vfork();
int lowerLimit,upperLimit;
if(pid>0)
{
wait(NULL);
printf("Per nos. in the ange %d-%d are:\n",lowerLimit,upperLimit);
for(int i=lowerLimit;i<=upperLimit;i++)
if(isPerfectNumber(i))
printf("%d ",i);
printf("\n");
}
else if(pid==0)
{
printf("Enter LL : ");
scanf("%d",&lowerLimit);
printf("Enter UL : ");
scanf("%d",&upperLimit);
_exit(0);
}
} | true |
716d8db6c6731441e1ecf97c3cabb01fa0167f79 | C++ | Joshua-Joseph/s3cllgLAB | /c++/LAB.C.1/date.cpp | UTF-8 | 4,217 | 3.78125 | 4 | [] | no_license | /* JOSHUA JOSEPH
CSA 43*/
#include <iostream>
using namespace std;
class Date
{
private:
int day, month, year, nxt_day, nxt_month, nxt_year;
bool is_leap_year = false;
public:
void intake()
{
cout << "Enter the day, month and year : ";
cin >> day >> month >> year;
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
is_leap_year = true;
}
void verify_and_calc()
{
string status = "Valid date";
nxt_year = year;
nxt_month = month;
nxt_day = day;
if ((day < 0) || (month < 0) || (year < 0) || (day > 31) || (month > 12))
status = "Invalid date";
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
if (day > 31)
status = "Invalid date";
else
{
if (day < 31)
nxt_day += 1;
else
{
nxt_day = 1;
nxt_month += 1;
}
}
break;
case 4:
case 6:
case 9:
case 11:
if (day > 30)
status = "Invalid date";
else
{
if (day < 30)
nxt_day += 1;
else
{
nxt_day = 1;
nxt_month = 5;
}
}
break;
case 2:
if ((is_leap_year) && (day > 29)) // leap year check
status = "Invalid date";
else if ((day > 28) && (!is_leap_year)) // non-leap year check
status = "Invalid date";
else
{
if ((day < 29) && (is_leap_year))
nxt_day += 1;
else if ((day < 28) && (!is_leap_year))
nxt_day += 1;
else
{
nxt_day = 1;
nxt_month = 3;
}
}
break;
case 12:
if (day > 31)
status = "Invalid date";
else
{
if (day < 31)
nxt_day += 1;
else
{
nxt_day = 1;
nxt_month += 1;
nxt_year += 1;
}
}
break;
default:
break;
}
cout << "\n" << status << "\n";
if ( status == "Invalid date" )
exit(0);
else
{
cout << "Input date : " << day << " / " << month << " / " << year << "\n";
cout << "Next date : " << nxt_day << " / " << nxt_month << " / " << nxt_year << "\n";
}
}
};
int main()
{
Date d;
d.intake();
d.verify_and_calc();
return 0;
}
/* SAMPLE OUTPUT
Enter the day, month and year : 5
4
1978
Valid date
Input date : 5 / 4 / 1978
Next date : 6 / 4 / 1978
joshua@Joshuas-Air c++ % ./a.out
Enter the day, month and year : 29
2
1700
Invalid date
joshua@Joshuas-Air c++ % ./a.out
Enter the day, month and year : 29
2
2000
Valid date
Input date : 29 / 2 / 2000
Next date : 1 / 3 / 2000*/
| true |
8ba3540c2192882dcc78b8d27a99e2cf03a5e009 | C++ | willis7/Programming-Tutorials | /C++/Classes/Point_Class.h | UTF-8 | 1,718 | 3.796875 | 4 | [] | no_license | #ifndef POINT_CLASS_H
#define POINT_CLASS_H
/* Welcome to the wonder world of classes and encapsulation. What makes C++ different
(and better) is the ability to encapsulate data. When programming in C the general flow of
a program is this:
-- Make structures/variables, write functions to do stuff with them
But in C++ land the general program flow is this:
-- Create functional objects that can interact to do stuff
So all encapsulation is, is grouping data and the functions that manipulate the data
in one "object"
An object can be thought of as a struct in C world -- But, you have the ability to call
functions from the struct
Yeah I know as I'm reading this I'm like, "This doesn't make any sense" so what I'm going to do
is a program that defines a Cartesian Point (X,Y) and has one operation "Swap" which changes
the X and Y -- So if had a point (X1,Y1) after calling "Swap" on it the point would equal (Y1,X1)
Also for every step of the program I'm going to put the "equivalent" (what we would HAVE to do in C land)
below each major code section
*/
class CPOINT // Cartesian Point
{
public: // For the time being don't worry about this -- JUST KNOW (for this example)
// it HAS to be there
int x;
int y;
void Swap(); // Looks a lot like a function (and really it is) but "functions" that
// are inside of classes are referred to as "methods"
};
/* In C world we'd need first a struct -- Then a function to do the swapping
typedef struct _CPOINT
{
int x;
int y;
} CPOINT;
void Swap(CPOINT *point); // Since we want to swap x and y we HAVE to pass in a pointer
// to the function Swap() to accomplish this */
// Well let's move onto the coding portion...
#endif | true |
9aa5ce18c5c87dbe56431273cb81d27a022eb569 | C++ | sneakfax/AlgoProgAbgabe | /src/ImageConverter.cpp | UTF-8 | 4,405 | 3.1875 | 3 | [] | no_license | /*INFO: This class is resposible for two image-transformation operations:
* rgb to grayscale and changing of the brightness.
*
* */
#include <cstdio>
#include <iostream>
#include <omp.h>
#include "opencv2/opencv.hpp"
class ImageConverter {
private:
cv::Mat image;
double lastOperationTime;
bool assemblyEnabled;
int numberOfThreads;
public:
void setNumberOfThreads(int numOfThreads)
{
numberOfThreads = numOfThreads;
omp_set_dynamic(0); // garantees the right number of threads
omp_set_num_threads(numberOfThreads);
}
void setAssemblyExecution(bool enabled)
{
assemblyEnabled = enabled;
}
ImageConverter(std::string pathImage)
{
assemblyEnabled = true;
image = cv::imread(pathImage, cv::IMREAD_UNCHANGED);
}
double getDurationOfLastOperation()
{
return lastOperationTime;
}
static uchar sadd(uchar a, uchar b)
{
return (a > 0xFF - b) ? 0xFF : a + b;
}
void rgbToGrayscale()
{
double startTime = omp_get_wtime();
int rows = image.rows;
int cols = image.cols;
int channels = image.channels();
uchar* ptr = image.data;
// which version should be executed - asm or c++:
if (!assemblyEnabled) {
#pragma omp parallel for
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
uchar* pixel = ptr + channels * (i * cols + j);
uchar b = *(pixel + 0);
uchar g = *(pixel + 1);
uchar r = *(pixel + 2);
double grayscale = 0.21 * r + 0.72 * g + 0.07 * b;
pixel[0] = grayscale;
pixel[1] = grayscale;
pixel[2] = grayscale;
}
}
} else {
#pragma omp parallel for
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
uchar* pixel = ptr + channels * (i * cols + j);
__asm {
mov rcx, pixel
mov eax, [rcx]
shr al, 4
shr ah, 1
add al, ah
shr ah, 1
add ah, al
shr eax, 8
shr ah, 2
add al, ah
jnc label
mov al, 255
label:
mov [rcx], al
mov [rcx+1], al
mov [rcx+2], al
}
}
}
}
double endTime = omp_get_wtime();
lastOperationTime = endTime - startTime;
}
void changeBrightness(uchar brightness)
{
double startTime = omp_get_wtime();
int rows = image.rows;
int cols = image.cols;
int channels = image.channels();
uchar* ptr = image.data;
// which version should be executed - asm or c++:
if (!assemblyEnabled) {
#pragma omp parallel for
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
uchar* pixel = ptr + channels * (i * cols + j);
uchar b = *(pixel + 0);
uchar g = *(pixel + 1);
uchar r = *(pixel + 2);
pixel[0] = sadd(b, brightness);
pixel[1] = sadd(g, brightness);
pixel[2] = sadd(r, brightness);
}
}
} else {
uchar brightnessArr[4] = { brightness, brightness, brightness, 0 };
#pragma omp parallel for
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
uchar* pixel = ptr + channels * (i * cols + j);
__asm {
mov rcx, pixel
movd mm1, [rcx]
movd mm0, brightnessArr
paddusb mm1, mm0
movd [rcx], mm1
}
}
}
}
double endTime = omp_get_wtime();
lastOperationTime = endTime - startTime;
}
cv::Mat getImage()
{
return image;
}
};
| true |
e12aae9c259dcc1123804f827c61ca6d86cb14e1 | C++ | kaabimg/opengl-demos | /lighting/ex_fog/fogscene.cpp | UTF-8 | 2,254 | 2.6875 | 3 | [] | no_license | #include "fogscene.h"
#include "torus.h"
#include <math.h>
FogScene::FogScene()
: CameraScene(),
m_modelMatrix(),
m_torus( 0 )
{
m_modelMatrix.setToIdentity();
// Initialize the camera position and orientation
m_camera->setPosition( QVector3D( 5.0f, 0.0f, 5.0f ) );
m_camera->setViewCenter( QVector3D( 3.0f, 0.0f, 0.0f ) );
m_camera->setUpVector( QVector3D( 0.0f, 1.0f, 0.0f ) );
}
void FogScene::initialise()
{
// Create a material
MaterialPtr material( new Material );
material->setShaders( ":/shaders/fog.vert", ":/shaders/fog.frag" );
// Create a torus (hmmm doughnuts)
m_torus = new Torus;
m_torus->setRings( 30 );
m_torus->setSides( 25 );
m_torus->setMinorRadius( 0.5f );
m_torus->setMaterial( material );
m_torus->create();
// Enable depth testing
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );
}
void FogScene::update(float t)
{
Q_UNUSED(t);
}
void FogScene::render()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
QOpenGLShaderProgramPtr shader = m_torus->material()->shader();
shader->bind();
// Set the fog parameters
shader->setUniformValue( "fog.color", QVector3D( 1.0f, 1.0f, 1.0f ) );
shader->setUniformValue( "fog.minDistance", 10.0f );
shader->setUniformValue( "fog.maxDistance", 50.0f );
// Set the lighting parameters
shader->setUniformValue( "light.position", QVector4D( 0.0f, 0.0f, 0.0f, 1.0f ) );
shader->setUniformValue( "light.intensity", QVector3D( 0.8f, 0.8f, 0.8f ) );
// Set the material properties
shader->setUniformValue( "material.kd", QVector3D( 0.9f, 0.5f, 0.3f ) );
shader->setUniformValue( "material.ks", QVector3D( 0.5f, 0.5f, 0.5f ) );
shader->setUniformValue( "material.ka", QVector3D( 0.2f, 0.2f, 0.2f ) );
shader->setUniformValue( "material.shininess", 10.0f );
// Draw torus
for ( int i = 0; i < 10; ++i )
{
// Calculate needed matrices
m_modelMatrix.setToIdentity();
m_modelMatrix.translate( 0.0f, 0.0f, -4.0f * float( i ) );
m_camera->setStandardUniforms( shader, m_modelMatrix );
// Draw torus
m_torus->render();
}
}
| true |
4a67fc9aa36856fdcbbf8b7da7be6dae23a6cef8 | C++ | xianjimli/Elastos | /Elastos/Framework/Droid/eco/src/core/widget/RadioButton.cpp | UTF-8 | 794 | 2.640625 | 3 | [] | no_license |
#include "widget/RadioButton.h"
RadioButton::RadioButton()
{}
RadioButton::RadioButton(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs,
/* [in] */ Int32 defStyle)
: CompoundButton(context, attrs, defStyle)
{}
/**
* {@inheritDoc}
* <p>
* If the radio button is already checked, this method will not toggle the radio button.
*/
ECode RadioButton::Toggle()
{
// we override to prevent toggle when the radio is already
// checked (as opposed to check boxes widgets)
if (!IsChecked()) {
return CompoundButton::Toggle();
}
return NOERROR;
}
ECode RadioButton::Init(
/* [in] */ IContext* context,
/* [in] */ IAttributeSet* attrs,
/* [in] */ Int32 defStyle)
{
return CompoundButton::Init(context, attrs, defStyle);
}
| true |
01de56f64d381f8ed8254cca3662341fb4e47c76 | C++ | DylanDeWaele/DAudioVisualizer | /DDWChannel.h | UTF-8 | 315 | 2.515625 | 3 | [] | no_license | #pragma once
class DDWSound;
class DDWChannel
{
public:
DDWChannel();
void WriteSoundData(signed short* pData, int count);
void Play(DDWSound* pSound);
void Stop();
void SetVolume(float volume);
bool IsFree() const;
private:
DDWSound* m_pCurrentSound;
unsigned int m_Position;
float m_Volume;
};
| true |
76eceb40c3f5c434d2f5142d92d85210560c1edf | C++ | zhaozf13/MyCppTemplete | /AddMinusMutiDivideByBit/AddMinusMutiDivideByBit.cpp | UTF-8 | 2,308 | 3.75 | 4 | [] | no_license | // AddMinusMutiDivideByBit.cpp :
// 用位运算实现加减乘除,但用户要保证给的数字不能超出范围
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
//加法
int addByBit(int a, int b) {
int sum = a;
while (b != 0) {
sum = a ^ b; //无进位相加
b = (a & b) << 1; //进位结果
a = sum;
}
return sum;
}
//取相反数,x=~x+1
int negNum(int n) {
return addByBit(~n, 1);
}
//减法
int minusByBit(int a, int b) {
return addByBit(a, negNum(b));
}
//乘法
int multiByBit(int a, int b) {
int res = 0;
unsigned int temp_unsign = b;
while (temp_unsign != 0) {
if ((temp_unsign & 1) != 0) {
res = addByBit(res, a);
}
a <<= 1;
temp_unsign >>= 1; //这一步要无符号右移,即前面要补0,C++中没有无符号右移,所以要先转换成无符号数再右移
}
return res;
}
//判断是否是负数
bool isNeg(int n) {
return n < 0;
}
//除法
int divByBit(int a, int b) {
int x = isNeg(a) ? negNum(a) : a;
int y = isNeg(b) ? negNum(b) : b;
int res = 0;
for (int i = 31; i > -1; i = minusByBit(i, 1)) {
if ((x >> i) >= y) { //x依次右移,当>=y时说明该位为1,然后要减去y,继续右移
res |= (1 << i);
x = minusByBit(x, y << i);
}
}
return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
}
int divideByBit(int a, int b) {
try {
if (b == 0) {
throw "divisor is zero";
}
if (a == INT_MIN && b == INT_MIN) {
return 1;
}
else if (b == INT_MIN) {
return 0;
}
else if (a == INT_MIN) {
int res = divByBit(addByBit(a, 1), b);
return addByBit(res, divByBit(minusByBit(a, multiByBit(res, b)), b));
}
else {
return divByBit(a, b);
}
}
catch (char* e) {
//cout << e << endl;
printf("%s", e);
}
}
int main()
{
int a = INT_MIN;
int b = 1;
cout << addByBit(a, b) << endl;
cout << minusByBit(a, b) << endl;
cout << multiByBit(a, b) << endl;
cout << divideByBit(a, b) << endl;
//cout << a / b << endl;
return 0;
}
| true |
c644fdca80e78b94306d7f315d8cc8a7a85af752 | C++ | jakorten/softrobotics | /Small/PumpValveTestLEDs/PumpValveTestLEDs.ino | UTF-8 | 1,175 | 2.515625 | 3 | [] | no_license | /*
RobotPatient Simulators BV
Test for Breath Circuit
*/
#define PumpA 6 // PA20
#define PumpB 7 // PA21
#define ValveA 2 // PA14
#define ValveB 5 // PA15
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(PumpA, OUTPUT);
pinMode(PumpB, OUTPUT);
pinMode(ValveA, OUTPUT);
pinMode(ValveB, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
blinkLeds();
}
void ledsOn() {
digitalWrite(PumpA, HIGH);
digitalWrite(PumpB, HIGH);
digitalWrite(ValveA, HIGH);
digitalWrite(ValveB, HIGH);
}
void blinkLeds() {
digitalWrite(ValveA, HIGH);
digitalWrite(ValveB, LOW);
digitalWrite(PumpA, LOW);
digitalWrite(PumpB, LOW);
delay(100);
digitalWrite(ValveA, LOW);
digitalWrite(ValveB, HIGH);
digitalWrite(PumpA, LOW);
digitalWrite(PumpB, LOW);
delay(100);
digitalWrite(ValveA, LOW);
digitalWrite(ValveB, LOW);
digitalWrite(PumpA, HIGH);
digitalWrite(PumpB, LOW);
delay(100);
digitalWrite(ValveA, LOW);
digitalWrite(ValveB, LOW);
digitalWrite(PumpA, LOW);
digitalWrite(PumpB, HIGH);
delay(100);
}
| true |
3649be44e36e00cd05ba32b857b9dca342ac3163 | C++ | kmoerman/pqvm | /tests/control-z.cpp | UTF-8 | 3,931 | 2.5625 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "../performance.h"
#include "../quantum/quantum.h"
#include "../options.h"
using namespace quantum;
/*
* The the performance of the Z operator
* options:
* q number of qubits
* r number of iterations (set high to overcome init times)
* i select quantum backend implementation
* f output filename
* t target qubit number
* c control qubit number
* v verbose output
* g grainsize
* s random seed, to obtain same results twice
* o display the statevector (before and after) output on screen
* p explicitly set the number of threads
*/
int main (int argc, char** argv) {
//default options
int num_qubits = 20; //q
int num_repeat = 1; //r
std::string imp = "tbb_blk"; //i
std::string file = "control-z-speedup.data"; //f
bool measure = false; //f
size_type target = 10; //t
size_type control = 15; //c
bool verbose = false; //v
set_grainsize (512); //g
uint seed = (uint)time(NULL); //s
bool output = false; //o
//get options
int option;
while ((option = getopt (argc, argv, "q:r:i:f:p:t:c:vg:s:o")) != -1) {
switch (option) {
case 'q':
num_qubits = parseopt<int>();
break;
case 'r':
num_repeat = parseopt<int>();
break;
case 'i':
imp = parseopt<std::string>();
break;
case 'f':
measure = true;
file = parseopt<std::string>();
break;
case 'p':
performance::set_threads(parseopt<int>());
break;
case 't':
target = parseopt<size_type>();
break;
case 'c':
control = parseopt<size_type>();
break;
case 'v':
verbose = true;
break;
case 'g':
set_grainsize(parseopt<size_type>());
break;
case 's':
seed = parseopt<uint>();
break;
case 'o':
output = true;
break;
}
}
/*
* Initialize random state
* use a seed for repeatable results.
*/
srand(seed);
implementation(imp);
size_type size = 1 << num_qubits;
quregister a (1 << num_qubits),
b;
for (iterator i (a.begin()); i < a.end(); ++i) {
*i = complex ((rand() % 100) / 100.0, (rand() % 100) / 100.0);
}
/*
* initilaize the performance counters
*/
performance::init();
if (verbose) {
std::cout
<< "Running control-z on "
<< num_qubits << " qubits, target qubit "
<< target << std::endl
<< "control qubit "
<< control << std::endl
<< "State vector contains "
<< size << " amplitudes, "
<< ((double)(size* sizeof(complex)) / (1024*1024))
<< "MiB" << std::endl;
}
/*
* Either measure the speedup (if output file is give)
* Of just execute th operator (for external measurements with PERF
* or correctness testing.
*/
if (measure) {
if (imp != "seq" && imp != "omp")
measure_parallel (file, num_repeat, verbose)
controlled_z(control, target, a, b);
else
measure_sequential (file, num_repeat, verbose)
controlled_z(control, target, a, b);
}
else {
if (output) print(a);
for (int i = 1;num_repeat > 0; --num_repeat) {
if (verbose) std::cout << "iteration " << i++ << std::endl;
controlled_z(control, target, a, b);
}
if (output) {if (imp == "tbb_blk") print(a); else print(b);}
}
return 0;
} | true |
1de471c6a8a7dbbbab8773bdc4b2cdf4cb604158 | C++ | ttune/dayz_0-45-124252 | /extern/SimulWeather/Simul/Math/SimVector.h | UTF-8 | 14,231 | 2.625 | 3 | [] | no_license | #ifndef SimVectorH
#define SimVectorH
#include <stdlib.h>
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include "DebugNew.h" // Enable Visual Studio's memory debugging
#endif
#include <float.h>
#if !defined(DOXYGEN) && !defined(__GNUC__)
#define ALIGN16 _declspec(align(16))
#else
#define ALIGN16
#endif
#include "Simul/Math/Export.h"
#include "Simul/Math/Matrix.h"
#include "Simul/Math/Matrix4x4.h"
#include "Simul/Math/MathFunctions.h"
#include <iostream>
namespace simul
{
namespace math
{
class Vector3;
class Quaternion;
/// A resizeable vector class
SIMUL_MATH_EXPORT_CLASS Vector
{
protected:
float *Values;
public:
unsigned size;
unsigned S16;
protected:
float *V;
public:
Vector(void);
Vector(unsigned psize);
Vector(const float *x);
Vector(float x1,float x2,float x3);
Vector(const Vector &v);
virtual ~Vector(void);
void ClearMemory(void); ///< Resize to zero and free the memory which was used.
float *FloatPointer(void) const
{
return Values;
}
float *FloatPointer(unsigned idx) const
{
return &(Values[idx]);
}
/// Multiply this vector by a scalar
virtual void operator*=(float f); ///< Multiply by f.
bool operator>(float R) const;
/// Set all values to zero.
void Zero(void); ///< Set all values to zero.
bool ContainsNAN(void); ///< Is any value not a number?
void Clear(void)
{
size=0;
}
/// Remove the value at Idx, shift the remainder down one place.
void Cut(unsigned Idx); ///< Remove the value at Idx, shifting values after it back one place.
void CutUnordered(unsigned Idx);
/// Insert a value at Idx.
void Insert(unsigned Idx); ///< Insert a value at Idx, shifting succeeding values up one place.
void Append(float s); ///< Increase vector size by one, putting s on the end.
void CheckEdges(void) const;
bool NonZero(void);
/// Scale the vector so its magnitude is unity.
bool Unit(void); ///< Divide by the vector's magnitude.
void CheckNAN(void);
/// Change the vector size.
virtual void Resize(unsigned s); ///< Resize the vector, allocating memory if s>size.
protected:
void ChangeSize(unsigned s);
public:
class BadSize{};
class BadNumber{};
/// The float at position given by index.
inline float &operator() (unsigned index)
{
#ifdef CHECK_MATRIX_BOUNDS
if(index>=size)
{
unsigned errorhere=0;
errorhere++;
errorhere;
throw BadSize();
}
#endif
return Values[index];
}
/// The float at position given by index.
inline float operator() (unsigned index) const
{
#ifdef CHECK_MATRIX_BOUNDS
if(index>=size)
{
unsigned errorhere=0;
errorhere++;
errorhere;
throw BadSize();
}
#endif
// CheckEdges();
return Values[index];
}
float *Position(unsigned index) const;
friend void SIMUL_MATH_EXPORT_FN CrossProduct(Matrix &result,const Vector &v1,const Matrix &M2);
friend void SIMUL_MATH_EXPORT_FN CrossProductWithTranspose(Matrix &result,const Vector &V1,const Matrix &M2);
friend void SIMUL_MATH_EXPORT_FN Multiply(Vector &ret,const Quaternion &q,const Vector &v);
friend void SIMUL_MATH_EXPORT_FN MultiplyElements8(Vector &ret,const Vector &V1,const Vector &V2);
friend void SIMUL_MATH_EXPORT_FN MultiplyElements(Vector &ret,const Vector &V1,const Vector &V2);
friend void SIMUL_MATH_EXPORT_FN MultiplyElementsAndAdd(Vector &ret,const Vector &V1,const Vector &V2);
friend void SIMUL_MATH_EXPORT_FN AddQuaternionTimesVector(Vector &ret,const Quaternion &q,const Vector &v);
friend void SIMUL_MATH_EXPORT_FN Divide(Vector &ret,const Quaternion &q,const Vector &v);
friend void SIMUL_MATH_EXPORT_FN Multiply(Vector &V2,const Matrix &M,const Vector &V1);
friend void SIMUL_MATH_EXPORT_FN MultiplyNegative(Vector &V2,const Matrix &M,const Vector &V1);
friend void SIMUL_MATH_EXPORT_FN MultiplyVectorByTranspose(Vector &result,const Vector &v,const Matrix &M);
friend void SIMUL_MATH_EXPORT_FN Multiply(Vector &v2,const Vector &v1,const Matrix &m);
friend void SIMUL_MATH_EXPORT_FN MultiplyTransposeAndSubtract(Vector &v2,const Vector &v1,const Matrix &m);
friend void SIMUL_MATH_EXPORT_FN MultiplyAndAdd(Vector &v2,const Matrix &m,const Vector &v1);
friend void SIMUL_MATH_EXPORT_FN MultiplyAndSubtract(Vector &v2,const Vector &v1,const Matrix &m);
friend void SIMUL_MATH_EXPORT_FN TransposeMultiply(Vector &v2,const Matrix &m,const Vector &v1);
friend void SIMUL_MATH_EXPORT_FN TransposeMultiplyAndAdd(Vector &v2,const Matrix &m,const Vector &v1);
friend void SIMUL_MATH_EXPORT_FN TransposeMultiplyAndSubtract(Vector &v2,const Matrix &m,const Vector &v1);
friend void SIMUL_MATH_EXPORT_FN AddFloatTimesVector(Vector &V2,const float f,const Vector &V1);
friend void SIMUL_MATH_EXPORT_FN AddFloatTimesLargerVector(Vector &V2,const float f,const Vector &V1);
friend void SIMUL_MATH_EXPORT_FN SubtractFloatTimesVector(Vector &V2,const float f,const Vector &V1);
friend void SIMUL_MATH_EXPORT_FN Multiply(Vector &V2,const float f,const Vector &V1);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertVectorTimesMatrix(const Vector &V,const Matrix &M,unsigned Row,unsigned Col);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertVectorTimesSubMatrix(const Vector &V,const Matrix &M,unsigned Row,unsigned Col,unsigned Width);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertAddVectorTimesSubMatrix(const Vector &V,const Matrix &M,const unsigned Row,const unsigned Col,const unsigned Width);
friend void SIMUL_MATH_EXPORT_FN MultiplyAndSubtract(Matrix &m,const Matrix &m1,const Matrix &m2);
friend void SIMUL_MATH_EXPORT_FN MultiplyNegative(Vector &result,const Vector &v,const Matrix &m);
friend void SIMUL_MATH_EXPORT_FN RowToVector(const Matrix &M,Vector &V,unsigned Row);
friend void SIMUL_MATH_EXPORT_FN ColumnToVector(Matrix &M,Vector &V,unsigned Col);
friend void SIMUL_MATH_EXPORT_FN Swap(Vector &V1,Vector &V2);
friend bool SIMUL_MATH_EXPORT_FN operator==(Vector &v1,Vector &v2);
friend bool SIMUL_MATH_EXPORT_FN operator!=(Vector &v1,Vector &v2);
friend void SIMUL_MATH_EXPORT_FN Matrix::RowMatrix(Vector& v);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertAddVectorTimesMatrix(const Vector &V,const Matrix &M,unsigned Row,unsigned Col);
friend float SIMUL_MATH_EXPORT_FN MultiplyRows(Matrix &M,unsigned R1,unsigned R2);
friend void SIMUL_MATH_EXPORT_FN Multiply(Matrix &M,const Vector &V1,const Matrix &M2,unsigned Column);
friend void SIMUL_MATH_EXPORT_FN ShiftElement(Vector &V1,Vector &V2,unsigned Idx2);
friend SIMUL_MATH_EXPORT class Matrix;
friend SIMUL_MATH_EXPORT class Quaternion;
friend void SIMUL_MATH_EXPORT_FN TransposeMultiply3x3(Vector &V2,const Matrix4x4 &M,const Vector &V1);
// Divide this vector by a scalar
void operator/=(float f);
float & operator [] (unsigned index);
float operator [] (unsigned index) const;
float * operator! (void);
float Magnitude(void) const;
float SquareSize(void) const;
// Assignment operator - copy constr should do the work???
virtual void operator=(const Vector &v);
void operator=(const Vector3 &v);
void operator=(const float *f);
// Assign a vector which we KNOW is the same size!
void operator|=(const Vector &v);
// Unary operators
Vector operator+()
{
return *this;
}
Vector operator-();
void operator+=(const Vector &v);
void operator+=(const Vector3 &v);
void operator-=(const Vector3 &v);
Vector& operator-= (const Vector &v);
void AddLarger(const Vector &v);
// Vector times matrix functions
Matrix operator^(const Matrix &m);
Vector operator*(const Matrix &m);
// Sub-vector operations;
Vector SubVector(unsigned start,unsigned length) const;
void SubVector(Vector &v,unsigned start,unsigned length) const
{
register unsigned i;
for(i=0;i<length;++i)
{
v.Values[i]=Values[start+i];
}
}
void SubVector(Vector3 &v,unsigned start) const;
Vector RemoveElement(unsigned index)
{
Vector v(size-(unsigned)1);
register unsigned i;
for(i=0;i<size-1;++i)
v.Values[i]=Values[i+(i>=index)];
return v;
}
void Insert(const Vector &v,unsigned pos);
void Insert(const Vector3 &v,unsigned pos);
void InsertSubVector(const Vector &v,unsigned InsertPos,unsigned SourcePos,unsigned Length)
{
#ifdef CHECK_MATRIX_BOUNDS
if(InsertPos+Length>size||SourcePos+Length>v.size)
throw BadSize();
#endif
register unsigned i;
for(i=0;i<Length;++i)
{
Values[InsertPos+i]=v.Values[SourcePos+i];
}
}
void InsertAddSubVector(const Vector &v,unsigned InsertPos,unsigned SourcePos,unsigned Length)
{
#ifdef CHECK_MATRIX_BOUNDS
if(InsertPos+Length>size||SourcePos+Length>v.size)
throw BadSize();
#endif
register unsigned i;
for(i=0;i<Length;++i)
{
Values[InsertPos+i]+=v.Values[SourcePos+i];
}
}
void InsertAdd(const Vector &v,unsigned pos)
{
#ifdef CHECK_MATRIX_BOUNDS
if(pos+v.size>size)
throw BadSize();
#endif
register unsigned i;
for(i=0;i<v.size;++i)
{
Values[pos+i]+=v[i];
}
}
void InsertAdd(const Vector3 &v,unsigned pos);
/// Return the dot product of v1 and v2.
friend float SIMUL_MATH_EXPORT_FN operator*(const Vector &v1,const Vector &v2);
friend float SIMUL_MATH_EXPORT_FN operator*(const Vector3 &v1,const Vector &v2);
friend bool SIMUL_MATH_EXPORT_FN DotProductTestGE(const Vector &v1,const Vector &v2,float f); // is DP greater than f?
// Logical operators
friend bool SIMUL_MATH_EXPORT_FN operator == (const Vector &v1,const Vector &v2);
friend bool SIMUL_MATH_EXPORT_FN operator != (const Vector &v1,const Vector &v2);
// Calculation operators
friend Vector SIMUL_MATH_EXPORT_FN operator+(const Vector &v1,const Vector &v2); ///< Return v1+v2.
friend Vector SIMUL_MATH_EXPORT_FN operator-(const Vector &v1,const Vector &v2); ///< Return v1-v2.
friend Vector SIMUL_MATH_EXPORT_FN operator*(float d,const Vector &v2); ///< Return d times v2.
friend Vector SIMUL_MATH_EXPORT_FN operator*(const Vector &v1,float d); ///< Return d times v1.
friend Vector SIMUL_MATH_EXPORT_FN operator/(const Vector &v1,float d); ///< Return v1 divided by d.
friend Vector SIMUL_MATH_EXPORT_FN operator^(const Vector &v1,const Vector &v2); ///< Return the cross product of v1 and v2.
/// Put the cross product of v1 and v2 in result.
friend void SIMUL_MATH_EXPORT_FN CrossProduct(Vector &result,const Vector &v1,const Vector &v2);
/// Add the cross product of v1 and v2 to result.
friend void SIMUL_MATH_EXPORT_FN AddCrossProduct(Vector &result,const Vector &v1,const Vector &v2);
friend void SIMUL_MATH_EXPORT_FN AddDoubleCross(Vector &result,const Vector &v1,const Vector &v2);
friend void SIMUL_MATH_EXPORT_FN SubtractDoubleCross(Vector &result,const Vector &v1,const Vector &v2);
/// Return dot product of D and (X1-X2).
friend float SIMUL_MATH_EXPORT_FN DotDifference(const Vector &D,const Vector &X1,const Vector &X2);
/// Return dot product of D and (X1+X2).
friend float SIMUL_MATH_EXPORT_FN DotSum(const Vector &D,const Vector &X1,const Vector &X2);
/// Put X1-X2 in R.
friend void SIMUL_MATH_EXPORT_FN Subtract(Vector &R,const Vector &X1,const Vector &X2);
friend void SIMUL_MATH_EXPORT_FN Subtract3(Vector &R,const Vector &X1,const Vector &X2);
/// Put X1+X2 in R.
friend void SIMUL_MATH_EXPORT_FN Add(Vector &R,const Vector &X1,const Vector &X2);
friend void SIMUL_MATH_EXPORT_FN AddRow(Vector3 &V1,Matrix &M2,unsigned Row2);
friend void SIMUL_MATH_EXPORT_FN Matrix::AddOuter(const Vector &v1,const Vector &v2);
friend void SIMUL_MATH_EXPORT_FN Matrix::SubtractOuter(const Vector &v1,const Vector &v2);
// outer product
friend Matrix SIMUL_MATH_EXPORT_FN Outer(const Vector &v1,const Vector &v2);
friend void SIMUL_MATH_EXPORT_FN Precross(Matrix &M,const Vector &v);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertVectorAsColumn(const Vector &v,unsigned col);
friend void SIMUL_MATH_EXPORT_FN InsertVectorAsColumn(const Matrix &M,const Vector &v,const unsigned row);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertNegativeVectorAsColumn(const Vector &v,unsigned col);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertCrossProductAsColumn(const Vector &v1,const Vector &v2,unsigned col);
friend void SIMUL_MATH_EXPORT_FN Matrix::InsertAddVectorCrossMatrix(const Vector &v,const Matrix &M);
friend void SIMUL_MATH_EXPORT_FN InsertCrossProductAsRow(Matrix &M,const Vector &V1,const Vector &V2,const unsigned Row);
friend float SIMUL_MATH_EXPORT_FN MatrixRowTimesVector(const Matrix &M,const unsigned Row,const Vector &V);
friend void SIMUL_MATH_EXPORT_FN InsertVectorAsRow(Matrix &M,const Vector &v,const unsigned row);
friend void SIMUL_MATH_EXPORT_FN SubtractVectorFromRow(Matrix &M,unsigned Row,Vector &V);
friend void SIMUL_MATH_EXPORT_FN InsertNegativeVectorAsRow(Matrix &M,const Vector &v,const unsigned row);
friend void SIMUL_MATH_EXPORT_FN InsertVectorAsColumn(Matrix &M,const Vector &v,const unsigned col);
friend void SIMUL_MATH_EXPORT_FN InsertNegativeVectorAsRow(Matrix &M,const Vector3 &v,const unsigned row);
friend float SIMUL_MATH_EXPORT_FN LineInterceptPosition(Vector &i,const Vector &surf_x,const Vector &surf_n,const Vector &line_x,const Vector &line_d);
friend bool SIMUL_MATH_EXPORT_FN FiniteLineIntercept(Vector &i,const Vector &surf_x,const Vector &surf_n,const Vector &line_x,const float l,const Vector &line_d);
friend void SIMUL_MATH_EXPORT_FN AddFloatTimesRow(Vector &V1,float Multiplier,Matrix &M2,unsigned Row2);
friend void SIMUL_MATH_EXPORT_FN AddFloatTimesColumn(Vector &V1,float Multiplier,Matrix &M2,unsigned Col2);
friend void SIMUL_MATH_EXPORT_FN SolveFromCholeskyFactors(Vector &R,Matrix &Fac,Vector &X);
friend void SIMUL_MATH_EXPORT_FN SolveFromLowerTriangular(Vector &R,Matrix &Fac,Vector &X);
friend void SIMUL_MATH_EXPORT_FN SSORP(Matrix &A,Vector &X,Vector &B,unsigned Num,unsigned Lim,Vector &InverseDiagonals);
friend void SIMUL_MATH_EXPORT_FN SSORP2(Matrix &A,Vector &X,Vector &B,unsigned Num,unsigned Lim,Vector &InverseDiagonals,void* Nv);
friend void SIMUL_MATH_EXPORT_FN Multiply4(Vector &v2,const Matrix &m,const Vector &v1);
friend SIMUL_MATH_EXPORT std::ostream &operator<<(std::ostream &, Vector const &);
friend SIMUL_MATH_EXPORT std::istream &operator>>(std::istream &, Vector &);
#ifdef PLAYSTATION_2
} __attribute__((aligned (16)));
#else
};
#endif
}
}
#endif
| true |
bc8a452c339e18f568aa8fd56689494f3530234f | C++ | vivekpisal/450-problem-solving | /stack/ReverseStack.cpp | UTF-8 | 527 | 3.3125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void insertAtBottom(stack<int> &st,int val)
{
if(st.empty())
{
st.push(val);
return;
}
int top = st.top();
st.pop();
insertAtBottom(st,val);
st.push(top);
}
void reverse(stack<int> &st)
{
if(st.empty())
return;
int top = st.top();
st.pop();
reverse(st);
insertAtBottom(st,top);
}
int main()
{
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
reverse(st);
while(!st.empty())
{
cout<<st.top()<<" ";
st.pop();
}
return 0;
} | true |
76fb6ca1d081c1f3cd653c0234c8ab02c09559fc | C++ | walnutkakki/cpptut | /chap4.object/array.cpp | UTF-8 | 469 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Sample {
int a;
public:
Sample() { a = 100 ; cout << a << ' ' ;}
Sample(int x) {a =x; cout << a << ' ';}
Sample(int x, int y) { a = x*y ; cout << a << ' ';}
int get(){return a;}
};
int main()
{
// Sample arr[3];
Sample arr2D[2][2] = {{Sample(2,3), Sample(2,4)}, {Sample(5), Sample()}};
int b;
b = Sample arr2D[0][0] + Sample arr2D[0][1] + Sample arr2D[1][0] + Sample arr2D[1][1]);
} | true |
6e7cf3580333aa9254f5246deb945788c9949ba9 | C++ | gprunecode/AlgoritCabrera | /Tarea 3/src/3.cpp | UTF-8 | 452 | 3.96875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main (int argc,char** argv){
int numero;
cout<<"Ingrese un numero"<<endl;
cin>>numero;
if (numero % 2 == 0){
cout<<"El numero es multiplo de 2"<<endl;
}
if (numero > 12){
cout<<"El numero es mayor que 12"<<endl;
}
if (numero % 3 == 0){
cout<<"El numero es multiplo de 3"<<endl;
}
if (numero < 21 ){
cout<<"El numero es menor que 21"<<endl;
}
}
| true |
54742a06e1dc743c873433aa332013a6750b6819 | C++ | NoSpooksAllowed/cpp-coursera | /cpp-white-belt/week_2/set/unique_str/main.cpp | UTF-8 | 323 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
set<string> uniqueStr;
int queries;
string s;
cin >> queries;
for (int i = 0; i < queries; i++) {
cin >> s;
uniqueStr.insert(s);
}
cout << uniqueStr.size() << endl;
return 0;
}
| true |
8e8df52930fd4bc7b8a67dcaa6f307c4531e256f | C++ | lavanych22/lab4 | /lab4.cpp | UTF-8 | 1,563 | 3.625 | 4 | [] | no_license | #include<iostream>
#include<math.h>
#define n 5
using namespace std;
class Matrix
{
private:
int a[n][n];
int sum[n];
int i, j, k, c;
long double g_m, sumg;
public:
void matrix_input();
void matrix_output();
void matrix_sorting();
void raw_geometric_mean_and_summation();
};
void Matrix::matrix_input()
{
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout << "Please, enter the element [" << i+1 << ";" << j+1 << "]";
cin >> a[i][j];
cout << endl;
}
}
}
void Matrix::matrix_output()
{
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j == 0) cout << endl;
cout << a[i][j] << "\t";
}
}
}
void Matrix::matrix_sorting()
{
for(j = 0; j < n; j++) {
for(k = n-1; k >=0 ; k--) {
for(i = 0; i < k; i++) {
if(a[i][j] < a[i+1][j]) {
c = a[i][j];
a[i][j] = a[i+1][j];
a[i+1][j] =c;
}
}
}
}
}
void Matrix::raw_geometric_mean_and_summation()
{
cout << endl;
for (i = 0; i < (n - 1); i++) {
g_m = 1;
for (j = 0; j < n; j++) {
if (j > i) {
g_m *= a[i][j];
}
}
g_m = pow(fabs(g_m),0.25);
cout << "Geometric mean of " << i + 1 << " raw is " << g_m << endl;
sumg += g_m;
}
cout << "Sum of geometric means is " << sumg << endl;
}
int main()
{ Matrix X;
X.matrix_input();
cout << endl;
cout << "Entered matrix:\n";
X.matrix_output();
cout << endl;
X.matrix_sorting();
cout <<"\n New matrix:\n";
X.matrix_output();
cout << endl;
X.raw_geometric_mean_and_summation();
}
| true |
d883a10d9a250ff3ae40afbf220fd610813c60a2 | C++ | Mariars11/RealizadoEmClasse | /dddswitch.cpp | ISO-8859-1 | 623 | 3.140625 | 3 | [] | no_license | //ddd com switch case
#include <stdio.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Portuguese");
int ddd;
printf("Informe o ddd: ");
scanf("%d", &ddd);
switch(ddd)
{
case 61: printf("Braslia"); break;
case 71: printf("Salvador"); break;
case 11: printf("So Paulo"); break;
case 21: printf("Rio de janeiro"); break;
case 32: printf("Juiz de Fora"); break;
case 19: printf("Campinas"); break;
case 27: printf("Vitria"); break;
case 31: printf("Belo Horizonte"); break;
default: printf("DDD no consta no sistema, por favor! Digite um vlido");
}
}
| true |
7578cc1c30cd513feab1a2370a54a8a7defa9f57 | C++ | nkteaching/assignment-2-sualehalam | /Ch5.q17c recursion remove all occur [C].cpp | UTF-8 | 591 | 3.296875 | 3 | [] | no_license |
#include <string.h>
#include<iostream>
using namespace std;
void deletechar(char *s,char c)
{
static int i=0,k=0;
if(s[i] == NULL) // if ( !s[i] )
{
return; // exit from function
}
else
{
s[i]=s[i+k];
if(s[i]==c)
{
k++;
i--;
}
i++;
deletechar(s,c);
}
}
int main()
{
char s[100];
char c;
cout<<"Enter string: ";
cin>>s;
cout<<"Enter character: ";
cin>>c;
deletechar(s,c);
cout<<s;
}
| true |
f1b9ace8acee1cb35c458e62426b761897a4b2fe | C++ | qqonline/EasyNetFramework | /src/common/impl/ArrayObjectPool.cpp | UTF-8 | 1,125 | 2.71875 | 3 | [] | no_license | /*
* ArrayObjectPool.cpp
*
* Created on: Apr 18, 2013
* Author: LiuYongJin
*/
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include "ArrayObjectPool.h"
namespace easynet
{
ArrayObjectPool::ArrayObjectPool(uint32_t elem_size, uint32_t elem_num)
{
m_ElemNum = elem_num;
if(elem_size < sizeof(void*))
m_ElemSize = sizeof(void*);
else
m_ElemSize = elem_size;
m_Elements = malloc(m_ElemSize*m_ElemNum);
m_End = (void*)((char*)m_Elements+m_ElemSize*m_ElemNum);
assert(m_Elements != NULL);
//构建链表
int i;
void *node = m_Elements;
for(i=0; i<m_ElemNum-1; ++i)
{
*(void**)node = (void*)((char*)node+m_ElemSize);
node = *(void**)node;
}
*(void**)node = NULL;
m_FreeHead = m_Elements; //链表头
}
ArrayObjectPool::~ArrayObjectPool()
{
free(m_Elements);
}
void* ArrayObjectPool::Get()
{
if(m_FreeHead == NULL)
return NULL;
void *temp = m_FreeHead;
m_FreeHead = *(void**)m_FreeHead;
return temp;
}
bool ArrayObjectPool::Recycle(void *elem)
{
if(elem<m_Elements || elem>=m_End)
return false;
*(void**)elem = m_FreeHead;
m_FreeHead = elem;
return true;
}
}
| true |
4960a734d3df5ecfe674f7e65afad43fc830e8b8 | C++ | saurishphatak/Data-Structures | /CPP/Linked Lists/GenericSentinelLinkedList.cpp | UTF-8 | 4,845 | 4.25 | 4 | [
"MIT"
] | permissive | /*
* --------------------------------------------------------------------------------
* File : GenericSentinelLinkedList.cpp
* Project : CPP
* Author : Saurish Phatak
*
*
* Description : Generic Sentinel Linked List
* --------------------------------------------------------------------------------
*
* Revision History :
* 2020-August-12 [SP] : Created
* --------------------------------------------------------------------------------
*/
#include <iostream>
#include <string>
using namespace std;
// Node represents a value in the List
template <class V>
struct Node
{
// Points to the previous Node
Node<V> *previous;
// Holds the Node's value
V value;
// Points to the next Node
Node<V> *next;
// Constructor
Node(V v)
{
previous = next = nullptr;
(*this).value = v;
}
};
// Represents the SentinelLinkedList
template <class V>
class SentinelLinkedList
{
// Points to the Dummy Head
Node<V> *head;
// Points to the Dummy Tail
Node<V> *tail;
public:
// Constructor
SentinelLinkedList()
{
// Create dummy Nodes
// of default value of a type
// (invokes the Default Constructor of a type
// SWEET C++
head = new Node<V>(V());
tail = new Node<V>(V());
// Point head and tail to each other
head->next = tail;
tail->previous = head;
}
// Method to add a Node in the Linked List
void pushBack(V value)
{
/**
* This is where the Sentinel Linked List
* really SHINES!
* We don't have to check if this the First Node
* that we're adding.
*
* We simply create a newNode and add it before the
* tail.
*/
// Holds the new Node
Node<V> *newNode;
// If the allocation failed
if (!(newNode = new Node<V>(value)))
return;
/**
* Add the newNode before the tail
* Think of the List as a wall
*/
// Make the newNode climb up the wall
newNode->next = tail;
newNode->previous = tail->previous;
// Pull the newNode up the wall
newNode->previous->next = newNode;
tail->previous = newNode;
// And that's it! That's how easy it is
// to add a new Node to the Sentinel List
}
// Method to remove a Node from the List
bool remove(V valueToRemove)
{
// Search for the value
// Start from the head's next and not the head
// as head itself points to a Dummy Node
for (Node<V> *current = head->next; current != tail; current = current->next)
{
// Value found
if ((*current).value == valueToRemove)
{
// Disconnect the current Node from the List
current->previous->next = current->next;
current->next->previous = current->previous;
// Delete the current Node
delete current;
return true;
}
}
// Value not in the List
return false;
}
// Method to print the List in Forward direction
void printForward()
{
// Start from head's next and go upto tail
for (Node<V> *current = head->next; current != tail; current = current->next)
{
// Print the current Node's value
cout << current->value;
if (current->next != tail)
cout << " <=> ";
}
cout << endl;
}
// Method to clear the entire List
int clear()
{
int counter = 0;
// If the List exists
if (head->next != tail)
{
// Start from the head and keep on deleting
// the Nodes until we reach the tail
while (head->next != tail)
{
// Shift the head forward
head->next = head->next->next;
// Delete head->next's previous and
// point it to head
delete head->next->previous;
head->next->previous = head;
counter++;
}
}
return counter;
}
};
int main()
{
// Create a new Sentinel List
SentinelLinkedList<string> list;
// Add some values to the list
string value;
while (cout << "Enter value to add (0 to stop) : ",
cin >> value,
value != "n")
{
list.pushBack(value);
list.printForward();
}
while (cout << "Enter value to remove (0 to stop) : ",
cin >> value,
value != "n")
{
list.remove(value);
list.printForward();
}
cout << list.clear() << endl;
list.printForward();
return 0;
} | true |
b7f1f67cc984f0d7fbeb3e7cbbe442b4b550bfbe | C++ | SamuelXing/Algorithm | /cpp_solutions/sequence/36_Valid_SudoKu.cpp | UTF-8 | 1,399 | 3.515625 | 4 | [] | no_license | /*
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
*/
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool used[9];
for(int i=0; i<9; i++ )
{
// check row
fill(used, used + 9, false);
for(int j=0; j< 9; j++)
{
if(!validate(used, board[i][j])) return false;
}
// check column
fill(used, used + 9, false);
for(int j=0; j< 9; j++)
{
if(!validate(used, board[j][i])) return false;
}
}
// check 3x3 block
for(int i=0; i< 3; i++)
{
for(int j=0; j< 3; j++)
{
fill(used, used + 9, false);
for(int r=0; r<3; r++)
{
for(int c=0; c<3;c++)
{
if(!validate(used, board[i*3+r][j*3+c])) return false;
}
}
}
}
return true;
}
private:
bool validate(bool used[9], char ch)
{
if (ch == '.') return true;
if (used[ch - '1']) return false;
return used[ch - '1'] = true;
}
}; | true |
31cd4e26bc4f2dd6e197c84cdfa7bd67f95010eb | C++ | jjjpolo/Pi-Pico-Demo-Blinking-Led-Using-Modern-Cpp | /Led.h | UTF-8 | 280 | 2.8125 | 3 | [] | no_license | #pragma once
class Led
{
private:
const uint ledPin = 0;
int state = 0;
public:
//Constructor
Led(const uint, int);
//Change LED state (no parameter needed)
void toggle();
//A demo animation for the LED
void demoQuickBlinking();
//Destructor
~Led();
}; | true |
8acaabe6f914befa1a3f779283d02d907b3f40ad | C++ | mjww3/algorithms | /nsteps.cpp | UTF-8 | 488 | 2.8125 | 3 | [] | no_license | ///n steps problem
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int N;
cin>>N;
long int x,y;
while(N--)
{
cin>>x>>y;
if(x==y)
{
if(x%2==0 && y%2==0)
{
cout<<2*x<<endl;
}
else
{
cout<<2*x-1<<endl;
}
}
else if(x-y==2)
{
if(x%2==0)
{
cout<<x+y<<endl;
}
else
{
cout<<x+y-1<<endl;
}
}
else
{
cout<<"No Number"<<endl;
}
}
return 0;
}
///solved | true |
9712bab54f6a4063083f556bbbe7db3baced1460 | C++ | kuonanhong/UVa-2 | /10452 - Marcus.cpp | UTF-8 | 930 | 2.53125 | 3 | [] | no_license | /**
UVa 10452 - Marcus
by Rico Tiongson
Submitted: July 13, 2013
Accepted 0.019s C++
O(?) time
*/
#include<iostream>
#include<cstdio>
using namespace std;
const char* dir[] = {"forth", "right", "left"};
char I[] = "AVOHEI@";
char grid[10][10];
int t, m, n, i, dx[] = {1,0,0}, dy[] = {0,-1,1};
bool inRange( int x, int y ){
return x>=0 && y>=0 && x<m && y<n;
}
bool dfs( int x, int y, int d ){
if( d==7 ){
return true;
}
for( int k=0; k<3; ++k ){
if( inRange( x+dx[k], y+dy[k] ) && I[d]==grid[x+dx[k]][y+dy[k]] ){
if( dfs( x+dx[k], y+dy[k], d+1 ) ){
printf(dir[k]);
if( d ) putchar(' ');
return true;
}
}
}
return false;
}
int main(){
scanf( "%d\n", &t);
while( t-- ){
scanf("%d %d\n",&m,&n);
for( i=0; i<m; ++i ){
gets( grid[i] );
}
for( i=0; i<n; ++i ){
if( grid[0][i]=='#' ){
break;
}
}
dfs( 0, i, 0 );
putchar('\n');
}
}
| true |
b71259a9fb685f6f647468a66abc70a84358cf7c | C++ | McBrez/ESIF_Task2 | /Subtask1/ESIFTask2_1.sdk/ESIF2_1_App/src/main.cc | UTF-8 | 1,686 | 3.140625 | 3 | [] | no_license | #include<xparameters.h>
#include<xgpio.h>
#include<xil_printf.h>
#define GPIO_CHANNEL 1
#define GPIO_DD_BITMASK 0b111
#define GPIO_BITMASK 0b111
void bin2grey(unsigned int val, char* retVal, unsigned int bitWidth) {
unsigned int greyVal;
switch(val) {
case 0:
greyVal = 0;
break;
case 1:
greyVal = 1;
break;
case 2:
greyVal = 3;
break;
case 3:
greyVal = 2;
break;
case 4:
greyVal = 6;
break;
case 5:
greyVal = 7;
break;
case 6:
greyVal = 5;
break;
case 7:
greyVal = 4;
break;
default:
greyVal = 0;
break;
}
// Iterate bitwise over val and write bit values to retVal
for(unsigned int i = 0 ; i < bitWidth ; i++) {
if(greyVal & (1 << i)) {
// fill up string from right
retVal[bitWidth-i-1] = '1';
}
else {
// fill up string from right
retVal[bitWidth-i-1] = '0';
}
}
// Terminate string
retVal[bitWidth] = 0;
}
int main()
{
XGpio gpio;
unsigned int lastDIP = 0;
unsigned int currDIP = 0;
char printStr[4];
// Init GPIO
unsigned int status = XGpio_Initialize(&gpio, XPAR_GPIO_0_DEVICE_ID);
if (status != XST_SUCCESS) {
xil_printf("GPIO Initialization Failed\r\n");
return XST_FAILURE;
}
// Set data direction of GPIOs
XGpio_SetDataDirection(&gpio, GPIO_CHANNEL, GPIO_DD_BITMASK);
while (1) {
// Read from GPIO
currDIP = XGpio_DiscreteRead(&gpio, GPIO_CHANNEL);
// Cut away all bits except the 3 LSBs
currDIP = currDIP & GPIO_BITMASK;
// Write to UART, if currDIP has changed.
if(currDIP != lastDIP) {
bin2grey(currDIP, printStr, 3);
xil_printf("%s\n", printStr);
}
lastDIP = currDIP;
}
xil_printf("Successfully ran Gpio Example\r\n");
return XST_SUCCESS;
}
| true |
07e65aeab5dc1c704a309fd02f459a8991807559 | C++ | WuyangPeng/Engine | /Engine/Code/Mathematics/Objects2D/Box2.h | GB18030 | 2,500 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// ߣʶ
/// ϵߣ94458936@qq.com
///
/// std:c++20
/// 汾0.9.0.11 (2023/06/08 15:11)
#ifndef MATHEMATICS_OBJECTS_2D_BOX2_H
#define MATHEMATICS_OBJECTS_2D_BOX2_H
#include "Mathematics/MathematicsDll.h"
#include "CoreTools/Helper/Export/PerformanceUnsharedExportMacro.h"
#include "Mathematics/Algebra/Vector2.h"
#include <iosfwd>
#include <type_traits>
#include <vector>
namespace Mathematics
{
template <typename Real>
class Box2 final
{
public:
static_assert(std::is_arithmetic_v<Real>, "Real must be arithmetic.");
using ClassType = Box2<Real>;
using Math = Math<Real>;
using Vector2 = Vector2<Real>;
using VerticesType = std::vector<Vector2>;
public:
// һĵC᷽U[0]U[1]ֱ͵λȵ
// ͷΧe[0]e[1]Ǹ
// A point X = C + y[0] * U[0] + y[1] * U[1]ڲںϣ
// ÿ|y[i]| <= e[i]еi
Box2() noexcept;
Box2(const Vector2& center, const Vector2& axis0, const Vector2& axis1, const Real extent0, const Real extent1, const Real epsilon = Math::GetZeroTolerance()) noexcept;
CLASS_INVARIANT_DECLARE;
NODISCARD VerticesType ComputeVertices() const;
NODISCARD Vector2 GetCenter() const noexcept;
NODISCARD Vector2 GetAxis0() const noexcept;
NODISCARD Vector2 GetAxis1() const noexcept;
NODISCARD Real GetExtent0() const noexcept;
NODISCARD Real GetExtent1() const noexcept;
NODISCARD Real GetEpsilon() const noexcept;
NODISCARD Box2 GetMove(Real t, const Vector2& velocity) const;
private:
static constexpr auto axisSize = 2;
using AxisType = std::array<Vector2, axisSize>;
using ExtentType = std::array<Real, axisSize>;
private:
Vector2 center;
AxisType axis;
ExtentType extent;
Real epsilon;
};
using Box2F = Box2<float>;
using Box2D = Box2<double>;
template <typename Real>
NODISCARD bool Approximate(const Box2<Real>& lhs, const Box2<Real>& rhs, Real epsilon) noexcept(gAssert < 1 || gMathematicsAssert < 1);
//
template <typename Real>
std::ostream& operator<<(std::ostream& outFile, const Box2<Real>& box);
}
#endif // MATHEMATICS_OBJECTS_2D_BOX2_H
| true |
58cf52b9e566f815f4b4c35147da34f16bad6521 | C++ | vldmalov/ShootingGallery | /src/Scene/Scene.cpp | UTF-8 | 6,534 | 2.6875 | 3 | [] | no_license | #include "Scene.h"
#include "Utils/Random.hpp"
#include "Objects/CircleTarget.h"
#include "Objects/Projectile.h"
#include "Objects/CannonObject.h"
#include "Preferences.h"
namespace Scene {
Scene::Scene()
: _cannon(nullptr)
, _isGameActive(false)
, _isPause(false)
, _timeToEnd(0.f)
, _onLevelCompleteCallback(nullptr)
, _onLevelFailureCallback(nullptr)
{
ResetScore();
Log::log.WriteDebug("Scene has been constructed");
}
Scene::~Scene()
{
Log::log.WriteDebug("Scene has been destroyed");
}
void Scene::SetRect(const IRect& rect)
{
_sceneRect = rect;
// Обновляем область размещения целей
unsigned bottomIndent = _sceneRect.Height() / 3;
_targetsRect = IRect(_sceneRect.x, _sceneRect.y + bottomIndent,
_sceneRect.Width(), _sceneRect.Height() - bottomIndent);
}
void Scene::Reset()
{
ResetScore();
_targets.clear();
_isGameActive = true;
_isPause = false;
_timeToEnd = Preferences::Instance().getFloatValue("Time", 0.f);
assert(_timeToEnd > 0);
InitCannon();
_projectiles.clear();
GenerateTargets();
}
void Scene::SetPause(bool val)
{
_isPause = val;
}
bool Scene::GetPause() const
{
return _isPause;
}
void Scene::TogglePause()
{
_isPause = !_isPause;
}
void Scene::InitCannon()
{
Preferences& prefs = Preferences::Instance();
const float CANNON_BASE_WIDTH = prefs.getFloatValue("CannonBaseWidth", -1);
const float CANNON_BASE_HEIGHT = prefs.getFloatValue("CannonBaseHeight", -1);
assert(CANNON_BASE_WIDTH > 0 && CANNON_BASE_HEIGHT > 0);
FPoint CannonSize(CANNON_BASE_WIDTH, CANNON_BASE_HEIGHT);
const float cannonBoardlineIndent = prefs.getIntValue("CannonBoardlineIndent", 0.f);
FPoint CannonPosition(static_cast<float>(_targetsRect.Width()) / 2.f, CannonSize.y / 2.f + cannonBoardlineIndent);
_cannon.reset(new CannonObject(CannonPosition, CannonSize));
}
void Scene::GenerateTargets()
{
Preferences& prefs = Preferences::Instance();
const int TARGETS_COUNT = prefs.getIntValue("CountTarget", -1);
assert(TARGETS_COUNT > 0);
const float MIN_TARGET_RADIUS = prefs.getFloatValue("MinTargetRadius", -1);
const float MAX_TARGET_RADIUS = prefs.getFloatValue("MaxTargetRadius", -1);
const float TARGET_MAX_SPEED = prefs.getFloatValue("TargetMaxSpeed", -1);
assert(MIN_TARGET_RADIUS > 0 && MAX_TARGET_RADIUS > 0 && TARGET_MAX_SPEED > 0);
for(unsigned i = 0; i < TARGETS_COUNT; ++i) {
const float radius = math::random(MIN_TARGET_RADIUS, MAX_TARGET_RADIUS);
FPoint position(math::random(_targetsRect.x + radius,
_targetsRect.RightTop().x - radius),
math::random(_targetsRect.y + radius,
_targetsRect.RightTop().y - radius));
FPoint direction(math::random(0.f, TARGET_MAX_SPEED), 0.f);
direction.Rotate(math::random(0.f, 2.f * math::PI));
CircleTargetPtr newTarget = std::make_shared<CircleTarget>(position, radius, direction);
//newTarget->SetProcessBoarderCollisions(false);
_targets.push_back(newTarget);
}
}
void Scene::Draw()
{
for(CircleTargetPtr targetPtr : _targets) {
targetPtr->Draw();
}
for(ProjectilePtr projectilePtr : _projectiles) {
projectilePtr->Draw();
}
if(_cannon) {
_cannon->Draw();
}
_effCont.Draw();
}
void Scene::Update(float dt)
{
if(_isPause) {
return;
}
if(_isGameActive) {
_timeToEnd -= dt;
if (_timeToEnd < 0.f) {
OnGameOver();
}
}
UpdateEffects(dt);
UpdateTargets(dt);
UpdateProjectiles(dt);
UpdateCannon(dt);
ProcessCollisions();
}
void Scene::UpdateEffects(float dt)
{
_effCont.Update(dt);
}
void Scene::UpdateTargets(float dt)
{
CircleTargetPtrList::const_iterator it = _targets.begin();
while(it != _targets.end())
{
(*it)->Update(dt, _targetsRect);
if((*it)->IsMarkedOnDelete()) {
OnPreDestroyTarget(*it);
it = _targets.erase(it);
OnDestroyTarget();
}
else {
++it;
}
}
}
void Scene::UpdateProjectiles(float dt)
{
ProjectilePtrList::const_iterator it = _projectiles.begin();
while(it != _projectiles.end())
{
(*it)->Update(dt, _targetsRect);
if((*it)->IsMarkedOnDelete()) {
it = _projectiles.erase(it);
}
else {
++it;
}
}
}
void Scene::UpdateCannon(float dt)
{
if(_cannon) {
_cannon->Update(dt);
}
}
void Scene::ProcessCollisions()
{
float projectileCollisionRadius = Preferences::Instance().getFloatValue("ProjectileCollisionRadius", 0.f);
for(ProjectilePtr projectilePtr : _projectiles) {
const FPoint& projectilePos = projectilePtr->GetPosition();
for(CircleTargetPtr targetPtr : _targets) {
if(targetPtr->IsCollisionWithCircle(projectilePos, projectileCollisionRadius)) {
projectilePtr->SetMarkedOnDelete(true);
targetPtr->SetMarkedOnDelete(true);
break;
}
}
}
}
void Scene::OnPreDestroyTarget(CircleTargetPtr obj)
{
ParticleEffectPtr eff = _effCont.AddEffect("BubbleBoom");
eff->SetPos( obj->GetPosition() );
eff->Reset();
}
void Scene::OnDestroyTarget()
{
if(_isGameActive) {
IncreaseScore();
}
}
void Scene::ResetScore()
{
_currentScore = 0;
OnScoreChanged();
}
void Scene::IncreaseScore()
{
++_currentScore;
OnScoreChanged();
}
unsigned Scene::GetScore() const
{
return _currentScore;
}
float Scene::GetTimeToEnd() const
{
return _timeToEnd;
}
bool Scene::IsGameActive() const
{
return _isGameActive;
}
void Scene::OnScoreChanged()
{
// Проверка окончания игры
if(_targets.empty()) {
OnLevelComplete();
}
}
void Scene::SetOnLevelCompleteCallback(voidCallback cb)
{
_onLevelCompleteCallback = cb;
}
void Scene::SetOnLevelFailureCallback(voidCallback cb)
{
_onLevelFailureCallback = cb;
}
void Scene::OnLevelComplete()
{
_isGameActive = false;
if(_onLevelCompleteCallback) {
_onLevelCompleteCallback();
}
}
void Scene::OnGameOver()
{
_isGameActive = false;
if(_onLevelFailureCallback) {
_onLevelFailureCallback();
}
}
bool Scene::MouseDown(const IPoint &mouse_pos)
{
if(!_isGameActive || _isPause) {
return false;
}
if(Core::mainInput.GetMouseLeftButton())
{
if(_cannon && _cannon->CanShot()) {
ProjectilePtr newProjectile = _cannon->Shot();
ParticleEffectPtr projectileTrackEffect = _effCont.AddEffect("ProjectileJet");
newProjectile->SetTrackEffect(projectileTrackEffect);
_projectiles.push_back(newProjectile);
}
}
return false;
}
void Scene::MouseMove(const IPoint &mousePosition)
{
if(_isPause) {
return;
}
if(_cannon) {
_cannon->SetObservePoint(mousePosition);
}
}
void Scene::MouseUp(const IPoint &mousePosition)
{
}
} // End namespace Scene
| true |
1faa6f84619d557662619ce876a08fcc9b160197 | C++ | enatalie122/cpsc350-fall2020-assignment3 | /file.h | UTF-8 | 1,902 | 3.40625 | 3 | [] | no_license | /*
Natalie Ewing
2313895
ewing@chapman.edu
CPSC 350-01
Assignment 3
file.h is the header file for the File class.
*/
#ifndef FILE_H
#define FILE_H
#include <fstream>
#include <string>
#include <iostream>
#include "gen_stack.h"
using namespace std;
//The File class reads and collects data from files.
class File{
public:
/*Default constructor: File
Sets ints to 0 and strings to be empty.
*/
File();
/*Destructor: ~File
Does not delete anything because no memory is allocated to the heap.
*/
~File();
/*get_file_contents
Returns a string that contains the contents of a file.
*/
string get_file_contents();
/*get_number_of_lines
Returns an int represting the number of lines in a file.
*/
int get_number_of_lines();
/*set_file_name
Sets the member variable file_name_.
Parameters:
file_name: a string represting the name of a file to be processed.
*/
void set_file_name(string file_name);
/*ProcessFile
Sets the name of the file to be processed, reads from that file, and counts the number of lines in the file.
Parameters:
name: a string represting the name of a file to be processed
*/
void ProcessFile(string name);
private:
/*ReadFile
Opens and reads a given file. Adds the contents of the file to a string. Once processed, the file is closed.
If the file could not be opened, the method lets the user know, and allows them to try a new file.
*/
void ReadFile();
/*CountLines
Counts the number of lines in a file.
*/
void CountLines();
/*file_name_
A string representing the name of a file.
*/
string file_name_;
/*file_contents_
A string represting the contents of a file
*/
string file_contents_;
/*number_of_lines
An int represting the number of lines in a file.
*/
int number_of_lines_;
};
#endif
| true |
8a65e0f9d3a9e6ddd17d66cb3956cc956cdcfbe0 | C++ | yrrSelena/Computer-BasicKnowledge | /剑指offer/15反转链表.cpp | UTF-8 | 1,082 | 3.859375 | 4 | [] | no_license | /*
考点:链表
题目:
输入一个链表,反转链表后,输出新链表的表头。
思路:
定义前、中、后三个指针p1,p2,p3,p3用于指向原链表的下一个节点,每次都修改p2的next指针,使其指向前面一个节点p1,直至p3指向空(遍历完链表中的所有节点)
此时p2作为新链表的表头指针,最后将原链表的头节点的next指向NULL
注意考虑链表为空以及链表中只有一个节点的情况。
*/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pNewHead;
if(pHead == NULL || pHead->next == NULL){
return pHead;
}
ListNode* p1 = pHead;
ListNode* p2 = pHead->next;
ListNode* p3 = p2->next;
p2->next = p1;
while(p3 != NULL){
p1 = p2;
p2 = p3;
p3 = p3->next;
p2->next = p1;
}
pHead->next = NULL;
return p2;
}
};
| true |
dc63a5287917fd12b899892817f419dcddf594a0 | C++ | chrisoldwood/FarmMonitor | /Logon.hpp | UTF-8 | 1,650 | 3.140625 | 3 | [
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////
//! \file Logon.hpp
//! \brief The Logon class declaration.
//! \author Chris Oldwood
// Check for previous inclusion
#ifndef APP_LOGON_HPP
#define APP_LOGON_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include <Core/SharedPtr.hpp>
////////////////////////////////////////////////////////////////////////////////
//! The custom credentials to use for querying a host.
class Logon
{
public:
//! Default constructor.
Logon();
//! Constructor.
Logon(const tstring& user, const tstring& password);
//
// Members.
//
tstring m_user; //!< The user name.
tstring m_password; //!< The password.
};
//! The default Logon const smart pointer type.
typedef Core::SharedPtr<const Logon> ConstLogonPtr;
////////////////////////////////////////////////////////////////////////////////
//! Default constructor.
inline Logon::Logon()
: m_user()
, m_password()
{
}
////////////////////////////////////////////////////////////////////////////////
//! Constructor.
inline Logon::Logon(const tstring& user, const tstring& password)
: m_user(user)
, m_password(password)
{
}
////////////////////////////////////////////////////////////////////////////////
//! Create a new logon.
inline ConstLogonPtr makeLogon(const tstring& user, const tstring& password)
{
return ConstLogonPtr(new Logon(user, password));
}
////////////////////////////////////////////////////////////////////////////////
//! Create a new logon.
inline ConstLogonPtr makeLogon(const Logon& logon)
{
return ConstLogonPtr(new Logon(logon.m_user, logon.m_password));
}
#endif // APP_LOGON_HPP
| true |
17d4c4b96abea42150551db7c8f23cd19aac11b2 | C++ | Alexander1000/image | /filters/zonefilter.cpp | UTF-8 | 24,278 | 2.78125 | 3 | [] | no_license | using namespace std;
class ZoneFilter : public Filter
{
public:
ZoneFilter() : Filter() {
// do something ...
}
ZoneFilter(int* bitMap, int width, int height) : Filter(bitMap, width, height) {
// do something ...
}
int* filterSmooth() {
this->buffer = (int*) malloc(width * height * sizeof(int));
memcpy(this->buffer, this->originalBitMap, width * height * sizeof(int));
this->bitMap = (int*) malloc(width * height * sizeof(int));
// плавно сглаживаем цвета
this->smoothBitMap(16);
this->smoothBitMap(32);
this->smoothBitMap(64);
this->cutPopularColor(3);
this->smoothBitMap(64);
//this->diffuseImage(64, 2);
// строим сигнатуру изображения
// this->buildSignature();
Pixel pixel;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
pixel.load(this->buffer[i * width + j]);
this->bitMap[i * width + j] = pixel.toInt32();
}
}
return this->bitMap;
}
int* filter() {
this->buffer = (int*) malloc(width * height * sizeof(int));
memcpy(this->buffer, this->originalBitMap, width * height * sizeof(int));
this->bitMap = (int*) malloc(width * height * sizeof(int));
// плавно сглаживаем цвета
this->smoothBitMap(16);
this->smoothBitMap(32);
this->smoothBitMap(64);
// todo: дополнительно сгладить цвет?
// this->diffuseImage(64, 3);
// строим сигнатуру изображения
this->buildSignature();
// подавляем немного шума
this->noiseClear(1, 64);
this->noiseClear(2, 64);
this->noiseClear(3, 48);
this->noiseClear(4, 48);
this->noiseClear(5, 32);
this->noiseClear(6, 32);
this->noiseClear(7, 16);
this->noiseClear(8, 8);
Pixel pixel;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
pixel.load(this->buffer[i * width + j]);
this->bitMap[i * width + j] = pixel.toInt32();
}
}
return this->bitMap;
}
private:
int* buffer;
int* preBitMap;
void cutPopularColor(int count) {
this->preBitMap = (int*) malloc(width * height * sizeof(int));
int red[256][2], green[256][2], blue[256][2];
Pixel pixel;
for (int i = 0; i < 256; ++i) {
red[i][0] = 0;
red[i][1] = i;
green[i][0] = 0;
green[i][1] = i;
blue[i][0] = 0;
blue[i][1] = i;
}
for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
pixel.load(this->buffer[i * this->width + j]);
++red[pixel.red][0];
++green[pixel.green][0];
++blue[pixel.blue][0];
}
}
int temp[2];
for (int i = 0; i < 256; ++i) {
for (int j = 0; j < 255; ++j) {
if (red[j][0] < red[j + 1][0]) {
temp[0] = red[j][0];
temp[1] = red[j][1];
red[j][0] = red[j + 1][0];
red[j][1] = red[j + 1][1];
red[j + 1][0] = temp[0];
red[j + 1][1] = temp[1];
}
if (green[j][0] < green[j + 1][0]) {
temp[0] = green[j][0];
temp[1] = green[j][1];
green[j][0] = green[j + 1][0];
green[j][1] = green[j + 1][1];
green[j + 1][0] = temp[0];
green[j + 1][1] = temp[1];
}
if (blue[j][0] < blue[j + 1][0]) {
temp[0] = blue[j][0];
temp[1] = blue[j][1];
blue[j][0] = blue[j + 1][0];
blue[j][1] = blue[j + 1][1];
blue[j + 1][0] = temp[0];
blue[j + 1][1] = temp[1];
}
}
}
Pixel newPixel(red[count][1], green[count][1], blue[count][1]);
for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
pixel.load(this->buffer[i * this->width + j]);
bool redExist = false, greenExist = false, blueExist = false;
for (int k = 0; k < count / 3; ++k) {
if (red[k][1] == pixel.red) {
redExist = true;
}
if (green[k][1] == pixel.green) {
greenExist = true;
}
if (blue[k][1] == pixel.blue) {
blueExist = true;
}
}
if (redExist && greenExist && blueExist) {
this->preBitMap[i * this->width + j] = newPixel.toInt32();
} else {
this->preBitMap[i * this->width + j] = pixel.toInt32();
}
}
}
memcpy(this->buffer, this->preBitMap, width * height * sizeof(int));
free(this->preBitMap);
}
void smoothBitMap(int divider) {
this->preBitMap = (int*) malloc(width * height * sizeof(int));
Pixel pixel;
Pixel newPixel;
int half = divider >> 1;
int mod;
for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
pixel.load(this->buffer[i * this->width + j]);
mod = pixel.red % divider;
if (mod >= half) {
newPixel.red = pixel.red - mod + divider;
} else {
newPixel.red = pixel.red - mod;
}
mod = pixel.green % divider;
if (mod >= half) {
newPixel.green = pixel.green - mod + divider;
} else {
newPixel.green = pixel.green - mod;
}
mod = pixel.blue % divider;
if (mod >= half) {
newPixel.blue = pixel.blue - mod + divider;
} else {
newPixel.blue = pixel.blue - mod;
}
this->preBitMap[i * this->width + j] = newPixel.toInt32();
}
}
memcpy(this->buffer, this->preBitMap, width * height * sizeof(int));
free(this->preBitMap);
}
void buildSignature() {
this->preBitMap = (int*) malloc(width * height * sizeof(int));
int countDiff;
Pixel curPixel;
int curPixelInt;
unsigned char gray;
for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
countDiff = 0;
curPixelInt = this->buffer[i * this->width + j];
if (i - 1 >= 0 && j - 1 >= 0 && curPixelInt != this->buffer[(i - 1) * this->width + j - 1]) {
++countDiff;
}
if (i - 1 >= 0 && curPixelInt != this->buffer[(i - 1) * this->width + j]) {
++countDiff;
}
if (i - 1 >= 0 && j + 1 <= this->width && curPixelInt != this->buffer[(i - 1) * this->width + j + 1]) {
++countDiff;
}
if (j - 1 >= 0 && curPixelInt != this->buffer[i * this->width + j - 1]) {
++countDiff;
}
if (j + 1 <= this->width && curPixelInt != this->buffer[i * this->width + j + 1]) {
++countDiff;
}
if (i + 1 <= this->height && j - 1 >= 0 && curPixelInt != this->buffer[(i + 1) * this->width + j - 1]) {
++countDiff;
}
if (i + 1 <= this->height && curPixelInt != this->buffer[(i + 1) * this->width + j]) {
++countDiff;
}
if (i + 1 <= this->height && j + 1 <= this->width && curPixelInt != this->buffer[(i + 1) * this->width + j + 1]) {
++countDiff;
}
gray = 0xFF >> countDiff;
curPixel.load(gray);
this->preBitMap[i * this->width + j] = curPixel.toInt32();
}
}
memcpy(this->buffer, this->preBitMap, width * height * sizeof(int));
free(this->preBitMap);
}
/**
* diff - разница между 2-мя цветами
* countDiffs - количество отличающихся цветов
*/
void diffuseImage(int diff, int countDiffs) {
this->preBitMap = (int*) malloc(width * height * sizeof(int));
Pixel curPixel;
Pixel pixel;
Pixel diffPixel;
int nDiffs;
vector<int*> fills;
int halfDiff = diff >> 1;
for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
curPixel.load(this->buffer[i * this->width + j]);
if (i - 1 >= 0) {
nDiffs = 0;
pixel.load(this->buffer[(i - 1) * this->width + j]);
diffPixel.load(pixel.toInt32());
if (abs(pixel.red - curPixel.red) <= diff && pixel.red != curPixel.red) {
++nDiffs;
diffPixel.red = pixel.red > curPixel.red ? curPixel.red + halfDiff : pixel.red + halfDiff;
}
if (abs(pixel.green - curPixel.green) <= diff && pixel.green != curPixel.green) {
++nDiffs;
diffPixel.green = pixel.green > curPixel.green ? curPixel.green + halfDiff : pixel.green + halfDiff;
}
if (abs(pixel.blue - curPixel.blue) <= diff && pixel.blue != curPixel.blue) {
++nDiffs;
diffPixel.blue = pixel.blue > curPixel.blue ? curPixel.blue + halfDiff : pixel.blue + halfDiff;
}
if (countDiffs >= nDiffs && nDiffs > 0) {
int* params = (int*) malloc(5 * sizeof(int));
params[0] = i - 1;
params[1] = j;
params[2] = i;
params[3] = j;
params[4] = diffPixel.toInt32();
fills.push_back(params);
}
}
if (j - 1 >= 0) {
nDiffs = 0;
pixel.load(this->buffer[i * this->width + j - 1]);
diffPixel.load(pixel.toInt32());
if (abs(pixel.red - curPixel.red) <= diff && pixel.red != curPixel.red) {
++nDiffs;
diffPixel.red = pixel.red > curPixel.red ? curPixel.red + halfDiff : pixel.red + halfDiff;
}
if (abs(pixel.green - curPixel.green) <= diff && pixel.green != curPixel.green) {
++nDiffs;
diffPixel.green = pixel.green > curPixel.green ? curPixel.green + halfDiff : pixel.green + halfDiff;
}
if (abs(pixel.blue - curPixel.blue) <= diff && pixel.blue != curPixel.blue) {
++nDiffs;
diffPixel.blue = pixel.blue > curPixel.blue ? curPixel.blue + halfDiff : pixel.blue + halfDiff;
}
if (countDiffs >= nDiffs && nDiffs > 0) {
int* params = (int*) malloc(5 * sizeof(int));
params[0] = i;
params[1] = j - 1;
params[2] = i;
params[3] = j;
params[4] = diffPixel.toInt32();
fills.push_back(params);
}
}
if (j + 1 < this->width) {
nDiffs = 0;
pixel.load(this->buffer[i * this->width + j + 1]);
diffPixel.load(pixel.toInt32());
if (abs(pixel.red - curPixel.red) <= diff && pixel.red != curPixel.red) {
++nDiffs;
diffPixel.red = pixel.red > curPixel.red ? curPixel.red + halfDiff : pixel.red + halfDiff;
}
if (abs(pixel.green - curPixel.green) <= diff && pixel.green != curPixel.green) {
++nDiffs;
diffPixel.green = pixel.green > curPixel.green ? curPixel.green + halfDiff : pixel.green + halfDiff;
}
if (abs(pixel.blue - curPixel.blue) <= diff && pixel.blue != curPixel.blue) {
++nDiffs;
diffPixel.blue = pixel.blue > curPixel.blue ? curPixel.blue + halfDiff : pixel.blue + halfDiff;
}
if (countDiffs >= nDiffs && nDiffs > 0) {
int* params = (int*) malloc(5 * sizeof(int));
params[0] = i;
params[1] = j + 1;
params[2] = i;
params[3] = j;
params[4] = diffPixel.toInt32();
fills.push_back(params);
}
}
if (i + 1 < this->height) {
nDiffs = 0;
pixel.load(this->buffer[(i + 1) * this->width + j]);
diffPixel.load(pixel.toInt32());
if (abs(pixel.red - curPixel.red) <= diff && pixel.red != curPixel.red) {
++nDiffs;
diffPixel.red = pixel.red > curPixel.red ? curPixel.red + halfDiff : pixel.red + halfDiff;
}
if (abs(pixel.green - curPixel.green) <= diff && pixel.green != curPixel.green) {
++nDiffs;
diffPixel.green = pixel.green > curPixel.green ? curPixel.green + halfDiff : pixel.green + halfDiff;
}
if (abs(pixel.blue - curPixel.blue) <= diff && pixel.blue != curPixel.blue) {
++nDiffs;
diffPixel.blue = pixel.blue > curPixel.blue ? curPixel.blue + halfDiff : pixel.blue + halfDiff;
}
if (countDiffs >= nDiffs && nDiffs > 0) {
int* params = (int*) malloc(5 * sizeof(int));
params[0] = i + 1;
params[1] = j;
params[2] = i;
params[3] = j;
params[4] = diffPixel.toInt32();
fills.push_back(params);
}
}
}
}
memcpy(this->preBitMap, this->buffer, width * height * sizeof(int));
//cout << fills.size() << endl;
//int i = 0;
for (int i = 0; i < fills.size(); ++i) {
this->fillMap(fills[i][0], fills[i][1], fills[i][4]);
this->fillMap(fills[i][2], fills[i][3], fills[i][4]);
}
memcpy(this->buffer, this->preBitMap, width * height * sizeof(int));
free(this->preBitMap);
}
/**
* Заливка
* x - номер строчки
* y - номер столбца
*/
void fillMap(int x, int y, int color) {
Pixel pixel(this->preBitMap[x * this->width + y]);
int curColor = pixel.toInt32();
if (curColor == color) {
return;
}
bool* matrix = (bool*) malloc(this->width * this->height * sizeof(bool));
memset(matrix, false, this->width * this->height * sizeof(bool));
matrix[x * this->width + y] = true;
this->scanFill(matrix, curColor, color, x, y);
/*for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
if (matrix[i * this->width + j] == true) {
this->preBitMap[i * this->width + j] = color;
}
}
}*/
free(matrix);
}
void scanFill(bool* matrix, int color, int fillColor, int fillX, int fillY) {
bool test = false;
int xMin = fillX, xMax = fillX + 1, yMin = fillY, yMax = fillY + 1;
int iStart, iStop, jStart, jStop;
while (true) {
test = false;
iStart = xMin;
jStart = yMin;
iStop = xMax;
jStop = yMax;
for (int i = iStart; i < iStop; ++i) {
for (int j = jStart; j < jStop; ++j) {
if (matrix[i * this->width + j] == true) {
if (i - 1 >= 0 && matrix[(i - 1) * this->width + j] == false && this->preBitMap[(i - 1) * this->width + j] == color) {
matrix[(i - 1) * this->width + j] = true;
this->preBitMap[(i - 1) * this->width + j] = fillColor;
test = true;
if (xMin > i - 1) {
xMin = i - 1;
}
}
if (j - 1 >= 0 && matrix[i * this->width + j - 1] == false && this->preBitMap[i * this->width + j - 1] == color) {
matrix[i * this->width + j - 1] = true;
this->preBitMap[i * this->width + j - 1] = fillColor;
test = true;
if (yMin > j - 1) {
yMin = j - 1;
}
}
if (j + 1 < this->width && matrix[i * this->width + j + 1] == false && this->preBitMap[i * this->width + j + 1] == color) {
matrix[i * this->width + j + 1] = true;
this->preBitMap[i * this->width + j + 1] = fillColor;
test = true;
if (yMax < j + 1) {
yMax = j + 1;
}
}
if (i + 1 < this->height && matrix[(i + 1) * this->width + j] == false && this->preBitMap[(i + 1) * this->width + j] == color) {
matrix[(i + 1) * this->width + j] = true;
this->preBitMap[(i + 1) * this->width + j] = fillColor;
test = true;
if (xMax < i + 1) {
xMax = i + 1;
}
}
}
}
}
if (test == false) {
break;
}
}
}
/**
* 8 (ячеек вокруг) х 8 (оттенков серого) = 64
* kDot - оттенок серого зачищаемых точек 1..8
* k - коэффициент подавления шума 1..64
*/
void noiseClear(int kDot, int k) {
this->preBitMap = (int*) malloc(width * height * sizeof(int));
Pixel curPixel;
int kCurDot;
int kSumDots;
Pixel pixel;
for (int i = 0; i < this->height; ++i) {
for (int j = 0; j < this->width; ++j) {
kSumDots = 0;
curPixel.load(this->buffer[i * this->width + j]);
// kCurDot = 8 - ((curPixel.red + 1) >> 5);
kCurDot = this->getKGray(curPixel.red, 8);
if (kCurDot != kDot) {
this->preBitMap[i * this->width + j] = curPixel.toInt32();
continue;
}
if (i - 1 >= 0 && j - 1 >= 0) {
pixel.load(this->buffer[(i - 1) * this->width + j - 1]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (i - 1 >= 0) {
pixel.load(this->buffer[(i - 1) * this->width + j]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (i - 1 >= 0 && j + 1 < this->width) {
pixel.load(this->buffer[(i - 1) * this->width + j + 1]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (j - 1 >= 0) {
pixel.load(this->buffer[i * this->width + j - 1]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (j + 1 < this->width) {
pixel.load(this->buffer[i * this->width + j + 1]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (i + 1 < this->height && j - 1 >= 0) {
pixel.load(this->buffer[(i + 1) * this->width + j - 1]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (i + 1 < this->height) {
pixel.load(this->buffer[(i + 1) * this->width + j]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (i + 1 < this->height && j + 1 < this->width) {
pixel.load(this->buffer[(i + 1) * this->width + j + 1]);
kSumDots += this->getKGray(pixel.red, 8);
}
if (kSumDots <= k) {
pixel.load((UCHAR) 0xFF);
this->preBitMap[i * this->width + j] = pixel.toInt32();
} else {
this->preBitMap[i * this->width + j] = curPixel.toInt32();
}
}
}
memcpy(this->buffer, this->preBitMap, width * height * sizeof(int));
free(this->preBitMap);
}
int getKGray(unsigned char color, int maxK) {
// return maxK - ((color + 1) * maxK / 0x100);
return (int) round(maxK * (1 - (float) (color + 1) / 0x100));
}
};
| true |
740d109c525798a5f76d589e69eff2f2b1b79327 | C++ | GaoLF/LeetCode_THD | /13.Roman to Integer.cpp | UTF-8 | 1,075 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<string>
#include<unordered_set>
#include<unordered_map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int romanToInt(string s) {
vector<int> vec;
int res = 0;
for(int i = 0;i < s.length(); i++ ){
switch(s[i]){
case 'I': vec.push_back(1);break;
case 'V': vec.push_back(5);break;
case 'X': vec.push_back(10);break;
case 'L': vec.push_back(50);break;
case 'C': vec.push_back(100);break;
case 'D': vec.push_back(500);break;
case 'M': vec.push_back(1000);break;
}
}
for(int i = 0;i < s.size(); i++){
if(i + 1 < vec.size() && vec[i] < vec[i+1])
res -= vec[i];
else
res += vec[i];
}
return res;
}
void test(){
cout<<romanToInt("")<<endl;
cout<<romanToInt("XXXIV")<<endl;
cout<<romanToInt("MDCLXVI")<<endl;
cout<<romanToInt("MDCCCLXXXVIII")<<endl;
}
};
int main(){
Solution A;
A.test();
system("pause");
}
| true |
0888df5be6014f20cf1ff65477d4042339610047 | C++ | Aaronlanni/DataStruct | /冒泡排序/bubblesort1.hpp | UTF-8 | 424 | 3.90625 | 4 | [] | no_license | void BubbleSort(int *array, int size)
{
assert(array || size < 0);
int i = 0;
int j = 0;
for (; i < size - 1; ++i)
{
bool flag = false;
for (j = 0; j < size - i - 1; ++j)
{
if (array[j] > array[j + 1])
{
flag = true;
swap(array[j], array[j + 1]);
}
}
if (flag == false)
break;
}
} | true |
fc75eef96ac2ba7d19487bff2b3b787fb43a9c77 | C++ | viskey98/uva-solution | /CH03/11057.cpp | UTF-8 | 1,157 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#define FOR(i,n) for(i=0;i<n;i++)
int N;
using namespace std;
vector <long int> books;
int binarysearch(int start, int end, long int J)
{
if(start>end)return 0;
int mid=(start+end)/2;
if(books[mid]==J)
return 1;
else if(J>books[mid])
return binarysearch(mid+1,end,J);
else if(J<books[mid])
return binarysearch(0,mid-1,J);
}
int main()
{
long int temp,I,J,M;
int i,ans,mid,low;
vector< long int>::iterator Low;
while(cin>>N)
{
books.clear();
FOR(i,N)
{cin>>temp;books.push_back(temp);}
cin>>M;
sort(books.begin(),books.end());
Low=lower_bound(books.begin(),books.end(),M/2);
low=(Low-books.begin());
for(i=low;i<N;i++)
{
ans=0;
I=books[i];
J=M-I;
if(J>0)
{
if(J<I)
ans=binarysearch(0,low-1,J);
else
{
if(((i-1>=0)&&books[i-1]==J)||((i+1<N)&&books[i+1]==J))
ans=1;
}
}
if(ans==1)
{
break;
}
}
if(J<I){temp=J;
J=I;
I=temp;
}
printf("Peter should buy books whose prices are %d and %d.\n\n",I,J);
}
return 0;
} | true |
a9cf6a7f8ab14e6b74dfb970b8f010b8e4cbef51 | C++ | uvsq-versailles/Licence3_Informatique | /Semestre_5/IN505/PROJET/fractales/app/src/enregistreurFractale.cc | UTF-8 | 2,612 | 3.3125 | 3 | [
"MIT"
] | permissive | /**
* \file enregistreurFractale.cc
* \author {Clement Caumes Doudouh Yassin}
* \date 9 janvier 2018
* \brief contient la definition des methodes de EnregistreurFractale
*/
#include "../head/enregistreurFractale.hh"
#include "../head/types.hh"
using namespace Cairo;
/**
* \fn EnregistreurFractale::EnregistreurFractale(string filename)
* Constructeur de EnregistreurFractale
*/
EnregistreurFractale::EnregistreurFractale(string filename){
this->filename=filename;
this->largeur=0;
this->hauteur=0;
}
/**
* \fn EnregistreurFractale::~EnregistreurFractale()
* Destructeur de EnregistreurFractale
*/
EnregistreurFractale::~EnregistreurFractale(){}
/**
* \fn void EnregistreurFractale::dessinePixel(double x,double y,double r,double g,double b)
* Fonction qui dessine un pixel
* Redfinition de la methode de AbstractDessin pour dessiner un pixel selon Cairo
*/
void EnregistreurFractale::dessinePixel(double x,double y,double r,double g,double b){
contexte->stroke(); //afficher
contexte->set_source_rgb(r, g, b); //dessiner en couleur r,g,b
contexte->move_to(x, y); //place le point en (x,y)
contexte->line_to(x+1, y); // place le point juste a cote
}
/**
* \fn void EnregistreurFractale::enregistrerFractale(DessinFractaleGL& dessin)
* Fonction qui enregistre la fractale, cad qui cree un fichier SVG afin de la dessiner
*/
void EnregistreurFractale::enregistrerFractale(DessinFractaleGL& dessin){
// en fonction de la granularite du dessin, on va creer une image SVG selon la taille de la fractale
// permet de determiner le nombre de pixels dans l'image svg
double calculTaille=((dessin.getXMax()-dessin.getXMin())/dessin.getGranularite());
this->largeur=calculTaille;
this->hauteur=calculTaille;
//creation de SvgSurface
this->surface = SvgSurface::create(this->filename,this->largeur, this->hauteur);
//creation du contexte pour dessiner
this->contexte = Context::create(surface);
contexte->set_source_rgb(0, 0, 0); //couleur noire
contexte->set_line_width(1); //mettre des traits de la taille d'un pixel
double compteurX=dessin.getXMin();
double compteurY=dessin.getYMax();
double x,y;
int test;
for(x=0;x<(this->largeur); x=x+0.5){ //pour chaque pixel de l'image SVG
compteurY=dessin.getYMax();
for(y=0;y<(this->hauteur);y=y+0.5){
//calcul de la fractale pour chaque pixel
test=dessin.getFractale().calculFractale(compteurX,compteurY);
if(test==FRACTALE) dessinePixel(x,y,0,0,0);
compteurY-=dessin.getGranularite();
}
compteurX+=dessin.getGranularite();
}
contexte->stroke();
std::cout<<"Nouveau fichier "<<filename<<" cree"<<std::endl;
}
| true |
8e244b06800023465fb7fb6a9ec2ad6e449f62ab | C++ | Ostrichisme/LeetCode | /202. Happy Number.cpp | BIG5 | 360 | 3.15625 | 3 | [] | no_license | class Solution {
public:
bool isHappy(int n) {
int temp;
//ɤOѡAu17~|Otrue
while(n>=10){
int temp=n;
n=0;
for(auto c:to_string(temp))
n+=(c-48)*(c-48);
}
if(n==1||n==7)
return true;
else
return false;
}
};
| true |
3f39ef8b46265ebd039650ca7013c597a8767b53 | C++ | wintel2014/LinuxProgram | /CPU/cache/strip-mined_2.cpp | UTF-8 | 1,590 | 2.859375 | 3 | [] | no_license | #include <vector>
#include <stdio.h>
#include "../../Utils/readTsc.hpp"
#include "../../Utils/affinity.hpp"
//
// cat /sys/devices/system/cpu/cpu0/cache/index*/size
// 32K
// 32K
// 256K
// 9216K
//
long __attribute__((noinline)) Add(const int*pData, const size_t count)
{
long ret = 0;
for(unsigned i=0; i<count; i++)
{
ret += pData[i];
}
return ret;
}
long __attribute__((noinline)) Sub(const int*pData, const size_t count)
{
long ret = 0;
for(unsigned i=0; i<count; i++)
{
ret -= pData[i];
}
return ret;
}
constexpr size_t L3_CACHE_SIZE = 9126*1024;
int main()
{
SetAffinity(3);
constexpr auto ElementCount = L3_CACHE_SIZE*8; ////sizeof(int)==4, 32*L3_CACHE_SIZE;
std::vector<int> Data(ElementCount, 0);
for(int i=0; i<10; i++)
for(auto &ref:Data)
ref = i;
long ret = 0;
auto start = readTsc();
ret += Add(Data.data(), ElementCount);
ret += Sub(Data.data(), ElementCount);
auto end = readTsc()-start;
printf("%ld, cycles=%ld \n", ret, end);
auto stride = L3_CACHE_SIZE/sizeof(int)/4;
ret = 0;
start = readTsc();
for(int current=0; current<ElementCount; current+=stride)
{
/*
Even more function calls are generated here, but the performance much better than the previous.
0, cycles=200171358
0, cycles=108667153
*/
ret += Add(Data.data()+current, stride);
ret += Sub(Data.data()+current, stride);
}
end = readTsc()-start;
printf("%ld, cycles=%ld\n", ret, end);
}
| true |
b0c86cafc92bf2974f68bc928d4f7b7c20826053 | C++ | avaxman/scisim | /scisim/ConstrainedMaps/IpoptUtilities.cpp | UTF-8 | 3,989 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | // IpoptUtilities.cpp
//
// Breannan Smith
// Last updated: 09/03/2015
#include "IpoptUtilities.h"
#include <string>
bool IpoptUtilities::linearSolverSupported( const std::string& linear_solver_name )
{
if( linear_solver_name != "ma27" && linear_solver_name != "ma57" && linear_solver_name != "mumps" && linear_solver_name != "ma86" && linear_solver_name != "ma97" )
{
return false;
}
return true;
}
bool IpoptUtilities::containsDuplicates( const std::vector<std::string>& linear_solvers )
{
for( std::vector<std::string>::size_type idx0 = 0; idx0 < linear_solvers.size(); ++idx0 )
{
for( std::vector<std::string>::size_type idx1 = idx0 + 1; idx1 < linear_solvers.size(); ++idx1 )
{
if( linear_solvers[idx0] == linear_solvers[idx1] )
{
return true;
}
}
}
return false;
}
std::string IpoptUtilities::ipoptReturnStatusToString( const Ipopt::SolverReturn& status )
{
switch( status )
{
case Ipopt::SUCCESS:
{
return "SUCCESS";
}
case Ipopt::MAXITER_EXCEEDED:
{
return "MAXITER_EXCEEDED";
}
case Ipopt::CPUTIME_EXCEEDED:
{
return "CPUTIME_EXCEEDED";
}
case Ipopt::STOP_AT_TINY_STEP:
{
return "STOP_AT_TINY_STEP";
}
case Ipopt::STOP_AT_ACCEPTABLE_POINT:
{
return "STOP_AT_ACCEPTABLE_POINT";
}
case Ipopt::LOCAL_INFEASIBILITY:
{
return "LOCAL_INFEASIBILITY";
}
case Ipopt::USER_REQUESTED_STOP:
{
return "USER_REQUESTED_STOP";
}
case Ipopt::FEASIBLE_POINT_FOUND:
{
return "FEASIBLE_POINT_FOUND";
}
case Ipopt::DIVERGING_ITERATES:
{
return "DIVERGING_ITERATES";
}
case Ipopt::RESTORATION_FAILURE:
{
return "RESTORATION_FAILURE";
}
case Ipopt::ERROR_IN_STEP_COMPUTATION:
{
return "ERROR_IN_STEP_COMPUTATION";
}
case Ipopt::INVALID_NUMBER_DETECTED:
{
return "INVALID_NUMBER_DETECTED";
}
case Ipopt::TOO_FEW_DEGREES_OF_FREEDOM:
{
return "TOO_FEW_DEGREES_OF_FREEDOM";
}
case Ipopt::INVALID_OPTION:
{
return "INVALID_OPTION";
}
case Ipopt::OUT_OF_MEMORY:
{
return "OUT_OF_MEMORY";
}
case Ipopt::INTERNAL_ERROR:
{
return "INTERNAL_ERROR";
}
case Ipopt::UNASSIGNED:
{
return "UNASSIGNED";
}
}
return "ERROR: UNHANDLED CASE IN IpoptUtilities::ipoptReturnStatusToString";
}
int IpoptUtilities::nzLowerTriangular( const SparseMatrixsc& A )
{
int num{ 0 };
for( int col = 0; col < A.outerSize(); ++col )
{
for( SparseMatrixsc::InnerIterator it( A, col ); it; ++it )
{
// Skip entries above the diagonal
if( col > it.row() )
{
continue;
}
++num;
}
}
return num;
}
int IpoptUtilities::sparsityPatternLowerTriangular( const SparseMatrixsc& A, int* rows, int* cols )
{
assert( rows != nullptr );
assert( cols != nullptr );
int curel{ 0 };
for( int col = 0; col < A.outerSize(); ++col )
{
for( SparseMatrixsc::InnerIterator it( A, col ); it; ++it )
{
if( col > it.row() )
{
continue;
}
rows[curel] = int(it.row());
cols[curel] = col;
++curel;
}
}
return curel;
}
int IpoptUtilities::values( const SparseMatrixsc& A, scalar* vals )
{
assert( vals != nullptr );
int curel{ 0 };
for( int col = 0; col < A.outerSize(); ++col )
{
for( SparseMatrixsc::InnerIterator it( A, col ); it; ++it )
{
vals[curel] = it.value();
++curel;
}
}
assert( curel == A.nonZeros() );
return curel;
}
int IpoptUtilities::valuesLowerTriangular( const SparseMatrixsc& A, scalar* vals )
{
assert( vals != nullptr );
int curel{ 0 };
for( int col = 0; col < A.outerSize(); ++col )
{
for( SparseMatrixsc::InnerIterator it( A, col ); it; ++it )
{
if( col > it.row() )
{
continue;
}
vals[curel] = it.value();
++curel;
}
}
return curel;
}
| true |
ff5bbbc37339de54aa1d72b0b0f9b5d0207da3c4 | C++ | Luisill0/Activity-Selection | /src/ActivitySelector.hpp | UTF-8 | 543 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void recursiveActivitySelector(int* s,int* f, int k, int n,int *res,int iRes){
int m;
m = k + 1;
while(m <= n && s[m] < f[k]){
m++;
}
if(m <= n){
iRes++;
res[iRes] = m;
recursiveActivitySelector(s,f,k,n,res,iRes);
}else{
return;
}
}
int* greedyActivitySelector(int* s,int* f,int n,int *index){
int *A,*aux,i = 1;
A = createArray(n);
A[i] = 1;
int k = 1;
for(int m = 2; m <= n; m++){
if(s[m] >= f[k]){
A[i] = m;
++i;
k = m;
}
}
(*index) = i;
return A;
}
| true |
3504ffcf374d60452f5d9218eca693aaf1a921a0 | C++ | xuechensh/demo | /pipe.cpp | UTF-8 | 639 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
using namespace std;
#define MAX_MSG_SIZE 1024
int main(int argc, char** argv){
pid_t pid = -1;
int pipefd[2] = {0};
if(0 != pipe(pipefd)){
printf("create pipe error\n");
return 0;
}
pid = fork();
if( pid < 0){
printf("call fork error\n");
}
else if( pid > 0){
char msg[MAX_MSG_SIZE] = {0};
close(pipefd[1]);
read(pipefd[0], msg, MAX_MSG_SIZE);
printf("Recv: %s\n",msg);
}
else{
const char* msg = "hello world";
close(pipefd[0]);
write(pipefd[1], msg, strlen(msg));
}
printf(" exit pid = %d\n",getpid());
return 0;
}
| true |
761667ea8b84d05ff4b7b52bf863d48719c91cf6 | C++ | totticarter/myleetcode | /RemoveDuplicatesFromSortedList2.cc | UTF-8 | 831 | 3.453125 | 3 | [] | no_license | #include"leetcode.h"
ListNode* deleteDuplicates(ListNode* head){
ListNode* oneNode = head;
ListNode dummy(-1);
ListNode *newList = &dummy;
int lastValue = head->val;
while(oneNode != NULL){
if(oneNode->val == lastValue && oneNode != head){
oneNode = oneNode->next;
}else{
ListNode *newNode = new ListNode(oneNode->val);
newList->next = newNode;
newList = newList->next;
lastValue = oneNode->val;
oneNode = oneNode->next;
}
}
return dummy.next;
}
int main(){
ListNode list1(1);
ListNode node1(1);list1.next = &node1;
ListNode node2(2);node1.next = &node2;
ListNode node3(2);node2.next = &node3;
ListNode node4(4);node3.next = &node4;
ListNode node5(6);node4.next = &node5;
ListNode node6(6);node5.next = &node6;
print(&list1);
ListNode *n = deleteDuplicates(&list1);
print(n);
}
| true |
8ec379322a3320b3b88dffa7fae06fb3716aa68f | C++ | Jungzhang/cPlusPlus | /10_42.cpp | UTF-8 | 683 | 2.8125 | 3 | [] | no_license | /*************************************************************************
> File Name: 10_42.cpp
> Author: Jung
> Mail: jungzhang@xiyoulinux.org or zhanggen.jung@gmail.com
> Created Time: 2016年02月21日 星期日 17时40分21秒
> Description:
************************************************************************/
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <list>
int main(int argc, char *argv[])
{
std::list<std::string> l;
std::string str;
while(std::cin >> str) {
l.push_back(str);
}
l.sort();
l.unique();
for (auto a : l) {
std::cout << a << " ";
}
std::cout << std::endl;
return EXIT_SUCCESS;
}
| true |
5fefa7d56458cc3ceb63809c5b9010c0420e832a | C++ | usi-systems/railwaydb | /code/libcommon/include/intergdb/common/QueryWorkload.h | UTF-8 | 2,097 | 2.53125 | 3 | [] | no_license | #pragma once
#include <intergdb/common/Attribute.h>
#include <intergdb/common/QuerySummary.h>
#include <intergdb/common/Query.h>
#include <vector>
#include <unordered_map>
namespace intergdb { namespace common
{
class QueryWorkload
{
public:
QueryWorkload()
{}
QueryWorkload(std::vector<Attribute> const & attributes)
: totalQueries_(0)
{
for (auto &attribute : attributes)
{
attributes_.push_back(&attribute);
nameToAttribute_[attribute.getName()] = &attribute;
}
}
QueryWorkload(std::vector<Attribute> const & attributes,
std::vector<QuerySummary> const & queries)
: QueryWorkload(attributes)
{
queries_ = queries;
}
void addAttribute(Attribute const & attribute)
{
attributes_.push_back(&attribute);
}
Attribute const & getAttribute(int index) const
{
return *attributes_.at(index);
}
std::vector<Attribute const *> const & getAttributes() const
{
return attributes_;
}
void addQuerySummary(QuerySummary const & query)
{
queries_.push_back(query);
}
std::vector<QuerySummary> const & getQuerySummaries() const
{
return queries_;
}
std::vector<QuerySummary> & getQuerySummaries()
{
return queries_;
}
std::string toString() const;
void addQuery(Query const & q);
double getFrequency(QuerySummary const & s) const;
void setFrequency(QuerySummary const & s, double f);
private:
std::vector<Attribute const *> attributes_;
std::vector<QuerySummary> queries_;
std::unordered_map<Query, QuerySummary> summaries_;
std::unordered_map<QuerySummary, double> counts_;
std::unordered_map<std::string, const Attribute *> nameToAttribute_;
double totalQueries_;
};
} } /* namespace */
| true |
1412bb3add70d4c32ea0963bfb8c4596b34292e4 | C++ | bullfrognz/Pool | /Project/Source/LogManager.cpp | UTF-8 | 2,211 | 2.6875 | 3 | [] | no_license | //
// Diploma of Interactive Gaming
// Game Development Faculty
// Media Design School
// Auckland
// New Zealand
//
// (c) 2011 Media Design School
//
// File Name : "-----"
// Description : Template for implementation (source) files
// Author : Bryce Booth
// Mail : bryce.booth@mediadesign.school.nz
//
// Library Includes
#include <cassert>
#include <cstring>
// Local Includes
#include "LogTarget.h"
#include "LogGameWindow.h"
#include "LogOutputWindow.h"
// This Include
#include "LogManager.h"
// Static Variables
// Static Function Prototypes
// Implementation
CLogManager::CLogManager()
: m_cpTextBuffer(0)
{
}
CLogManager::~CLogManager()
{
Deinitialise();
}
bool
CLogManager::Initialise()
{
m_cpTextBuffer = new char[s_kiTextBufferSize];
return(true);
}
bool
CLogManager::Deinitialise()
{
delete m_cpTextBuffer;
m_cpTextBuffer = 0;
std::vector<ILogTarget*>::iterator Iter;
for(Iter = m_vecLogTargets.begin(); Iter != m_vecLogTargets.end(); ++Iter)
{
delete (*Iter);
(*Iter) = 0;
}
return (true);
}
void
CLogManager::Process(float _fDeltaTick)
{
std::vector<ILogTarget*>::iterator Iter;
for(Iter = m_vecLogTargets.begin(); Iter != m_vecLogTargets.end(); ++Iter)
{
(*Iter)->Process(_fDeltaTick);
}
}
void
CLogManager::Draw()
{
std::vector<ILogTarget*>::iterator Iter;
for(Iter = m_vecLogTargets.begin(); Iter != m_vecLogTargets.end(); ++Iter)
{
(*Iter)->Draw();
}
}
bool
CLogManager::AddLogTarget(ELogTarget _eLogTarget)
{
ILogTarget* pLogTarget = 0;
switch (_eLogTarget)
{
case LOGTARGET_FILE:
break;
case LOGTARGET_OUTPUT:
pLogTarget = new CLogOutputWindow();
break;
case LOGTARGET_GAMEWINDOW:
pLogTarget = new CLogGameWindow();
break;
}
pLogTarget->Initialise();
m_vecLogTargets.push_back(pLogTarget);
return(false);
}
bool
CLogManager::RemoveLogTarget(ELogTarget _eLogTarget)
{
return(true);
}
void
CLogManager::Write(const char* _pcMessage)
{
std::vector<ILogTarget*>::iterator iter;
iter = m_vecLogTargets.begin();
(*iter)->Write(_pcMessage);
}
void
CLogManager::WriteOutput(const char* _pcMessage)
{
std::vector<ILogTarget*>::iterator iter;
iter = m_vecLogTargets.begin() + 1;
(*iter)->Write(_pcMessage);
} | true |
bddc9e0fa49fed31bd7201c2fd36f1a7503fd6e6 | C++ | josezm/cpp-exercises | /multiplo mas pequeno.cpp | UTF-8 | 333 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int x=2520,i=1,contador=0,res=0;
bool z=true, y=true;
while (z){
if (contador==20){
z=false;
res=x;}
if (contador<20)
contador = 0;
x++;
for(i=1;i<21;i++){
if (x%i==0)
contador++;
}
}
cout << "el menor es: " <<res;
return 0;
}
| true |
985660a6338c37c4518724549a4af86a0b182518 | C++ | wiwitrifai/competitive-programming | /codeforces/453/b.cpp | UTF-8 | 1,946 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef vector<double> polinom;
polinom mult(polinom a, polinom b) {
polinom res(a.size() + b.size() - 1);
for (int i = 0; i < a.size(); ++i)
for (int j = 0; j < b.size(); ++j) {
res[i+j] += a[i] * b[j];
}
return res;
}
polinom add(polinom a, polinom b) {
polinom res(max(a.size(), b.size()));
for (int i = 0; i < a.size(); ++i)
res[i] = a[i] + b[i];
return res;
}
const int N = 151;
const long double eps = 1e-9;
pair<polinom, polinom> ans[N];
bool val[N];
polinom modu(polinom a, polinom b) {
polinom cur = a;
while (cur.size() >= b.size()) {
polinom kali((int)cur.size() - (int)b.size() + 1);
kali[(int)cur.size() - b.size()] = -cur.back() / b.back();
cur = add(cur, mult(kali, b));
while (cur.size() > 0 && fabs(cur.back()) < eps) cur.pop_back();
}
return cur;
}
bool get(polinom a, polinom b) {
polinom c = modu(a, b);
if (c.size() < (int)b.size()-1)
return 0;
if (c.size() == 0) return 1;
return get(b, c);
}
polinom generate(int n) {
polinom ret(n+1);
ret[n] = 1;
for (int i = 0; i < n; ++i) {
int val = rand() % 3;
while (val > 1) val -= 3;
while (val < -1) val += 3;
ret[i] = val;
}
return ret;
}
int main() {
srand(time(0));
polinom p = {-1,-1,-1,1,0,-1,1,1,-1,1,1,0,-1,0,1,1,-1,1,0,-1,1,1,-1,0,1,1,1,0,1,0,0,-1,0,-1,0,1,-1,-1,1,1,1,-1,-1,0,0,0,-1,-1,1},
q = {-1,0,-1,-1,-1,-1,-1,-1,0,1,0,-1,-1,0,1,0,-1,1,1,1,1,-1,0,0,-1,0,1,0,1,1,0,-1,-1,0,1,-1,0,1,1,0,-1,-1,0,1,-1,-1,1,1};
cerr << get(p, q) << endl;
int n;
scanf("%d", &n);
while (1) {
polinom a = generate(n), b = generate(n-1);
if (!get(a, b)) continue;
printf("%d\n", n);
for (int i = 0; i <= n; ++i)
printf("%d%c", (int)a[i], (i == n) ? '\n' : ' ');
printf("%d\n", n-1);
for (int i = 0; i <= n-1; ++i)
printf("%d%c", (int)b[i], (i == n-1) ? '\n' : ' ');
break;
}
return 0;
} | true |
4d8cb01306604d756a96b1fed40a000c6349b520 | C++ | sellersgrant/AdventOfCode2018 | /src/Day07/sellersgrant.cpp | UTF-8 | 9,767 | 3 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#define BOUNDS 26
#define OFFSET 61
#define WORKERS 5
int convertChar(char a)
{
return (int)(a) - 65;
}
char convertInt(int a)
{
return (char)(a + 65);
}
void extend(std::vector<int>* buffer, std::vector<int> to_append)
{
for (std::vector<int>::iterator it = to_append.begin(); it != to_append.end(); it++)
{
if (std::find(buffer->begin(),buffer->end(), *it) == buffer->end())
buffer->push_back(*it);
}
}
class Graph
{
int data[BOUNDS][BOUNDS] = {0};
public:
void insert(int a, int b)
{
data[a][b] = 1;
}
void print()
{
for (int i = 0; i<BOUNDS; i++)
{
for (int j = 0; j<BOUNDS; j++)
{
std::cout << data[i][j];
}
std::cout << std::endl;
}
}
void print(std::vector<int> toPrint)
{
for (std::vector<int>::iterator it = toPrint.begin(); it != toPrint.end(); it++)
std::cout << *it;
}
std::string getProblemOne()
{
std::string output = "";
std::vector<int> outputInt;
std::vector<int> options = this->findBegins();
while(!options.empty())
{
std::vector<int>::iterator toRemove;
std::vector<int> new_options;
//iterate over options, choosing the first one which has been previously sorted
for (std::vector<int>::iterator it = options.begin(); it != options.end(); it++)
{
// Check each element to see if the option has met given dependencies
if (checkRequirements(outputInt,*it))
{
// If the node hasn't already been added, add it. Otherwise, just remove from options
if (std::find(outputInt.begin(), outputInt.end(), *it) == outputInt.end())
{
outputInt.push_back(*it);
new_options = this->getRow(*it);
}
toRemove = it;
break;
}
}
// Remove chosen element from viable options
options.erase(toRemove);
// Add the chosen elements branches to options
extend(&options,new_options);
// Sort options so that the first valid option will appear in the next for loop
std::sort(options.begin(),options.end());
}
// Convert integer indices to character vector
for (std::vector<int>::iterator it = outputInt.begin(); it != outputInt.end(); it++)
{
output.push_back(convertInt(*it));
}
return output;
}
int getProblemTwo()
{
std::string output = "";
std::vector<int> outputInt;
std::vector<int> options = this->findBegins();
std::vector<std::pair<int,int>> workers;
int answer = -1; // since the first iteration is round second 0
while(!options.empty() || workerIsBusy(workers))
{
std::vector<int> finishedWorkers = getFinishedWorkers(&workers);
for (std::vector<int>::iterator it = finishedWorkers.begin(); it!= finishedWorkers.end(); it++)
{
if (std::find(outputInt.begin(), outputInt.end(), *it) == outputInt.end())
{
outputInt.push_back(*it);
extend(&options,this->getRow(*it));
}
}
std::vector<int>::iterator toRemove = options.end();
bool optionsAvailable = !options.empty();;
while (workerIsFree(workers) && optionsAvailable)
{
bool noOptionsMeetRequirements = true;
//iterate over options, choosing the first one which has been previously sorted
for (std::vector<int>::iterator it = options.begin(); it != options.end(); it++)
{
// Check each element to see if the option has met given dependencies
if (checkRequirements(outputInt,*it))
{
toRemove = it;
if (std::find(outputInt.begin(), outputInt.end(), *it) == outputInt.end())
startWorker(&workers,*it);
noOptionsMeetRequirements = false;
break;
}
}
// Remove chosen element from viable options
if (toRemove != options.end())
options.erase(toRemove);
// Sort options so that the first valid option will appear in the next for loop
std::sort(options.begin(),options.end());
optionsAvailable = !options.empty() & !noOptionsMeetRequirements;
}
answer++;
advanceWorkers(&workers);
}
return answer;
}
private:
void printO(std::vector<int> outputInt)
{
// Convert integer indices to character vector
for (std::vector<int>::iterator it = outputInt.begin(); it != outputInt.end(); it++)
{
std::cout << convertInt(*it);
}
}
void printW(std::vector<std::pair<int,int>> workers)
{
std::cout << " Workers: ";
for (std::vector<std::pair<int,int>>::iterator it = workers.begin(); it != workers.end(); it++)
{
std::cout << convertInt(it->first);
}
}
bool workerIsFree(std::vector<std::pair<int,int>> workers)
{
return workers.size() < WORKERS;
}
bool workerIsBusy(std::vector<std::pair<int,int>> workers)
{
return workers.size() >0 ;
}
void startWorker(std::vector<std::pair<int,int>>* workers, int element)
{
workers->push_back(std::pair<int,int>(element, element+OFFSET));
}
std::vector<int> getFinishedWorkers(std::vector<std::pair<int,int>>* workers)
{
std::vector<std::vector<std::pair<int,int>>::iterator> to_remove;
std::vector<int> finishedWorkers;
for (std::vector<std::pair<int,int>>::iterator it = workers->begin(); it != workers->end(); it++)
{
if (it->second == 0)
to_remove.push_back(it);
}
for (std::vector<std::vector<std::pair<int,int>>::iterator>::iterator it = to_remove.begin(); it!= to_remove.end(); it++)
{
finishedWorkers.push_back((*it)->first);
workers->erase(*it);
}
return finishedWorkers;
}
void advanceWorkers(std::vector<std::pair<int,int>>* workers)
{
for (std::vector<std::pair<int,int>>::iterator it = workers->begin(); it != workers->end(); it++)
{
it->second--;
}
}
bool checkRequirements(std::vector<int> output, int ele)
{
bool requirementsMet = true;
std::vector<int> dependencies = this->getCol(ele);
for (std::vector<int>::iterator it = dependencies.begin(); it != dependencies.end(); it++)
requirementsMet &= std::find(output.begin(),output.end(),*it) != output.end();
return requirementsMet;
}
std::vector<int> findBegins()
{
std::vector<int> output;
for (int i = 0; i < BOUNDS; i++)
{
bool connectionExists = false;
for (int j = 0; j < BOUNDS; j++)
{
connectionExists |= data[j][i];
}
if (!connectionExists)
output.push_back(i);
}
return output;
}
std::vector<int> getRow(int i)
{
std::vector<int> output;
for (int j = 0; j < BOUNDS; j++)
{
if(data[i][j])
output.push_back(j);
}
return output;
}
std::vector<int> getCol(int j)
{
std::vector<int> output;
for (int i = 0; i < BOUNDS; i++)
{
if(data[i][j])
output.push_back(i);
}
return output;
}
};
Graph parseInput(std::string filename)
{
std::ifstream inputFile;
inputFile.open(filename);
Graph graph;
if (inputFile.is_open())
{
std::string line;
while (getline(inputFile,line))
{
char a, b;
sscanf(line.c_str(), "Step %c must be finished before step %c can begin.", &a,&b);
graph.insert(convertChar(a),convertChar(b));
}
}
return graph;
}
int main(int argc, char const *argv[])
{
Graph graph = parseInput(argv[1]);
graph.print();
std::cout << graph.getProblemOne() << std::endl;
std::cout << graph.getProblemTwo() << std::endl;
return 0;
}
| true |
0828e94e61f2f2ce533ebbd69f6634bc7edd5562 | C++ | hbchen121/SimpleCNN_Release | /SimpleCNN/SdlfFunction.cpp | GB18030 | 7,113 | 2.765625 | 3 | [] | no_license | /***********************************************
* File: SdlfFunction.cpp
*
* Author: CHB
* Date: 2020-04-18
*
* Purpose:峣ú
*
*
**********************************************/
#include <math.h>
#include <algorithm>
#include "SdlfFunction.h"
#include "KernelCPU.h"
#include "Common.h"
float SdlfFunction::MaxInPool(float* Data, int Num, int& MaxIndex)
{
// ðһ
float MaxValue = Data[0];
MaxIndex = 0;
for (int i = 1; i < Num; i++)
{
if (MaxValue < Data[i])
{
MaxValue = Data[i];
MaxIndex = i;
}
}
return MaxValue;
}
float SdlfFunction::DotProduct(float* Data1, float* Data2, int Num)
{
float Sum = 0.0f;
for (int i = 0; i < Num; i++)
{
Sum += Data1[i] * Data2[i];
}
return Sum;
}
float SdlfFunction::UnitRandom()
{
static bool FirstRun = true;
if (FirstRun) {
srand((unsigned)time(NULL));
FirstRun = false;
}
return float(rand()) / float(RAND_MAX);
}
float SdlfFunction::RangeRandom(float Min, float Max)
{
return Min + (Max - Min) * UnitRandom();
}
double SdlfFunction::Pow(double x, double y)
{
return pow(x, y);
}
double SdlfFunction::Exp(double n)
{
return exp(n);
}
double SdlfFunction::ln(double n)
{
return log(n);
}
double SdlfFunction::lg(double n)
{
return log10(n);
}
double SdlfFunction::log_m_n(double m, double n)
{
return ln(n) / ln(m);
}
void SdlfFunction::softmax(float* InArrayDest, float* OutArray, int Num)
{
float sum = 0;
for (int i = 0; i < Num; i++) {
OutArray[i] = (float)Exp(InArrayDest[i]);
sum += OutArray[i];
}
for (int i = 0; i < Num; i++)
{
OutArray[i] /= sum;
}
return;
}
void SdlfFunction::BuildConvArrayPerBatch(ConvBlocks* CB, float* ImageData, int ImageWidth, int ImageHeight, int ImageDepth, int ConvWidth, int ConvHeight, int BatchSizeIndex)
{
// ÿСĴСǾ˵ĴС
int ConvLen = ConvWidth * ConvHeight * ImageDepth;
// ͼƬһһС
// ÿBatchôС
int ImgSizePerChannel = ImageHeight * ImageWidth;
int HalfConv = ConvWidth >> 1;
float* ConvQuad = new float[ConvLen];
for (int i = 0; i < ImageHeight; i++) {
for (int j = 0; j < ImageWidth; j++) {
// ʼquad
for (int k = 0; k < ImageDepth; k++) {
for (int m = 0; m < ConvHeight; m++) {
for (int n = 0; n < ConvWidth; n++) {
int ConvPos = k * ConvHeight * ConvWidth + m * ConvWidth + n;
int x_ = n - HalfConv;
int y_ = m - HalfConv;
int x = j + x_;
int y = i + y_;
if (x < 0 || x >= ImageWidth || y < 0 || y >= ImageHeight) {
ConvQuad[ConvPos] = 0;
}
else {
int Pos = ImgSizePerChannel * k + y * ImageWidth + x;
ConvQuad[ConvPos] = ImageData[Pos];
}
}
}
}
memcpy(CB->ConvArray + (ImgSizePerChannel * BatchSizeIndex + i * ImageWidth + j) * ConvLen, ConvQuad, sizeof(float) * ConvLen);
}
}
SAFE_DELETE_ARRAY(ConvQuad);
}
void SdlfFunction::BuildConvArray(ConvBlocks* CB, float* ImageData, int ImageWidth, int ImageHeight, int ImageDepth, int ConvWidth, int ConvHeight, int BatchSize)
{
int ConvLen = ConvWidth * ConvHeight * ImageDepth;
int ImageSize = ImageWidth * ImageHeight * ImageDepth;
if (CB->ConvArray == nullptr) {
CB->ConvArray = new float[ImageWidth * ImageHeight * BatchSize * ConvLen];
CB->ArrayLen = ConvLen;
}
// batch convArray м
for (int i = 0; i < BatchSize; i++) {
int Pos = i * ImageSize;
BuildConvArrayPerBatch(CB, &ImageData[Pos], ImageWidth, ImageHeight, ImageDepth, ConvWidth, ConvHeight, i);
}
return;
}
void SdlfFunction::BuildFullConnectedArrayPerBatch(ConvBlocks* CB, float* ImageData, int ImageWidth, int ImageHeight, int ImageDepth, int BatchIndex)
{
int ImgSize = ImageWidth * ImageHeight * ImageDepth;
memcpy(CB->ConvArray + BatchIndex * ImgSize, ImageData, sizeof(float) * ImgSize);
}
void SdlfFunction::BuildFullConnectedArray(ConvBlocks* CB, float* ImageData, int ImageWidth, int ImageHeight, int ImageDepth, int BatchSize)
{
int ImgSize = ImageWidth * ImageHeight * ImageDepth;
if (CB->ConvArray == nullptr) {
CB->ConvArray = new float[ImgSize * BatchSize];
CB->ArrayLen = ImgSize;
}
for (int i = 0; i < BatchSize; i++) {
BuildFullConnectedArrayPerBatch(CB, ImageData + i * ImgSize, ImageWidth, ImageHeight, ImageDepth, i);
}
}
void SdlfFunction::ConvFullConnected(ConvBlocks* CB, ConvKernel* CK, float* ImageOutData, float* ReluOutData, int BatchSize)
{
// ȫ˵һͼƬһľbatch
for (int i = 0; i < BatchSize; i++)
{
for (int j = 0; j < CK->ConvKernelCount; j++)
{
float ConvResult = CK->Conv2D(&CB->ConvArray[i * CB->ArrayLen], j);
if (ConvResult > 0.0f)
{
ImageOutData[i * CK->ConvKernelCount + j] = ConvResult;
ReluOutData[i * CK->ConvKernelCount + j] = 1.0f;
}
}
}
}
void SdlfFunction::Conv2D(ConvBlocks* CB, int ConvBlocksPerBatch, ConvKernel* CK, float* ImageOutData, int ImageSize2D, float* ReluOutData, int BatchSize)
{
// batch ConvBlock
int ImageSize3D = ImageSize2D * CK->ConvKernelCount;
for (int i = 0; i < BatchSize; i++)
{
Conv2DPerImage(CB, ConvBlocksPerBatch, i, CK, &ImageOutData[i * ImageSize3D], ImageSize2D, &ReluOutData[i * ImageSize3D]);
}
}
void SdlfFunction::Conv2DPerImage(ConvBlocks* CB, int ConvBlocksPerBatch, int BatchIndex, ConvKernel* CK, float* ImageOutData, int ImageSize2D, float* ReluOutData)
{
// ÿһ ͼƬо
for (int i = 0; i < CK->ConvKernelCount; i++)
{
Conv2DPerImagePerConvKernel(CB, ConvBlocksPerBatch, BatchIndex, CK, i, &ImageOutData[ImageSize2D * i], &ReluOutData[ImageSize2D * i]);
}
}
void SdlfFunction::Conv2DPerImagePerConvKernel(ConvBlocks* CB, int ConvBlocksPerBatch, int BatchIndex, ConvKernel* CK, int ConvKernelIndex, float* ImageOutData, float* ReluOutData)
{
// ConvBlocksPerBatch Ϊ CB аÿ batch ConvLen array
int StartPos = ConvBlocksPerBatch * BatchIndex;
for (int i = 0; i < ConvBlocksPerBatch; i++)
{
float ConvResult = CK->Conv2D(&CB->ConvArray[(StartPos + i) * CB->ArrayLen], ConvKernelIndex);
if (ConvResult > 0)
{
// ٶImageOutDataReluOutDataѾʼΪ0
ImageOutData[i] = ConvResult;
ReluOutData[i] = 1.0f;
}
}
}
| true |
881ad153583e11db26daafc83373064197a517e6 | C++ | viswaf1/MultiModelFitting | /MultiRansac.cpp | UTF-8 | 3,563 | 2.609375 | 3 | [] | no_license | /*
* MultiRansac.cpp
*
* Created on: Apr 1, 2016
* Author: teja
*/
#include "MultiRansac.h"
namespace std {
bool CSElmCompare(CSElement el1, CSElement el2) {
return(el1.inliers.size() < el2.inliers.size());
}
MultiRansac::MultiRansac(vector<vec2f> inpts, int initerNum, float inthDist, float ininlrRatio) {
iterNum = initerNum;
inlrRatio = ininlrRatio;
thInlrNum = inlrRatio*inpts.size();
thDist = inthDist;
for(unsigned int i=0; i<inpts.size(); i++) {
DataPoint tempPt;
tempPt.point = inpts[i];
tempPt.index = i;
dataPts.push_back(tempPt);
}
srand(time(NULL));
}
vector<vec2f> MultiRansac::getMultiModels() {
int numMultiIters = 1;
for(int i=0; i<numMultiIters; i++) {
vector<DataPoint> currentData = dataPts;
int startInd = rand() % (currentData.size() );
vector<CSElement> newCS;
for(int j=0; j<1000; j++) {
if(currentData.size() < 2) {
break;
}
vector<vec2f> dataPts;
for(unsigned int x=0; x<currentData.size(); x++)
dataPts.push_back(currentData[x].point);
CSElement curCSEl;
Ransac ransac(dataPts, iterNum, thDist, inlrRatio, startInd);
curCSEl.model = ransac.getModel();
vector<int> ptsUsedIter = ransac.getUsedPts();
//if the size of points used is empty, then there are no models in the data
if(ptsUsedIter.size() < 1) {
break;
}
/* Conver the points used in the current iteration of RANSAC
to inliers indexed on the original data */
vector<int> inliersIter;
for(unsigned int x=0; x<ptsUsedIter.size(); x++) {
inliersIter.push_back(currentData[ptsUsedIter[x]].index);
}
curCSEl.inliers = inliersIter;
// remove point used in the current iteration from currentData
vector<int> usedPtsMap(currentData.size());
for(unsigned int x=0; x<ptsUsedIter.size(); x++) {
usedPtsMap[ptsUsedIter[x]] = 1;
}
vector<DataPoint> newCurrentData;
for(unsigned int x=0; x<currentData.size(); x++) {
if(!usedPtsMap[x]){
newCurrentData.push_back(currentData[x]);
}
}
startInd = startInd - ptsUsedIter.size();
startInd = (startInd+10)%newCurrentData.size();
currentData = newCurrentData;
newCS.push_back(curCSEl);
//cout << "size of remaining points is " << currentData.size() << "\n";
//cout << "the model iter is " << curCSEl.model.x << " " << curCSEl.model.y << "\n";
}
updateCS(newCS);
}
vector<vec2f> multiModels;
for(int i=0; i<CS.size(); i++) {
multiModels.push_back(CS[i].model);
}
return multiModels;
}
void MultiRansac::updateCS(vector<CSElement> &Sw) {
vector<CSElement> allCS = CS;
CS.clear();
for(unsigned int i=0; i<Sw.size(); i++){
allCS.push_back(Sw[i]);
}
sort(allCS.begin(), allCS.end(), CSElmCompare);
while(allCS.size() > 0) {
CSElement curEl = allCS[allCS.size()-1];
allCS.pop_back();
if(checkDisjoint(CS, curEl)) {
CS.push_back(curEl);
}
}
}
bool MultiRansac::checkDisjoint(vector<CSElement> &Sw, CSElement &S) {
if(Sw.size() < 1)
return true;
for(unsigned int i=0; i<Sw.size(); i++) {
if(!checkDisjointElements(Sw[i], S))
return false;
}
return true;
}
bool MultiRansac::checkDisjointElements(CSElement &E1, CSElement &E2) {
sort(E1.inliers.begin(), E1.inliers.end());
sort(E2.inliers.begin(), E2.inliers.end());
vector<int> interInliers;
set_intersection(E1.inliers.begin(), E1.inliers.end(), E2.inliers.begin(),
E2.inliers.end(), back_inserter(interInliers));
if(interInliers.size() > 10) {
return false;
}
else {
return true;
}
return true;
}
MultiRansac::~MultiRansac() {
}
} /* namespace std */
| true |
48f74410b044fd7729ea6b8dfb464388aaf1a57b | C++ | baixigxn/2021_first | /基础巩固/C_43/main.cpp | GB18030 | 1,255 | 4.25 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
/*
Ŀһ
Ǵʱʹͷ巨˳ģǿڸĻϽ
*/
typedef struct Node{
int data;
struct Node* next;
}Node,*LinkList;
//ͷβ巨
LinkList creste(int n){
LinkList head=(Node*)malloc(sizeof(Node));
Node *p=head;
Node *q;
int i;
printf("Ԫֵ\n");
for (i = 0; i < n; i++)
{
q=(Node*)malloc(sizeof(Node));
scanf("%d",&q->data);
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
//ԭãԪʹͷ巨ʹ
LinkList reverse(LinkList L){
Node *prep;
Node *p,*q;
p=L->next;
q=p->next;
p->next=NULL;
while (q)
{
prep=q;
q=q->next;
prep->next=p;
p=prep;
}
L->next=prep;
return L;
}
void Print(LinkList L){
L=L->next;
while (L)
{
printf("%3d",L->data);
L=L->next;
}
printf("\n");
}
int main(){
printf("Ҫ:\n");
int n;
scanf("%d",&n);
LinkList L=creste(n);
printf("ǰ£\n");
Print(L);
printf("Ԫúǣ\n");
Print(reverse(L));
system("pause");
return 0;
} | true |
fe997b52cba0cdf7f6b57c6d63d8622c56830948 | C++ | bwhitely/DungeonBuilder | /Core/Dungeon/Common/blockeddoorway.cpp | UTF-8 | 1,379 | 3.046875 | 3 | [] | no_license | #include "blockeddoorway.h"
#include <iostream>
namespace core::dungeon::common {
BlockedDoorWay::BlockedDoorWay(Direction direction): Doorway{direction} {
_direction = direction;
}
/**
* @brief BlockedDoorWay::~BlockedDoorWay
* Sets _opposite doorway to nullptr
*/
BlockedDoorWay::~BlockedDoorWay() {
// remove dangling ptr
if (_opposite)
_opposite = nullptr;
}
/**
* @brief BlockedDoorWay::connect - Connects to opposite doorway via bare pointer
* @param opposite
*/
void BlockedDoorWay::connect(Doorway* opposite) {
if (_opposite == nullptr){
// connecting via bare pointer
_opposite = opposite;
opposite->connect(this);
}
}
/**
* @brief BlockedDoorWay::isEntrance
* @return false
*/
bool BlockedDoorWay::isEntrance()
{
return false;
}
/**
* @brief BlockedDoorWay::isExit
* @return false
*/
bool BlockedDoorWay::isExit()
{
return false;
}
/**
* @brief BlockedDoorWay::isPassage
* @return false
*/
bool BlockedDoorWay::isPassage() const {
return false;
}
/**
* @brief BlockedDoorWay::displayCharacter
* @return 'X'
*/
char BlockedDoorWay::displayCharacter() const {
return 'X';
}
/**
* @brief BlockedDoorWay::description
* @return returns one line description of Doorway
*/
std::string BlockedDoorWay::description() const {
return "a Blocked Doorway to another chamber";
}
}
| true |
bf47937364e61bd68fdf4844501abe16283559d5 | C++ | michalsvagerka/competitive | /arch/a2oj/mix/CColoradoPotatoBeetle.cpp | UTF-8 | 2,847 | 2.515625 | 3 | [] | no_license | #include "../l/lib.h"
// #include "../l/mod.h"
class CColoradoPotatoBeetle {
public:
vector<int> RG, CG;
vector<vector<int>> S;
void dfs(int x, int y) {
if (x >= 0 && x < RG.size() && y >= 0 && y < CG.size() && !S[x][y]) {
S[x][y] = 2;
dfs(x+1, y);
dfs(x-1, y);
dfs(x, y+1);
dfs(x, y-1);
}
}
void solve(istream& cin, ostream& cout) {
int N; cin >> N;
int r = 0, c = 0;
set<int> R, C;
R.insert(-2e9);
R.insert(2e9);
C.insert(-2e9);
C.insert(2e9);
vector<pair<char,int>> T;
for (int i = 0; i < N; ++i) {
char d; int l;
cin >> d >> l;
T.push_back({d,l});
R.insert(r-1);
R.insert(r);
R.insert(r+1);
C.insert(c-1);
C.insert(c);
C.insert(c+1);
switch (d) {
case 'U':
r -= l;
break;
case 'D':
r += l;
break;
case 'R':
c += l;
break;
case 'L':
c -= l;
break;
}
R.insert(r-1);
R.insert(r);
R.insert(r+1);
C.insert(c-1);
C.insert(c);
C.insert(c+1);
}
RG = vector<int>(R.begin(),R.end());
CG = vector<int>(C.begin(),C.end());
map<int, int> RI, CI;
for (int i = 0; i < RG.size(); ++i) RI[RG[i]] = i;
for (int i = 0; i < CG.size(); ++i) CI[CG[i]] = i;
S = vector2<int>(RG.size(), CG.size(), 0);
r = c = 0;
for (int i = 0; i < N; ++i) {
char d = T[i].x; int l = T[i].y;
switch (d) {
case 'U':
for (int j = RI[r-l]; j <= RI[r]; ++j) S[j][CI[c]] = 1;
r -= l;
break;
case 'D':
for (int j = RI[r]; j <= RI[r+l]; ++j) S[j][CI[c]] = 1;
r += l;
break;
case 'R':
for (int j = CI[c]; j <= CI[c+l]; ++j) S[RI[r]][j] = 1;
c += l;
break;
case 'L':
for (int j = CI[c-l]; j <= CI[c]; ++j) S[RI[r]][j] = 1;
c -= l;
break;
}
}
dfs(0,0);
ll ans = 0;
for (int i = 0; i < RG.size(); ++i) {
for (int j = 0; j < CG.size(); ++j) {
if (S[i][j] != 2) {
ans += ll(RG[i+1] - RG[i]) * (CG[j+1] - CG[j]);
}
}
}
cout << ans << endl;
}
};
| true |
024f9a46896523204a734326e403fbb7ccf4bb2d | C++ | midnitekoder/Latte | /src/activation_function.cpp | UTF-8 | 801 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | #include<stdio.h>
#include<math.h>
#include "util.h"
float maxfloat(float num1, float num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
float activation(activation_type type_of_activation, float val, float negative_slope)
{
double positive_exp, negative_exp;
switch (type_of_activation)
{
case AF_RELU:
return maxfloat(0, val);
case AF_SIGM:
return (float)(1.0 / (1.0 + exp(-val)));
case AF_TANH:
positive_exp = exp(val);
negative_exp = exp(-val);
return (float)((positive_exp - negative_exp) / (positive_exp + negative_exp));
case AF_LEAKY_RELU:
return val > 0 ? val : val*negative_slope;
case AF_ELU:
return (float)(exp(val)*(val < 0) + val*(val >= 0));
case AF_NOACTIVATION:
return val;
default:
return 0.0;
}
} | true |
712cb2e2a00b37d7135800237655331e642342a6 | C++ | astrellon/GPP | /GPP/lab02/lab02/main.cpp | UTF-8 | 334 | 2.859375 | 3 | [] | no_license | /*#include "Vector3.hpp"
#include <Windows.h>
#include <iostream>
using namespace std;
void disp(Vector3 &vec)
{
cout << vec.m_fX << ", " << vec.m_fY << ", " << vec.m_fZ << endl;
}
int main()
{
Vector3 vec1(1, 2, 3);
Vector3 vec2(2, 4, 6);
Vector3 vec3(1, 1, 1);
vec3 = -vec1;
disp(vec3);
system("PAUSE");
return 0;
}*/ | true |
ca88e6749eac476e376f0a8edb9129a0a86d541a | C++ | tomotomek/Cpp | /09_cvicenie.h | UTF-8 | 6,646 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
//#include "riesenie9.h"
//Toto je vlozeny hlavickovy subor riesenie9.h
#if !defined( _RIESENIE_H_ )
#define _RIESENIE_H_
class Vynimka {};
class ZlyVstup : public Vynimka {
string text;
public:
ZlyVstup(const char *v) { text = v; };
string vypis() const { return text; };
};
//1.uloha
struct Cas {
int hod, min, sek, mikrosek;
string vlozenyCas = "00:00:00,000";
Cas(const string &vstup = "");
bool vloz(const string &cas);
string vratVlozenyCas() const { return vlozenyCas; };
bool skontrolujCas(int h, int m, int s, int mik) const;
bool skontrolujCas() const;
string vratCas() const;
//2.uloha
void operator+=(const Cas &posun);
void operator-=(const Cas &posun);
void vlozUpravene(int h, int m, int s, int mik);
};
//3.uloha
class Titulok {
int poradie = 0; //poradove cislo titulku
Cas zaciatok, koniec; // cas zaciatku a konca zobrazenia titulku
string titulky[3]; //samotn0 texty titulku
string chyba = ""; //chybov0 vynimka, ak titulok nema spravny format
bool vlozTextChyby(const string &textChyby);
public:
bool vlozPoradoveCislo(const string &cislo);
int poradoveCisloTitulku() const { return poradie; };
bool vlozCasy(const string &casy);
void vlozZaciatok(const string &cas);
void vlozKoniec(const string &cas);
string casZaciatku() const;
string casKonca() const;
void vloz(const string texty[]);
string titulok(int index) const;
string textChyby() const { return chyba; };
void vloz(const Titulok &vstup);
};
//4.uloha
class Element : public Titulok {
Element *nasl;
public:
Element() : nasl(nullptr) {};
void nasledujuci(Element *n) { nasl = n; };
Element *dajDalsi() const { return nasl; };
};
class VsetkyTitulky {
Element *prvy;
Element *aktualny;
public:
VsetkyTitulky();
~VsetkyTitulky();
void vymazVsetkyTitulky();
void vloz(const Titulok &vstup);
Element *vratAktualny() const;
bool nastavNaZaciatok();
bool posunNaDalsi();
int pocetTitulkov();
//5.uloha
bool nacitajZoSuboru(const string &menoSuboru);
bool zapisDoSuboru(const string &menoSuboru);
//5.uloha
void operator+=(const Cas &posun);
void operator-=(const Cas &posun);
};
#endif
const bool DUMMY_BOOL = false;
const int DUMMY_INT = 0;
const string DUMMY_STRING = "";
//Pomocne Fcie
int konverziaCharNaInt(char znak) {
if (znak == ' ') {
return -2;
}
if (znak == '-') {
return 99;
}
if (znak >= '0' && znak <= '9') {
return znak - '0';
}
if (znak == ':') {
return -3;
}
if (znak == ',') {
return -4;
}
return -99;
}
//1.uloha
Cas::Cas(const string &vstup) {
if (vstup == "") {
hod = 0, min = 0, sek = 0, mikrosek = 0;
return;
}
vloz(vstup);
return;
}
bool Cas::skontrolujCas() const {
return skontrolujCas(hod, min, sek, mikrosek);
}
bool Cas::skontrolujCas(int h, int m, int s, int mik) const {
if (h < 0 || h > 23) {
throw ZlyVstup("Hodina je mimo povolenych hodnot");
}
if (m < 0 || m > 59) {
throw ZlyVstup("Minuta je mimo povolenych hodnot");
}
if (s < 0 || s > 59) {
throw ZlyVstup("Sekunda je mimo povolenych hodnot");
}
if (mik < 0 || mik > 999) {
throw ZlyVstup("Mikrosekunda je mimo povolenych hodnot");
}
return true;
}
bool Cas::vloz(const string &cas0) {
vlozenyCas = cas0;
stringstream vstup(cas0);
char o1, o2, o3;
int h, m, s, ms;
if (vstup >> h >> o1 >> m >> o2 >> s >> o3 >> ms) {
if (o1 == ':' && o2 == ':' && o3 == ',') {
if (skontrolujCas(h, m, s, ms)) {
hod = h, min = m, sek = s, mikrosek = ms;
return true;
}
}
}
throw ZlyVstup("Zly format casu");
}
string Cas::vratCas() const {
stringstream vystup;
vystup << setw(2) << setfill('0') << hod << ":" << setw(2) << min << ":" << setw(2) << sek << "," << setw(3) << mikrosek;
return vystup.str();
}
//2.uloha
void Cas::operator+=(const Cas &posun) {
Cas pripocitany = posun;
int h = pripocitany.hod + hod;
int m = pripocitany.min + min;
int s = pripocitany.sek + sek;
int ms = pripocitany.mikrosek + mikrosek;
vlozUpravene(h, m, s, ms);
}
void Cas::operator-=(const Cas &posun) {
Cas odpocitany = posun;
int h = hod - odpocitany.hod;
int m = min - odpocitany.min;
int s = sek - odpocitany.sek;
int ms = mikrosek - odpocitany.mikrosek;
vlozUpravene(h, m, s, ms);
}
void Cas::vlozUpravene(int h, int m, int s, int mik) {
if (mik > 1000 - 1) {
mik -= 1000;
s++;
}
else if (mik < 0) {
}
if (s < 0) {
s += 60;
m--;
}
else if (s > 60 - 1) {
s -= 60;
m++;
}
if (m < 0) {
m += 60;
h--;
}
else if (m > 60 - 1) {
m -= 60;
h++;
}
hod = h;
min = m;
sek = s;
mikrosek = mik;
vloz(vratCas());
}
//3.uloha
bool Titulok::vlozPoradoveCislo(const string &textPoradia) {
int p = 0;
for (unsigned int i = 0; i < textPoradia.size(); i++) {
p *= 10;
p += konverziaCharNaInt(textPoradia[i]);
if (textPoradia[i] == '-') {
poradie = 0;
chyba = "Zle poradie";
return false;
}
}
if (p > 0) {
poradie = p;
return true;
}
poradie = 0;
chyba = "Zle poradie";
return false;
}
bool Titulok::vlozCasy(const string &casy) {
stringstream vstup(casy);
string zac, kon, odd;
if (vstup >> zac >> odd >> kon) {
if (odd == "-->") {
try {
vlozZaciatok(zac);
vlozKoniec(kon);
return true;
}
catch (ZlyVstup) {
chyba = "Zle casy";
vlozZaciatok("00:00:00,000");
vlozKoniec("00:00:00,000");
return false;
}
}
}
if (chyba == "") chyba = "Zle casy";
return false;
}
void Titulok::vlozZaciatok(const string &cas) {
zaciatok.vloz(cas);
}
void Titulok::vlozKoniec(const string &cas) {
koniec.vloz(cas);
}
string Titulok::casZaciatku() const {
return zaciatok.vlozenyCas;
};
string Titulok::casKonca() const {
return koniec.vlozenyCas;
};
string Titulok::titulok(int index) const {
if (index >= 0 && index < 3) {
return titulky[index];
}
return "";
};
void Titulok::vloz(const string text[]) {
for (unsigned int i = 0; i < sizeof(text)-1; i++) {
titulky[i] = text[i];
}
}
bool Titulok::vlozTextChyby(const string &textChyby) {
return DUMMY_BOOL;
}
void Titulok::vloz(const Titulok &vstup) {
}
//4.uloha
VsetkyTitulky::VsetkyTitulky() : prvy(nullptr), aktualny(nullptr) { }
VsetkyTitulky::~VsetkyTitulky() {
}
void VsetkyTitulky::vymazVsetkyTitulky() {
}
void VsetkyTitulky::vloz(const Titulok &vstup) {
}
Element *VsetkyTitulky::vratAktualny() const {
return new Element();
}
bool VsetkyTitulky::nastavNaZaciatok() {
return DUMMY_BOOL;
}
bool VsetkyTitulky::posunNaDalsi() {
return DUMMY_BOOL;
}
int VsetkyTitulky::pocetTitulkov() {
return DUMMY_INT;
}
//5.uloha
void VsetkyTitulky::operator+=(const Cas &posun) {
}
void VsetkyTitulky::operator-=(const Cas &posun) {
}
| true |
8d0e2f033f03355d9f59d5f740f87cf860fec834 | C++ | jstraveler/C-C.plus.plus | /DT Bayes-Laplace criterion/main.cpp | UTF-8 | 3,412 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
/** Задача планирования на год
* Определить оптимальный объем заказа автомобилей в условиях неравномерного спроса.
*/
void init_matrix_first_year(int *matrix, int size);
void init_probability_matrix(double *probability_matrix, int const *init_matrix, double const *vector, int size);
void eval_mathematical_expectation(double *matrix, int *mathematical_expectation, int size);
template<class T> void print_matrix(T *matrix, int size);
template<class T> void print_vector(T *matrix, int size);
int main() {
// Init variables
int size = 5;
int matrix[size][size];
double probability_matrix[size][size];
double probability[5] = {0.1, 0.25, 0.3, 0.2, 0.15};
int mathematical_expectation[5] = {0, 0, 0, 0, 0};
// Init matrix
init_matrix_first_year(*matrix, size);
// Print matrix
cout << "Matrix" << "\n";
print_matrix(*matrix, size);
// Init probability matrix
init_probability_matrix(*probability_matrix, *matrix, probability, size);
// Print probability matrix
cout << "Probability matrix" << "\n";
print_matrix(*probability_matrix, size);
// Evaluate mathematical expectation
eval_mathematical_expectation(*probability_matrix, mathematical_expectation, size);
// Print mathematical expectation
cout << "Mathematical expectation matrix" << "\n";
print_vector(mathematical_expectation, size);
return 0;
}
void init_matrix_first_year(int *matrix, int size) {
int demand = 100; // спрос
int order = 100; // заказ
int price = 49000; // стоимость одной машины
int price_discont = 15000; // дисконтная стоимость одной машины
int seb = 25000; // себестоимость 1 автомобиля
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (order > demand) {
matrix[i*size+j] = ((demand * price) + ((order - demand) * price_discont) - (order * seb));
}
else {
matrix[i*size+j] = (order * price) - (order * seb);
}
demand = demand + 50;
}
demand = 100;
order = order + 50;
}
}
void init_probability_matrix(double *probability_matrix, int const *init_matrix, double const *vector, int size){
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
probability_matrix[i*size+j] = (double) init_matrix[i*size+j] * vector[j];
}
}
}
void eval_mathematical_expectation(double *matrix, int *mathematical_expectation, int size){
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
mathematical_expectation[i] = mathematical_expectation[i] + matrix[i*size+j];
}
}
}
template<class T> void print_matrix(T *matrix, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout.precision(10);
cout << right << setw(10) << matrix[i*size+j] << "|";
}
cout << "\n";
}
}
template<class T> void print_vector(T *matrix, int size) {
for (int i = 0; i < size; i++) {
cout.precision(10);
cout << right << setw(10) << matrix[i] << "|" << "\n";
}
}
| true |
936f04d388ff51911ee385226c2399721b928e98 | C++ | LaylaHirsh/Victor | /tools/GetArg.h | UTF-8 | 4,493 | 3.21875 | 3 | [] | no_license | /**
* @Author: Ulrike Hoefer, updated by Silvio Tosatto
* @Name of the method: getArg(s)
* @Description:
* - interprets the inputs of the command line, assigne a
* variable a command line input, possibly set default value,
* - check, if an option is chosen, if stop=true, the program will
* end, if the option is chosen, if the text is defined, it will be
* shown
* - if bool justOption=true, then you can just chose the option and
* as input will be taken the default value, if the option is not
* chosen, then the value will be ""
* - if you define "PATH", then the default name is added at the input,
* if the input is just a path
* - if bool twiceSameNumber=false, the program will remove every
* number, that is already member of the vector
* Call method by: getArg( "a", a_name, argc, argv [, default name] )
* getArg( "-all", all_name, argc, argv )
* if an option has several characters, it must begin with a "-"
* (called at the command line with --all)
*
* ERROR:
* - if an opton is called several times or a value is specified
* several times (except for the method "getArgs")
* - if an option is called but no value is given (except if the bool
* justOption is set on true)
* This can be hold back if "CONTINUE" is defined (return false)
*
*
* Name of the method: showText
* @Decription: show the text, if the option is chosen and ends,
* if the option "CONTINUE" is defined, then the program doesn't end
* Call method by: showText( "t", text, argc, argv )
* showText( "-text", text, argc, argv )
*
*
* Name of the method: checkArg
*
* Description: check, if there are chosen wrong options
* Call method by: checkArg( [text], argc, argv, 5,
* "a", "b", "c", "-test", "-help" )
*
* ERROR: if a wrong option is chosen or the first input isn't an
* option
* This can be hold back if "CONTINUE" is defined (return false)
*/
#ifndef __GET_ARG_H__
#define __GET_ARG_H__
#include <iostream>
#include <cstdarg>
#include <string>
#include <vector>
#include <Debug.h>
#include <String2Number.h> // convert number to string and and vice versa
#include <FileName.h>
#include <limits>
// "value" has only one "word" as input, set default value (if
// wanted), set gotten path AND default value (if wanted):
bool getArg( const char *option, string &value,
const int &argc, char *argv[], string defaultValue = "",
bool justOption = false );
bool getArg( const char *option, int &value,
const int &argc, char *argv[], int defaultValue = 0 );
bool getArg( const char *option, unsigned int &value,
const int &argc, char *argv[], unsigned int defaultValue = 0 );
bool getArg( const char *option, long &value,
const int &argc, char *argv[], long defaultValue = 0);
bool getArg( const char *option, float &value,
const int &argc, char *argv[], float defaultValue = 0 );
bool getArg( const char *option, double &value,
const int &argc, char *argv[], double defaultValue = 0 );
bool getArg( const char *option, vector<int> &value,
const int &argc, char *argv[],
bool twiceSameNumber = true );
bool getArg( const char *option, vector<unsigned int> &value,
const int &argc, char *argv[],
bool twiceSameNumber = true );
bool getArg( const char *option, vector<double> &value,
const int &argc, char *argv[],
bool twiceSameNumber = true );
bool getArg( const char *option, vector<string> &value,
const int &argc, char *argv[],
bool twiceSameNumber = true );
// several words with the same option are put together in the string
// "value":
bool getArgs( const char *option, string &value,
const int &argc, char *argv[], string defaultValue = "" );
// check, if an option is chosen:
bool getArg( const char *givenOption, const int &argc, char *argv[],
string text = "", bool stop = false );
// check command line, if all options are right:
bool checkArg( const int &argc, char *argv[], int optionNumber ... );
bool checkArg( string text, const int &argc, char *argv[],
int optionNumber ... );
void getOption(double& param, char* optName, int nArgs, char* argv[],
bool verbose = false);
void getOption(unsigned int& param, char* optName, int nArgs, char* argv[],
bool verbose = false);
void getOption(float& param, char* optName, int nArgs, char* argv[],
bool verbose = false);
bool getOption(char* optName, int nArgs, char* argv[], bool verbose = true);
#endif // __GET_ARG_H__
| true |
bd3d5cb7d2dfa3ad05757058f2ca6a6ecefa124a | C++ | YogeshSingla/compiler_design | /10042018/p7.cpp | UTF-8 | 1,502 | 3.671875 | 4 | [] | no_license | // C++ program to find out execution time of
// of functions
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
//measure time of this function
void myfunction(){
int x = 0;
int y = 10;
int z = 20;
long n = 50000; //50 thousand elements in array
int a[n];
int x2 = x*x;
for (int i = 0; i < n; i++) {
//Change 1 : Move this statement outside the loop
//x = y + z;
//Result : Time of program execution reduces by 20 microseconds.
//A ~16% increase in performance.
a[i] = 6 * i + x * x;
//Change 2 : Replace x*x by another variable.
// a[i] = 6 * i + x2;
//Result : Time of program execution reduces by
//a[i] = 6 * i + x2;
}
x = y + z;
}
#define LOOP_COUNT 10000
int main(){
long time[LOOP_COUNT];
long sum=0;
for(int i=0;i<LOOP_COUNT;i++){
// Get starting timepoint
auto start = high_resolution_clock::now();
// Call the function, here sort()
myfunction();
// Get ending timepoint
auto stop = high_resolution_clock::now();
// Get duration. Substart timepoints to
// get durarion. To cast it to proper unit
// use duration cast method
auto duration = duration_cast<microseconds>(stop - start);
time[i] = duration.count();
sum+=time[i];
}
cout << "Average time taken by function: "
<< sum/LOOP_COUNT << " microseconds" << endl;
return 0;
} | true |
54f6bd4145030ee42597e7e877aa9cc9f7ba7ad4 | C++ | gsotirchos/ball-chaser-bot | /ball_chaser/src/drive_bot.cpp | UTF-8 | 2,200 | 3.109375 | 3 | [
"MIT"
] | permissive | #include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "ball_chaser/DriveToTarget.h"
// Single class containing ROS entities and relevant state variables, inspired by Martin Peris' answer:
// https://answers.ros.org/question/59725/publishing-to-a-topic-via-subscriber-callback-function/?answer=59738#post-id-59738
class CommandRobotServer {
public:
CommandRobotServer() {
// Inform ROS master that we will be publishing a message of type geometry_msgs::Twist on the robot actuation topic with a publishing queue size of 10
motor_command_pub_ = n_.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
// Define a drive /ball_chaser/command_robot service with a handle_drive_request callback function
srv_ = n_.advertiseService(
"/ball_chaser/command_robot",
&CommandRobotServer::handle_drive_request,
this
);
}
// This method publishes the requested linear x and angular velocities to the robot wheel joints
bool handle_drive_request(
ball_chaser::DriveToTarget::Request& req,
ball_chaser::DriveToTarget::Response& res
) {
// Create a motor_command object of type geometry_msgs::Twist
geometry_msgs::Twist motor_command;
// Set wheel velocities
motor_command.linear.x = req.linear_x;
motor_command.angular.z = req.angular_z;
// Publish velocities to drive the robot
motor_command_pub_.publish(motor_command);
// Return a response message
res.msg_feedback =
"Velocities set - linear x: " + std::to_string(req.linear_x)
+ " , angular z: " + std::to_string(req.angular_z);
ROS_INFO_STREAM(res.msg_feedback);
return true;
}
private:
ros::NodeHandle n_;
ros::ServiceServer srv_;
ros::Publisher motor_command_pub_;
}; // class CommandRobotServer
int main(int argc, char * * argv) {
// Initialize a ROS node
ros::init(argc, argv, "drive_bot");
// Create an object of class CommandRobotServer
CommandRobotServer CRSObject;
ROS_INFO("Ready to send commands");
// Handle ROS communication events
ros::spin();
return 0;
}
| true |
ae25a584ef5d29a99ff9f0f1a3f563e158339803 | C++ | jeffreymutethia/Data-Structures-C- | /Sorted Sequence/sorted_seq.h | UTF-8 | 1,165 | 3.453125 | 3 | [] | no_license | /******************
* Header file for a Sorted Sequence class sorted_seq.
*
*
*
*/
#ifndef SORTED_SEQ_H
#define SORTED_SEQ_H
#include <iostream>
#include <cstdlib>
#include "node.h"
#include "const_node_iterator.h"
template <class Item>
class sorted_seq {
public:
// Default constructor
sorted_seq() { head = NULL; count = 0; }
// copy constructor
sorted_seq(const sorted_seq& other);
// destructor
~sorted_seq() { list_clear(head); }
// public methods
void insert(const Item& entry);
bool contains(const Item& target);
int index(const Item& target);
bool erase_one(const Item& target);
// iterators -- provide const iterators only because we will not
// allow clients to alter the data inside of our list
const_node_iterator<Item> begin() { return const_node_iterator<Item>(head); }
const_node_iterator<Item> end() { return const_node_iterator<Item>(); }
// const methods
size_t length() { return count; }
private:
node<Item>* head;
size_t count;
};
#include "sorted_seq.template"
#endif
| true |
34a65f948489e9aefd6f35277b5d419428bbb92c | C++ | DreadArceus/LeetCode | /Explore Cards/JulyLC2020/J28-Task_Scheduler.cpp | UTF-8 | 2,396 | 3.09375 | 3 | [] | no_license | //Not sorting all the time causes WA because the answer isnt min
//Sorting all the time causes TLE
//Came up with a less time consuming case specific sort, accepted.
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
bool key(vector<int> a, vector<int> b)
{
return a[1] > b[1];
}
int solve(vector<char> tasks, int n)
{
unordered_set<char> s(tasks.begin(), tasks.end());
vector<vector<int> > f;
for(char cx : s)
{
vector<int> local(4);
local[0] = cx;
local[1] = 0;
local[2] = true;
local[3] = 0;
for(char cy : tasks)
{
if(cx == cy)
{
local[1]++;
}
}
f.push_back(local);
}
int i = 0, x = 0;
bool go = true;
sort(f.begin(), f.end(), key);
while(i != tasks.size())
{
x++;
for(int j = 0; j < f.size(); j++)
{
if(!f[j][2])
{
if(f[j][3] == n)
{
f[j][2] = true;
}
f[j][3]++;
}
if(go && f[j][2] && f[j][1] > 0)
{
f[j][1]--;
i++;
f[j][2] = false;
f[j][3] = 0;
go = false;
for(int z = j + 1; z < f.size(); z++)
{
if(f[j][1] < f[z][1])
{
swap(f[j], f[z]);
break;
}
}
}
}
go = true;
// sort(f.begin(), f.end(), key);
}
return x;
}
template<class Ti, class To>
void func(Ti &in, To &o, ifstream &c)
{
int t = 0;
in >> t;
in.ignore(3, '\n');
while(t--)
{
int n = 0, k = 0;
in >> n >> k;
in.ignore(3, '\n');
vector<char> v(n);
for(int i = 0; i < n; i++)
{
in >> v[i];
}
int var = solve(v, k);
if(c.is_open())
{
int ans = 0;
c >> ans;
c.ignore(3, '\n');
cout << "Testing.. ";
if(var != ans)
{
cout << "Wrong Answer\n";
o << "x ";
}
else
{
cout << "Passed\n";
}
}
o << var << "\n";
}
}
int main()
{
ifstream checkFile, inFile("/Users/dreadarceus/github/LeetCode/Testers/input.txt");
ofstream outFile;
if(inFile.is_open())
{
checkFile.open("/Users/dreadarceus/github/LeetCode/Testers/correctOutput.txt");
outFile.open("/Users/dreadarceus/github/LeetCode/Testers/output.txt");
func(inFile, outFile, checkFile);
}
else
{
func(cin, cout, checkFile);
}
}
| true |